qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
sequence
input
stringlengths
12
45k
output
stringlengths
2
31.8k
32,145
<p>I'm going to try something with the format of this question and I'm very open to suggestions about a better way to handle it.</p> <p>I didn't want to just dump a bunch of code in the question so I've posted the code for the class on <code>refactormycode</code>.</p> <p><strong><a href="http://www.refactormycode.com/codes/461-base-class-for-easy-class-property-handling" rel="nofollow noreferrer">base class for easy class property handling</a></strong></p> <p>My thought was that people can either post code snippets here or make changes on <code>refactormycode</code> and post links back to their refactorings. I'll make upvotes and accept an answer (assuming there's a clear "winner") based on that.</p> <p>At any rate, on to the class itself:</p> <p>I see a lot of debate about getter/setter class methods and is it better to just access simple property variables directly or should every class have explicit get/set methods defined, blah blah blah. I like the idea of having explicit methods in case you have to add more logic later. Then you don't have to modify any code that uses the class. However I hate having a million functions that look like this:</p> <pre><code>public function getFirstName() { return $this-&gt;firstName; } public function setFirstName($firstName) { return $this-&gt;firstName; } </code></pre> <p>Now I'm sure I'm not the first person to do this (I'm hoping that there's a better way of doing it that someone can suggest to me).</p> <p>Basically, the PropertyHandler class has a __call magic method. Any methods that come through __call that start with "get" or "set" are then routed to functions that set or retrieve values into an associative array. The key into the array is the name of the calling method after getting or setting. So, if the method coming into __call is "getFirstName", the array key is "FirstName".</p> <p>I liked using __call because it will automatically take care of the case where the subclass already has a "getFirstName" method defined. My impression (and I may be wrong) is that the __get &amp; __set magic methods don't do that.</p> <p>So here's an example of how it would work:</p> <pre><code>class PropTest extends PropertyHandler { public function __construct() { parent::__construct(); } } $props = new PropTest(); $props-&gt;setFirstName("Mark"); echo $props-&gt;getFirstName(); </code></pre> <p>Notice that PropTest doesn't actually have "setFirstName" or "getFirstName" methods and neither does PropertyHandler. All that's doing is manipulating array values.</p> <p>The other case would be where your subclass is already extending something else. Since you can't have true multiple inheritances in PHP, you can make your subclass have a PropertyHandler instance as a private variable. You have to add one more function but then things behave in exactly the same way.</p> <pre><code>class PropTest2 { private $props; public function __construct() { $this-&gt;props = new PropertyHandler(); } public function __call($method, $arguments) { return $this-&gt;props-&gt;__call($method, $arguments); } } $props2 = new PropTest2(); $props2-&gt;setFirstName('Mark'); echo $props2-&gt;getFirstName(); </code></pre> <p>Notice how the subclass has a __call method that just passes everything along to the PropertyHandler __call method.</p> <hr> <p>Another good argument against handling getters and setters this way is that it makes it really hard to document.</p> <p>In fact, it's basically impossible to use any sort of document generation tool since the explicit methods to be don't documented don't exist.</p> <p>I've pretty much abandoned this approach for now. It was an interesting learning exercise but I think it sacrifices too much clarity.</p>
[ { "answer_id": 32191, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 3, "selected": false, "text": "<p>The way I do it is the following:</p>\n\n<pre><code>class test {\n protected $x='';\n protected $y='';\n\n function set_y ($y) {\n print \"specific function set_y\\n\";\n $this-&gt;y = $y;\n }\n\n function __call($function , $args) {\n print \"generic function $function\\n\";\n list ($name , $var ) = split ('_' , $function );\n if ($name == 'get' &amp;&amp; isset($this-&gt;$var)) {\n return $this-&gt;$var;\n }\n if ($name == 'set' &amp;&amp; isset($this-&gt;$var)) {\n $this-&gt;$var= $args[0];\n return;\n }\n trigger_error (\"Fatal error: Call to undefined method test::$function()\");\n }\n}\n\n$p = new test();\n$p-&gt;set_x(20);\n$p-&gt;set_y(30);\nprint $p-&gt;get_x();\nprint $p-&gt;get_y();\n\n$p-&gt;set_z(40);\n</code></pre>\n\n<p>Which will output (line breaks added for clarity)</p>\n\n<pre><code>generic function set_x\nspecific function set_y\n\ngeneric function get_x\n20\ngeneric function get_y\n30\n\ngeneric function set_z\nNotice: Fatal error: Call to undefined method set_z() in [...] on line 16\n</code></pre>\n" }, { "answer_id": 32218, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 2, "selected": false, "text": "<p>Yes that's right the variables have to be manually declared but i find that better since I fear a typo in the setter </p>\n\n<pre><code>$props2-&gt;setFristName('Mark');\n</code></pre>\n\n<p>will auto-generate a new property (FristName instead of FirstName) which will make debugging harder.</p>\n" }, { "answer_id": 32219, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 1, "selected": false, "text": "<p>I like having methods instead of just using public fields, as well, but my problem with PHP's default implementation (using __get() and __set()) or your custom implementation is that you aren't establishing getters and setters on a per-property basis. My problem with this is that adding \"more logic later\" requires that you add blanket logic that applies to all properties accessed with the getter/setter or that you use if or switch statements to evaluate which property you're accessing so that you can apply specific logic.</p>\n\n<p>I like your solution, and I applaud you for it--I'm just not satisfied with the limitations that PHP has when it comes to implicit accessor methods.</p>\n" }, { "answer_id": 32356, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/32145/is-this-a-reasonable-way-to-handle-getterssetters-in-a-php-class#32219\">@Brian</a></p>\n\n<blockquote>\n <blockquote>\n <blockquote>\n <blockquote>\n <p>My problem with this is that adding \"more logic later\" requires that you add blanket logic that applies to all properties accessed with the getter/setter or that you use if or switch statements to evaluate which property you're accessing so that you can apply specific logic.</p>\n </blockquote>\n </blockquote>\n </blockquote>\n</blockquote>\n\n<p>That's not quite true. Take my first example:</p>\n\n<pre><code>class PropTest extends PropertyHandler\n{\n public function __construct()\n {\n parent::__construct();\n }\n}\n\n$props = new PropTest();\n\n$props-&gt;setFirstName(\"Mark\");\necho $props-&gt;getFirstName();\n</code></pre>\n\n<p>Let's say that I need to add some logic for validating FirstNames. All I have to do is add a setFirstName method to my subclass and that method is automatically used instead.</p>\n\n<pre><code>class PropTest extends PropertyHandler\n{\n public function __construct()\n {\n parent::__construct();\n }\n\n public function setFirstName($name)\n {\n if($name == 'Mark')\n {\n echo \"I love you, Mark!\";\n }\n }\n}\n</code></pre>\n\n<blockquote>\n <blockquote>\n <blockquote>\n <blockquote>\n <p>I'm just not satisfied with the limitations that PHP has when it comes to implicit accessor methods. </p>\n </blockquote>\n </blockquote>\n </blockquote>\n</blockquote>\n\n<p>I agree completely. I like the Python way of handling this (my implementation is just a clumsy rip-off of it).</p>\n" }, { "answer_id": 32405, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 1, "selected": false, "text": "<p>@Mark</p>\n\n<p>But even your method requires a fresh declaration of the method, and it somewhat takes away the advantage of putting it in a method so that you can add more logic, because to add more logic requires the old-fashioned declaration of the method, anyway. In its default state (which is where it is impressive in what it detects/does), your technique is offering no advantage (in PHP) over public fields. You're restricting access to the field but giving carte blanche through accessor methods that don't have any restrictions of their own. I'm not aware that unchecked explicit accessors offer any advantage over public fields in <em>any</em> language, but people can and should feel free to correct me if I'm wrong.</p>\n" }, { "answer_id": 32507, "author": "reefnet_alex", "author_id": 2745, "author_profile": "https://Stackoverflow.com/users/2745", "pm_score": 0, "selected": false, "text": "<p>I've always handled this issue in a similar with a __call which ends up pretty much as boiler plate code in many of my classes. However, it's compact, and uses the reflection classes to only add getters / setters for properties you have already set (won't add new ones). Simply adding the getter / setter explicitly will add more complex functionality. It expects to be </p>\n\n<p>Code looks like this:</p>\n\n<pre><code>/**\n* Handles default set and get calls\n*/\npublic function __call($method, $params) {\n\n //did you call get or set\n if ( preg_match( \"|^[gs]et([A-Z][\\w]+)|\", $method, $matches ) ) {\n\n //which var?\n $var = strtolower($matches[1]);\n\n $r = new ReflectionClass($this);\n $properties = $r-&gt;getdefaultProperties();\n\n //if it exists\n if ( array_key_exists($var,$properties) ) {\n //set\n if ( 's' == $method[0] ) {\n $this-&gt;$var = $params[0];\n }\n //get\n elseif ( 'g' == $method[0] ) {\n return $this-&gt;$var;\n }\n }\n }\n}\n</code></pre>\n\n<p>Adding this to a class where you have declared default properties like: </p>\n\n<pre><code>class MyClass {\n public $myvar = null;\n}\n\n$test = new MyClass;\n$test-&gt;setMyvar = \"arapaho\";\n\necho $test-&gt;getMyvar; //echos arapaho \n</code></pre>\n\n<p>The reflection class may add something of use to what you were proposing. Neat solution @Mark.</p>\n" }, { "answer_id": 417966, "author": "Dan Soap", "author_id": 25253, "author_profile": "https://Stackoverflow.com/users/25253", "pm_score": 0, "selected": false, "text": "<p>Just recently, I also thought about handling getters and setters the way you suggested (the second approach was my favorite, i.e. the private $props array), but I discarded it for it wouldn't have worked out in my app.</p>\n\n<p>I am working on a rather large SoapServer-based application and the soap interface of PHP 5 injects the values that are transmitted via soap directly into the associated class, without bothering about existing or non-existing properties in the class.</p>\n" }, { "answer_id": 2658786, "author": "SeanJA", "author_id": 75924, "author_profile": "https://Stackoverflow.com/users/75924", "pm_score": 0, "selected": false, "text": "<p>I can't help putting in my 2 cents...</p>\n\n<p>I have taken to using <code>__get</code> and <code>__set</code> in this manor <a href=\"http://gist.github.com/351387\" rel=\"nofollow noreferrer\">http://gist.github.com/351387</a> (similar to the way that doctrine does it), then only ever accessing the properties via the <code>$obj-&gt;var</code> in an outside of the class. That way you can override functionality as needed instead of making a huge <code>__get</code> or <code>__set</code> function, or overriding <code>__get</code> and <code>__set</code> in the child classes.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
I'm going to try something with the format of this question and I'm very open to suggestions about a better way to handle it. I didn't want to just dump a bunch of code in the question so I've posted the code for the class on `refactormycode`. **[base class for easy class property handling](http://www.refactormycode.com/codes/461-base-class-for-easy-class-property-handling)** My thought was that people can either post code snippets here or make changes on `refactormycode` and post links back to their refactorings. I'll make upvotes and accept an answer (assuming there's a clear "winner") based on that. At any rate, on to the class itself: I see a lot of debate about getter/setter class methods and is it better to just access simple property variables directly or should every class have explicit get/set methods defined, blah blah blah. I like the idea of having explicit methods in case you have to add more logic later. Then you don't have to modify any code that uses the class. However I hate having a million functions that look like this: ``` public function getFirstName() { return $this->firstName; } public function setFirstName($firstName) { return $this->firstName; } ``` Now I'm sure I'm not the first person to do this (I'm hoping that there's a better way of doing it that someone can suggest to me). Basically, the PropertyHandler class has a \_\_call magic method. Any methods that come through \_\_call that start with "get" or "set" are then routed to functions that set or retrieve values into an associative array. The key into the array is the name of the calling method after getting or setting. So, if the method coming into \_\_call is "getFirstName", the array key is "FirstName". I liked using \_\_call because it will automatically take care of the case where the subclass already has a "getFirstName" method defined. My impression (and I may be wrong) is that the \_\_get & \_\_set magic methods don't do that. So here's an example of how it would work: ``` class PropTest extends PropertyHandler { public function __construct() { parent::__construct(); } } $props = new PropTest(); $props->setFirstName("Mark"); echo $props->getFirstName(); ``` Notice that PropTest doesn't actually have "setFirstName" or "getFirstName" methods and neither does PropertyHandler. All that's doing is manipulating array values. The other case would be where your subclass is already extending something else. Since you can't have true multiple inheritances in PHP, you can make your subclass have a PropertyHandler instance as a private variable. You have to add one more function but then things behave in exactly the same way. ``` class PropTest2 { private $props; public function __construct() { $this->props = new PropertyHandler(); } public function __call($method, $arguments) { return $this->props->__call($method, $arguments); } } $props2 = new PropTest2(); $props2->setFirstName('Mark'); echo $props2->getFirstName(); ``` Notice how the subclass has a \_\_call method that just passes everything along to the PropertyHandler \_\_call method. --- Another good argument against handling getters and setters this way is that it makes it really hard to document. In fact, it's basically impossible to use any sort of document generation tool since the explicit methods to be don't documented don't exist. I've pretty much abandoned this approach for now. It was an interesting learning exercise but I think it sacrifices too much clarity.
The way I do it is the following: ``` class test { protected $x=''; protected $y=''; function set_y ($y) { print "specific function set_y\n"; $this->y = $y; } function __call($function , $args) { print "generic function $function\n"; list ($name , $var ) = split ('_' , $function ); if ($name == 'get' && isset($this->$var)) { return $this->$var; } if ($name == 'set' && isset($this->$var)) { $this->$var= $args[0]; return; } trigger_error ("Fatal error: Call to undefined method test::$function()"); } } $p = new test(); $p->set_x(20); $p->set_y(30); print $p->get_x(); print $p->get_y(); $p->set_z(40); ``` Which will output (line breaks added for clarity) ``` generic function set_x specific function set_y generic function get_x 20 generic function get_y 30 generic function set_z Notice: Fatal error: Call to undefined method set_z() in [...] on line 16 ```
32,149
<p>Does anyone have a trusted Proper Case or PCase algorithm (similar to a UCase or Upper)? I'm looking for something that takes a value such as <code>"GEORGE BURDELL"</code> or <code>"george burdell"</code> and turns it into <code>"George Burdell"</code>.</p> <p>I have a simple one that handles the simple cases. The ideal would be to have something that can handle things such as <code>"O'REILLY"</code> and turn it into <code>"O'Reilly"</code>, but I know that is tougher.</p> <p>I am mainly focused on the English language if that simplifies things.</p> <hr> <p><strong>UPDATE:</strong> I'm using C# as the language, but I can convert from almost anything (assuming like functionality exists).</p> <p>I agree that the McDonald's scneario is a tough one. I meant to mention that along with my O'Reilly example, but did not in the original post.</p>
[ { "answer_id": 32189, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<p>What programming language do you use? Many languages allow callback functions for regular expression matches. These can be used to propercase the match easily. The regular expression that would be used is quite simple, you just have to match all word characters, like so:</p>\n\n<pre><code>/\\w+/\n</code></pre>\n\n<p>Alternatively, you can already extract the first character to be an extra match:</p>\n\n<pre><code>/(\\w)(\\w*)/\n</code></pre>\n\n<p>Now you can access the first character and successive characters in the match separately. The callback function can then simply return a concatenation of the hits. In pseudo Python (I don't actually know Python):</p>\n\n<pre><code>def make_proper(match):\n return match[1].to_upper + match[2]\n</code></pre>\n\n<p>Incidentally, this would also handle the case of “O'Reilly” because “O” and “Reilly” would be matched separately and both propercased. There are however other special cases that are not handled well by the algorithm, e.g. “McDonald's” or generally any apostrophed word. The algorithm would produce “Mcdonald'S” for the latter. A special handling for apostrophe could be implemented but that would interfere with the first case. Finding a thereotical perfect solution isn't possible. In practice, it might help considering the length of the part after the apostrophe.</p>\n" }, { "answer_id": 32236, "author": "JimmyJ", "author_id": 2083, "author_profile": "https://Stackoverflow.com/users/2083", "pm_score": 0, "selected": false, "text": "<p>a simple way to capitalise the first letter of each word (seperated by a space)</p>\n\n<pre><code>$words = explode(” “, $string);\nfor ($i=0; $i&lt;count($words); $i++) {\n$s = strtolower($words[$i]);\n$s = substr_replace($s, strtoupper(substr($s, 0, 1)), 0, 1);\n$result .= “$s “;\n}\n$string = trim($result);\n</code></pre>\n\n<p>in terms of catching the \"O'REILLY\" example you gave\nsplitting the string on both spaces and ' would not work as it would capitalise any letter that appeared after a apostraphe i.e. the s in Fred's</p>\n\n<p>so i would probably try something like </p>\n\n<pre><code>$words = explode(” “, $string);\nfor ($i=0; $i&lt;count($words); $i++) {\n\n$s = strtolower($words[$i]);\n\nif (substr($s, 0, 2) === \"o'\"){\n$s = substr_replace($s, strtoupper(substr($s, 0, 3)), 0, 3);\n}else{\n$s = substr_replace($s, strtoupper(substr($s, 0, 1)), 0, 1);\n}\n$result .= “$s “;\n}\n$string = trim($result);\n</code></pre>\n\n<p>This should catch O'Reilly, O'Clock, O'Donnell etc hope it helps</p>\n\n<p>Please note this code is untested.</p>\n" }, { "answer_id": 32249, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": -1, "selected": false, "text": "<p>You do not mention which language you would like the solution in so here is some pseudo code.</p>\n\n<pre><code>Loop through each character\n If the previous character was an alphabet letter\n Make the character lower case\n Otherwise\n Make the character upper case\nEnd loop\n</code></pre>\n" }, { "answer_id": 32254, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 2, "selected": false, "text": "<p>There's also this neat Perl script for title-casing text.</p>\n\n<p><a href=\"http://daringfireball.net/2008/08/title_case_update\" rel=\"nofollow noreferrer\">http://daringfireball.net/2008/08/title_case_update</a></p>\n\n<blockquote>\n<pre><code>#!/usr/bin/perl\n\n# This filter changes all words to Title Caps, and attempts to be clever\n# about *un*capitalizing small words like a/an/the in the input.\n#\n# The list of \"small words\" which are not capped comes from\n# the New York Times Manual of Style, plus 'vs' and 'v'. \n#\n# 10 May 2008\n# Original version by John Gruber:\n# http://daringfireball.net/2008/05/title_case\n#\n# 28 July 2008\n# Re-written and much improved by Aristotle Pagaltzis:\n# http://plasmasturm.org/code/titlecase/\n#\n# Full change log at __END__.\n#\n# License: http://www.opensource.org/licenses/mit-license.php\n#\n\n\nuse strict;\nuse warnings;\nuse utf8;\nuse open qw( :encoding(UTF-8) :std );\n\n\nmy @small_words = qw( (?&lt;!q&amp;)a an and as at(?!&amp;t) but by en for if in of on or the to v[.]? via vs[.]? );\nmy $small_re = join '|', @small_words;\n\nmy $apos = qr/ (?: ['’] [[:lower:]]* )? /x;\n\nwhile ( &lt;&gt; ) {\n s{\\A\\s+}{}, s{\\s+\\z}{};\n\n $_ = lc $_ if not /[[:lower:]]/;\n\n s{\n \\b (_*) (?:\n ( (?&lt;=[ ][/\\\\]) [[:alpha:]]+ [-_[:alpha:]/\\\\]+ | # file path or\n [-_[:alpha:]]+ [@.:] [-_[:alpha:]@.:/]+ $apos ) # URL, domain, or email\n |\n ( (?i: $small_re ) $apos ) # or small word (case-insensitive)\n |\n ( [[:alpha:]] [[:lower:]'’()\\[\\]{}]* $apos ) # or word w/o internal caps\n |\n ( [[:alpha:]] [[:alpha:]'’()\\[\\]{}]* $apos ) # or some other word\n ) (_*) \\b\n }{\n $1 . (\n defined $2 ? $2 # preserve URL, domain, or email\n : defined $3 ? \"\\L$3\" # lowercase small word\n : defined $4 ? \"\\u\\L$4\" # capitalize word w/o internal caps\n : $5 # preserve other kinds of word\n ) . $6\n }xeg;\n\n\n # Exceptions for small words: capitalize at start and end of title\n s{\n ( \\A [[:punct:]]* # start of title...\n | [:.;?!][ ]+ # or of subsentence...\n | [ ]['\"“‘(\\[][ ]* ) # or of inserted subphrase...\n ( $small_re ) \\b # ... followed by small word\n }{$1\\u\\L$2}xig;\n\n s{\n \\b ( $small_re ) # small word...\n (?= [[:punct:]]* \\Z # ... at the end of the title...\n | ['\"’”)\\]] [ ] ) # ... or of an inserted subphrase?\n }{\\u\\L$1}xig;\n\n # Exceptions for small words in hyphenated compound words\n ## e.g. \"in-flight\" -&gt; In-Flight\n s{\n \\b\n (?&lt;! -) # Negative lookbehind for a hyphen; we don't want to match man-in-the-middle but do want (in-flight)\n ( $small_re )\n (?= -[[:alpha:]]+) # lookahead for \"-someword\"\n }{\\u\\L$1}xig;\n\n ## # e.g. \"Stand-in\" -&gt; \"Stand-In\" (Stand is already capped at this point)\n s{\n \\b\n (?&lt;!…) # Negative lookbehind for a hyphen; we don't want to match man-in-the-middle but do want (stand-in)\n ( [[:alpha:]]+- ) # $1 = first word and hyphen, should already be properly capped\n ( $small_re ) # ... followed by small word\n (?! - ) # Negative lookahead for another '-'\n }{$1\\u$2}xig;\n\n print \"$_\";\n}\n\n__END__\n</code></pre>\n</blockquote>\n\n<p>But it sounds like by proper case you mean.. for people's names <em>only</em>.</p>\n" }, { "answer_id": 33168, "author": "Markus Olsson", "author_id": 2114, "author_profile": "https://Stackoverflow.com/users/2114", "pm_score": 5, "selected": true, "text": "<p>Unless I've misunderstood your question I don't think you need to roll your own, the TextInfo class can do it for you.</p>\n\n<pre><code>using System.Globalization;\n\nCultureInfo.InvariantCulture.TextInfo.ToTitleCase(\"GeOrGE bUrdEll\")\n</code></pre>\n\n<p>Will return \"George Burdell. And you can use your own culture if there's some special rules involved.</p>\n\n<p><strong>Update:</strong> <a href=\"https://stackoverflow.com/users/1684/michael-wolfenden\">Michael</a> (in a comment to this answer) pointed out that this will not work if the input is all caps since the method will assume that it is an acronym. The naive workaround for this is to .ToLower() the text before submitting it to ToTitleCase.</p>\n" }, { "answer_id": 33291, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 1, "selected": false, "text": "<p>Here's a perhaps naive C# implementation:-</p>\n\n<pre><code>public class ProperCaseHelper {\n public string ToProperCase(string input) {\n string ret = string.Empty;\n\n var words = input.Split(' ');\n\n for (int i = 0; i &lt; words.Length; ++i) {\n ret += wordToProperCase(words[i]);\n if (i &lt; words.Length - 1) ret += \" \";\n }\n\n return ret;\n }\n\n private string wordToProperCase(string word) {\n if (string.IsNullOrEmpty(word)) return word;\n\n // Standard case\n string ret = capitaliseFirstLetter(word);\n\n // Special cases:\n ret = properSuffix(ret, \"'\");\n ret = properSuffix(ret, \".\");\n ret = properSuffix(ret, \"Mc\");\n ret = properSuffix(ret, \"Mac\");\n\n return ret;\n }\n\n private string properSuffix(string word, string prefix) {\n if(string.IsNullOrEmpty(word)) return word;\n\n string lowerWord = word.ToLower(), lowerPrefix = prefix.ToLower();\n if (!lowerWord.Contains(lowerPrefix)) return word;\n\n int index = lowerWord.IndexOf(lowerPrefix);\n\n // If the search string is at the end of the word ignore.\n if (index + prefix.Length == word.Length) return word;\n\n return word.Substring(0, index) + prefix +\n capitaliseFirstLetter(word.Substring(index + prefix.Length));\n }\n\n private string capitaliseFirstLetter(string word) {\n return char.ToUpper(word[0]) + word.Substring(1).ToLower();\n }\n}\n</code></pre>\n" }, { "answer_id": 485362, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Kronoz, thank you. I found in your function that the line:</p>\n\n<pre><code>`if (!lowerWord.Contains(lowerPrefix)) return word`;\n</code></pre>\n\n<p>must say</p>\n\n<pre><code>if (!lowerWord.StartsWith(lowerPrefix)) return word;\n</code></pre>\n\n<p>so \"información\" is not changed to \"InforMacIón\"</p>\n\n<p>best,</p>\n\n<p>Enrique</p>\n" }, { "answer_id": 3553524, "author": "Dasith Wijes", "author_id": 422427, "author_profile": "https://Stackoverflow.com/users/422427", "pm_score": 0, "selected": false, "text": "<p>I use this as the textchanged event handler of text boxes. Support entry of \"McDonald\" </p>\n\n<pre><code>Public Shared Function DoProperCaseConvert(ByVal str As String, Optional ByVal allowCapital As Boolean = True) As String\n Dim strCon As String = \"\"\n Dim wordbreak As String = \" ,.1234567890;/\\-()#$%^&amp;*€!~+=@\"\n Dim nextShouldBeCapital As Boolean = True\n\n 'Improve to recognize all caps input\n 'If str.Equals(str.ToUpper) Then\n ' str = str.ToLower\n 'End If\n\n For Each s As Char In str.ToCharArray\n\n If allowCapital Then\n strCon = strCon &amp; If(nextShouldBeCapital, s.ToString.ToUpper, s)\n Else\n strCon = strCon &amp; If(nextShouldBeCapital, s.ToString.ToUpper, s.ToLower)\n End If\n\n If wordbreak.Contains(s.ToString) Then\n nextShouldBeCapital = True\n Else\n nextShouldBeCapital = False\n End If\n Next\n\n Return strCon\nEnd Function\n</code></pre>\n" }, { "answer_id": 6576464, "author": "Colin", "author_id": 645902, "author_profile": "https://Stackoverflow.com/users/645902", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/users/388520/zwol\">@zwol</a>: I'll post it as a separate reply.</p>\n<p>Here's an example based on <a href=\"https://stackoverflow.com/users/3394/ljs\">ljs</a>'s <a href=\"https://stackoverflow.com/a/33291\">post</a>.</p>\n<pre><code>void Main()\n{\n List&lt;string&gt; names = new List&lt;string&gt;() {\n &quot;bill o'reilly&quot;, \n &quot;johannes diderik van der waals&quot;, \n &quot;mr. moseley-williams&quot;, \n &quot;Joe VanWyck&quot;, \n &quot;mcdonald's&quot;, \n &quot;william the third&quot;, \n &quot;hrh prince charles&quot;, \n &quot;h.r.m. queen elizabeth the third&quot;,\n &quot;william gates, iii&quot;, \n &quot;pope leo xii&quot;,\n &quot;a.k. jennings&quot;\n };\n \n names.Select(name =&gt; name.ToProperCase()).Dump();\n}\n\n// http://stackoverflow.com/questions/32149/does-anyone-have-a-good-proper-case-algorithm\npublic static class ProperCaseHelper\n{\n public static string ToProperCase(this string input)\n {\n if (IsAllUpperOrAllLower(input))\n {\n // fix the ALL UPPERCASE or all lowercase names\n return string.Join(&quot; &quot;, input.Split(' ').Select(word =&gt; wordToProperCase(word)));\n }\n else\n {\n // leave the CamelCase or Propercase names alone\n return input;\n }\n }\n\n public static bool IsAllUpperOrAllLower(this string input)\n {\n return (input.ToLower().Equals(input) || input.ToUpper().Equals(input));\n }\n\n private static string wordToProperCase(string word)\n {\n if (string.IsNullOrEmpty(word)) return word;\n\n // Standard case\n string ret = capitaliseFirstLetter(word);\n\n // Special cases:\n ret = properSuffix(ret, &quot;'&quot;); // D'Artagnon, D'Silva\n ret = properSuffix(ret, &quot;.&quot;); // ???\n ret = properSuffix(ret, &quot;-&quot;); // Oscar-Meyer-Weiner\n ret = properSuffix(ret, &quot;Mc&quot;, t =&gt; t.Length &gt; 4); // Scots\n ret = properSuffix(ret, &quot;Mac&quot;, t =&gt; t.Length &gt; 5); // Scots except Macey\n\n // Special words:\n ret = specialWords(ret, &quot;van&quot;); // Dick van Dyke\n ret = specialWords(ret, &quot;von&quot;); // Baron von Bruin-Valt\n ret = specialWords(ret, &quot;de&quot;);\n ret = specialWords(ret, &quot;di&quot;);\n ret = specialWords(ret, &quot;da&quot;); // Leonardo da Vinci, Eduardo da Silva\n ret = specialWords(ret, &quot;of&quot;); // The Grand Old Duke of York\n ret = specialWords(ret, &quot;the&quot;); // William the Conqueror\n ret = specialWords(ret, &quot;HRH&quot;); // His/Her Royal Highness\n ret = specialWords(ret, &quot;HRM&quot;); // His/Her Royal Majesty\n ret = specialWords(ret, &quot;H.R.H.&quot;); // His/Her Royal Highness\n ret = specialWords(ret, &quot;H.R.M.&quot;); // His/Her Royal Majesty\n\n ret = dealWithRomanNumerals(ret); // William Gates, III\n\n return ret;\n }\n\n private static string properSuffix(string word, string prefix, Func&lt;string, bool&gt; condition = null)\n {\n if (string.IsNullOrEmpty(word)) return word;\n if (condition != null &amp;&amp; ! condition(word)) return word;\n \n string lowerWord = word.ToLower();\n string lowerPrefix = prefix.ToLower();\n\n if (!lowerWord.Contains(lowerPrefix)) return word;\n\n int index = lowerWord.IndexOf(lowerPrefix);\n\n // If the search string is at the end of the word ignore.\n if (index + prefix.Length == word.Length) return word;\n\n return word.Substring(0, index) + prefix +\n capitaliseFirstLetter(word.Substring(index + prefix.Length));\n }\n\n private static string specialWords(string word, string specialWord)\n {\n if (word.Equals(specialWord, StringComparison.InvariantCultureIgnoreCase))\n {\n return specialWord;\n }\n else\n {\n return word;\n }\n }\n\n private static string dealWithRomanNumerals(string word)\n {\n // Roman Numeral parser thanks to [djk](https://stackoverflow.com/users/785111/djk)\n // Note that it excludes the Chinese last name Xi\n return new Regex(@&quot;\\b(?!Xi\\b)(X|XX|XXX|XL|L|LX|LXX|LXXX|XC|C)?(I|II|III|IV|V|VI|VII|VIII|IX)?\\b&quot;, RegexOptions.IgnoreCase).Replace(word, match =&gt; match.Value.ToUpperInvariant());\n }\n\n private static string capitaliseFirstLetter(string word)\n {\n return char.ToUpper(word[0]) + word.Substring(1).ToLower();\n }\n\n}\n</code></pre>\n" }, { "answer_id": 22058928, "author": "gillytech", "author_id": 1332828, "author_profile": "https://Stackoverflow.com/users/1332828", "pm_score": 2, "selected": false, "text": "<p>I wrote this today to implement in an app I'm working on. I think this code is pretty self explanatory with comments. It's not 100% accurate in all cases but it will handle most of your western names easily.</p>\n\n<p>Examples:</p>\n\n<p><code>mary-jane =&gt; Mary-Jane</code></p>\n\n<p><code>o'brien =&gt; O'Brien</code></p>\n\n<p><code>Joël VON WINTEREGG =&gt; Joël von Winteregg</code></p>\n\n<p><code>jose de la acosta =&gt; Jose de la Acosta</code></p>\n\n<p>The code is extensible in that you may add any string value to the arrays at the top to suit your needs. Please study it and add any special feature that may be required.</p>\n\n<pre><code>function name_title_case($str)\n{\n // name parts that should be lowercase in most cases\n $ok_to_be_lower = array('av','af','da','dal','de','del','der','di','la','le','van','der','den','vel','von');\n // name parts that should be lower even if at the beginning of a name\n $always_lower = array('van', 'der');\n\n // Create an array from the parts of the string passed in\n $parts = explode(\" \", mb_strtolower($str));\n\n foreach ($parts as $part)\n {\n (in_array($part, $ok_to_be_lower)) ? $rules[$part] = 'nocaps' : $rules[$part] = 'caps';\n }\n\n // Determine the first part in the string\n reset($rules);\n $first_part = key($rules);\n\n // Loop through and cap-or-dont-cap\n foreach ($rules as $part =&gt; $rule)\n {\n if ($rule == 'caps')\n {\n // ucfirst() words and also takes into account apostrophes and hyphens like this:\n // O'brien -&gt; O'Brien || mary-kaye -&gt; Mary-Kaye\n $part = str_replace('- ','-',ucwords(str_replace('-','- ', $part)));\n $c13n[] = str_replace('\\' ', '\\'', ucwords(str_replace('\\'', '\\' ', $part)));\n }\n else if ($part == $first_part &amp;&amp; !in_array($part, $always_lower))\n {\n // If the first part of the string is ok_to_be_lower, cap it anyway\n $c13n[] = ucfirst($part);\n }\n else\n {\n $c13n[] = $part;\n }\n }\n\n $titleized = implode(' ', $c13n);\n\n return trim($titleized);\n}\n</code></pre>\n" }, { "answer_id": 45774526, "author": "user326608", "author_id": 326608, "author_profile": "https://Stackoverflow.com/users/326608", "pm_score": 2, "selected": false, "text": "<p>I did a quick C# port of <a href=\"https://github.com/tamtamchik/namecase\" rel=\"nofollow noreferrer\">https://github.com/tamtamchik/namecase</a>, which is based on Lingua::EN::NameCase.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static class CIQNameCase\n{\n static Dictionary&lt;string, string&gt; _exceptions = new Dictionary&lt;string, string&gt;\n {\n {@\"\\bMacEdo\" ,\"Macedo\"},\n {@\"\\bMacEvicius\" ,\"Macevicius\"},\n {@\"\\bMacHado\" ,\"Machado\"},\n {@\"\\bMacHar\" ,\"Machar\"},\n {@\"\\bMacHin\" ,\"Machin\"},\n {@\"\\bMacHlin\" ,\"Machlin\"},\n {@\"\\bMacIas\" ,\"Macias\"},\n {@\"\\bMacIulis\" ,\"Maciulis\"},\n {@\"\\bMacKie\" ,\"Mackie\"},\n {@\"\\bMacKle\" ,\"Mackle\"},\n {@\"\\bMacKlin\" ,\"Macklin\"},\n {@\"\\bMacKmin\" ,\"Mackmin\"},\n {@\"\\bMacQuarie\" ,\"Macquarie\"}\n };\n\n static Dictionary&lt;string, string&gt; _replacements = new Dictionary&lt;string, string&gt;\n {\n {@\"\\bAl(?=\\s+\\w)\" , @\"al\"}, // al Arabic or forename Al.\n {@\"\\b(Bin|Binti|Binte)\\b\" , @\"bin\"}, // bin, binti, binte Arabic\n {@\"\\bAp\\b\" , @\"ap\"}, // ap Welsh.\n {@\"\\bBen(?=\\s+\\w)\" , @\"ben\"}, // ben Hebrew or forename Ben.\n {@\"\\bDell([ae])\\b\" , @\"dell$1\"}, // della and delle Italian.\n {@\"\\bD([aeiou])\\b\" , @\"d$1\"}, // da, de, di Italian; du French; do Brasil\n {@\"\\bD([ao]s)\\b\" , @\"d$1\"}, // das, dos Brasileiros\n {@\"\\bDe([lrn])\\b\" , @\"de$1\"}, // del Italian; der/den Dutch/Flemish.\n {@\"\\bEl\\b\" , @\"el\"}, // el Greek or El Spanish.\n {@\"\\bLa\\b\" , @\"la\"}, // la French or La Spanish.\n {@\"\\bL([eo])\\b\" , @\"l$1\"}, // lo Italian; le French.\n {@\"\\bVan(?=\\s+\\w)\" , @\"van\"}, // van German or forename Van.\n {@\"\\bVon\\b\" , @\"von\"} // von Dutch/Flemish\n };\n\n static string[] _conjunctions = { \"Y\", \"E\", \"I\" };\n\n static string _romanRegex = @\"\\b((?:[Xx]{1,3}|[Xx][Ll]|[Ll][Xx]{0,3})?(?:[Ii]{1,3}|[Ii][VvXx]|[Vv][Ii]{0,3})?)\\b\";\n\n /// &lt;summary&gt;\n /// Case a name field into its appropriate case format \n /// e.g. Smith, de la Cruz, Mary-Jane, O'Brien, McTaggart\n /// &lt;/summary&gt;\n /// &lt;param name=\"nameString\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static string NameCase(string nameString)\n {\n // Capitalize\n nameString = Capitalize(nameString);\n nameString = UpdateIrish(nameString);\n\n // Fixes for \"son (daughter) of\" etc\n foreach (var replacement in _replacements.Keys)\n {\n if (Regex.IsMatch(nameString, replacement))\n {\n Regex rgx = new Regex(replacement);\n nameString = rgx.Replace(nameString, _replacements[replacement]);\n } \n }\n\n nameString = UpdateRoman(nameString);\n nameString = FixConjunction(nameString);\n\n return nameString;\n }\n\n /// &lt;summary&gt;\n /// Capitalize first letters.\n /// &lt;/summary&gt;\n /// &lt;param name=\"nameString\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n private static string Capitalize(string nameString)\n {\n nameString = nameString.ToLower();\n nameString = Regex.Replace(nameString, @\"\\b\\w\", x =&gt; x.ToString().ToUpper());\n nameString = Regex.Replace(nameString, @\"'\\w\\b\", x =&gt; x.ToString().ToLower()); // Lowercase 's\n return nameString;\n }\n\n /// &lt;summary&gt;\n /// Update for Irish names.\n /// &lt;/summary&gt;\n /// &lt;param name=\"nameString\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n private static string UpdateIrish(string nameString)\n {\n if(Regex.IsMatch(nameString, @\".*?\\bMac[A-Za-z^aciozj]{2,}\\b\") || Regex.IsMatch(nameString, @\".*?\\bMc\"))\n {\n nameString = UpdateMac(nameString);\n } \n return nameString;\n }\n\n /// &lt;summary&gt;\n /// Updates irish Mac &amp; Mc.\n /// &lt;/summary&gt;\n /// &lt;param name=\"nameString\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n private static string UpdateMac(string nameString)\n {\n MatchCollection matches = Regex.Matches(nameString, @\"\\b(Ma?c)([A-Za-z]+)\");\n if(matches.Count == 1 &amp;&amp; matches[0].Groups.Count == 3)\n {\n string replacement = matches[0].Groups[1].Value;\n replacement += matches[0].Groups[2].Value.Substring(0, 1).ToUpper();\n replacement += matches[0].Groups[2].Value.Substring(1);\n nameString = nameString.Replace(matches[0].Groups[0].Value, replacement);\n\n // Now fix \"Mac\" exceptions\n foreach (var exception in _exceptions.Keys)\n {\n nameString = Regex.Replace(nameString, exception, _exceptions[exception]);\n }\n }\n return nameString;\n }\n\n /// &lt;summary&gt;\n /// Fix roman numeral names.\n /// &lt;/summary&gt;\n /// &lt;param name=\"nameString\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n private static string UpdateRoman(string nameString)\n {\n MatchCollection matches = Regex.Matches(nameString, _romanRegex);\n if (matches.Count &gt; 1)\n {\n foreach(Match match in matches)\n {\n if(!string.IsNullOrEmpty(match.Value))\n {\n nameString = Regex.Replace(nameString, match.Value, x =&gt; x.ToString().ToUpper());\n }\n }\n }\n return nameString;\n }\n\n /// &lt;summary&gt;\n /// Fix Spanish conjunctions.\n /// &lt;/summary&gt;\n /// &lt;param name=\"\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n private static string FixConjunction(string nameString)\n { \n foreach (var conjunction in _conjunctions)\n {\n nameString = Regex.Replace(nameString, @\"\\b\" + conjunction + @\"\\b\", x =&gt; x.ToString().ToLower());\n }\n return nameString;\n }\n}\n</code></pre>\n\n<p>Usage</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>string name_cased = CIQNameCase.NameCase(\"McCarthy\");\n</code></pre>\n\n<p>This is my test method, everything seems to pass OK:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>[TestMethod]\npublic void Test_NameCase_1()\n{\n string[] names = {\n \"Keith\", \"Yuri's\", \"Leigh-Williams\", \"McCarthy\",\n // Mac exceptions\n \"Machin\", \"Machlin\", \"Machar\",\n \"Mackle\", \"Macklin\", \"Mackie\",\n \"Macquarie\", \"Machado\", \"Macevicius\",\n \"Maciulis\", \"Macias\", \"MacMurdo\",\n // General\n \"O'Callaghan\", \"St. John\", \"von Streit\",\n \"van Dyke\", \"Van\", \"ap Llwyd Dafydd\",\n \"al Fahd\", \"Al\",\n \"el Grecco\",\n \"ben Gurion\", \"Ben\",\n \"da Vinci\",\n \"di Caprio\", \"du Pont\", \"de Legate\",\n \"del Crond\", \"der Sind\", \"van der Post\", \"van den Thillart\",\n \"von Trapp\", \"la Poisson\", \"le Figaro\",\n \"Mack Knife\", \"Dougal MacDonald\",\n \"Ruiz y Picasso\", \"Dato e Iradier\", \"Mas i Gavarró\",\n // Roman numerals\n \"Henry VIII\", \"Louis III\", \"Louis XIV\",\n \"Charles II\", \"Fred XLIX\", \"Yusof bin Ishak\",\n };\n\n foreach(string name in names)\n {\n string name_upper = name.ToUpper();\n string name_cased = CIQNameCase.NameCase(name_upper);\n Console.WriteLine(string.Format(\"name: {0} -&gt; {1} -&gt; {2}\", name, name_upper, name_cased));\n Assert.IsTrue(name == name_cased);\n }\n\n}\n</code></pre>\n" }, { "answer_id": 45872439, "author": "Klyphtn", "author_id": 4705498, "author_profile": "https://Stackoverflow.com/users/4705498", "pm_score": 0, "selected": false, "text": "<p>A lot of good answers here. Mine is pretty simple and only takes into account the names we have in our organization. You can expand it as you wish. This is not a perfect solution and will change vancouver to VanCouver, which is wrong. So tweak it if you use it.</p>\n\n<p>Here was my solution in C#. This hard-codes the names into the program but with a little work you could keep a text file outside of the program and read in the name exceptions (i.e. Van, Mc, Mac) and loop through them. </p>\n\n<pre><code>public static String toProperName(String name)\n{\n if (name != null)\n {\n if (name.Length &gt;= 2 &amp;&amp; name.ToLower().Substring(0, 2) == \"mc\") // Changes mcdonald to \"McDonald\"\n return \"Mc\" + Regex.Replace(name.ToLower().Substring(2), @\"\\b[a-z]\", m =&gt; m.Value.ToUpper());\n\n if (name.Length &gt;= 3 &amp;&amp; name.ToLower().Substring(0, 3) == \"van\") // Changes vanwinkle to \"VanWinkle\"\n return \"Van\" + Regex.Replace(name.ToLower().Substring(3), @\"\\b[a-z]\", m =&gt; m.Value.ToUpper());\n\n return Regex.Replace(name.ToLower(), @\"\\b[a-z]\", m =&gt; m.Value.ToUpper()); // Changes to title case but also fixes \n // appostrophes like O'HARE or o'hare to O'Hare\n }\n\n return \"\";\n}\n</code></pre>\n" }, { "answer_id": 47704958, "author": "Michael Pinkard", "author_id": 5712417, "author_profile": "https://Stackoverflow.com/users/5712417", "pm_score": 1, "selected": false, "text": "<p>I know this thread has been open for awhile, but as I was doing research for this problem I came across this nifty site, which allows you to paste in names to be capitalized quite quickly: <a href=\"https://dialect.ca/code/name-case/\" rel=\"nofollow noreferrer\">https://dialect.ca/code/name-case/</a>. I wanted to include it here for reference for others doing similar research/projects.</p>\n\n<p>They release the algorithm they have written in php at this link: <a href=\"https://dialect.ca/code/name-case/name_case.phps\" rel=\"nofollow noreferrer\">https://dialect.ca/code/name-case/name_case.phps</a></p>\n\n<p>A preliminary test and reading of their code suggests they have been quite thorough.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3203/" ]
Does anyone have a trusted Proper Case or PCase algorithm (similar to a UCase or Upper)? I'm looking for something that takes a value such as `"GEORGE BURDELL"` or `"george burdell"` and turns it into `"George Burdell"`. I have a simple one that handles the simple cases. The ideal would be to have something that can handle things such as `"O'REILLY"` and turn it into `"O'Reilly"`, but I know that is tougher. I am mainly focused on the English language if that simplifies things. --- **UPDATE:** I'm using C# as the language, but I can convert from almost anything (assuming like functionality exists). I agree that the McDonald's scneario is a tough one. I meant to mention that along with my O'Reilly example, but did not in the original post.
Unless I've misunderstood your question I don't think you need to roll your own, the TextInfo class can do it for you. ``` using System.Globalization; CultureInfo.InvariantCulture.TextInfo.ToTitleCase("GeOrGE bUrdEll") ``` Will return "George Burdell. And you can use your own culture if there's some special rules involved. **Update:** [Michael](https://stackoverflow.com/users/1684/michael-wolfenden) (in a comment to this answer) pointed out that this will not work if the input is all caps since the method will assume that it is an acronym. The naive workaround for this is to .ToLower() the text before submitting it to ToTitleCase.
32,168
<p>A question related to <a href="https://stackoverflow.com/questions/28002">Regular cast vs. static_cast vs. dynamic_cast</a>:</p> <p>What cast syntax style do you prefer in C++?</p> <ul> <li>C-style cast syntax: <code>(int)foo</code></li> <li>C++-style cast syntax: <code>static_cast&lt;int&gt;(foo)</code></li> <li>constructor syntax: <code>int(foo)</code></li> </ul> <p>They may not translate to exactly the same instructions (do they?) but their effect should be the same (right?).</p> <p>If you're just casting between the built-in numeric types, I find C++-style cast syntax too verbose. As a former Java coder I tend to use C-style cast syntax instead, but my local C++ guru insists on using constructor syntax.</p> <p>What do you think?</p>
[ { "answer_id": 32180, "author": "CiNN", "author_id": 2566, "author_profile": "https://Stackoverflow.com/users/2566", "pm_score": 1, "selected": false, "text": "<p>C-style cast syntax, do not error check.\nC++-style cast syntax, does some checking.\nWhen using static_cast, even if it doesn't do checking, at least you know you should be carefull here.</p>\n" }, { "answer_id": 32194, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 4, "selected": false, "text": "<p>According to <a href=\"http://www.research.att.com/~bs/bs_faq2.html#static-cast\" rel=\"noreferrer\">Stroustrup</a>:</p>\n\n<blockquote>\n <p>The \"new-style casts\" were introduced\n to give programmers a chance to state\n their intentions more clearly and for\n the compiler to catch more errors.</p>\n</blockquote>\n\n<p>So really, its for safety as it does extra compile-time checking.</p>\n" }, { "answer_id": 32210, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 1, "selected": false, "text": "<p>C-style cast is the worst way to go. It's harder to see, ungreppable, conflates different actions that should not be conflated, and can't do everything that C++-style casts can do. They really should have removed C-style casts from the language.</p>\n" }, { "answer_id": 32224, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 7, "selected": true, "text": "<p>It's best practice <em>never</em> to use C-style casts for three main reasons:</p>\n\n<ul>\n<li>as already mentioned, no checking is performed here. The programmer simply cannot know which of the various casts is used which weakens strong typing</li>\n<li>the new casts are intentionally visually striking. Since casts often reveal a weakness in the code, it's argued that making casts visible in the code is a good thing.</li>\n<li>this is especially true if searching for casts with an automated tool. Finding C-style casts reliably is nearly impossible.</li>\n</ul>\n\n<p>As palm3D noted:</p>\n\n<blockquote>\n <p>I find C++-style cast syntax too verbose.</p>\n</blockquote>\n\n<p>This is intentional, for the reasons given above.</p>\n\n<p>The constructor syntax (official name: function-style cast) is semantically <em>the same</em> as the C-style cast and should be avoided as well (except for variable initializations on declaration), for the same reasons. It is debatable whether this should be true even for types that define custom constructors but in Effective C++, Meyers argues that even in those cases you should refrain from using them. To illustrate:</p>\n\n<pre><code>void f(auto_ptr&lt;int&gt; x);\n\nf(static_cast&lt;auto_ptr&lt;int&gt; &gt;(new int(5))); // GOOD\nf(auto_ptr&lt;int&gt;(new int(5)); // BAD\n</code></pre>\n\n<p>The <code>static_cast</code> here will actually call the <code>auto_ptr</code> constructor.</p>\n" }, { "answer_id": 32225, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>I use static_cast for two reasons.</p>\n\n<ol>\n<li>It's explicitly clear what's taking place. I can't read over that without realizing there's a cast going on. With C-style casts you eye can pass right over it without pause.</li>\n<li>It's easy to search for every place in my code where I'm casting.</li>\n</ol>\n" }, { "answer_id": 32228, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 2, "selected": false, "text": "<p>Definitely C++-style. The extra typing will help prevent you from casting when you shouldn't :-)</p>\n" }, { "answer_id": 32234, "author": "Jérôme", "author_id": 2796, "author_profile": "https://Stackoverflow.com/users/2796", "pm_score": 3, "selected": false, "text": "<p>Regarding this subject, I'm following the recommandations made by <a href=\"http://en.wikipedia.org/wiki/Scott_Meyers\" rel=\"noreferrer\">Scott Meyers</a> (<a href=\"https://rads.stackoverflow.com/amzn/click/com/020163371X\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">More Effective C++</a>, Item 2 : Prefer C++-style casts).</p>\n\n<p>I agree that C++ style cast are verbose, but that's what I like about them : they are very easy to spot, and they make the code easier to read (which is more important than writing).</p>\n\n<p>They also force you to think about what kind of cast you need, and to chose the right one, reducing the risk of mistakes. They will also help you detecting errors at compile time instead at runtime.</p>\n" }, { "answer_id": 32267, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 1, "selected": false, "text": "<p>We currently use C-style casts everywhere. I asked the other <a href=\"https://stackoverflow.com/questions/28002\">casting question</a>, and I now see the advantage of using static_cast instead, if for no other reason than it's \"greppable\" (I like that term). I will probably start using that.</p>\n\n<p>I don't like the C++ style; it looks too much like a function call.</p>\n" }, { "answer_id": 9457254, "author": "CAH", "author_id": 1234388, "author_profile": "https://Stackoverflow.com/users/1234388", "pm_score": 1, "selected": false, "text": "<p>Go for C++ style and, at worse, the ugly verbose code snippets that comprised C++'s explicit typecast will be a constant reminder of what we all know (i.e explicit casting is bad -- the lead to the coin-ing of expletives). \nDo not go with C++ style if you want to master the art of tracking runtime errors. </p>\n" }, { "answer_id": 41303511, "author": "QBziZ", "author_id": 11572, "author_profile": "https://Stackoverflow.com/users/11572", "pm_score": 2, "selected": false, "text": "<p>The constructor syntax. C++ is OO, constructors exist, I use them. \nIf you feel the need to annotate these conversion ctor's you should do it for every type, not just the built-in ones. Maybe you use the 'explicit' keyword for conversion ctors but the client syntax mimics exactly what the ctor syntax for built-in types does.\nBeing greppable, that may be true, but what a big surprise that typing more characters makes searches easy. Why treat these ones as special? \nIf you are writing math formulas with lots of int/unsigned/... to and from double/float - graphics - and you need to write a static_cast every time, the look of the formula gets cluttered and is very much unreadable.\nAnd it's an uphill battle anyway as a lot of times you will convert without even noticing that you are. \nFor downcasting pointers I do use the static_cast as of course no ctor exists by default that would do that.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2686/" ]
A question related to [Regular cast vs. static\_cast vs. dynamic\_cast](https://stackoverflow.com/questions/28002): What cast syntax style do you prefer in C++? * C-style cast syntax: `(int)foo` * C++-style cast syntax: `static_cast<int>(foo)` * constructor syntax: `int(foo)` They may not translate to exactly the same instructions (do they?) but their effect should be the same (right?). If you're just casting between the built-in numeric types, I find C++-style cast syntax too verbose. As a former Java coder I tend to use C-style cast syntax instead, but my local C++ guru insists on using constructor syntax. What do you think?
It's best practice *never* to use C-style casts for three main reasons: * as already mentioned, no checking is performed here. The programmer simply cannot know which of the various casts is used which weakens strong typing * the new casts are intentionally visually striking. Since casts often reveal a weakness in the code, it's argued that making casts visible in the code is a good thing. * this is especially true if searching for casts with an automated tool. Finding C-style casts reliably is nearly impossible. As palm3D noted: > > I find C++-style cast syntax too verbose. > > > This is intentional, for the reasons given above. The constructor syntax (official name: function-style cast) is semantically *the same* as the C-style cast and should be avoided as well (except for variable initializations on declaration), for the same reasons. It is debatable whether this should be true even for types that define custom constructors but in Effective C++, Meyers argues that even in those cases you should refrain from using them. To illustrate: ``` void f(auto_ptr<int> x); f(static_cast<auto_ptr<int> >(new int(5))); // GOOD f(auto_ptr<int>(new int(5)); // BAD ``` The `static_cast` here will actually call the `auto_ptr` constructor.
32,173
<p>I'm trying to disable a bunch of controls with JavaScript (so that they post back values). All the controls work fine except for my radio buttons as they lose their value. In the below code which is called via a recursive function to disable all child controls the Second else (else if (control is <code>RadioButton</code>)) is never hit and the RadioButton control is identified as a <code>Checkbox</code> control.</p> <pre><code> private static void DisableControl(WebControl control) { if (control is CheckBox) { ((CheckBox)control).InputAttributes.Add("disabled", "disabled"); } else if (control is RadioButton) { } else if (control is ImageButton) { ((ImageButton)control).Enabled = false; } else { control.Attributes.Add("readonly", "readonly"); } } </code></pre> <p>Two Questions:<br> 1. How do I identify which control is a radiobutton? <br> 2. How do I disable it so that it posts back its value?</p>
[ { "answer_id": 32203, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Off the top of my head, I think you have to check the \"type\" attribute of the checkbox to determine if it's a radio button.</p>\n" }, { "answer_id": 32473, "author": "Nicholas", "author_id": 2808, "author_profile": "https://Stackoverflow.com/users/2808", "pm_score": 3, "selected": true, "text": "<p>I found 2 ways to get this to work, the below code correctly distinguishes between the RadioButton and Checkbox controls.</p>\n\n<pre><code> private static void DisableControl(WebControl control)\n {\n Type controlType = control.GetType();\n\n if (controlType == typeof(CheckBox))\n {\n ((CheckBox)control).InputAttributes.Add(\"disabled\", \"disabled\");\n\n }\n else if (controlType == typeof(RadioButton))\n {\n ((RadioButton)control).InputAttributes.Add(\"disabled\", \"true\");\n }\n else if (controlType == typeof(ImageButton))\n {\n ((ImageButton)control).Enabled = false;\n }\n else\n {\n control.Attributes.Add(\"readonly\", \"readonly\");\n }\n }\n</code></pre>\n\n<p>And the solution I used is to set SubmitDisabledControls=\"True\" in the form element which is not ideal as it allows a user to fiddle with the values but is fine in my scenario. The second solution is to mimic the Disabled behavior and details can be found here: https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx'><a href=\"https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx</a>.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2808/" ]
I'm trying to disable a bunch of controls with JavaScript (so that they post back values). All the controls work fine except for my radio buttons as they lose their value. In the below code which is called via a recursive function to disable all child controls the Second else (else if (control is `RadioButton`)) is never hit and the RadioButton control is identified as a `Checkbox` control. ``` private static void DisableControl(WebControl control) { if (control is CheckBox) { ((CheckBox)control).InputAttributes.Add("disabled", "disabled"); } else if (control is RadioButton) { } else if (control is ImageButton) { ((ImageButton)control).Enabled = false; } else { control.Attributes.Add("readonly", "readonly"); } } ``` Two Questions: 1. How do I identify which control is a radiobutton? 2. How do I disable it so that it posts back its value?
I found 2 ways to get this to work, the below code correctly distinguishes between the RadioButton and Checkbox controls. ``` private static void DisableControl(WebControl control) { Type controlType = control.GetType(); if (controlType == typeof(CheckBox)) { ((CheckBox)control).InputAttributes.Add("disabled", "disabled"); } else if (controlType == typeof(RadioButton)) { ((RadioButton)control).InputAttributes.Add("disabled", "true"); } else if (controlType == typeof(ImageButton)) { ((ImageButton)control).Enabled = false; } else { control.Attributes.Add("readonly", "readonly"); } } ``` And the solution I used is to set SubmitDisabledControls="True" in the form element which is not ideal as it allows a user to fiddle with the values but is fine in my scenario. The second solution is to mimic the Disabled behavior and details can be found here: https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx'><https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx>.
32,231
<p>Are there any rapid Database protoyping tools that don't require me to declare a database schema, but rather create it based on the way I'm using my entities.</p> <p>For example, assuming an empty database (pseudo code):</p> <pre><code>user1 = new User() // Creates the user table with a single id column user1.firstName = "Allain" // alters the table to have a firstName column as varchar(255) user2 = new User() // Reuses the table user2.firstName = "Bob" user2.lastName = "Loblaw" // Alters the table to have a last name column </code></pre> <p>Since there are logical assumptions that can be made when dynamically creating the schema, and you could always override its choices by using your DB tools to tweak it later.</p> <p>Also, you could generate your schema by unit testing it this way.</p> <p>And obviously this is only for prototyping.</p> <p>Is there anything like this out there?</p>
[ { "answer_id": 32297, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://code.google.com/appengine/\" rel=\"nofollow noreferrer\">Google's Application Engine</a> works like this. When you download the toolkit you get a local copy of the database engine for testing.</p>\n" }, { "answer_id": 32301, "author": "Tom Carter", "author_id": 2839, "author_profile": "https://Stackoverflow.com/users/2839", "pm_score": 0, "selected": false, "text": "<p>May be not exactly responding to your <em>general</em> question, but if you used <a href=\"http://www.hibernate.org\" rel=\"nofollow noreferrer\">(N)Hibernate</a> then you can automatically generate the database schema from your hbm mapping files.</p>\n\n<p>Its not done directly from your code as you seem to be wanting but Hibernate Schema generation seems to work well for us </p>\n" }, { "answer_id": 32463, "author": "Ed.T", "author_id": 3014, "author_profile": "https://Stackoverflow.com/users/3014", "pm_score": 1, "selected": false, "text": "<p>Grails uses Hibernate to persist domain objects and produces behavior similar to what you describe. To alter the schema you simply modify the domain, in this simple case the file is named User.groovy.</p>\n\n<pre><code>class User {\n\n String userName\n String firstName\n String lastName\n Date dateCreated\n Date lastUpdated\n\n static constraints = {\n userName(blank: false, unique: true)\n firstName(blank: false)\n lastName(blank: false)\n }\n\n String toString() {\"$lastName, $firstName\"}\n\n}\n</code></pre>\n\n<p>Saving the file alters the schema automatically. Likewise, if you are using scaffolding it is updated. The prototype process becomes run the application, view the page in your browser, modify the domain, refresh the browser, and see the changes.</p>\n" }, { "answer_id": 36312, "author": "Nic Wise", "author_id": 2947, "author_profile": "https://Stackoverflow.com/users/2947", "pm_score": 0, "selected": false, "text": "<p>Do you want the schema, but have it generated, or do you actually want <strong>NO schema</strong>?</p>\n\n<p>For the former I'd go with nhibernate as @tom-carter said. Have it generate your schema for you, and you are all good (atleast until you roll your app out, then look at something like Tarantino and RedGate SQL Diff or whatever it's called to generate update scripts)</p>\n\n<p>If you want the latter.... google app engine does this, as I've discovered this afternoon, and it's very nice. If you want to stick with code under your control, I'd suggest looking at CouchDB, tho it's a bit of upfront work getting it setup. But once you have it, it's a totally, 100% schema-free database. Well, you have an ID and a Version, but thats it - the rest is up to you. <a href=\"http://incubator.apache.org/couchdb/\" rel=\"nofollow noreferrer\">http://incubator.apache.org/couchdb/</a></p>\n\n<p>But by the sounds of it (N)hibernate would suite the best, but I could be wrong.</p>\n" }, { "answer_id": 52055, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 0, "selected": false, "text": "<p>You could use an object database. </p>\n" }, { "answer_id": 52086, "author": "Anthony Mastrean", "author_id": 3619, "author_profile": "https://Stackoverflow.com/users/3619", "pm_score": 1, "selected": false, "text": "<p>I agree with the NHibernate approach and auto-database-generation. But, if you want to avoid writing a configuration file, and stay close to the code, use Castle's <a href=\"http://www.castleproject.org/activerecord/index.html\" rel=\"nofollow noreferrer\">ActiveRecord</a>. You declare the 'schema' directly on the class with via attributes.</p>\n\n<pre><code>[ActiveRecord]\npublic class User : ActiveRecordBase&lt;User&gt;\n{\n [PrimaryKey]\n public Int32 UserId { get; set; }\n\n [Property]\n public String FirstName { get; set; }\n}\n</code></pre>\n\n<p>There are a variety of constraints you can apply (validation, bounds, etc) and you can declare relationships between different data model classes. Most of these options are parameters added to the attributes. It's rather simple.</p>\n\n<p>So, you're working with code. Declaring usage in code. And when you're done, let ActiveRecord <a href=\"http://www.castleproject.org/activerecord/documentation/trunk/usersguide/schemagen.html\" rel=\"nofollow noreferrer\">create the database</a>.</p>\n\n<pre><code>ActiveRecordStarter.Initialize();\nActiveRecordStarter.CreateSchema();\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
Are there any rapid Database protoyping tools that don't require me to declare a database schema, but rather create it based on the way I'm using my entities. For example, assuming an empty database (pseudo code): ``` user1 = new User() // Creates the user table with a single id column user1.firstName = "Allain" // alters the table to have a firstName column as varchar(255) user2 = new User() // Reuses the table user2.firstName = "Bob" user2.lastName = "Loblaw" // Alters the table to have a last name column ``` Since there are logical assumptions that can be made when dynamically creating the schema, and you could always override its choices by using your DB tools to tweak it later. Also, you could generate your schema by unit testing it this way. And obviously this is only for prototyping. Is there anything like this out there?
[Google's Application Engine](http://code.google.com/appengine/) works like this. When you download the toolkit you get a local copy of the database engine for testing.
32,241
<p><a href="https://stackoverflow.com/questions/32149/does-anyone-have-a-good-proper-case-algorithm">Using this question</a> as the base is there an alogrithm or coding example to change some text to Pascal or Camel casing.</p> <p>For example:</p> <pre><code>mynameisfred </code></pre> <p>becomes</p> <pre><code>Camel: myNameIsFred Pascal: MyNameIsFred </code></pre>
[ { "answer_id": 32277, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 0, "selected": false, "text": "<p>The only way to do that would be to run each section of the word through a dictionary.</p>\n\n<p>\"mynameisfred\" is just an array of characters, splitting it up into my Name Is Fred means understanding what the joining of each of those characters means.</p>\n\n<p>You could do it easily if your input was separated in some way, e.g. \"my name is fred\" or \"my_name_is_fred\".</p>\n" }, { "answer_id": 32429, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 3, "selected": true, "text": "<p>I found a thread with a bunch of Perl guys arguing the toss on this question over at <a href=\"http://www.perlmonks.org/?node_id=336331\" rel=\"nofollow noreferrer\">http://www.perlmonks.org/?node_id=336331</a>.</p>\n\n<p>I hope this isn't too much of a non-answer to the question, but I would say you have a bit of a problem in that it would be a very open-ended algorithm which could have a lot of 'misses' as well as hits. For example, say you inputted:-</p>\n\n<pre><code>camelCase(\"hithisisatest\");\n</code></pre>\n\n<p>The output could be:-</p>\n\n<pre><code>\"hiThisIsATest\"\n</code></pre>\n\n<p>Or:-</p>\n\n<pre><code>\"hitHisIsATest\"\n</code></pre>\n\n<p>There's no way the algorithm would know which to prefer. You could add some extra code to specify that you'd prefer more common words, but again misses would occur (Peter Norvig wrote a very small spelling corrector over at <a href=\"http://norvig.com/spell-correct.html\" rel=\"nofollow noreferrer\">http://norvig.com/spell-correct.html</a> which <em>might</em> help algorithm-wise, I wrote a <a href=\"http://web.archive.org/web/20080930045207/http://www.codegrunt.co.uk/code/cs/spellcorrect/spell-correct.cs\" rel=\"nofollow noreferrer\">C# implementation</a> if C#'s your language).</p>\n\n<p>I'd agree with Mark and say you'd be better off having an algorithm that takes a delimited input, i.e. this_is_a_test and converts that. That'd be simple to implement, i.e. in pseudocode:-</p>\n\n<pre><code>SetPhraseCase(phrase, CamelOrPascal):\n if no delimiters\n if camelCase\n return lowerFirstLetter(phrase)\n else\n return capitaliseFirstLetter(phrase)\n words = splitOnDelimiter(phrase)\n if camelCase \n ret = lowerFirstLetter(first word) \n else\n ret = capitaliseFirstLetter(first word)\n for i in 2 to len(words): ret += capitaliseFirstLetter(words[i])\n return ret\n\ncapitaliseFirstLetter(word):\n if len(word) &lt;= 1 return upper(word)\n return upper(word[0]) + word[1..len(word)]\n\nlowerFirstLetter(word):\n if len(word) &lt;= 1 return lower(word)\n return lower(word[0]) + word[1..len(word)]\n</code></pre>\n\n<p>You could also replace my capitaliseFirstLetter() function with a proper case algorithm if you so wished.</p>\n\n<p>A C# implementation of the above described algorithm is as follows (complete console program with test harness):-</p>\n\n<pre><code>using System;\n\nclass Program {\n static void Main(string[] args) {\n\n var caseAlgorithm = new CaseAlgorithm('_');\n\n while (true) {\n string input = Console.ReadLine();\n\n if (string.IsNullOrEmpty(input)) return;\n\n Console.WriteLine(\"Input '{0}' in camel case: '{1}', pascal case: '{2}'\",\n input,\n caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.CamelCase),\n caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.PascalCase));\n }\n }\n}\n\npublic class CaseAlgorithm {\n\n public enum CaseMode { PascalCase, CamelCase }\n\n private char delimiterChar;\n\n public CaseAlgorithm(char inDelimiterChar) {\n delimiterChar = inDelimiterChar;\n }\n\n public string SetPhraseCase(string phrase, CaseMode caseMode) {\n\n // You might want to do some sanity checks here like making sure\n // there's no invalid characters, etc.\n\n if (string.IsNullOrEmpty(phrase)) return phrase;\n\n // .Split() will simply return a string[] of size 1 if no delimiter present so\n // no need to explicitly check this.\n var words = phrase.Split(delimiterChar);\n\n // Set first word accordingly.\n string ret = setWordCase(words[0], caseMode);\n\n // If there are other words, set them all to pascal case.\n if (words.Length &gt; 1) {\n for (int i = 1; i &lt; words.Length; ++i)\n ret += setWordCase(words[i], CaseMode.PascalCase);\n }\n\n return ret;\n }\n\n private string setWordCase(string word, CaseMode caseMode) {\n switch (caseMode) {\n case CaseMode.CamelCase:\n return lowerFirstLetter(word);\n case CaseMode.PascalCase:\n return capitaliseFirstLetter(word);\n default:\n throw new NotImplementedException(\n string.Format(\"Case mode '{0}' is not recognised.\", caseMode.ToString()));\n }\n }\n\n private string lowerFirstLetter(string word) {\n return char.ToLower(word[0]) + word.Substring(1);\n }\n\n private string capitaliseFirstLetter(string word) {\n return char.ToUpper(word[0]) + word.Substring(1);\n }\n}\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075/" ]
[Using this question](https://stackoverflow.com/questions/32149/does-anyone-have-a-good-proper-case-algorithm) as the base is there an alogrithm or coding example to change some text to Pascal or Camel casing. For example: ``` mynameisfred ``` becomes ``` Camel: myNameIsFred Pascal: MyNameIsFred ```
I found a thread with a bunch of Perl guys arguing the toss on this question over at <http://www.perlmonks.org/?node_id=336331>. I hope this isn't too much of a non-answer to the question, but I would say you have a bit of a problem in that it would be a very open-ended algorithm which could have a lot of 'misses' as well as hits. For example, say you inputted:- ``` camelCase("hithisisatest"); ``` The output could be:- ``` "hiThisIsATest" ``` Or:- ``` "hitHisIsATest" ``` There's no way the algorithm would know which to prefer. You could add some extra code to specify that you'd prefer more common words, but again misses would occur (Peter Norvig wrote a very small spelling corrector over at <http://norvig.com/spell-correct.html> which *might* help algorithm-wise, I wrote a [C# implementation](http://web.archive.org/web/20080930045207/http://www.codegrunt.co.uk/code/cs/spellcorrect/spell-correct.cs) if C#'s your language). I'd agree with Mark and say you'd be better off having an algorithm that takes a delimited input, i.e. this\_is\_a\_test and converts that. That'd be simple to implement, i.e. in pseudocode:- ``` SetPhraseCase(phrase, CamelOrPascal): if no delimiters if camelCase return lowerFirstLetter(phrase) else return capitaliseFirstLetter(phrase) words = splitOnDelimiter(phrase) if camelCase ret = lowerFirstLetter(first word) else ret = capitaliseFirstLetter(first word) for i in 2 to len(words): ret += capitaliseFirstLetter(words[i]) return ret capitaliseFirstLetter(word): if len(word) <= 1 return upper(word) return upper(word[0]) + word[1..len(word)] lowerFirstLetter(word): if len(word) <= 1 return lower(word) return lower(word[0]) + word[1..len(word)] ``` You could also replace my capitaliseFirstLetter() function with a proper case algorithm if you so wished. A C# implementation of the above described algorithm is as follows (complete console program with test harness):- ``` using System; class Program { static void Main(string[] args) { var caseAlgorithm = new CaseAlgorithm('_'); while (true) { string input = Console.ReadLine(); if (string.IsNullOrEmpty(input)) return; Console.WriteLine("Input '{0}' in camel case: '{1}', pascal case: '{2}'", input, caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.CamelCase), caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.PascalCase)); } } } public class CaseAlgorithm { public enum CaseMode { PascalCase, CamelCase } private char delimiterChar; public CaseAlgorithm(char inDelimiterChar) { delimiterChar = inDelimiterChar; } public string SetPhraseCase(string phrase, CaseMode caseMode) { // You might want to do some sanity checks here like making sure // there's no invalid characters, etc. if (string.IsNullOrEmpty(phrase)) return phrase; // .Split() will simply return a string[] of size 1 if no delimiter present so // no need to explicitly check this. var words = phrase.Split(delimiterChar); // Set first word accordingly. string ret = setWordCase(words[0], caseMode); // If there are other words, set them all to pascal case. if (words.Length > 1) { for (int i = 1; i < words.Length; ++i) ret += setWordCase(words[i], CaseMode.PascalCase); } return ret; } private string setWordCase(string word, CaseMode caseMode) { switch (caseMode) { case CaseMode.CamelCase: return lowerFirstLetter(word); case CaseMode.PascalCase: return capitaliseFirstLetter(word); default: throw new NotImplementedException( string.Format("Case mode '{0}' is not recognised.", caseMode.ToString())); } } private string lowerFirstLetter(string word) { return char.ToLower(word[0]) + word.Substring(1); } private string capitaliseFirstLetter(string word) { return char.ToUpper(word[0]) + word.Substring(1); } } ```
32,243
<p>The following PHP code snippet uses GD to resize a browser-uploaded PNG to 128x128. It works great, except that the transparent areas in the original image are being replaced with a solid color- black in my case. </p> <p>Even though <code>imagesavealpha</code> is set, something isn't quite right.</p> <p>What's the best way to preserve the transparency in the resampled image?</p> <pre><code>$uploadTempFile = $myField[ 'tmp_name' ] list( $uploadWidth, $uploadHeight, $uploadType ) = getimagesize( $uploadTempFile ); $srcImage = imagecreatefrompng( $uploadTempFile ); imagesavealpha( $targetImage, true ); $targetImage = imagecreatetruecolor( 128, 128 ); imagecopyresampled( $targetImage, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight ); imagepng( $targetImage, 'out.png', 9 ); </code></pre>
[ { "answer_id": 32270, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 4, "selected": false, "text": "<p>I believe this should do the trick:</p>\n\n<pre><code>$srcImage = imagecreatefrompng($uploadTempFile);\nimagealphablending($srcImage, false);\nimagesavealpha($srcImage, true);\n</code></pre>\n\n<p><em>edit:</em> Someone in the PHP docs claims <code>imagealphablending</code> should be true, not false. YMMV.</p>\n" }, { "answer_id": 32302, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 9, "selected": true, "text": "<pre><code>imagealphablending( $targetImage, false );\nimagesavealpha( $targetImage, true );\n</code></pre>\n\n<p>did it for me. Thanks ceejayoz.</p>\n\n<p>note, the target image needs the alpha settings, not the source image.</p>\n\n<p>Edit:\nfull replacement code. See also answers below and their comments. This is not guaranteed to be be perfect in any way, but did achieve my needs at the time.</p>\n\n<pre><code>$uploadTempFile = $myField[ 'tmp_name' ]\nlist( $uploadWidth, $uploadHeight, $uploadType ) \n = getimagesize( $uploadTempFile );\n\n$srcImage = imagecreatefrompng( $uploadTempFile ); \n\n$targetImage = imagecreatetruecolor( 128, 128 ); \nimagealphablending( $targetImage, false );\nimagesavealpha( $targetImage, true );\n\nimagecopyresampled( $targetImage, $srcImage, \n 0, 0, \n 0, 0, \n 128, 128, \n $uploadWidth, $uploadHeight );\n\nimagepng( $targetImage, 'out.png', 9 );\n</code></pre>\n" }, { "answer_id": 37364, "author": "Kalle", "author_id": 3908, "author_profile": "https://Stackoverflow.com/users/3908", "pm_score": 2, "selected": false, "text": "<p>Regrading the preserve transparency, then yes like stated in other posts imagesavealpha() have to be set to true, to use the alpha flag imagealphablending() must be set to false else it doesn't work.</p>\n\n<p>Also I spotted two minor things in your code:</p>\n\n<ol>\n<li>You don't need to call <code>getimagesize()</code> to get the width/height for <code>imagecopyresmapled()</code></li>\n<li>The <code>$uploadWidth</code> and <code>$uploadHeight</code> should be <code>-1</code> the value, since the cordinates starts at <code>0</code> and not <code>1</code>, so it would copy them into an empty pixel. Replacing it with: <code>imagesx($targetImage) - 1</code> and <code>imagesy($targetImage) - 1</code>, relativily should do :)</li>\n</ol>\n" }, { "answer_id": 291766, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Why do you make things so complicated? the following is what I use and so far it has done the job for me.</p>\n\n<pre><code>$im = ImageCreateFromPNG($source);\n$new_im = imagecreatetruecolor($new_size[0],$new_size[1]);\nimagecolortransparent($new_im, imagecolorallocate($new_im, 0, 0, 0));\nimagecopyresampled($new_im,$im,0,0,0,0,$new_size[0],$new_size[1],$size[0],$size[1]);\n</code></pre>\n" }, { "answer_id": 1302888, "author": "Linus Unnebäck", "author_id": 148072, "author_profile": "https://Stackoverflow.com/users/148072", "pm_score": 3, "selected": false, "text": "<p>I suppose that this might do the trick:</p>\n\n<pre><code>$uploadTempFile = $myField[ 'tmp_name' ]\nlist( $uploadWidth, $uploadHeight, $uploadType ) \n = getimagesize( $uploadTempFile );\n\n$srcImage = imagecreatefrompng( $uploadTempFile );\n\n$targetImage = imagecreatetruecolor( 128, 128 );\n\n$transparent = imagecolorallocate($targetImage,0,255,0);\nimagecolortransparent($targetImage,$transparent);\nimagefilledrectangle($targetImage,0,0,127,127,$transparent);\n\nimagecopyresampled( $targetImage, $srcImage, \n 0, 0, \n 0, 0, \n 128, 128, \n $uploadWidth, $uploadHeight );\n\nimagepng( $targetImage, 'out.png', 9 );\n</code></pre>\n\n<p>The downside is that the image will be stripped of every 100% green pixels. Anyhow, hope it helps :)</p>\n" }, { "answer_id": 4618019, "author": "Jorrit Schippers", "author_id": 261747, "author_profile": "https://Stackoverflow.com/users/261747", "pm_score": 3, "selected": false, "text": "<p>An addition that might help some people:</p>\n\n<p>It is possible to toggle imagealphablending while building the image. I the specific case that I needed this, I wanted to combine some semi-transparent PNG's on a transparent background.</p>\n\n<p>First you set imagealphablending to false and fill the newly created true color image with a transparent color. If imagealphablending were true, nothing would happen because the transparent fill would merge with the black default background and result in black.</p>\n\n<p>Then you toggle imagealphablending to true and add some PNG images to the canvas, leaving some of the background visible (ie. not filling up the entire image).</p>\n\n<p>The result is an image with a transparent background and several combined PNG images.</p>\n" }, { "answer_id": 7731400, "author": "pricopz", "author_id": 990203, "author_profile": "https://Stackoverflow.com/users/990203", "pm_score": 3, "selected": false, "text": "<p>I have made a function for resizing image like JPEG/GIF/PNG with <code>copyimageresample</code> and PNG images still keep there transparency:</p>\n\n<pre><code>$myfile=$_FILES[\"youimage\"];\n\nfunction ismyimage($myfile) {\n if((($myfile[\"type\"] == \"image/gif\") || ($myfile[\"type\"] == \"image/jpg\") || ($myfile[\"type\"] == \"image/jpeg\") || ($myfile[\"type\"] == \"image/png\")) &amp;&amp; ($myfile[\"size\"] &lt;= 2097152 /*2mb*/) ) return true; \n else return false;\n}\n\nfunction upload_file($myfile) { \n if(ismyimage($myfile)) {\n $information=getimagesize($myfile[\"tmp_name\"]);\n $mywidth=$information[0];\n $myheight=$information[1];\n\n $newwidth=$mywidth;\n $newheight=$myheight;\n while(($newwidth &gt; 600) || ($newheight &gt; 400 )) {\n $newwidth = $newwidth-ceil($newwidth/100);\n $newheight = $newheight-ceil($newheight/100);\n } \n\n $files=$myfile[\"name\"];\n\n if($myfile[\"type\"] == \"image/gif\") {\n $tmp=imagecreatetruecolor($newwidth,$newheight);\n $src=imagecreatefromgif($myfile[\"tmp_name\"]);\n imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $mywidth, $myheight);\n $con=imagegif($tmp, $files);\n imagedestroy($tmp);\n imagedestroy($src);\n if($con){\n return true;\n } else {\n return false;\n }\n } else if(($myfile[\"type\"] == \"image/jpg\") || ($myfile[\"type\"] == \"image/jpeg\") ) {\n $tmp=imagecreatetruecolor($newwidth,$newheight);\n $src=imagecreatefromjpeg($myfile[\"tmp_name\"]); \n imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $mywidth, $myheight);\n $con=imagejpeg($tmp, $files);\n imagedestroy($tmp);\n imagedestroy($src);\n if($con) { \n return true;\n } else {\n return false;\n }\n } else if($myfile[\"type\"] == \"image/png\") {\n $tmp=imagecreatetruecolor($newwidth,$newheight);\n $src=imagecreatefrompng($myfile[\"tmp_name\"]);\n imagealphablending($tmp, false);\n imagesavealpha($tmp,true);\n $transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);\n imagefilledrectangle($tmp, 0, 0, $newwidth, $newheight, $transparent); \n imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $mywidth, $myheight);\n $con=imagepng($tmp, $files);\n imagedestroy($tmp);\n imagedestroy($src);\n if($con) {\n return true;\n } else {\n return false;\n }\n } \n } else\n return false;\n}\n</code></pre>\n" }, { "answer_id": 37871122, "author": "Md. Imadul Islam", "author_id": 3950386, "author_profile": "https://Stackoverflow.com/users/3950386", "pm_score": 0, "selected": false, "text": "<p>Here is my total test code. It works for me</p>\n\n<pre><code>$imageFileType = pathinfo($_FILES[\"image\"][\"name\"], PATHINFO_EXTENSION);\n$filename = 'test.' . $imageFileType;\nmove_uploaded_file($_FILES[\"image\"][\"tmp_name\"], $filename);\n\n$source_image = imagecreatefromjpeg($filename);\n\n$source_imagex = imagesx($source_image);\n$source_imagey = imagesy($source_image);\n\n$dest_imagex = 400;\n$dest_imagey = 600;\n$dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);\n\nimagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);\n\nimagesavealpha($dest_image, true);\n$trans_colour = imagecolorallocatealpha($dest_image, 0, 0, 0, 127);\nimagefill($dest_image, 0, 0, $trans_colour);\n\nimagepng($dest_image,\"test1.png\",1);\n</code></pre>\n" }, { "answer_id": 46084683, "author": "nsinvocation", "author_id": 1804311, "author_profile": "https://Stackoverflow.com/users/1804311", "pm_score": 0, "selected": false, "text": "<p>Pay attention to the source image's <code>width</code> and <code>height</code> values which are passed to <code>imagecopyresampled</code> function. If they are bigger than actual source image size, the rest of image area will be filled with black color. </p>\n" }, { "answer_id": 51810856, "author": "Marco", "author_id": 2969320, "author_profile": "https://Stackoverflow.com/users/2969320", "pm_score": 0, "selected": false, "text": "<p>I combined the answers from ceejayoz and Cheekysoft, which gave the best result for me. Without imagealphablending() and imagesavealpha() the image is not clear:</p>\n\n<pre><code>$img3 = imagecreatetruecolor(128, 128);\nimagecolortransparent($img3, imagecolorallocate($img3, 0, 0, 0));\nimagealphablending( $img3, false );\nimagesavealpha( $img3, true );\nimagecopyresampled($img3, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight);\nimagepng($img3, 'filename.png', 9);\n</code></pre>\n" }, { "answer_id": 72346188, "author": "Lepy", "author_id": 11582724, "author_profile": "https://Stackoverflow.com/users/11582724", "pm_score": 0, "selected": false, "text": "<p>For anyone having problems with <code>imagecopyresampled</code> or <code>imagerotate</code> with black bars on background, I have found a code example here:</p>\n<p><a href=\"https://qna.habr.com/q/646622#answer_1417035\" rel=\"nofollow noreferrer\">https://qna.habr.com/q/646622#answer_1417035</a></p>\n<pre><code> // get image sizes (X,Y)\n $wx = imagesx($imageW);\n $wy = imagesy($imageW);\n\n // create a new image from the sizes on transparent canvas\n $new = imagecreatetruecolor($wx, $wy);\n\n $transparent = imagecolorallocatealpha($new, 0, 0, 0, 127);\n $rotate = imagerotate($imageW, 280, $transparent);\n imagealphablending($rotate, true);\n imagesavealpha($rotate, true);\n\n // get the newest image X and Y\n $ix = imagesx($rotate);\n $iy = imagesy($rotate);\n\n //copy the image to the canvas\n imagecopyresampled($destImg, $rotate, 940, 2050, 0, 0, $ix, $iy, $ix, $iy);\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1820/" ]
The following PHP code snippet uses GD to resize a browser-uploaded PNG to 128x128. It works great, except that the transparent areas in the original image are being replaced with a solid color- black in my case. Even though `imagesavealpha` is set, something isn't quite right. What's the best way to preserve the transparency in the resampled image? ``` $uploadTempFile = $myField[ 'tmp_name' ] list( $uploadWidth, $uploadHeight, $uploadType ) = getimagesize( $uploadTempFile ); $srcImage = imagecreatefrompng( $uploadTempFile ); imagesavealpha( $targetImage, true ); $targetImage = imagecreatetruecolor( 128, 128 ); imagecopyresampled( $targetImage, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight ); imagepng( $targetImage, 'out.png', 9 ); ```
``` imagealphablending( $targetImage, false ); imagesavealpha( $targetImage, true ); ``` did it for me. Thanks ceejayoz. note, the target image needs the alpha settings, not the source image. Edit: full replacement code. See also answers below and their comments. This is not guaranteed to be be perfect in any way, but did achieve my needs at the time. ``` $uploadTempFile = $myField[ 'tmp_name' ] list( $uploadWidth, $uploadHeight, $uploadType ) = getimagesize( $uploadTempFile ); $srcImage = imagecreatefrompng( $uploadTempFile ); $targetImage = imagecreatetruecolor( 128, 128 ); imagealphablending( $targetImage, false ); imagesavealpha( $targetImage, true ); imagecopyresampled( $targetImage, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight ); imagepng( $targetImage, 'out.png', 9 ); ```
32,260
<p>Instead of relying on my host to send an email, I was thinking of sending the email messages using my <strong>Gmail</strong> account. The emails are personalized emails to the bands I play on my show. </p> <p>Is it possible to do it?</p>
[ { "answer_id": 32336, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 11, "selected": true, "text": "<p>Be sure to use <code>System.Net.Mail</code>, not the deprecated <code>System.Web.Mail</code>. Doing SSL with <code>System.Web.Mail</code> is a gross mess of hacky extensions.</p>\n<pre><code>using System.Net;\nusing System.Net.Mail;\n\nvar fromAddress = new MailAddress(&quot;[email protected]&quot;, &quot;From Name&quot;);\nvar toAddress = new MailAddress(&quot;[email protected]&quot;, &quot;To Name&quot;);\nconst string fromPassword = &quot;fromPassword&quot;;\nconst string subject = &quot;Subject&quot;;\nconst string body = &quot;Body&quot;;\n\nvar smtp = new SmtpClient\n{\n Host = &quot;smtp.gmail.com&quot;,\n Port = 587,\n EnableSsl = true,\n DeliveryMethod = SmtpDeliveryMethod.Network,\n UseDefaultCredentials = false,\n Credentials = new NetworkCredential(fromAddress.Address, fromPassword)\n};\nusing (var message = new MailMessage(fromAddress, toAddress)\n{\n Subject = subject,\n Body = body\n})\n{\n smtp.Send(message);\n}\n</code></pre>\n<p>Additionally go to the <a href=\"https://myaccount.google.com/security\" rel=\"noreferrer\"><em>Google Account &gt; Security</em></a> page and look at the <em>Signing in to Google &gt; 2-Step Verification</em> setting.</p>\n<ul>\n<li>If it is enabled, then you have to generate a password allowing .NET to bypass the 2-Step Verification. To do this, click on <a href=\"https://myaccount.google.com/apppasswords\" rel=\"noreferrer\"><em>Signing in to Google &gt; App passwords</em></a>, select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the <code>fromPassword</code> constant instead of your standard Gmail password.</li>\n<li>If it is disabled, then you have to turn on <a href=\"https://myaccount.google.com/lesssecureapps\" rel=\"noreferrer\"><em>Less secure app access</em></a>, which is not recommended! So better enable the 2-Step verification.</li>\n</ul>\n" }, { "answer_id": 489594, "author": "Donny V.", "author_id": 1231, "author_profile": "https://Stackoverflow.com/users/1231", "pm_score": 7, "selected": false, "text": "<p>The above answer doesn't work. You have to set <code>DeliveryMethod = SmtpDeliveryMethod.Network</code> or it will come back with a \"<strong>client was not authenticated</strong>\" error. Also it's always a good idea to put a timeout.</p>\n\n<p>Revised code:</p>\n\n<pre><code>using System.Net.Mail;\nusing System.Net;\n\nvar fromAddress = new MailAddress(\"[email protected]\", \"From Name\");\nvar toAddress = new MailAddress(\"[email protected]\", \"To Name\");\nconst string fromPassword = \"password\";\nconst string subject = \"test\";\nconst string body = \"Hey now!!\";\n\nvar smtp = new SmtpClient\n{\n Host = \"smtp.gmail.com\",\n Port = 587,\n EnableSsl = true,\n DeliveryMethod = SmtpDeliveryMethod.Network,\n Credentials = new NetworkCredential(fromAddress.Address, fromPassword),\n Timeout = 20000\n};\nusing (var message = new MailMessage(fromAddress, toAddress)\n{\n Subject = subject,\n Body = body\n})\n{\n smtp.Send(message);\n}\n</code></pre>\n" }, { "answer_id": 3955349, "author": "tehie", "author_id": 478781, "author_profile": "https://Stackoverflow.com/users/478781", "pm_score": 4, "selected": false, "text": "<p>Here is my version: \"<a href=\"http://www.techiespider.com/?p=7\" rel=\"noreferrer\">Send Email In C # Using Gmail</a>\".</p>\n\n<pre><code>using System;\nusing System.Net;\nusing System.Net.Mail;\n\nnamespace SendMailViaGmail\n{\n class Program\n {\n static void Main(string[] args)\n {\n\n //Specify senders gmail address\n string SendersAddress = \"[email protected]\";\n //Specify The Address You want to sent Email To(can be any valid email address)\n string ReceiversAddress = \"[email protected]\";\n //Specify The password of gmial account u are using to sent mail(pw of [email protected])\n const string SendersPassword = \"Password\";\n //Write the subject of ur mail\n const string subject = \"Testing\";\n //Write the contents of your mail\n const string body = \"Hi This Is my Mail From Gmail\";\n\n try\n {\n //we will use Smtp client which allows us to send email using SMTP Protocol\n //i have specified the properties of SmtpClient smtp within{}\n //gmails smtp server name is smtp.gmail.com and port number is 587\n SmtpClient smtp = new SmtpClient\n {\n Host = \"smtp.gmail.com\",\n Port = 587,\n EnableSsl = true,\n DeliveryMethod = SmtpDeliveryMethod.Network,\n Credentials = new NetworkCredential(SendersAddress, SendersPassword),\n Timeout = 3000\n };\n\n //MailMessage represents a mail message\n //it is 4 parameters(From,TO,subject,body)\n\n MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);\n /*WE use smtp sever we specified above to send the message(MailMessage message)*/\n\n smtp.Send(message);\n Console.WriteLine(\"Message Sent Successfully\");\n Console.ReadKey();\n }\n\n catch (Exception ex)\n {\n Console.WriteLine(ex.Message);\n Console.ReadKey();\n }\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 10784857, "author": "Ranadheer Reddy", "author_id": 1215594, "author_profile": "https://Stackoverflow.com/users/1215594", "pm_score": 6, "selected": false, "text": "<p>This is to send email with attachement.. Simple and short..</p>\n\n<p>source: <a href=\"http://coding-issues.blogspot.in/2012/11/sending-email-with-attachments-from-c.html\">http://coding-issues.blogspot.in/2012/11/sending-email-with-attachments-from-c.html</a></p>\n\n<pre><code>using System.Net;\nusing System.Net.Mail;\n\npublic void email_send()\n{\n MailMessage mail = new MailMessage();\n SmtpClient SmtpServer = new SmtpClient(\"smtp.gmail.com\");\n mail.From = new MailAddress(\"your [email protected]\");\n mail.To.Add(\"[email protected]\");\n mail.Subject = \"Test Mail - 1\";\n mail.Body = \"mail with attachment\";\n\n System.Net.Mail.Attachment attachment;\n attachment = new System.Net.Mail.Attachment(\"c:/textfile.txt\");\n mail.Attachments.Add(attachment);\n\n SmtpServer.Port = 587;\n SmtpServer.Credentials = new System.Net.NetworkCredential(\"your [email protected]\", \"your password\");\n SmtpServer.EnableSsl = true;\n\n SmtpServer.Send(mail);\n\n}\n</code></pre>\n" }, { "answer_id": 12073195, "author": "Yasser Shaikh", "author_id": 1182982, "author_profile": "https://Stackoverflow.com/users/1182982", "pm_score": 4, "selected": false, "text": "<p><strong>Source</strong> : <a href=\"http://yassershaikh.com/how-to-send-email-in-asp-net-c-mvc-3-with-sample-working-code/\" rel=\"noreferrer\">Send email in ASP.NET C#</a></p>\n\n<p>Below is a sample working code for sending in a mail using C#, in the below example I am using google’s smtp server. </p>\n\n<p>The code is pretty self explanatory, replace email and password with your email and password values.</p>\n\n<pre><code>public void SendEmail(string address, string subject, string message)\n{\n string email = \"[email protected]\";\n string password = \"put-your-GMAIL-password-here\";\n\n var loginInfo = new NetworkCredential(email, password);\n var msg = new MailMessage();\n var smtpClient = new SmtpClient(\"smtp.gmail.com\", 587);\n\n msg.From = new MailAddress(email);\n msg.To.Add(new MailAddress(address));\n msg.Subject = subject;\n msg.Body = message;\n msg.IsBodyHtml = true;\n\n smtpClient.EnableSsl = true;\n smtpClient.UseDefaultCredentials = false;\n smtpClient.Credentials = loginInfo;\n smtpClient.Send(msg);\n}\n</code></pre>\n" }, { "answer_id": 17516257, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 3, "selected": false, "text": "<p>Changing sender on Gmail / Outlook.com email:</p>\n\n<p>To prevent spoofing - Gmail/Outlook.com won't let you send from an arbitrary user account name.</p>\n\n<p>If you have a limited number of senders you can follow these instructions and then set the <code>From</code> field to this address: <a href=\"http://support.google.com/a/bin/answer.py?hl=en&amp;answer=22370\" rel=\"noreferrer\">Sending mail from a different address</a></p>\n\n<p>If you are wanting to send from an arbitrary email address (such as a feedback form on website where the user enters their email and you don't want them emailing you directly) about the best you can do is this :</p>\n\n<pre><code> msg.ReplyToList.Add(new System.Net.Mail.MailAddress(email, friendlyName));\n</code></pre>\n\n<p>This would let you just hit 'reply' in your email account to reply to the fan of your band on a feedback page, but they wouldn't get your actual email which would likely lead to a tonne of spam.</p>\n\n<p>If you're in a controlled environment this works great, but please note that I've seen some email clients send to the from address even when reply-to is specified (I don't know which).</p>\n" }, { "answer_id": 17806790, "author": "RAJESH KUMAR", "author_id": 2598139, "author_profile": "https://Stackoverflow.com/users/2598139", "pm_score": 3, "selected": false, "text": "<p>If you want to send background email, then please do the below</p>\n\n<pre><code> public void SendEmail(string address, string subject, string message)\n {\n Thread threadSendMails;\n threadSendMails = new Thread(delegate()\n {\n\n //Place your Code here \n\n });\n threadSendMails.IsBackground = true;\n threadSendMails.Start();\n}\n</code></pre>\n\n<p>and add namespace</p>\n\n<pre><code>using System.Threading;\n</code></pre>\n" }, { "answer_id": 19240345, "author": "iTURTEV", "author_id": 2853517, "author_profile": "https://Stackoverflow.com/users/2853517", "pm_score": 2, "selected": false, "text": "<p>Here is one method to send mail and getting credentials from web.config:</p>\n\n<pre><code>public static string SendEmail(string To, string Subject, string Msg, bool bodyHtml = false, bool test = false, Stream AttachmentStream = null, string AttachmentType = null, string AttachmentFileName = null)\n{\n try\n {\n System.Net.Mail.MailMessage newMsg = new System.Net.Mail.MailMessage(System.Configuration.ConfigurationManager.AppSettings[\"mailCfg\"], To, Subject, Msg);\n newMsg.BodyEncoding = System.Text.Encoding.UTF8;\n newMsg.HeadersEncoding = System.Text.Encoding.UTF8;\n newMsg.SubjectEncoding = System.Text.Encoding.UTF8;\n\n System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();\n if (AttachmentStream != null &amp;&amp; AttachmentType != null &amp;&amp; AttachmentFileName != null)\n {\n System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(AttachmentStream, AttachmentFileName);\n System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;\n disposition.FileName = AttachmentFileName;\n disposition.DispositionType = System.Net.Mime.DispositionTypeNames.Attachment;\n\n newMsg.Attachments.Add(attachment);\n }\n if (test)\n {\n smtpClient.PickupDirectoryLocation = \"C:\\\\TestEmail\";\n smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;\n }\n else\n {\n //smtpClient.EnableSsl = true;\n }\n\n newMsg.IsBodyHtml = bodyHtml;\n smtpClient.Send(newMsg);\n return SENT_OK;\n }\n catch (Exception ex)\n {\n\n return \"Error: \" + ex.Message\n + \"&lt;br/&gt;&lt;br/&gt;Inner Exception: \"\n + ex.InnerException;\n }\n\n}\n</code></pre>\n\n<p>And the corresponding section in web.config:</p>\n\n<pre><code>&lt;appSettings&gt;\n &lt;add key=\"mailCfg\" value=\"[email protected]\"/&gt;\n&lt;/appSettings&gt;\n&lt;system.net&gt;\n &lt;mailSettings&gt;\n &lt;smtp deliveryMethod=\"Network\" from=\"[email protected]\"&gt;\n &lt;network defaultCredentials=\"false\" host=\"mail.exapmple.com\" userName=\"[email protected]\" password=\"your_password\" port=\"25\"/&gt;\n &lt;/smtp&gt;\n &lt;/mailSettings&gt;\n&lt;/system.net&gt;\n</code></pre>\n" }, { "answer_id": 19272274, "author": "GOPI", "author_id": 2522714, "author_profile": "https://Stackoverflow.com/users/2522714", "pm_score": 4, "selected": false, "text": "<p>Include this,</p>\n<pre><code>using System.Net.Mail;\n</code></pre>\n<p>And then,</p>\n<pre><code>MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body); \nSmtpClient client = new SmtpClient(&quot;smtp.gmail.com&quot;);\n\nclient.Port = 587;\nclient.Credentials = new System.Net.NetworkCredential(&quot;[email protected]&quot;,&quot;password&quot;);\nclient.EnableSsl = true;\n\nclient.Send(sendmsg);\n</code></pre>\n" }, { "answer_id": 19378314, "author": "Premdeep Mohanty", "author_id": 2749766, "author_profile": "https://Stackoverflow.com/users/2749766", "pm_score": 4, "selected": false, "text": "<p>I hope this code will work fine. You can have a try.</p>\n\n<pre><code>// Include this. \nusing System.Net.Mail;\n\nstring fromAddress = \"[email protected]\";\nstring mailPassword = \"*****\"; // Mail id password from where mail will be sent.\nstring messageBody = \"Write the body of the message here.\";\n\n\n// Create smtp connection.\nSmtpClient client = new SmtpClient();\nclient.Port = 587;//outgoing port for the mail.\nclient.Host = \"smtp.gmail.com\";\nclient.EnableSsl = true;\nclient.Timeout = 10000;\nclient.DeliveryMethod = SmtpDeliveryMethod.Network;\nclient.UseDefaultCredentials = false;\nclient.Credentials = new System.Net.NetworkCredential(fromAddress, mailPassword);\n\n\n// Fill the mail form.\nvar send_mail = new MailMessage();\n\nsend_mail.IsBodyHtml = true;\n//address from where mail will be sent.\nsend_mail.From = new MailAddress(\"[email protected]\");\n//address to which mail will be sent. \nsend_mail.To.Add(new MailAddress(\"[email protected]\");\n//subject of the mail.\nsend_mail.Subject = \"put any subject here\";\n\nsend_mail.Body = messageBody;\nclient.Send(send_mail);\n</code></pre>\n" }, { "answer_id": 20907006, "author": "Mark Homans", "author_id": 2009368, "author_profile": "https://Stackoverflow.com/users/2009368", "pm_score": 5, "selected": false, "text": "<p>For me to get it to work, i had to enable my gmail account making it possible for other apps to gain access. This is done with the \"enable less secure apps\" and <strong>also</strong> using this link:\n<a href=\"https://accounts.google.com/b/0/DisplayUnlockCaptcha\" rel=\"noreferrer\">https://accounts.google.com/b/0/DisplayUnlockCaptcha</a></p>\n" }, { "answer_id": 25216277, "author": "mjb", "author_id": 520848, "author_profile": "https://Stackoverflow.com/users/520848", "pm_score": 5, "selected": false, "text": "<p>Google may block sign in attempts from some apps or devices that do not use modern security standards. Since these apps and devices are easier to break into, blocking them helps keep your account safer.</p>\n\n<p>Some examples of apps that do not support the latest security standards include:</p>\n\n<ul>\n<li>The Mail app on your iPhone or iPad with iOS 6 or below<br /></li>\n<li>The Mail app on your Windows phone preceding the 8.1 release<br /></li>\n<li>Some Desktop mail clients like Microsoft Outlook and Mozilla Thunderbird</li>\n</ul>\n\n<p>Therefore, you have to enable <b>Less Secure Sign-In</b> in your google account.</p>\n\n<p>After sign into google account, go to:</p>\n\n<p><a href=\"https://myaccount.google.com/lesssecureapps\" rel=\"noreferrer\">https://myaccount.google.com/lesssecureapps</a> <br />\nor <br />\n<a href=\"https://www.google.com/settings/security/lesssecureapps\" rel=\"noreferrer\">https://www.google.com/settings/security/lesssecureapps</a> <br /></p>\n\n<p>In C#, you can use the following code:</p>\n\n<pre><code>using (MailMessage mail = new MailMessage())\n{\n mail.From = new MailAddress(\"[email protected]\");\n mail.To.Add(\"[email protected]\");\n mail.Subject = \"Hello World\";\n mail.Body = \"&lt;h1&gt;Hello&lt;/h1&gt;\";\n mail.IsBodyHtml = true;\n mail.Attachments.Add(new Attachment(\"C:\\\\file.zip\"));\n\n using (SmtpClient smtp = new SmtpClient(\"smtp.gmail.com\", 587))\n {\n smtp.Credentials = new NetworkCredential(\"[email protected]\", \"password\");\n smtp.EnableSsl = true;\n smtp.Send(mail);\n }\n}\n</code></pre>\n" }, { "answer_id": 31043524, "author": "DarkPh03n1X", "author_id": 3431863, "author_profile": "https://Stackoverflow.com/users/3431863", "pm_score": 2, "selected": false, "text": "<p>I had the same issue, but it was resolved by going to gmail's security settings and <strong>Allowing Less Secure apps</strong>.\nThe Code from Domenic &amp; Donny works, but only if you enabled that setting</p>\n\n<p>If you are signed in (to Google) you can follow <a href=\"https://www.google.com/settings/security/lesssecureapps\" rel=\"nofollow\">this</a> link and toggle <strong>\"Turn on\"</strong> for <strong>\"Access for less secure apps\"</strong></p>\n" }, { "answer_id": 31310222, "author": "alireza amini", "author_id": 3970128, "author_profile": "https://Stackoverflow.com/users/3970128", "pm_score": 3, "selected": false, "text": "<p>use this way </p>\n\n<pre><code>MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body); \nSmtpClient client = new SmtpClient(\"smtp.gmail.com\");\n\nclient.Port = Convert.ToInt32(\"587\");\nclient.EnableSsl = true;\nclient.Credentials = new System.Net.NetworkCredential(\"[email protected]\",\"MyPassWord\");\nclient.Send(sendmsg);\n</code></pre>\n\n<p>Don't forget this :</p>\n\n<pre><code>using System.Net;\nusing System.Net.Mail;\n</code></pre>\n" }, { "answer_id": 32457468, "author": "BCS Software", "author_id": 4222871, "author_profile": "https://Stackoverflow.com/users/4222871", "pm_score": 7, "selected": false, "text": "<p><strong>Edit 2022</strong>\nStarting May 30, 2022, <a href=\"https://support.google.com/accounts/answer/6010255?hl=en\" rel=\"noreferrer\">​​Google will no longer support</a> the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.\n<strong>But you still can send E-Mail via your gmail account.</strong></p>\n<ol>\n<li>Go to <a href=\"https://myaccount.google.com/security\" rel=\"noreferrer\">https://myaccount.google.com/security</a> and turn on <strong>two step verification</strong>. Confirm your account by phone if needed.</li>\n<li>Click &quot;App Passwords&quot;, just below the &quot;2 step verification&quot; tick.</li>\n<li>Request a new password for the mail app.\n<a href=\"https://i.stack.imgur.com/LhP5V.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/LhP5V.png\" alt=\"enter image description here\" /></a></li>\n</ol>\n<p>Now just use this password instead of the original one for you account!</p>\n<pre><code>public static void SendMail2Step(string SMTPServer, int SMTP_Port, string From, string Password, string To, string Subject, string Body, string[] FileNames) { \n var smtpClient = new SmtpClient(SMTPServer, SMTP_Port) {\n DeliveryMethod = SmtpDeliveryMethod.Network,\n UseDefaultCredentials = false,\n EnableSsl = true\n }; \n smtpClient.Credentials = new NetworkCredential(From, Password); //Use the new password, generated from google!\n var message = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress(From, &quot;SendMail2Step&quot;), new System.Net.Mail.MailAddress(To, To));\n smtpClient.Send(message);\n }\n</code></pre>\n<p>Use like this:</p>\n<pre><code>SendMail2Step(&quot;smtp.gmail.com&quot;, 587, &quot;[email protected]&quot;,\n &quot;yjkjcipfdfkytgqv&quot;,//This will be generated by google, copy it here.\n &quot;[email protected]&quot;, &quot;test message subject&quot;, &quot;Test message body ...&quot;, null);\n</code></pre>\n<p>For the other answers to work &quot;from a server&quot; first <strong>Turn On Access for less secure apps</strong> in the gmail account. <strong>This will be deprecated 30 May 2022</strong></p>\n<p>Looks like recently google changed it's security policy. The top rated answer no longer works, until you change your account settings as described here: <a href=\"https://support.google.com/accounts/answer/6010255?hl=en-GB\" rel=\"noreferrer\">https://support.google.com/accounts/answer/6010255?hl=en-GB</a>\n<strong>As of March 2016, google changed the setting location again!</strong>\n<a href=\"https://i.stack.imgur.com/XqODf.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/XqODf.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 33054757, "author": "Moin Shirazi", "author_id": 4033273, "author_profile": "https://Stackoverflow.com/users/4033273", "pm_score": 3, "selected": false, "text": "<pre><code>using System;\nusing System.Net;\nusing System.Net.Mail;\n\nnamespace SendMailViaGmail\n{\n class Program\n {\n static void Main(string[] args)\n {\n\n //Specify senders gmail address\n string SendersAddress = \"[email protected]\";\n //Specify The Address You want to sent Email To(can be any valid email address)\n string ReceiversAddress = \"[email protected]\";\n //Specify The password of gmial account u are using to sent mail(pw of [email protected])\n const string SendersPassword = \"Password\";\n //Write the subject of ur mail\n const string subject = \"Testing\";\n //Write the contents of your mail\n const string body = \"Hi This Is my Mail From Gmail\";\n\n try\n {\n //we will use Smtp client which allows us to send email using SMTP Protocol\n //i have specified the properties of SmtpClient smtp within{}\n //gmails smtp server name is smtp.gmail.com and port number is 587\n SmtpClient smtp = new SmtpClient\n {\n Host = \"smtp.gmail.com\",\n Port = 587,\n EnableSsl = true,\n DeliveryMethod = SmtpDeliveryMethod.Network,\n Credentials = new NetworkCredential(SendersAddress, SendersPassword),\n Timeout = 3000\n };\n\n //MailMessage represents a mail message\n //it is 4 parameters(From,TO,subject,body)\n\n MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);\n /*WE use smtp sever we specified above to send the message(MailMessage message)*/\n\n smtp.Send(message);\n Console.WriteLine(\"Message Sent Successfully\");\n Console.ReadKey();\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.Message);\n Console.ReadKey();\n }\n}\n}\n}\n</code></pre>\n" }, { "answer_id": 35669909, "author": "reza.cse08", "author_id": 2597706, "author_profile": "https://Stackoverflow.com/users/2597706", "pm_score": 2, "selected": false, "text": "<p>Try this one </p>\n\n<pre><code>public static bool Send(string receiverEmail, string ReceiverName, string subject, string body)\n{\n MailMessage mailMessage = new MailMessage();\n MailAddress mailAddress = new MailAddress(\"[email protected]\", \"Sender Name\"); // [email protected] = input Sender Email Address \n mailMessage.From = mailAddress;\n mailAddress = new MailAddress(receiverEmail, ReceiverName);\n mailMessage.To.Add(mailAddress);\n mailMessage.Subject = subject;\n mailMessage.Body = body;\n mailMessage.IsBodyHtml = true;\n\n SmtpClient mailSender = new SmtpClient(\"smtp.gmail.com\", 587)\n {\n EnableSsl = true,\n UseDefaultCredentials = false,\n DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,\n Credentials = new NetworkCredential(\"[email protected]\", \"pass\") // [email protected] = input sender email address \n //pass = sender email password\n };\n\n try\n {\n mailSender.Send(mailMessage);\n return true;\n }\n catch (SmtpFailedRecipientException ex)\n { \n // Write the exception to a Log file.\n }\n catch (SmtpException ex)\n { \n // Write the exception to a Log file.\n }\n finally\n {\n mailSender = null;\n mailMessage.Dispose();\n }\n return false;\n}\n</code></pre>\n" }, { "answer_id": 41952779, "author": "Trimantra Software Solution", "author_id": 777171, "author_profile": "https://Stackoverflow.com/users/777171", "pm_score": 3, "selected": false, "text": "<p>Try This,</p>\n\n<pre><code> private void button1_Click(object sender, EventArgs e)\n {\n try\n {\n MailMessage mail = new MailMessage();\n SmtpClient SmtpServer = new SmtpClient(\"smtp.gmail.com\");\n\n mail.From = new MailAddress(\"[email protected]\");\n mail.To.Add(\"to_address\");\n mail.Subject = \"Test Mail\";\n mail.Body = \"This is for testing SMTP mail from GMAIL\";\n\n SmtpServer.Port = 587;\n SmtpServer.Credentials = new System.Net.NetworkCredential(\"username\", \"password\");\n SmtpServer.EnableSsl = true;\n\n SmtpServer.Send(mail);\n MessageBox.Show(\"mail Send\");\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.ToString());\n }\n }\n</code></pre>\n" }, { "answer_id": 49429541, "author": "rogerdpack", "author_id": 32453, "author_profile": "https://Stackoverflow.com/users/32453", "pm_score": 1, "selected": false, "text": "<p>Copying from <a href=\"https://stackoverflow.com/a/19723382/32453\">another answer</a>, the above methods work but gmail always replaces the \"from\" and \"reply to\" email with the actual sending gmail account. apparently there is a work around however:</p>\n\n<p><a href=\"http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html\" rel=\"nofollow noreferrer\">http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html</a></p>\n\n<p>\"3. In the Accounts Tab, Click on the link \"Add another email address you own\" then verify it\"</p>\n\n<p>Or possibly <a href=\"https://lifehacker.com/111166/how-to-use-gmail-as-your-smtp-server\" rel=\"nofollow noreferrer\">this</a></p>\n\n<p>Update 3: Reader Derek Bennett says, \"The solution is to go into your gmail Settings:Accounts and \"Make default\" an account other than your gmail account. This will cause gmail to re-write the From field with whatever the default account's email address is.\"</p>\n" }, { "answer_id": 56423660, "author": "Naveen", "author_id": 5718260, "author_profile": "https://Stackoverflow.com/users/5718260", "pm_score": 2, "selected": false, "text": "<p>You can try <code>Mailkit</code>. It gives you better and advance functionality for send mail. You can find more from <a href=\"https://github.com/jstedfast/MailKit\" rel=\"nofollow noreferrer\">this</a> Here is an example </p>\n\n<pre><code> MimeMessage message = new MimeMessage();\n message.From.Add(new MailboxAddress(\"FromName\", \"[email protected]\"));\n message.To.Add(new MailboxAddress(\"ToName\", \"[email protected]\"));\n message.Subject = \"MyEmailSubject\";\n\n message.Body = new TextPart(\"plain\")\n {\n Text = @\"MyEmailBodyOnlyTextPart\"\n };\n\n using (var client = new SmtpClient())\n {\n client.Connect(\"SERVER\", 25); // 25 is port you can change accordingly\n\n // Note: since we don't have an OAuth2 token, disable\n // the XOAUTH2 authentication mechanism.\n client.AuthenticationMechanisms.Remove(\"XOAUTH2\");\n\n // Note: only needed if the SMTP server requires authentication\n client.Authenticate(\"YOUR_USER_NAME\", \"YOUR_PASSWORD\");\n\n client.Send(message);\n client.Disconnect(true);\n }\n</code></pre>\n" }, { "answer_id": 57067328, "author": "Sayed Uz Zaman", "author_id": 10119759, "author_profile": "https://Stackoverflow.com/users/10119759", "pm_score": 4, "selected": false, "text": "<p>To avoid security issues in Gmail, you should generate an app password first from your Gmail settings and you can use this password instead of a real password to send an email even if you use two steps verification.</p>\n" }, { "answer_id": 63782647, "author": "Hasala Senevirathne", "author_id": 7292121, "author_profile": "https://Stackoverflow.com/users/7292121", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/xrl3W.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xrl3W.png\" alt=\"How to Set App-specific password for gmail\" /></a></p>\n<p>If your Google password doesn't work, you may need to create an app-specific password for Gmail on Google.\n<a href=\"https://support.google.com/accounts/answer/185833?hl=en\" rel=\"nofollow noreferrer\">https://support.google.com/accounts/answer/185833?hl=en</a></p>\n" }, { "answer_id": 73352730, "author": "Sunny Okoro Awa", "author_id": 2623765, "author_profile": "https://Stackoverflow.com/users/2623765", "pm_score": 1, "selected": false, "text": "<p>This is no longer supported incase you are trying to do this now.</p>\n<p><a href=\"https://support.google.com/accounts/answer/6010255?hl=en&amp;visit_id=637960864118404117-800836189&amp;p=less-secure-apps&amp;rd=1#zippy=\" rel=\"nofollow noreferrer\">https://support.google.com/accounts/answer/6010255?hl=en&amp;visit_id=637960864118404117-800836189&amp;p=less-secure-apps&amp;rd=1#zippy=</a></p>\n<p><a href=\"https://i.stack.imgur.com/y5zYQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/y5zYQ.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 74054933, "author": "Bhadresh Patel", "author_id": 3134543, "author_profile": "https://Stackoverflow.com/users/3134543", "pm_score": 2, "selected": false, "text": "<p><strong>From 1 Jun 2022, ​​Google has added some security features</strong></p>\n<p>Google is no longer support the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password or send mail directly using username and password of google account. But you still can send E-Mail via your gmail account using generating app password.</p>\n<blockquote>\n<p>Below are the steps for generate new password.</p>\n</blockquote>\n<ol>\n<li>Go to <a href=\"https://myaccount.google.com/security\" rel=\"nofollow noreferrer\">https://myaccount.google.com/security</a></li>\n<li>Turn on two step verification.</li>\n<li>Confirm your account by phone if needed.</li>\n<li>Click &quot;App Passwords&quot;, just below the &quot;2 step verification&quot; tick. Request a new password for the mail app.</li>\n</ol>\n<p>Now we have to use this password for sending mail instead of the original password of your account.</p>\n<blockquote>\n<p>Below is the example code for sending mail</p>\n</blockquote>\n<pre><code>public static void SendMailFromApp(string SMTPServer, int SMTP_Port, string From, string Password, string To, string Subject, string Body) { \n var smtpClient = new SmtpClient(SMTPServer, SMTP_Port) {\n DeliveryMethod = SmtpDeliveryMethod.Network,\n UseDefaultCredentials = false,\n EnableSsl = true\n }; \n smtpClient.Credentials = new NetworkCredential(From, Password); //Use the new password, generated from google!\n var message = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress(From, &quot;SendMail2Step&quot;), new System.Net.Mail.MailAddress(To, To));\n smtpClient.Send(message);\n }\n</code></pre>\n<p>You can to call method like below</p>\n<pre><code>SendMailFromApp(&quot;smtp.gmail.com&quot;, 25, &quot;[email protected]&quot;,\n &quot;tyugyyj1556jhghg&quot;,//This will be generated by google, copy it here.\n &quot;[email protected]&quot;, &quot;New Mail Subject&quot;, &quot;Body of mail from My App&quot;);\n</code></pre>\n" }, { "answer_id": 74404794, "author": "DaImTo", "author_id": 1841839, "author_profile": "https://Stackoverflow.com/users/1841839", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/Y5W1l.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Y5W1l.png\" alt=\"enter image description here\" /></a></p>\n<p>Google has removed the less secure apps setting from our Google accounts, this means that we can no longer send emails from the SMTP server using our actual google passwords. We need to either use Xoauth2 and authorize the user or create a an apps password on an account that has 2fa enabled.</p>\n<p>Once created an apps password can be used in place of your standard gmail password.</p>\n<pre><code>class Program\n{\n private const string To = &quot;[email protected]&quot;;\n private const string From = &quot;[email protected]&quot;;\n \n private const string GoogleAppPassword = &quot;XXXXXXXX&quot;;\n \n private const string Subject = &quot;Test email&quot;;\n private const string Body = &quot;&lt;h1&gt;Hello&lt;/h1&gt;&quot;;\n \n \n static void Main(string[] args)\n {\n Console.WriteLine(&quot;Hello World!&quot;);\n \n var smtpClient = new SmtpClient(&quot;smtp.gmail.com&quot;)\n {\n Port = 587,\n Credentials = new NetworkCredential(From , GoogleAppPassword),\n EnableSsl = true,\n };\n var mailMessage = new MailMessage\n {\n From = new MailAddress(From),\n Subject = Subject,\n Body = Body,\n IsBodyHtml = true,\n };\n mailMessage.To.Add(To);\n\n smtpClient.Send(mailMessage);\n }\n}\n</code></pre>\n<p><a href=\"https://www.youtube.com/watch?v=Y_u5KIeXiVI\" rel=\"nofollow noreferrer\">Quick fix for SMTP username and password not accepted error</a></p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2535/" ]
Instead of relying on my host to send an email, I was thinking of sending the email messages using my **Gmail** account. The emails are personalized emails to the bands I play on my show. Is it possible to do it?
Be sure to use `System.Net.Mail`, not the deprecated `System.Web.Mail`. Doing SSL with `System.Web.Mail` is a gross mess of hacky extensions. ``` using System.Net; using System.Net.Mail; var fromAddress = new MailAddress("[email protected]", "From Name"); var toAddress = new MailAddress("[email protected]", "To Name"); const string fromPassword = "fromPassword"; const string subject = "Subject"; const string body = "Body"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { smtp.Send(message); } ``` Additionally go to the [*Google Account > Security*](https://myaccount.google.com/security) page and look at the *Signing in to Google > 2-Step Verification* setting. * If it is enabled, then you have to generate a password allowing .NET to bypass the 2-Step Verification. To do this, click on [*Signing in to Google > App passwords*](https://myaccount.google.com/apppasswords), select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the `fromPassword` constant instead of your standard Gmail password. * If it is disabled, then you have to turn on [*Less secure app access*](https://myaccount.google.com/lesssecureapps), which is not recommended! So better enable the 2-Step verification.
32,280
<p>I am in the middle of reading the excellent <a href="https://rads.stackoverflow.com/amzn/click/com/0132350882" rel="noreferrer" rel="nofollow noreferrer">Clean Code</a></p> <p>One discussion is regarding passing nulls into a method.</p> <pre><code>public class MetricsCalculator { public double xProjection(Point p1, Point p2) { return (p2.x - p1.x) * 1.5; } } ... calculator.xProjection(null, new Point(12,13)); </code></pre> <p>It represents different ways of handling this:</p> <pre><code>public double xProjection(Point p1, Point p2) { if (p1 == null || p2 == null) { throw new IllegalArgumentException("Invalid argument for xProjection"); } return (p2.x - p1.x) * 1.5; } public double xProjection(Point p1, Point p2) { assert p1 != null : "p1 should not be null"; assert p2 != null : "p2 should not be null"; return (p2.x - p1.x) * 1.5; } </code></pre> <p>I prefer the <a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html" rel="noreferrer">assertions</a> approach, but I don't like the fact that assertions are turned off by default.</p> <p>The book finally states:</p> <blockquote> <p>In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default.</p> </blockquote> <p>It doesn't really go into how you would enforce this restriction?</p> <p>Do any of you have strong opinions either way.</p>
[ { "answer_id": 32295, "author": "wvdschel", "author_id": 2018, "author_profile": "https://Stackoverflow.com/users/2018", "pm_score": 1, "selected": false, "text": "<p>I generally prefer not doing either, since it's just slowing things down. NullPointerExceptions are thrown later on anyway, which will quickly lead the user to discovering they're passing null to the method. I used to check, but 40% of my code ended up being checking code, at which point I decided it was just not worth the nice assertion messages.</p>\n" }, { "answer_id": 32304, "author": "Chris Karcher", "author_id": 2773, "author_profile": "https://Stackoverflow.com/users/2773", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>It doesn't really go into how you would enforce this restriction?</p>\n</blockquote>\n\n<p>You enforce it by throwing an <a href=\"http://msdn.microsoft.com/en-us/library/system.argumentexception.aspx\" rel=\"nofollow noreferrer\">ArgumentExcexception</a> if they pass in null.</p>\n\n<pre><code>if (p1 == null || p2 == null) {\n throw new IllegalArgumentException(\"Invalid argument for xProjection\");\n}\n</code></pre>\n" }, { "answer_id": 32305, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 1, "selected": false, "text": "<p>I agree or disagree with <a href=\"https://stackoverflow.com/a/32295/3798217\">wvdschel's post</a>, it depends on what he's specifically saying.</p>\n\n<p>In this case, sure, this method will crash on <code>null</code> so the explicit check here is probably not needed.</p>\n\n<p>However, if the method simply stores the passed data, and there is some other method that you call later that will deal with it, <strong>discovering bad input as early as possible is the key to fixing bugs faster</strong>. At that later point, there could be a myriad of ways that bad data happened to be given to your class. It's sort of trying to figure out how the rats came into your house after the fact, trying to find the hole somewhere.</p>\n" }, { "answer_id": 32310, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 2, "selected": false, "text": "<p>I prefer the use of assertions. </p>\n\n<p>I have a rule that I only use assertions in public and protected methods. This is because I believe the calling method should ensure that it is passing valid arguments to private methods.</p>\n" }, { "answer_id": 32313, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "<p>General rule is if your method doesn't expect <code>null</code> arguments then you should throw <a href=\"http://msdn.microsoft.com/en-us/library/system.argumentnullexception.aspx\" rel=\"nofollow noreferrer\">System.ArgumentNullException</a>. Throwing proper <code>Exception</code> not only protects you from resource corruption and other bad things but serves as a guide for users of your code saving time spent debugging your code.</p>\n\n<p>Also read an article on <a href=\"http://en.wikipedia.org/wiki/Defensive_programming\" rel=\"nofollow noreferrer\">Defensive programming</a></p>\n" }, { "answer_id": 32314, "author": "Shaun Austin", "author_id": 1120, "author_profile": "https://Stackoverflow.com/users/1120", "pm_score": 1, "selected": false, "text": "<p>@Chris Karcher I would say absolutely correct. The only thing I would say is check the params separately and have the exeption report the param that was null also as it makes tracking where the null is coming from much easier.</p>\n\n<p>@wvdschel wow! If writing the code is too much effort for you, you should look into something like <a href=\"http://www.postsharp.org/\" rel=\"nofollow noreferrer\">PostSharp</a> (or a Java equivalent if one is available) which can post-process your assemblies and insert param checks for you. </p>\n" }, { "answer_id": 32384, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 1, "selected": false, "text": "<p>Although it is not strictly related you might want to take a look to <a href=\"http://research.microsoft.com/SpecSharp/\" rel=\"nofollow noreferrer\">Spec#</a>.</p>\n\n<p>I think it is still in development (by Microsoft) but some CTP are available and it looks promising. Basically it allows you to do this:</p>\n\n<pre><code> public static int Divide(int x, int y)\n requires y != 0 otherwise ArgumentException; \n {\n }\n</code></pre>\n\n<p>or</p>\n\n<pre><code> public static int Subtract(int x, int y)\n requires x &gt; y;\n ensures result &gt; y;\n {\n return x - y;\n } \n</code></pre>\n\n<p>It also provides another features like Notnull types. It's build on top of the .NET Framework 2.0 and it's fully compatible. The syntaxt, as you may see, is C#.</p>\n" }, { "answer_id": 32666, "author": "rcreswick", "author_id": 3446, "author_profile": "https://Stackoverflow.com/users/3446", "pm_score": 2, "selected": false, "text": "<p>Spec# looks very interesting!</p>\n\n<p>When something like that isn't available, I generally test non-private methods with a run-time null-check, and assertions for internal methods. Rather than code the null check explicitly in each method, I delegate that to a utilities class with a check null method:</p>\n\n<pre><code>/**\n * Checks to see if an object is null, and if so \n * generates an IllegalArgumentException with a fitting message.\n * \n * @param o The object to check against null.\n * @param name The name of the object, used to format the exception message\n *\n * @throws IllegalArgumentException if o is null.\n */\npublic static void checkNull(Object o, String name) \n throws IllegalArgumentException {\n if (null == o)\n throw new IllegalArgumentException(name + \" must not be null\");\n}\n\npublic static void checkNull(Object o) throws IllegalArgumentException {\n checkNull(o, \"object\");\n} \n\n// untested:\npublic static void checkNull(Object... os) throws IllegalArgumentException {\n for(Object o in os) checkNull(o); \n}\n</code></pre>\n\n<p>Then checking turns into:</p>\n\n<pre><code>public void someFun(String val1, String val2) throws IllegalArgumentException {\n ExceptionUtilities.checkNull(val1, \"val1\");\n ExceptionUtilities.checkNull(val2, \"val2\");\n\n /** alternatively:\n ExceptionUtilities.checkNull(val1, val2);\n **/\n\n /** ... **/\n} \n</code></pre>\n\n<p><em>That</em> can be added with editor macros, or a code-processing script.\n<strong>Edit:</strong> The verbose check could be added this way as well, but I think it's significantly easier to automate the addition of a single line.</p>\n" }, { "answer_id": 32716, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 2, "selected": false, "text": "<p>Also not of immediate use, but related to the mention of Spec#... There's a proposal to add \"null-safe types\" to a future version of Java: <a href=\"http://docs.google.com/View?docid=dfn5297z_2kjj2fk\" rel=\"nofollow noreferrer\">\"Enhanced null handling - Null-safe types\"</a>.</p>\n\n<p>Under the proposal, your method would become</p>\n\n<pre><code>public class MetricsCalculator {\n public double xProjection(#Point p1, #Point p2) {\n return (p2.x - p1.x) * 1.5;\n }\n}\n</code></pre>\n\n<p>where <code>#Point</code> is the type of non-<code>null</code> references to objects of type <code>Point</code>.</p>\n" }, { "answer_id": 32791, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 0, "selected": false, "text": "<p>Thwrowing C# <code>ArgumentException</code>, or Java <code>IllegalArgumentException</code> right at the beginning of the method looks to me as the clearest of solutions. </p>\n\n<p>One should always be careful with Runtime Exceptions - exceptions that are not declared on the method signature. Since the compiler doesn't enforce you to catch these it's really easy to forget about them. Make sure you have some kind of a \"catch all\" exception handling to prevent the software to halt abruptly. That's the most important part of your user experience.</p>\n" }, { "answer_id": 32808, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 0, "selected": false, "text": "<p>The best way to handle this really would be the use of exceptions. Ultimately, the asserts are going to end up giving a <em>similar</em> experience to the end user but provide no way for the developer calling your code to handle the situation before showing an exception to the end user. Ultimatley, you want to ensure that you test for invalid inputs as early as possible (especially in public facing code) and provide the appropriate exceptions that the calling code can catch.</p>\n" }, { "answer_id": 32907, "author": "Andrei", "author_id": 2718, "author_profile": "https://Stackoverflow.com/users/2718", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default.</p>\n</blockquote>\n\n<p>I found <strong>JetBrains</strong>' <code>@Nullable</code> and <code>@NotNull</code> annotations approach for dealing with this the most ingenious, so far. It's IDE specific, unfortunately, but really clean and powerful, IMO.</p>\n\n<p><a href=\"http://www.jetbrains.com/idea/documentation/howto.html\" rel=\"nofollow noreferrer\">http://www.jetbrains.com/idea/documentation/howto.html</a> </p>\n\n<p>Having this (or something similar) as a java standard would be really nice.</p>\n" }, { "answer_id": 33552, "author": "Russell Mayor", "author_id": 2649, "author_profile": "https://Stackoverflow.com/users/2649", "pm_score": 3, "selected": true, "text": "<p>Both the use of assertions and the throwing of exceptions are valid approaches here. Either mechanism can be used to indicate a programming error, not a runtime error, as is the case here.</p>\n\n<ul>\n<li>Assertions have the advantage of performance as they are typically disabled on production systems. </li>\n<li>Exceptions have the advantage of safety, as the check is always performed. </li>\n</ul>\n\n<p>The choice really depends on the development practices of the project. The project as a whole needs to decide on an assertion policy: if the choice is to enable assertions during all development, then I'd say to use assertions to check this kind of invalid parameter - in a production system, a NullPointerException thrown due to a programming error is unlikely to be able to be caught and handled in a meaningful way anyway and so will act just like an assertion.</p>\n\n<p>Practically though, I know a lot of developers that don't trust that assertions will be enabled when appropriate and so opt for the safety of throwing a NullPointerException.</p>\n\n<p>Of course if you can't enforce a policy for your code (if you're creating a library, for example, and so are dependent on how other developers run your code), you should opt for the safe approach of throwing NullPointerException for those methods that are part of the library's API.</p>\n" }, { "answer_id": 33566, "author": "Russell Mayor", "author_id": 2649, "author_profile": "https://Stackoverflow.com/users/2649", "pm_score": 1, "selected": false, "text": "<p>Slightly off-topic, but one feature of <a href=\"http://findbugs.sourceforge.net/\" rel=\"nofollow noreferrer\">findbugs</a> that I think is very useful is to be able to annotate the parameters of methods to describe which parameters should not be passed a null value. </p>\n\n<p>Using static analysis of your code, <em>findbugs</em> can then point out locations where the method is called with a potentially null value. </p>\n\n<p>This has two advantages:</p>\n\n<ol>\n<li>The annotation describes your intention for how the method should be called, aiding documentation</li>\n<li>FindBugs can point to potential problem callers of the method, allowing you to track down potential bugs.</li>\n</ol>\n\n<p>Only useful when you have access to the code that calls your methods, but that is usually the case.</p>\n" }, { "answer_id": 33679, "author": "Damien B", "author_id": 3069, "author_profile": "https://Stackoverflow.com/users/3069", "pm_score": 0, "selected": false, "text": "<p>In a Java way, assuming the null comes from a programming error (ie. should never go outside the testing phase), then leave the system throw it, or if there are side-effects reaching that point, check for null at the beginning and throw either IllegalArgumentException or NullPointerException.</p>\n\n<p>If the null could come from an actual <em>exception</em>al case but you don't want to use a checked exception for that, then you definitely want to go the IllegalArgumentException route at the beginning of the method.</p>\n" }, { "answer_id": 248687, "author": "Marcus Downing", "author_id": 1000, "author_profile": "https://Stackoverflow.com/users/1000", "pm_score": 1, "selected": false, "text": "<p>Since off-topic seems to have become the topic, Scala takes an interesting approach to this. All types are assumed to be not null, unless you explicity wrap it in an <code>Option</code> to indicate that it might be null. So:</p>\n\n<pre><code>// allocate null\nvar name : Option[String]\nname = None\n\n// allocate a value\nname = Any[\"Hello\"]\n\n// print the value if we can\nname match {\n Any[x] =&gt; print x\n _ =&gt; print \"Nothing at all\"\n}\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3295/" ]
I am in the middle of reading the excellent [Clean Code](https://rads.stackoverflow.com/amzn/click/com/0132350882) One discussion is regarding passing nulls into a method. ``` public class MetricsCalculator { public double xProjection(Point p1, Point p2) { return (p2.x - p1.x) * 1.5; } } ... calculator.xProjection(null, new Point(12,13)); ``` It represents different ways of handling this: ``` public double xProjection(Point p1, Point p2) { if (p1 == null || p2 == null) { throw new IllegalArgumentException("Invalid argument for xProjection"); } return (p2.x - p1.x) * 1.5; } public double xProjection(Point p1, Point p2) { assert p1 != null : "p1 should not be null"; assert p2 != null : "p2 should not be null"; return (p2.x - p1.x) * 1.5; } ``` I prefer the [assertions](http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html) approach, but I don't like the fact that assertions are turned off by default. The book finally states: > > In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default. > > > It doesn't really go into how you would enforce this restriction? Do any of you have strong opinions either way.
Both the use of assertions and the throwing of exceptions are valid approaches here. Either mechanism can be used to indicate a programming error, not a runtime error, as is the case here. * Assertions have the advantage of performance as they are typically disabled on production systems. * Exceptions have the advantage of safety, as the check is always performed. The choice really depends on the development practices of the project. The project as a whole needs to decide on an assertion policy: if the choice is to enable assertions during all development, then I'd say to use assertions to check this kind of invalid parameter - in a production system, a NullPointerException thrown due to a programming error is unlikely to be able to be caught and handled in a meaningful way anyway and so will act just like an assertion. Practically though, I know a lot of developers that don't trust that assertions will be enabled when appropriate and so opt for the safety of throwing a NullPointerException. Of course if you can't enforce a policy for your code (if you're creating a library, for example, and so are dependent on how other developers run your code), you should opt for the safe approach of throwing NullPointerException for those methods that are part of the library's API.
32,332
<p>This isn't a design question, really, though it may seem like it. (Well, okay, it's kind of a design question). What I'm wondering is why the C++ <code>std::fstream</code> classes don't take a <code>std::string</code> in their constructor or open methods. Everyone loves code examples so:</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; int main() { std::string filename = "testfile"; std::ifstream fin; fin.open(filename.c_str()); // Works just fine. fin.close(); //fin.open(filename); // Error: no such method. //fin.close(); } </code></pre> <p>This gets me all the time when working with files. Surely the C++ library would use <code>std::string</code> wherever possible?</p>
[ { "answer_id": 32353, "author": "Magnus Westin", "author_id": 2957, "author_profile": "https://Stackoverflow.com/users/2957", "pm_score": 0, "selected": false, "text": "<p>Is there any class in STL that takes a string... I dont think so (couldnt find any in my quick search). So it's probably some design decision, that no class in STL should be dependent on any other STL class (that is not directly needed for functionality).</p>\n" }, { "answer_id": 32368, "author": "Christopher", "author_id": 3186, "author_profile": "https://Stackoverflow.com/users/3186", "pm_score": 4, "selected": false, "text": "<p>There are several places where the C++ standard committee did not really optimize the interaction between facilities in the standard library.</p>\n\n<p><code>std::string</code> and its use in the library is one of these.</p>\n\n<p>One other example is <code>std::swap</code>. Many containers have a swap member function, but no overload of std::swap is supplied. The same goes for <code>std::sort</code>.</p>\n\n<p>I hope all these small things will be fixed in the upcoming standard.</p>\n" }, { "answer_id": 32406, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 0, "selected": false, "text": "<p>I believe that this has been thought about and was done to avoid the dependency; i.e. #include &lt;fstream&gt; should not force one to #include &lt;string&gt;.</p>\n\n<p>To be honest, this seems like quite an inconsequential issue. A better question would be, why is std::string's interface so large?</p>\n" }, { "answer_id": 32442, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>It is inconsequential, that is true. What do you mean by std::string's interface being large? What does large mean, in this context - lots of method calls? I'm not being facetious, I am actually interested.</p>\n</blockquote>\n\n<p>It has more methods than it really needs, and its behaviour of using integral offsets rather than iterators is a bit iffy (as it's contrary to the way the rest of the library works).</p>\n\n<p>The real issue I think is that the C++ library has three parts; it has the old C library, it has the STL, and it has strings-and-iostreams. Though some efforts were made to bridge the different parts (e.g. the addition of overloads to the C library, because C++ supports overloading; the addition of iterators to basic_string; the addition of the iostream iterator adaptors), there are a lot of inconsistencies when you look at the detail.</p>\n\n<p>For example, basic_string includes methods that are unnecessary duplicates of standard algorithms; the various find methods, could probably be safely removed. Another example: locales use raw pointers instead of iterators.</p>\n" }, { "answer_id": 37542, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 6, "selected": true, "text": "<p>By taking a C string the C++03 <a href=\"http://en.cppreference.com/w/cpp/io/basic_fstream\" rel=\"noreferrer\"><code>std::fstream</code></a> class reduced dependency on the <code>std::string</code> class. In C++11, however, the <code>std::fstream</code> class does allow passing a <code>std::string</code> for its constructor parameter.</p>\n\n<p>Now, you may wonder why isn't there a transparent conversion from a <code>std:string</code> to a C string, so a class that expects a C string could still take a <code>std::string</code> just like a class that expects a <code>std::string</code> can take a C string.</p>\n\n<p>The reason is that this would cause a conversion cycle, which in turn may lead to problems. For example, suppose <code>std::string</code> would be convertible to a C string so that you could use <code>std::string</code>s with <code>fstream</code>s. Suppose also that C string are convertible to <code>std::string</code>s as is the state in the current standard. Now, consider the following:</p>\n\n<pre><code>void f(std::string str1, std::string str2);\nvoid f(char* cstr1, char* cstr2);\n\nvoid g()\n{\n char* cstr = \"abc\";\n std::string str = \"def\";\n f(cstr, str); // ERROR: ambiguous\n}\n</code></pre>\n\n<p>Because you can convert either way between a <code>std::string</code> and a C string the call to <code>f()</code> could resolve to either of the two <code>f()</code> alternatives, and is thus ambiguous. The solution is to break the conversion cycle by making one conversion direction explicit, which is what the STL chose to do with <code>c_str()</code>.</p>\n" }, { "answer_id": 62852, "author": "swmc", "author_id": 7016, "author_profile": "https://Stackoverflow.com/users/7016", "pm_score": 2, "selected": false, "text": "<p>@ Bernard:<br>\nMonoliths \"Unstrung.\" \"All for one, and one for all\" may work for Musketeers, but it doesn't work nearly as well for class designers. Here's an example that is not altogether exemplary, and it illustrates just how badly you can go wrong when design turns into overdesign. The example is, unfortunately, taken from a standard library near you...\n~ <a href=\"http://www.gotw.ca/gotw/084.htm\" rel=\"nofollow noreferrer\">http://www.gotw.ca/gotw/084.htm</a></p>\n" }, { "answer_id": 62981, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 4, "selected": false, "text": "<p>Maybe it's a consolation: all fstream's have gotten an open(string const &amp;, ...) next to the open(char const *, ...) in the working draft of the C++0x standard.\n(see e.g. 27.8.1.6 for the basic_ifstream declaration)</p>\n\n<p>So when it gets finalised and implemented, it won't get you anymore :)</p>\n" }, { "answer_id": 73620, "author": "Drealmer", "author_id": 12291, "author_profile": "https://Stackoverflow.com/users/12291", "pm_score": 3, "selected": false, "text": "<p>The stream IO library has been added to the standard C++ library before the STL. In order to not break backward compatibility, it has been decided to avoid modifying the IO library when the STL was added, even if that meant some issues like the one you raise.</p>\n" }, { "answer_id": 13326739, "author": "doug65536", "author_id": 1127972, "author_profile": "https://Stackoverflow.com/users/1127972", "pm_score": 1, "selected": false, "text": "<p>C++ grew up on smaller machines than the monsters we write code for today. Back when iostream was new many developers really cared about code size (they had to fit their entire program and data into several hundred KB). Therefore, many didn't want to pull in the \"big\" C++ string library. Many didn't even use the iostream library for the same reasons, code size.</p>\n\n<p>We didn't have thousands of megabytes of RAM to throw around like we do today. We usually didn't have function level linking so we were at the mercy of the developer of the library to use a lot of separate object files or else pull in tons of uncalled code. All of this FUD made developers steer away from std::string.</p>\n\n<p>Back then I avoided std::string too. \"Too bloated\", \"called malloc too often\", etc. Foolishly using stack-based buffers for strings, then adding all kinds of tedious code to make sure it doesn't overrun.</p>\n" }, { "answer_id": 35925171, "author": "Jonathan Birge", "author_id": 787906, "author_profile": "https://Stackoverflow.com/users/787906", "pm_score": 0, "selected": false, "text": "<p>Nowadays you can solve this problem very easily: add <code>-std=c++11</code> to your <code>CFLAGS</code>.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ]
This isn't a design question, really, though it may seem like it. (Well, okay, it's kind of a design question). What I'm wondering is why the C++ `std::fstream` classes don't take a `std::string` in their constructor or open methods. Everyone loves code examples so: ``` #include <iostream> #include <fstream> #include <string> int main() { std::string filename = "testfile"; std::ifstream fin; fin.open(filename.c_str()); // Works just fine. fin.close(); //fin.open(filename); // Error: no such method. //fin.close(); } ``` This gets me all the time when working with files. Surely the C++ library would use `std::string` wherever possible?
By taking a C string the C++03 [`std::fstream`](http://en.cppreference.com/w/cpp/io/basic_fstream) class reduced dependency on the `std::string` class. In C++11, however, the `std::fstream` class does allow passing a `std::string` for its constructor parameter. Now, you may wonder why isn't there a transparent conversion from a `std:string` to a C string, so a class that expects a C string could still take a `std::string` just like a class that expects a `std::string` can take a C string. The reason is that this would cause a conversion cycle, which in turn may lead to problems. For example, suppose `std::string` would be convertible to a C string so that you could use `std::string`s with `fstream`s. Suppose also that C string are convertible to `std::string`s as is the state in the current standard. Now, consider the following: ``` void f(std::string str1, std::string str2); void f(char* cstr1, char* cstr2); void g() { char* cstr = "abc"; std::string str = "def"; f(cstr, str); // ERROR: ambiguous } ``` Because you can convert either way between a `std::string` and a C string the call to `f()` could resolve to either of the two `f()` alternatives, and is thus ambiguous. The solution is to break the conversion cycle by making one conversion direction explicit, which is what the STL chose to do with `c_str()`.
32,333
<p>Here's a perfect example of the problem: <a href="http://blog.teksol.info/2009/03/27/argumenterror-on-number-sum-when-using-classifier-bayes.html" rel="nofollow noreferrer">Classifier gem breaks Rails</a>.</p> <p>** Original question: **</p> <p>One thing that concerns me as a security professional is that Ruby doesn't have a parallel of Java's package-privacy. That is, this isn't valid Ruby:</p> <pre><code>public module Foo public module Bar # factory method for new Bar implementations def self.new(...) SimpleBarImplementation.new(...) end def baz raise NotImplementedError.new('Implementing Classes MUST redefine #baz') end end private class SimpleBarImplementation include Bar def baz ... end end end </code></pre> <p>It'd be really nice to be able to prevent monkey-patching of Foo::BarImpl. That way, people who rely on the library know that nobody has messed with it. Imagine if somebody changed the implementation of MD5 or SHA1 on you! I can call <code>freeze</code> on these classes, but I have to do it on a class-by-class basis, and other scripts might modify them before I finish securing my application if I'm not <strong>very</strong> careful about load order.</p> <p>Java provides lots of other tools for defensive programming, many of which are not possible in Ruby. (See Josh Bloch's book for a good list.) Is this really a concern? Should I just stop complaining and use Ruby for lightweight things and not hope for "enterprise-ready" solutions?</p> <p>(And no, core classes are not frozen by default in Ruby. See below:)</p> <pre><code>require 'md5' # =&gt; true MD5.frozen? # =&gt; false </code></pre>
[ { "answer_id": 32471, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 1, "selected": false, "text": "<p>I guess Ruby has that a feature - valued more over it being a security issue. Ducktyping too.<br>\nE.g. I can add my own methods to the Ruby String class rather than extending or wrapping it.</p>\n" }, { "answer_id": 33611, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 3, "selected": false, "text": "<p>I don't think this is a concern.</p>\n\n<p>Yes, the mythical \"somebody\" can replace the implementation of MD5 with something insecure. But in order to do that, the mythical somebody must actually be able to get his code into the Ruby process. And if he can do that, then he presumably could also inject his code into a Java process and e.g. rewrite the bytecode for the MD5 operation. Or just intercept the keypresses and not actually bother with fiddling with the cryptography code at all.</p>\n\n<p>One of the typical concerns is: I'm writing this awesome library, which is supposed to be used like so:</p>\n\n<pre><code>require 'awesome'\n# Do something awesome.\n</code></pre>\n\n<p>But what if someone uses it like so:</p>\n\n<pre><code>require 'evil_cracker_lib_from_russian_pr0n_site'\n# Overrides crypto functions and sends all data to mafia\nrequire 'awesome'\n# Now everything is insecure because awesome lib uses \n# cracker lib instead of builtin\n</code></pre>\n\n<p>And the simple solution is: don't do that! Educate your users that they shouldn't run untrusted code they downloaded from obscure sources in their security critical applications. And if they do, they probably deserve it.</p>\n\n<p>To come back to your Java example: it's true that in Java you can make your crypto code <code>private</code> and <code>final</code> and what not. However, someone can <em>still</em> replace your crypto implementation! In fact, someone actually did: many open-source Java implementations use OpenSSL to implement their cryptographic routines. And, as you probably know, Debian shipped with a broken, insecure version of OpenSSL for years. So, all Java programs running on Debian for the past couple of years actually <em>did</em> run with insecure crypto!</p>\n" }, { "answer_id": 33648, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Java provides lots of other tools for defensive programming</p>\n</blockquote>\n\n<p>Initially I thought you were talking about <a href=\"http://en.wikipedia.org/wiki/Defensive_programming#Some_Defensive_programming_techniques\" rel=\"nofollow noreferrer\">normal defensive programming</a>, \nwherein the idea is to defend the program (or your subset of it, or your single function) from invalid data input.<br>\nThat's a great thing, and I encourage everyone to go read that article.</p>\n\n<p>However it seems you are actually talking about \"defending your code from other programmers.\" </p>\n\n<p>In my opinion, this is a completely pointless goal, as no matter what you do, a malicious programmer can always run your program under a debugger, or use <a href=\"http://en.wikipedia.org/wiki/DLL_injection\" rel=\"nofollow noreferrer\">dll injection</a> or any number of other techniques.</p>\n\n<p>If you are merely seeking to protect your code from incompetent co-workers, this is ridiculous. <strong>Educate your co-workers, or get better co-workers.</strong></p>\n\n<p>At any rate, if such things are of great concern to you, ruby is not the programming language for you. Monkeypatching is in there by design, and to disallow it goes against the whole point of the feature.</p>\n" }, { "answer_id": 33900, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": false, "text": "<p>\"Educate your co-workers, or get better co-workers\" works great for a small software startup, and it works great for the big guns like Google and Amazon. It's ridiculous to think that every lowly developer contracted in for some small medical charts application in a doctor's office in a minor city.</p>\n\n<p>I'm not saying we should build for the lowest common denominator, but we have to be realistic that there are <em>lots</em> of mediocre programmers out there who will pull in any library that gets the job done, paying no attention to security. How <em>could</em> they pay attention to security? Maybe the took an algorithms and data structures class. Maybe they took a compilers class. They almost certainly didn't take an encryption protocols class. They definitely haven't all read Schneier or any of the others out there who practically have to <em>beg and plead</em> with even very good programmers to consider security when building software.</p>\n\n<p>I'm not worried about this:</p>\n\n<pre><code>require 'evil_cracker_lib_from_russian_pr0n_site'\nrequire 'awesome'\n</code></pre>\n\n<p>I'm worried about <code>awesome</code> requiring <code>foobar</code> and <code>fazbot</code>, and <code>foobar</code> requiring <code>has_gumption</code>, and ... eventually two of these conflict in some obscure way that undoes an important security aspect.</p>\n\n<p>One important security principle is \"defense in depth\" -- adding these extra layers of security help you from accidentally shooting yourself in the foot. They can't completely prevent it; nothing can. But they help.</p>\n" }, { "answer_id": 161268, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 2, "selected": true, "text": "<p>Check out <a href=\"http://scie.nti.st/2008/9/17/making-methods-immutable-in-ruby\" rel=\"nofollow noreferrer\">Immutable</a> by Garry Dolley.</p>\n\n<p>You can prevent redefinition of individual methods.</p>\n" }, { "answer_id": 161278, "author": "Alex", "author_id": 24420, "author_profile": "https://Stackoverflow.com/users/24420", "pm_score": 1, "selected": false, "text": "<p>If monkey patching is your concen, you can use the Immutable module (or one of similar function). </p>\n\n<p><a href=\"http://gilesbowkett.blogspot.com/2008/09/monkey-patch-which-prohibits-monkey.html\" rel=\"nofollow noreferrer\">Immutable</a></p>\n" }, { "answer_id": 161295, "author": "Lars Westergren", "author_id": 15627, "author_profile": "https://Stackoverflow.com/users/15627", "pm_score": 1, "selected": false, "text": "<p>You could take a look at Why the Lucky Stiff's \"Sandbox\"project, which you can use if you worry about potentially running unsafe code.\n<a href=\"http://code.whytheluckystiff.net/sandbox/\" rel=\"nofollow noreferrer\">http://code.whytheluckystiff.net/sandbox/</a></p>\n\n<p>An example (online TicTacToe):\n<a href=\"http://www.elctech.com/blog/safely-exposing-your-app-to-a-ruby-sandbox\" rel=\"nofollow noreferrer\">http://www.elctech.com/blog/safely-exposing-your-app-to-a-ruby-sandbox</a></p>\n" }, { "answer_id": 297991, "author": "Tetha", "author_id": 17663, "author_profile": "https://Stackoverflow.com/users/17663", "pm_score": 0, "selected": false, "text": "<p>If someone monkeypatched an object or a module, then you need to look at 2 cases: He added a new method. If he is the only one adding this meyhod (which is very likely), then no problems arise. If he is not the only one, you need to see if both methods do the same and tell the library developer about this severe problem.</p>\n\n<p>If they change a method, you should start to research why the method was changed. Did they change it due to some edge case behaviour or did they actually fix a bug? especially in the latter case, the monkeypatch is a god thing, because it fixes a bug in many places.</p>\n\n<p>Besides that, you are using a very dynamic language with the assumption that programmers use this freedom in a sane way. The only way to remove this assumption is not to use a dynamic language. </p>\n" }, { "answer_id": 331458, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": false, "text": "<p>Raganwald has a <a href=\"http://github.com/raganwald/homoiconic/tree/master/2008-12-1/keep_your_privates_to_yourself.md\" rel=\"nofollow noreferrer\">recent post</a> about this. In the end, he builds the following:</p>\n\n<pre><code>class Module\n def anonymous_module(&amp;block)\n self.send :include, Module.new(&amp;block)\n end\nend\n\nclass Acronym\n anonymous_module do\n fu = lambda { 'fu' }\n bar = lambda { 'bar' }\n define_method :fubar do\n fu.call + bar.call\n end\n end\nend\n</code></pre>\n\n<p>That exposes <code>fubar</code> as a public method on <code>Acronym</code>s, but keeps the internal guts (<code>fu</code> and <code>bar</code>) private and hides helper module from outside view.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
Here's a perfect example of the problem: [Classifier gem breaks Rails](http://blog.teksol.info/2009/03/27/argumenterror-on-number-sum-when-using-classifier-bayes.html). \*\* Original question: \*\* One thing that concerns me as a security professional is that Ruby doesn't have a parallel of Java's package-privacy. That is, this isn't valid Ruby: ``` public module Foo public module Bar # factory method for new Bar implementations def self.new(...) SimpleBarImplementation.new(...) end def baz raise NotImplementedError.new('Implementing Classes MUST redefine #baz') end end private class SimpleBarImplementation include Bar def baz ... end end end ``` It'd be really nice to be able to prevent monkey-patching of Foo::BarImpl. That way, people who rely on the library know that nobody has messed with it. Imagine if somebody changed the implementation of MD5 or SHA1 on you! I can call `freeze` on these classes, but I have to do it on a class-by-class basis, and other scripts might modify them before I finish securing my application if I'm not **very** careful about load order. Java provides lots of other tools for defensive programming, many of which are not possible in Ruby. (See Josh Bloch's book for a good list.) Is this really a concern? Should I just stop complaining and use Ruby for lightweight things and not hope for "enterprise-ready" solutions? (And no, core classes are not frozen by default in Ruby. See below:) ``` require 'md5' # => true MD5.frozen? # => false ```
Check out [Immutable](http://scie.nti.st/2008/9/17/making-methods-immutable-in-ruby) by Garry Dolley. You can prevent redefinition of individual methods.
32,360
<p>How do you specify that a foreign key constraint should be a 1:1 relationship in transact sql? Is declaring the column UNIQUE enough? Below is my existing code.!</p> <pre><code>CREATE TABLE [dbo].MyTable( [MyTablekey] INT IDENTITY(1,1) NOT FOR REPLICATION NOT NULL, [OtherTableKey] INT NOT NULL UNIQUE CONSTRAINT [FK_MyTable_OtherTable] FOREIGN KEY REFERENCES [dbo].[OtherTable]([OtherTableKey]), ... CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ( [MyTableKey] ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO </code></pre>
[ { "answer_id": 32372, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 2, "selected": false, "text": "<p>You could declare the column to be both the primary key and a foreign key. This is a good strategy for \"extension\" tables that are used to avoid putting nullable columns into the main table.</p>\n" }, { "answer_id": 32380, "author": "Peter Meyer", "author_id": 1875, "author_profile": "https://Stackoverflow.com/users/1875", "pm_score": 0, "selected": false, "text": "<p>Based on your code above, the unique constraint would be enough given that the for every primary key you have in the table, the unique constrained column is also unique. Also, this assumes that in [OtherTable], the [OtherTableKey] column is the primary key of that table.</p>\n" }, { "answer_id": 32394, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 4, "selected": true, "text": "<p>A foreign key column with the UNIQUE and NOT NULL constraints that references a UNIQUE, NOT NULL column in another table creates a 1:(0|1) relationship, which is probably what you want.</p>\n\n<p>If there was a true 1:1 relationship, every record in the first table would have a corresponding record in the second table and vice-versa. In that case, you would probably just want to make one table (unless you needed some strange storage optimization).</p>\n" }, { "answer_id": 32632, "author": "Ivan Bosnic", "author_id": 3221, "author_profile": "https://Stackoverflow.com/users/3221", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>If there was a true 1:1 relationship, every record in the first table would have a corresponding record in the second table and vice-versa. In that case, you would probably just want to make one table (unless you needed some strange storage optimization).</p>\n</blockquote>\n\n<p>This is very incorrect. Let me give you an example. You have a table CLIENT that has a 1:1 relationship with table SALES_OFFICE because, for example, the logic of your system says so. Would you really incorporate the data of SALES_OFFICE into CLIENT table? And if another tables need to relate them selfs with SALES_OFFICE? And what about database normalization best practices and patterns?</p>\n\n<blockquote>\n <p>A foreign key column with the UNIQUE and NOT NULL constraints that references a UNIQUE, NOT NULL column in another table creates a 1:(0|1) relationship, which is probably what you want.</p>\n</blockquote>\n\n<p>The first part of your answer is the right answer, without the second part, unless the data in second table is really a kind of information that belongs to first table and never will be used by other tables.</p>\n" }, { "answer_id": 32771, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>@bosnic:</p>\n\n<blockquote>\n <p>You have a table CLIENT that has a 1:1 relationship with table SALES_OFFICE because, for example, the logic of your system says so. </p>\n</blockquote>\n\n<p>What your app logic says, and what your data model say are 2 different things. There is nothing wrong with enforcing that relationship with your business logic code, but it has no place in the data model.</p>\n\n<blockquote>\n <p>Would you really incorporate the data of SALES_OFFICE into CLIENT table? </p>\n</blockquote>\n\n<p>If every CLIENT has a unique SALES_OFFICE, and every SALES_OFFICE has a singular, unique CLIENT - then yes, they should be in the same table. We just need a better name. ;)</p>\n\n<blockquote>\n <p>And if another tables need to relate them selfs with SALES_OFFICE? </p>\n</blockquote>\n\n<p>There's no reason to. Relate your other tables to CLIENT, since CLIENT has a unique SALES_OFFICE. </p>\n\n<blockquote>\n <p>And what about database normalization best practices and patterns?</p>\n</blockquote>\n\n<p>This <em>is</em> normalization.</p>\n\n<p>To be fair, SALES_OFFICE and CLIENT is obviously not a 1:1 relationship - it's 1:N. Hopefully, your SALES_OFFICE exists to serve more than 1 client, and will continue to exist (for a while, at least) without any clients.</p>\n\n<p>A more realistic example is SALES_OFFICE and ZIP_CODE. A SALES_OFFICE must have exactly 1 ZIP_CODE, and 2 SALES_OFFICEs - even if they have an equivalent ZIP_CODE - do not share the <em>instance</em> of a ZIP_CODE (so, changing the ZIP_CODE of 1 does not impact the other). Wouldn't you agree that ZIP_CODE belongs as a column in SALES_OFFICE?</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3400/" ]
How do you specify that a foreign key constraint should be a 1:1 relationship in transact sql? Is declaring the column UNIQUE enough? Below is my existing code.! ``` CREATE TABLE [dbo].MyTable( [MyTablekey] INT IDENTITY(1,1) NOT FOR REPLICATION NOT NULL, [OtherTableKey] INT NOT NULL UNIQUE CONSTRAINT [FK_MyTable_OtherTable] FOREIGN KEY REFERENCES [dbo].[OtherTable]([OtherTableKey]), ... CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ( [MyTableKey] ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ```
A foreign key column with the UNIQUE and NOT NULL constraints that references a UNIQUE, NOT NULL column in another table creates a 1:(0|1) relationship, which is probably what you want. If there was a true 1:1 relationship, every record in the first table would have a corresponding record in the second table and vice-versa. In that case, you would probably just want to make one table (unless you needed some strange storage optimization).
32,369
<p>One of the joys of working for a government healthcare agency is having to deal with all of the paranoia around dealing with PHI (Protected Health Information). Don't get me wrong, I'm all for doing everything possible to protect people's personal information (health, financial, surfing habits, etc.), but sometimes people get a little too jumpy.</p> <p>Case in point: One of our state customers recently found out that the browser provides the handy feature to save your password. We all know that it has been there for a while and is completely optional and is up to the end user to decide whether or not it is a smart decision to use or not. However, there is a bit of an uproar at the moment and we are being demanded to find a way to disable that functionality for our site.</p> <p><strong>Question</strong>: Is there a way for a site to tell the browser not to offer to remember passwords? I've been around web development a long time but don't know that I have come across that before.</p> <p>Any help is appreciated.</p>
[ { "answer_id": 32378, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 3, "selected": false, "text": "<p>Not really - the only thing you could realistically do is offer advice on the site; maybe, before their first time signing in, you could show them a form with information indicating that it is not recommended that they allow the browser to store the password.</p>\n\n<p>Then the user will immediately follow the advice, write down the password on a post-it note and tape it to their monitor.</p>\n" }, { "answer_id": 32386, "author": "Markus Olsson", "author_id": 2114, "author_profile": "https://Stackoverflow.com/users/2114", "pm_score": 9, "selected": true, "text": "<p>I'm not sure if it'll work in all browsers but you should try setting autocomplete=&quot;off&quot; on the form.</p>\n<pre><code>&lt;form id=&quot;loginForm&quot; action=&quot;login.cgi&quot; method=&quot;post&quot; autocomplete=&quot;off&quot;&gt;\n</code></pre>\n<blockquote>\n<p>The easiest and simplest way to disable Form <strong>and Password storage prompts</strong> and prevent form data from being cached in session history is to use the autocomplete form element attribute with value &quot;off&quot;.</p>\n</blockquote>\n<blockquote>\n<p>From <a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion</a></p>\n</blockquote>\n<p>Some minor research shows that this works in IE to but I'll leave no guarantees ;)</p>\n<p><a href=\"https://stackoverflow.com/questions/32369/disable-browser-save-password-functionality#32408\">@Joseph</a>: If it's a strict requirement to pass XHTML validation with the actual markup (don't know why it would be though) you could theoretically add this attribute with javascript afterwards but then users with js disabled (probably a neglectable amount of your userbase or zero if your site requires js) will still have their passwords saved.</p>\n<p>Example with jQuery:</p>\n<pre><code>$('#loginForm').attr('autocomplete', 'off');\n</code></pre>\n" }, { "answer_id": 32388, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": -1, "selected": false, "text": "<blockquote>\n <p>Is there a way for a site to tell the browser not to offer to remember passwords?</p>\n</blockquote>\n\n<p>The website tells the browser that it is a password by using <code>&lt;input type=\"password\"&gt;</code>. So if you <em>must</em> do this from a website perspective then you would have to change that. (Obviously I don't recommend this).</p>\n\n<p>The best solution would be to have the user configure their browser so it won't remember passwords.</p>\n" }, { "answer_id": 32390, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 0, "selected": false, "text": "<p>One way I know is to use (for instance) JavaScript to copy the value out of the password field before submitting the form.</p>\n\n<p>The main problem with this is that the solution is tied to JavaScript.</p>\n\n<p>Then again, if it can be tied to JavaScript you might as well hash the password on the client-side before sending a request to the server.</p>\n" }, { "answer_id": 32408, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": 1, "selected": false, "text": "<p>Markus raised a great point. I decided to look up the <code>autocomplete</code> attribute and got the following: </p>\n\n<blockquote>\n <p>The only downside to using this\n attribute is that it is not standard\n (it works in IE and Mozilla browsers),\n and would cause XHTML validation to\n fail. I think this is a case where\n it's reasonable to break validation\n however. <em>(<a href=\"http://www.petefreitag.com/item/481.cfm\" rel=\"nofollow noreferrer\">source</a>)</em></p>\n</blockquote>\n\n<p>So I would have to say that although it doesn't work 100% across the board it is handled in the major browsers so its a great solution.</p>\n" }, { "answer_id": 32409, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": false, "text": "<p>You can prevent the browser from matching the forms up by randomizing the name used for the password field on each show. Then the browser sees a password for the same the url, but can't be sure it's the <em>same password</em>. Maybe it's controlling something else.</p>\n<p><strong>Update:</strong> note that this should be <em>in addition to</em> using autocomplete or other tactics, not a replacement for them, for the reasons indicated by others.</p>\n<p>Also note that this will only prevent the browser from <em>auto-completing</em> the password. It won't prevent it from <em>storing</em> the password in whatever level of arbitrary security the browser chooses to use.</p>\n" }, { "answer_id": 380647, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 4, "selected": false, "text": "<p>Use real <a href=\"http://en.wikipedia.org/wiki/Two-factor_authentication\" rel=\"noreferrer\">two-factor authentication</a> to avoid the sole dependency on passwords which might be stored in many more places than the user's browser cache.</p>\n" }, { "answer_id": 2359480, "author": "Howard Young", "author_id": 283958, "author_profile": "https://Stackoverflow.com/users/283958", "pm_score": 3, "selected": false, "text": "<p>What I have been doing is a combination of autocomplete=\"off\" and clearing password fields using a javascript / jQuery.</p>\n\n<p>jQuery Example:</p>\n\n<pre><code>$(function() { \n $('#PasswordEdit').attr(\"autocomplete\", \"off\");\n setTimeout('$(\"#PasswordEdit\").val(\"\");', 50); \n});\n</code></pre>\n\n<p>By using <code>setTimeout()</code> you can wait for the browser to complete the field before you clear it, otherwise the browser will always autocomplete after you've clear the field.</p>\n" }, { "answer_id": 2555771, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 5, "selected": false, "text": "<p>I had been struggling with this problem a while, with a unique twist to the problem. Privileged users couldn't have the saved passwords work for them, but normal users needed it. This meant privileged users had to log in twice, the second time enforcing no saved passwords.</p>\n\n<p>With this requirement, the standard <code>autocomplete=\"off\"</code> method doesn't work across all browsers, because the password may have been saved from the first login. A colleague found a solution to replace the password field when it was focused with a new password field, and then focus on the new password field (then hook up the same event handler). This worked (except it caused an infinite loop in IE6). Maybe there was a way around that, but it was causing me a migraine.</p>\n\n<p>Finally, I tried to just have the username and password outside of the form. To my surprise, this worked! It worked on IE6, and current versions of Firefox and Chrome on Linux. I haven't tested it further, but I suspect it works in most if not all browsers (but it wouldn't surprise me if there was a browser out there that didn't care if there was no form).</p>\n\n<p>Here is some sample code, along with some jQuery to get it to work:</p>\n\n<pre><code>&lt;input type=\"text\" id=\"username\" name=\"username\"/&gt;\n&lt;input type=\"password\" id=\"password\" name=\"password\"/&gt;\n\n&lt;form id=\"theForm\" action=\"/your/login\" method=\"post\"&gt;\n &lt;input type=\"hidden\" id=\"hiddenUsername\" name=\"username\"/&gt;\n &lt;input type=\"hidden\" id=\"hiddenPassword\" name=\"password\"/&gt;\n &lt;input type=\"submit\" value=\"Login\"/&gt;\n&lt;/form&gt;\n\n&lt;script type=\"text/javascript\" language=\"JavaScript\"&gt;\n $(\"#theForm\").submit(function() {\n $(\"#hiddenUsername\").val($(\"#username\").val());\n $(\"#hiddenPassword\").val($(\"#password\").val());\n });\n $(\"#username,#password\").keypress(function(e) {\n if (e.which == 13) {\n $(\"#theForm\").submit();\n }\n });\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 4917668, "author": "Thrawn", "author_id": 605867, "author_profile": "https://Stackoverflow.com/users/605867", "pm_score": 2, "selected": false, "text": "<p>Just so people realise - the 'autocomplete' attribute works most of the time, but power users can get around it using a bookmarklet.</p>\n\n<p>Having a browser save your passwords actually increases protection against keylogging, so possibly the safest option is to save passwords in the browser but protect them with a master password (at least in Firefox).</p>\n" }, { "answer_id": 5676880, "author": "Peter Nelson", "author_id": 709813, "author_profile": "https://Stackoverflow.com/users/709813", "pm_score": -1, "selected": false, "text": "<p>autocomplete=\"off\" works for most modern browsers, but another method I used that worked successfully with Epiphany (a WebKit-powered browser for GNOME) is to store a randomly generated prefix in session state (or a hidden field, I happened to have a suitable variable in session state already), and use this to alter the name of the fields. Epiphany still wants to save the password, but when going back to the form it won't populate the fields.</p>\n" }, { "answer_id": 10305547, "author": "Spechal", "author_id": 427387, "author_profile": "https://Stackoverflow.com/users/427387", "pm_score": -1, "selected": false, "text": "<p>I haven't had any issues using this method:</p>\n\n<p>Use autocomplete=\"off\", add a hidden password field and then another non-hidden one. The browser tries to auto complete the hidden one if it doesn't respect autocomplete=\"off\"</p>\n" }, { "answer_id": 10853609, "author": "Tom", "author_id": 1431092, "author_profile": "https://Stackoverflow.com/users/1431092", "pm_score": -1, "selected": false, "text": "<p>If you do not want to trust the autocomplete flag, you can make sure that the user types in the box using the onchange event. The code below is a simple HTML form. The hidden form element password_edited starts out set to 0. When the value of password is changed, the JavaScript at the top (pw_edited function) changes the value to 1. When the button is pressed, it checks the valueenter code here before submitting the form. That way, even if the browser ignores you and autocompletes the field, the user cannot pass the login page without typing in the password field. Also, make sure to blank the password field when focus is set. Otherwise, you can add a character at the end, then go back and remove it to trick the system. I recommend adding the autocomplete=\"off\" to password in addition, but this example shows how the backup code works.</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;script&gt;\n function pw_edited() {\n document.this_form.password_edited.value = 1;\n }\n function pw_blank() {\n document.this_form.password.value = \"\";\n }\n function submitf() {\n if(document.this_form.password_edited.value &lt; 1) {\n alert(\"Please Enter Your Password!\");\n }\n else {\n document.this_form.submit();\n }\n }\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;form name=\"this_form\" method=\"post\" action=\"../../cgi-bin/yourscript.cgi?login\"&gt;\n &lt;div style=\"padding-left:25px;\"&gt;\n &lt;p&gt;\n &lt;label&gt;User:&lt;/label&gt;\n &lt;input name=\"user_name\" type=\"text\" class=\"input\" value=\"\" size=\"30\" maxlength=\"60\"&gt;\n &lt;/p&gt;\n &lt;p&gt;\n &lt;label&gt;Password:&lt;/label&gt;\n &lt;input name=\"password\" type=\"password\" class=\"input\" size=\"20\" value=\"\" maxlength=\"50\" onfocus=\"pw_blank();\" onchange=\"pw_edited();\"&gt;\n &lt;/p&gt;\n &lt;p&gt;\n &lt;span id=\"error_msg\"&gt;&lt;/span&gt;\n &lt;/p&gt;\n &lt;p&gt;\n &lt;input type=\"hidden\" name=\"password_edited\" value=\"0\"&gt;\n &lt;input name=\"submitform\" type=\"button\" class=\"button\" value=\"Login\" onclick=\"return submitf();\"&gt;\n &lt;/p&gt;\n &lt;/div&gt;\n &lt;/form&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 11141892, "author": "Marcelo Finki", "author_id": 996605, "author_profile": "https://Stackoverflow.com/users/996605", "pm_score": -1, "selected": false, "text": "<p>IMHO,<br/>\nThe best way is to randomize the name of the input field that has <code>type=password</code>.\nUse a prefix of \"pwd\" and then a random number.\nCreate the field dynamically and present the form to the user.</p>\n\n<p>Your log-in form will look like...</p>\n\n<pre><code>&lt;form&gt;\n &lt;input type=password id=pwd67584 ...&gt;\n &lt;input type=text id=username ...&gt;\n &lt;input type=submit&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Then, on the server side, when you analyze the form posted by the client, catch the field with a name that starts with \"pwd\" and use it as 'password'.</p>\n" }, { "answer_id": 14733402, "author": "Lord of the Goo", "author_id": 277389, "author_profile": "https://Stackoverflow.com/users/277389", "pm_score": -1, "selected": false, "text": "<p>Another solution is to make the POST using an hidden form where all the input are of type hidden. The visible form will use input of type \"password\". The latter form will never be submitted and so the browser can't intercept at all the operation of login.</p>\n" }, { "answer_id": 19223143, "author": "venimus", "author_id": 623288, "author_profile": "https://Stackoverflow.com/users/623288", "pm_score": 4, "selected": false, "text": "<p>The cleanest way is to use <code>autocomplete=\"off\"</code> tag attribute but\nFirefox does not properly obey it when you switch fields with Tab.</p>\n\n<p>The only way you could stop this is to add a fake hidden password field which tricks the browser to populate the password there.</p>\n\n<pre><code>&lt;input type=\"text\" id=\"username\" name=\"username\"/&gt;\n&lt;input type=\"password\" id=\"prevent_autofill\" autocomplete=\"off\" style=\"display:none\" tabindex=\"-1\" /&gt;\n&lt;input type=\"password\" id=\"password\" autocomplete=\"off\" name=\"password\"/&gt;\n</code></pre>\n\n<p>It is an ugly hack, because you change the browser behavior, which should be considered bad practice. Use it only if you really need it.</p>\n\n<p>Note: this will effectively stop password autofill, because FF will \"save\" the value of <code>#prevent_autofill</code> (which is empty) and will try to populate any saved passwords there, as it always uses the first <code>type=\"password\"</code> input it finds in DOM after the respective \"username\" input.</p>\n" }, { "answer_id": 20968859, "author": "Biau", "author_id": 3168622, "author_profile": "https://Stackoverflow.com/users/3168622", "pm_score": -1, "selected": false, "text": "<p>i think by putting autocomplete=\"off\" does not help at all</p>\n\n<p>i have alternative solution,</p>\n\n<pre><code>&lt;input type=\"text\" name=\"preventAutoPass\" id=\"preventAutoPass\" style=\"display:none\" /&gt;\n</code></pre>\n\n<p>add this before your password input. </p>\n\n<p>eg:<code>&lt;input type=\"text\" name=\"txtUserName\" id=\"txtUserName\" /&gt;\n&lt;input type=\"text\" name=\"preventAutoPass\" id=\"preventAutoPass\" style=\"display:none\" /&gt;\n&lt;input type=\"password\" name=\"txtPass\" id=\"txtPass\" autocomplete=\"off\" /&gt;</code></p>\n\n<p>this does not prevent browser ask and save the password. but it prevent the password to be filled in.</p>\n\n<p>cheer</p>\n" }, { "answer_id": 22215004, "author": "JW Lim", "author_id": 3155705, "author_profile": "https://Stackoverflow.com/users/3155705", "pm_score": -1, "selected": false, "text": "<p>Since Internet Explorer 11 no longer supports <code>autocomplete=\"off\"</code> for <code>input type=\"password\"</code> fields (hopefully no other browsers will follow their lead), the cleanest approach (at the time of writing) seems to be making users submit their username and password in different pages, i.e. the user enters their username, submit, then enters their password and submit. The <a href=\"https://www.bankofamerica.com/\" rel=\"nofollow noreferrer\">Bank Of America</a> and <a href=\"https://www.us.hsbc.com/1/2/home/personal-banking\" rel=\"nofollow noreferrer\">HSBC Bank</a> websites are using this, too.</p>\n\n<p>Because the browser is unable to associate the password with a username, it will not offer to store passwords. This approach works in all major browsers (at the time of writing) and will function properly without the use of Javascript. The downsides are that it would be more troublesome for the user, and would take 2 postbacks for a login action instead of one, so it really depends on how secure your website needs to be.</p>\n\n<p>Update: As mentioned in this <a href=\"https://stackoverflow.com/questions/32369/disable-browser-save-password-functionality/22215004#comment36051950_32386\">comment</a> by <a href=\"https://stackoverflow.com/users/119975/gregory-cosmo-haun\">Gregory</a>, Firefox will be following IE11's lead and ignore <code>autocomplete=\"off\"</code> for password fields.</p>\n" }, { "answer_id": 23927796, "author": "Asik", "author_id": 1387002, "author_profile": "https://Stackoverflow.com/users/1387002", "pm_score": 4, "selected": false, "text": "<p>I have tested that adding autocomplete=\"off\" in form tag in all major browsers. In fact, Most of the peoples in US using IE8 so far.</p>\n\n<ol>\n<li>IE8, IE9, IE10, Firefox, Safari are works fine. \n\n<blockquote>\n <p>Browser not asking \"save password\". \n Also, previously saved username &amp; password not populated.</p>\n</blockquote></li>\n<li>Chrome &amp; IE 11 not supporting the autocomplete=\"off\" feature</li>\n<li>FF supporting the autocomplete=\"off\". but sometimes existing saved\ncredentials are populated.</li>\n</ol>\n\n<p><strong>Updated on June 11, 2014</strong></p>\n\n<p>Finally, below is a cross browser solution using javascript and it is working fine in all browsers.</p>\n\n<p>Need to remove \"form\" tag in login form. After client side validation, put that credentials in hidden form and submit it.</p>\n\n<p>Also, add two methods. one for validation \"validateLogin()\" and another for listening enter event while click enter in textbox/password/button \"checkAndSubmit()\". because now login form does not have a form tag, so enter event not working here.</p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code>&lt;form id=\"HiddenLoginForm\" action=\"\" method=\"post\"&gt;\n&lt;input type=\"hidden\" name=\"username\" id=\"hidden_username\" /&gt;\n&lt;input type=\"hidden\" name=\"password\" id=\"hidden_password\" /&gt;\n&lt;/form&gt;\n\nUsername: &lt;input type=\"text\" name=\"username\" id=\"username\" onKeyPress=\"return checkAndSubmit(event);\" /&gt; \nPassword: &lt;input type=\"text\" name=\"password\" id=\"password\" onKeyPress=\"return checkAndSubmit(event);\" /&gt; \n&lt;input type=\"button\" value=\"submit\" onClick=\"return validateAndLogin();\" onKeyPress=\"return checkAndSubmit(event);\" /&gt; \n</code></pre>\n\n<p><strong>Javascript</strong></p>\n\n<pre><code>//For validation- you can modify as you like\nfunction validateAndLogin(){\n var username = document.getElementById(\"username\");\n var password = document.getElementById(\"password\");\n\n if(username &amp;&amp; username.value == ''){\n alert(\"Please enter username!\");\n return false;\n }\n\n if(password &amp;&amp; password.value == ''){\n alert(\"Please enter password!\");\n return false;\n }\n\n document.getElementById(\"hidden_username\").value = username.value;\n document.getElementById(\"hidden_password\").value = password.value;\n document.getElementById(\"HiddenLoginForm\").submit();\n}\n\n//For enter event\nfunction checkAndSubmit(e) {\n if (e.keyCode == 13) {\n validateAndLogin();\n }\n}\n</code></pre>\n\n<p>Good luck!!!</p>\n" }, { "answer_id": 24428343, "author": "ruruskyi", "author_id": 372939, "author_profile": "https://Stackoverflow.com/users/372939", "pm_score": 1, "selected": false, "text": "<p>The real problem is much deeper than just adding attributes to your HTML - this is common security concern, that's why people invented hardware keys and other crazy things for security. </p>\n\n<p>Imagine you have autocomplete=\"off\" perfectly working in all browsers. Would that help with security? Of course, no. Users will write down their passwords in textbooks, on stickers attached to their monitor where every office visitor can see them, save them to text files on the desktop and so on.</p>\n\n<p>Generally, web application and web developer isn't responsible in any way for end-user security. End-users can protect themselves only. Ideally, they MUST keep all passwords in their head and use password reset functionality (or contact administrator) in case they forgot it. Otherwise there always will be a risk that password can be seen and stolen somehow.</p>\n\n<p>So either you have some crazy security policy with hardware keys (like, some banks offer for Internet-banking which basically employs two-factor authentication) or NO SECURITY basically. Well, this is a bit over exaggerated of course. It's important to understand what are you trying to protect against:</p>\n\n<ol>\n<li>Not authorised access. Simplest login form is enough basically. There sometimes additional measures taken like random security questions, CAPTCHAs, password hardening etc.</li>\n<li>Credential sniffing. HTTPS is A MUST if people access your web application from public Wi-Fi hotspots etc. Mention that even having HTTPS, your users need to change their passwords regularly. </li>\n<li>Insider attack. There are two many examples of such, starting from simple stealing of your passwords from browser or those that you have written down somewhere on the desk (does not require any IT skills) and ending with session forging and intercepting local network traffic (even encrypted) and further accessing web application just like it was another end-user.</li>\n</ol>\n\n<p>In this particular post, I can see inadequate requirements put on developer which he will never be able to resolve due to the nature of the problem - end-user security. My subjective point is that developer should basically say NO and point on requirement problem rather than wasting time on such tasks, honestly. This does not absolutely make your system more secure, it will rather lead to the cases with stickers on monitors. Unfortunately, some bosses hear only what they want to hear. However, if I was you I would try to explain where the actual problem is coming from, and that autocomplete=\"off\" would not resolve it unless it will force users to keep all their passwords exclusively in their head! Developer on his end cannot protect users completely, users need to know how to use system and at the same time do not expose their sensitive/secure information and this goes far beyond authentication. </p>\n" }, { "answer_id": 24570452, "author": "Nikhil Dinesh", "author_id": 735597, "author_profile": "https://Stackoverflow.com/users/735597", "pm_score": 2, "selected": false, "text": "<p>if autocomplete=\"off\" is not working...remove the form tag and use a div tag instead, then pass the form values using jquery to the server. This worked for me.</p>\n" }, { "answer_id": 24955110, "author": "Dai Bok", "author_id": 198762, "author_profile": "https://Stackoverflow.com/users/198762", "pm_score": 2, "selected": false, "text": "<p>I have a work around, which may help. </p>\n\n<p>You could make a custom font hack. So, make a custom font, with all the characters as a dot / circle / star for example. Use this as a custom font for your website. Check how to do this in inkscape: <a href=\"http://www.youtube.com/watch?v=_KX-e6sijGE\" rel=\"nofollow\">how to make your own font</a></p>\n\n<p>Then on your log in form use:</p>\n\n<pre><code>&lt;form autocomplete='off' ...&gt;\n &lt;input type=\"text\" name=\"email\" ...&gt;\n &lt;input type=\"text\" name=\"password\" class=\"password\" autocomplete='off' ...&gt;\n &lt;input type=submit&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Then add your css:</p>\n\n<pre><code>@font-face {\n font-family: 'myCustomfont';\n src: url('myCustomfont.eot');\n src: url('myCustomfont?#iefix') format('embedded-opentype'),\n url('myCustomfont.woff') format('woff'),\n url('myCustomfont.ttf') format('truetype'),\n url('myCustomfont.svg#myCustomfont') format('svg');\n font-weight: normal;\n font-style: normal;\n\n}\n.password {\n font-family:'myCustomfont';\n}\n</code></pre>\n\n<p>Pretty cross browser compatible. I have tried IE6+, FF, Safari and Chrome. Just make sure that the oet font that you convert does not get corrupted. Hope it helps?</p>\n" }, { "answer_id": 25111774, "author": "whyAto8", "author_id": 1122463, "author_profile": "https://Stackoverflow.com/users/1122463", "pm_score": 5, "selected": false, "text": "<p>Well, its a very old post, but still I will give my solution, which my team had been trying to achieve for long. We just added a new input type=\"password\" field inside the form and wrapped it in div and made the div hidden. Made sure that this div is before the actual password input. \nThis worked for us and it didn't gave any Save Password option</p>\n\n<p>Plunk - <a href=\"http://plnkr.co/edit/xmBR31NQMUgUhYHBiZSg?p=preview\">http://plnkr.co/edit/xmBR31NQMUgUhYHBiZSg?p=preview</a> </p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;form method=\"post\" action=\"yoururl\"&gt;\n &lt;div class=\"hidden\"&gt;\n &lt;input type=\"password\"/&gt;\n &lt;/div&gt;\n &lt;input type=\"text\" name=\"username\" placeholder=\"username\"/&gt;\n &lt;input type=\"password\" name=\"password\" placeholder=\"password\"/&gt;\n &lt;/form&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>.hidden {display:none;}\n</code></pre>\n" }, { "answer_id": 25198684, "author": "Naradana", "author_id": 1555826, "author_profile": "https://Stackoverflow.com/users/1555826", "pm_score": -1, "selected": false, "text": "<p>autocomplete=\"off\" does not work for disabling the password manager in Firefox 31 and most likely not in some earlier versions, too.</p>\n\n<p>Checkout the discussion at mozilla about this issue:\n<a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=956906\" rel=\"nofollow\">https://bugzilla.mozilla.org/show_bug.cgi?id=956906</a></p>\n\n<p>We wanted to use a second password field to enter a one-time password generated by a token. Now we are using a text input instead of a password input. :-(</p>\n" }, { "answer_id": 31655148, "author": "Sheiky", "author_id": 3732989, "author_profile": "https://Stackoverflow.com/users/3732989", "pm_score": -1, "selected": false, "text": "<p>I was given a similar task to disable the auto-filling up of login name and passwords by browser, after lot of trial and errors i found the below solution to be optimal. Just add the below controls before your original controls.</p>\n\n<pre><code>&lt;input type=\"text\" style=\"display:none\"&gt;\n&lt;input type=\"text\" name=\"OriginalLoginTextBox\"&gt;\n\n&lt;input type=\"password\" style=\"display:none\"&gt;\n&lt;input type=\"text\" name=\"OriginalPasswordTextBox\"&gt;\n</code></pre>\n\n<p>This is working fine for IE11 and Chrome 44.0.2403.107 </p>\n" }, { "answer_id": 31813922, "author": "knee-cola", "author_id": 268905, "author_profile": "https://Stackoverflow.com/users/268905", "pm_score": 2, "selected": false, "text": "<p>The simplest way to solve this problem is to place INPUT fields outside the FORM tag and add two hidden fields inside the FORM tag. Then in a submit event listener before the form data gets submitted to server copy values from visible input to the invisible ones.</p>\n\n<p>Here's an example (you can't run it here, since the form action is not set to a real login script):</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;!doctype html&gt;\r\n&lt;html&gt;\r\n&lt;head&gt;\r\n &lt;title&gt;Login &amp; Save password test&lt;/title&gt;\r\n &lt;meta charset=\"utf-8\"&gt;\r\n &lt;script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;/head&gt;\r\n\r\n &lt;body&gt;\r\n &lt;!-- the following fields will show on page, but are not part of the form --&gt;\r\n &lt;input class=\"username\" type=\"text\" placeholder=\"Username\" /&gt;\r\n &lt;input class=\"password\" type=\"password\" placeholder=\"Password\" /&gt;\r\n\r\n &lt;form id=\"loginForm\" action=\"login.aspx\" method=\"post\"&gt;\r\n &lt;!-- thw following two fields are part of the form, but are not visible --&gt;\r\n &lt;input name=\"username\" id=\"username\" type=\"hidden\" /&gt;\r\n &lt;input name=\"password\" id=\"password\" type=\"hidden\" /&gt;\r\n &lt;!-- standard submit button --&gt;\r\n &lt;button type=\"submit\"&gt;Login&lt;/button&gt;\r\n &lt;/form&gt;\r\n\r\n &lt;script&gt;\r\n // attache a event listener which will get called just before the form data is sent to server\r\n $('form').submit(function(ev) {\r\n console.log('xxx');\r\n // read the value from the visible INPUT and save it to invisible one\r\n // ... so that it gets sent to the server\r\n $('#username').val($('.username').val());\r\n $('#password').val($('.password').val());\r\n });\r\n &lt;/script&gt;\r\n\r\n &lt;/body&gt;\r\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 32281293, "author": "ovalek", "author_id": 1102219, "author_profile": "https://Stackoverflow.com/users/1102219", "pm_score": 2, "selected": false, "text": "<p>My js (jquery) workaround is to <strong>change password input type to text on form submit</strong>. The password could become visible for a second, so I also hide the input just before that. <strong>I would rather not use this for login forms</strong>, but it is useful (together with autocomplete=\"off\") for example inside administration part of the website.</p>\n\n<p>Try putting this inside a console (with jquery), before you submit the form.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>$('form').submit(function(event) {\n $(this).find('input[type=password]').css('visibility', 'hidden').attr('type', 'text');\n});\n</code></pre>\n\n\n\n<p>Tested on Chrome 44.0.2403.157 (64-bit).</p>\n" }, { "answer_id": 36073643, "author": "Mike", "author_id": 4240993, "author_profile": "https://Stackoverflow.com/users/4240993", "pm_score": 0, "selected": false, "text": "<p>Facing the same HIPAA issue and found a relatively easy solution,</p>\n\n<ol>\n<li><p>Create a hidden password field with the field name as an array.</p>\n\n<pre><code>&lt;input type=\"password\" name=\"password[]\" style=\"display:none\" /&gt;\n</code></pre></li>\n<li><p>Use the same array for the actual password field.</p>\n\n<pre><code>&lt;input type=\"password\" name=\"password[]\" /&gt;\n</code></pre></li>\n</ol>\n\n<p>The browser (Chrome) may prompt you to \"Save password\" but regardless if the user selects save, the next time they login the password will auto-populate the hidden password field, the zero slot in the array, leaving the 1st slot blank.</p>\n\n<p>I tried defining the array, such as \"password[part2]\" but it still remembered. I think it throws it off if it's an unindexed array because it has no choice but to drop it in the first spot.</p>\n\n<p>Then you use your programming language of choice to access the array, PHP for example,</p>\n\n<pre><code>echo $_POST['password'][1];\n</code></pre>\n" }, { "answer_id": 37292424, "author": "Murat Yıldız", "author_id": 1604048, "author_profile": "https://Stackoverflow.com/users/1604048", "pm_score": 6, "selected": false, "text": "<blockquote>\n <p>In addition to</p>\n</blockquote>\n\n<pre><code>autocomplete=\"off\"\n</code></pre>\n\n<blockquote>\n <p>Use</p>\n</blockquote>\n\n<pre><code>readonly onfocus=\"this.removeAttribute('readonly');\"\n</code></pre>\n\n<p>for the inputs that you do not want them to remember form data (<code>username</code>, <code>password</code>, etc.) as shown below: </p>\n\n<pre><code>&lt;input type=\"text\" name=\"UserName\" autocomplete=\"off\" readonly \n onfocus=\"this.removeAttribute('readonly');\" &gt;\n\n&lt;input type=\"password\" name=\"Password\" autocomplete=\"off\" readonly \n onfocus=\"this.removeAttribute('readonly');\" &gt;\n</code></pre>\n\n<p>Tested on the latest versions of the major browsers i.e. <code>Google Chrome</code>, <code>Mozilla Firefox</code>, <code>Microsoft Edge</code>, etc. and works like a charm. Hope this helps.</p>\n" }, { "answer_id": 42929645, "author": "Lasitha Benaragama", "author_id": 853671, "author_profile": "https://Stackoverflow.com/users/853671", "pm_score": 1, "selected": false, "text": "<p>I tried above <code>autocomplete=\"off\"</code> and yet anything successful. if you are using angular js my recommendation is to go with button and the ng-click. </p>\n\n<pre><code>&lt;button type=\"button\" class=\"\" ng-click=\"vm.login()\" /&gt;\n</code></pre>\n\n<p>This already have a accepted answer im adding this if someone cant solve the problem with the accepted answer he can go with my mechanism. </p>\n\n<p>Thanks for the question and the answers. </p>\n" }, { "answer_id": 43206336, "author": "mfernandes", "author_id": 1892887, "author_profile": "https://Stackoverflow.com/users/1892887", "pm_score": 2, "selected": false, "text": "<p>Because autocomplete=\"off\" does not work for password fields, one must rely on javascript. Here's a simple solution based on answers found here.</p>\n\n<p>Add the attribute data-password-autocomplete=\"off\" to your password field:</p>\n\n<pre><code>&lt;input type=\"password\" data-password-autocomplete=\"off\"&gt;\n</code></pre>\n\n<p>Include the following JS:</p>\n\n<pre><code>$(function(){\n $('[data-password-autocomplete=\"off\"]').each(function() {\n $(this).prop('type', 'text');\n $('&lt;input type=\"password\"/&gt;').hide().insertBefore(this);\n $(this).focus(function() {\n $(this).prop('type', 'password');\n });\n }); \n});\n</code></pre>\n\n<p>This solution works for both Chrome and FF.</p>\n" }, { "answer_id": 43353829, "author": "Cedric Simon", "author_id": 2838910, "author_profile": "https://Stackoverflow.com/users/2838910", "pm_score": 2, "selected": false, "text": "<p>I tested lots of solutions. Dynamic password field name, multiple password fields (invisible for fake ones), changing input type from \"text\" to \"password\", autocomplete=\"off\", autocomplete=\"new-password\",... but nothing solved it with recent browser.</p>\n\n<p>To get rid of password remember, I finally treated the password as input field, and \"blur\" the text typed. </p>\n\n<p>It is less \"safe\" than a native password field since selecting the typed text would show it as clear text, but password is not remembered. It also depends on having Javascript activated.</p>\n\n<p>You will have estimate the risk of using below proposal vs password remember option from navigator.</p>\n\n<p>While password remember can be managed (disbaled per site) by the user, it's fine for a personal computer, not for a \"public\" or shared computer.</p>\n\n<p>I my case it's for a ERP running on shared computers, so I'll give it a try to my solution below. </p>\n\n<pre><code>&lt;input style=\"background-color: rgb(239, 179, 196); color: black; text-shadow: none;\" name=\"password\" size=\"10\" maxlength=\"30\" onfocus=\"this.value='';this.style.color='black'; this.style.textShadow='none';\" onkeypress=\"this.style.color='transparent'; this.style.textShadow='1px 1px 6px green';\" autocomplete=\"off\" type=\"text\"&gt;\n</code></pre>\n" }, { "answer_id": 49114022, "author": "CubicleSoft", "author_id": 917198, "author_profile": "https://Stackoverflow.com/users/917198", "pm_score": 0, "selected": false, "text": "<p>Since most of the <code>autocomplete</code> suggestions, including the accepted answer, don't work in today's web browsers (i.e. web browser password managers ignore <code>autocomplete</code>), a more novel solution is to swap between <code>password</code> and <code>text</code> types and make the background color match the text color when the field is a plain text field, which continues to hide the password while being a real password field when the user (or a program like KeePass) is entering a password. Browsers don't ask to save passwords that are stored in plain text fields.</p>\n\n<p>The advantage of this approach is that it allows for progressive enhancement and therefore doesn't require Javascript for a field to function as a normal password field (you could also start with a plain text field instead and apply the same approach but that's not really HIPAA PHI/PII-compliant). Nor does this approach depend on hidden forms/fields which might not necessarily be sent to the server (because they are hidden) and some of those tricks also don't work either in several modern browsers.</p>\n\n<p>jQuery plugin:</p>\n\n<p><a href=\"https://github.com/cubiclesoft/php-flexforms-modules/blob/master/password-manager/jquery.stoppasswordmanager.js\" rel=\"nofollow noreferrer\">https://github.com/cubiclesoft/php-flexforms-modules/blob/master/password-manager/jquery.stoppasswordmanager.js</a></p>\n\n<p>Relevant source code from the above link:</p>\n\n<pre><code>(function($) {\n$.fn.StopPasswordManager = function() {\n return this.each(function() {\n var $this = $(this);\n\n $this.addClass('no-print');\n $this.attr('data-background-color', $this.css('background-color'));\n $this.css('background-color', $this.css('color'));\n $this.attr('type', 'text');\n $this.attr('autocomplete', 'off');\n\n $this.focus(function() {\n $this.attr('type', 'password');\n $this.css('background-color', $this.attr('data-background-color'));\n });\n\n $this.blur(function() {\n $this.css('background-color', $this.css('color'));\n $this.attr('type', 'text');\n $this[0].selectionStart = $this[0].selectionEnd;\n });\n\n $this.on('keydown', function(e) {\n if (e.keyCode == 13)\n {\n $this.css('background-color', $this.css('color'));\n $this.attr('type', 'text');\n $this[0].selectionStart = $this[0].selectionEnd;\n }\n });\n });\n}\n}(jQuery));\n</code></pre>\n\n<p>Demo:</p>\n\n<p><a href=\"https://barebonescms.com/demos/admin_pack/admin.php\" rel=\"nofollow noreferrer\">https://barebonescms.com/demos/admin_pack/admin.php</a></p>\n\n<p>Click \"Add Entry\" in the menu and then scroll to the bottom of the page to \"Module: Stop Password Manager\".</p>\n\n<p>Disclaimer: While this approach works for sighted individuals, there might be issues with screen reader software. For example, a screen reader might read the user's password out loud because it sees a plain text field. There might also be other unforeseen consequences of using the above plugin. Altering built-in web browser functionality should be done sparingly with testing a wide variety of conditions and edge cases.</p>\n" }, { "answer_id": 64872142, "author": "Burak Ekincioğlu", "author_id": 9559819, "author_profile": "https://Stackoverflow.com/users/9559819", "pm_score": 2, "selected": false, "text": "<p>This is my html code for solution. <strong>It works for Chrome-Safari-Internet Explorer</strong>. I created new font which all characters seem as &quot;●&quot;. Then I use this font for my password text. Note: My font name is &quot;passwordsecretregular&quot;.</p>\n<pre><code>&lt;style type=&quot;text/css&quot;&gt;\n #login_parola {\n font-family: 'passwordsecretregular' !important;\n -webkit-text-security: disc !important;\n font-size: 22px !important;\n }\n &lt;/style&gt;\n\n\n&lt;input type=&quot;text&quot; class=&quot;w205 has-keyboard-alpha&quot; name=&quot;login_parola&quot; id=&quot;login_parola&quot; onkeyup=&quot;checkCapsWarning(event)&quot; \n onfocus=&quot;checkCapsWarning(event)&quot; onblur=&quot;removeCapsWarning()&quot; onpaste=&quot;return false;&quot; maxlength=&quot;32&quot;/&gt;\n</code></pre>\n" }, { "answer_id": 73055897, "author": "Stu", "author_id": 14274352, "author_profile": "https://Stackoverflow.com/users/14274352", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;input type=&quot;text&quot; id=&quot;mPassword&quot; required=&quot;required&quot; title=&quot;Valid password required&quot; autocomplete=&quot;off&quot; list=&quot;autocompleteOff&quot; readonly onfocus=&quot;this.removeAttribute('readonly');&quot; style=&quot;text-security:disc; -webkit-text-security:disc;&quot; oncopy=&quot;return false;&quot; onpaste=&quot;return false;&quot;/&gt;\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3262/" ]
One of the joys of working for a government healthcare agency is having to deal with all of the paranoia around dealing with PHI (Protected Health Information). Don't get me wrong, I'm all for doing everything possible to protect people's personal information (health, financial, surfing habits, etc.), but sometimes people get a little too jumpy. Case in point: One of our state customers recently found out that the browser provides the handy feature to save your password. We all know that it has been there for a while and is completely optional and is up to the end user to decide whether or not it is a smart decision to use or not. However, there is a bit of an uproar at the moment and we are being demanded to find a way to disable that functionality for our site. **Question**: Is there a way for a site to tell the browser not to offer to remember passwords? I've been around web development a long time but don't know that I have come across that before. Any help is appreciated.
I'm not sure if it'll work in all browsers but you should try setting autocomplete="off" on the form. ``` <form id="loginForm" action="login.cgi" method="post" autocomplete="off"> ``` > > The easiest and simplest way to disable Form **and Password storage prompts** and prevent form data from being cached in session history is to use the autocomplete form element attribute with value "off". > > > > > From <https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion> > > > Some minor research shows that this works in IE to but I'll leave no guarantees ;) [@Joseph](https://stackoverflow.com/questions/32369/disable-browser-save-password-functionality#32408): If it's a strict requirement to pass XHTML validation with the actual markup (don't know why it would be though) you could theoretically add this attribute with javascript afterwards but then users with js disabled (probably a neglectable amount of your userbase or zero if your site requires js) will still have their passwords saved. Example with jQuery: ``` $('#loginForm').attr('autocomplete', 'off'); ```
32,397
<p>On SO 18 Joel mentioned an algorithm that would rank items based on their age and popularity and it's based on gravity. Could someone post this? C# would be lovely, but really any language (well, I can't do LISP) would be fine. </p>
[ { "answer_id": 32399, "author": "Tall Jeff", "author_id": 1553, "author_profile": "https://Stackoverflow.com/users/1553", "pm_score": 5, "selected": true, "text": "<p>My understanding is that it is approximately the following from another <a href=\"https://stackoverflow.com/questions/24066/what-formula-should-be-used-to-determine-hot-questions\">Jeff Atwood</a> post</p>\n\n<pre><code>t = (time of entry post) - (Dec 8, 2005)\nx = upvotes - downvotes\n\ny = {1 if x &gt; 0, 0 if x = 0, -1 if x &lt; 0)\nz = {1 if x &lt; 1, otherwise x}\n\nlog(z) + (y * t)/45000\n</code></pre>\n" }, { "answer_id": 306236, "author": "Abhishek Mishra", "author_id": 8786, "author_profile": "https://Stackoverflow.com/users/8786", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.mt-soft.com.ar/wordpress/wp-content/plugins/wp-o-matic/cache/0ad4d_reddit_cf_algorithm.png\">alt text http://www.mt-soft.com.ar/wordpress/wp-content/plugins/wp-o-matic/cache/0ad4d_reddit_cf_algorithm.png</a></p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1942/" ]
On SO 18 Joel mentioned an algorithm that would rank items based on their age and popularity and it's based on gravity. Could someone post this? C# would be lovely, but really any language (well, I can't do LISP) would be fine.
My understanding is that it is approximately the following from another [Jeff Atwood](https://stackoverflow.com/questions/24066/what-formula-should-be-used-to-determine-hot-questions) post ``` t = (time of entry post) - (Dec 8, 2005) x = upvotes - downvotes y = {1 if x > 0, 0 if x = 0, -1 if x < 0) z = {1 if x < 1, otherwise x} log(z) + (y * t)/45000 ```
32,404
<p>I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service.</p> <p>I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to daemonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services.</p> <p><strong>Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)?</strong> I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines.</p> <p><i>Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: <b>How is Windows aware of my service? Can I manage it with the native Windows utilities?</b> <strong>What is the equivalent of putting a start/stop script in /etc/init.d?</i></strong></p>
[ { "answer_id": 32440, "author": "Ricardo Reyes", "author_id": 3399, "author_profile": "https://Stackoverflow.com/users/3399", "pm_score": 9, "selected": true, "text": "<p>Yes you can. I do it using the pythoncom libraries that come included with <a href=\"http://www.activestate.com/Products/activepython/index.mhtml\" rel=\"noreferrer\">ActivePython</a> or can be installed with <a href=\"https://sourceforge.net/projects/pywin32/\" rel=\"noreferrer\">pywin32</a> (Python for Windows extensions).</p>\n\n<p>This is a basic skeleton for a simple service:</p>\n\n<pre><code>import win32serviceutil\nimport win32service\nimport win32event\nimport servicemanager\nimport socket\n\n\nclass AppServerSvc (win32serviceutil.ServiceFramework):\n _svc_name_ = \"TestService\"\n _svc_display_name_ = \"Test Service\"\n\n def __init__(self,args):\n win32serviceutil.ServiceFramework.__init__(self,args)\n self.hWaitStop = win32event.CreateEvent(None,0,0,None)\n socket.setdefaulttimeout(60)\n\n def SvcStop(self):\n self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n win32event.SetEvent(self.hWaitStop)\n\n def SvcDoRun(self):\n servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,\n servicemanager.PYS_SERVICE_STARTED,\n (self._svc_name_,''))\n self.main()\n\n def main(self):\n pass\n\nif __name__ == '__main__':\n win32serviceutil.HandleCommandLine(AppServerSvc)\n</code></pre>\n\n<p>Your code would go in the <code>main()</code> method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the <code>SvcStop</code> method</p>\n" }, { "answer_id": 597750, "author": "popcnt", "author_id": 47850, "author_profile": "https://Stackoverflow.com/users/47850", "pm_score": 5, "selected": false, "text": "<p>There are a couple alternatives for installing as a service virtually any Windows executable.</p>\n\n<h2>Method 1: Use instsrv and srvany from rktools.exe</h2>\n\n<p>For Windows Home Server or Windows Server 2003 (works with WinXP too), the <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=9D467A69-57FF-4AE7-96EE-B18C4790CFFD&amp;displaylang=en\" rel=\"nofollow noreferrer\">Windows Server 2003 Resource Kit Tools</a> comes with utilities that can be used in tandem for this, called <strong>instsrv.exe</strong> and <strong>srvany.exe</strong>. See this Microsoft KB article <a href=\"http://support.microsoft.com/kb/137890\" rel=\"nofollow noreferrer\">KB137890</a> for details on how to use these utils. </p>\n\n<p>For Windows Home Server, there is a great user friendly wrapper for these utilities named aptly \"<a href=\"http://forum.wegotserved.com/index.php?autocom=downloads&amp;showfile=7\" rel=\"nofollow noreferrer\">Any Service Installer</a>\". </p>\n\n<h2>Method 2: Use ServiceInstaller for Windows NT</h2>\n\n<p>There is another alternative using <a href=\"http://www.kcmultimedia.com/smaster/\" rel=\"nofollow noreferrer\">ServiceInstaller for Windows NT</a> (<a href=\"http://www.kcmultimedia.com/smaster/download.html\" rel=\"nofollow noreferrer\">download-able here</a>) with <a href=\"http://conort.googlepages.com/runanywindowsapplicationasntservice\" rel=\"nofollow noreferrer\">python instructions available</a>. Contrary to the name, it works with both Windows 2000 and Windows XP as well. Here are some instructions for how to install a python script as a service.</p>\n\n<blockquote>\n <p><strong>Installing a Python script</strong></p>\n \n <p>Run ServiceInstaller to create a new\n service. (In this example, it is\n assumed that python is installed at\n c:\\python25)</p>\n\n<pre><code>Service Name : PythonTest\nDisplay Name : PythonTest \nStartup : Manual (or whatever you like)\nDependencies : (Leave blank or fill to fit your needs)\nExecutable : c:\\python25\\python.exe\nArguments : c:\\path_to_your_python_script\\test.py\nWorking Directory : c:\\path_to_your_python_script\n</code></pre>\n \n <p>After installing, open the Control\n Panel's Services applet, select and\n start the PythonTest service.</p>\n</blockquote>\n\n<p>After my initial answer, I noticed there were closely related Q&amp;A already posted on SO. See also:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/32404/can-i-run-a-python-script-as-a-service-in-windows-how\">Can I run a Python script as a service (in Windows)? How?</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/34328/how-do-i-make-windows-aware-of-a-service-i-have-written-in-python\">How do I make Windows aware of a service I have written in Python?</a></p>\n" }, { "answer_id": 24996607, "author": "mknaf", "author_id": 1085954, "author_profile": "https://Stackoverflow.com/users/1085954", "pm_score": 6, "selected": false, "text": "<p>Although I upvoted the chosen answer a couple of weeks back, in the meantime I struggled a lot more with this topic. It feels like having a special Python installation and using special modules to run a script as a service is simply the wrong way. What about portability and such?</p>\n\n<p>I stumbled across the wonderful <a href=\"http://nssm.cc/\">Non-sucking Service Manager</a>, which made it really simple and sane to deal with Windows Services. I figured since I could pass options to an installed service, I could just as well select my Python executable and pass my script as an option.</p>\n\n<p>I have not yet tried this solution, but I will do so right now and update this post along the process. I am also interested in using virtualenvs on Windows, so I might come up with a tutorial sooner or later and link to it here.</p>\n" }, { "answer_id": 41017425, "author": "pyOwner", "author_id": 5165357, "author_profile": "https://Stackoverflow.com/users/5165357", "pm_score": 5, "selected": false, "text": "<p>The simplest way to achieve this is to use native command sc.exe:</p>\n\n<pre><code>sc create PythonApp binPath= \"C:\\Python34\\Python.exe --C:\\tmp\\pythonscript.py\"\n</code></pre>\n\n<p><strong>References:</strong></p>\n\n<ol>\n<li><a href=\"https://technet.microsoft.com/en-us/library/cc990289(v=ws.11).aspx\" rel=\"noreferrer\">https://technet.microsoft.com/en-us/library/cc990289(v=ws.11).aspx</a></li>\n<li><a href=\"https://stackoverflow.com/questions/3663331/creating-a-service-with-sc-exe-how-to-pass-in-context-parameters\">When creating a service with sc.exe how to pass in context parameters?</a></li>\n</ol>\n" }, { "answer_id": 42587921, "author": "Seliverstov Maksim", "author_id": 7589877, "author_profile": "https://Stackoverflow.com/users/7589877", "pm_score": 3, "selected": false, "text": "<p>pysc: <a href=\"https://pypi.python.org/pypi/pysc\" rel=\"noreferrer\">Service Control Manager on Python</a></p>\n\n<p>Example script to run as a service <a href=\"http://pythonhosted.org/pysc/example.html\" rel=\"noreferrer\">taken from pythonhosted.org</a>:</p>\n\n<blockquote>\n<pre><code>from xmlrpc.server import SimpleXMLRPCServer\n\nfrom pysc import event_stop\n\n\nclass TestServer:\n\n def echo(self, msg):\n return msg\n\n\nif __name__ == '__main__':\n server = SimpleXMLRPCServer(('127.0.0.1', 9001))\n\n @event_stop\n def stop():\n server.server_close()\n\n server.register_instance(TestServer())\n server.serve_forever()\n</code></pre>\n \n <p><strong>Create and start service</strong></p>\n\n<pre><code>import os\nimport sys\nfrom xmlrpc.client import ServerProxy\n\nimport pysc\n\n\nif __name__ == '__main__':\n service_name = 'test_xmlrpc_server'\n script_path = os.path.join(\n os.path.dirname(__file__), 'xmlrpc_server.py'\n )\n pysc.create(\n service_name=service_name,\n cmd=[sys.executable, script_path]\n )\n pysc.start(service_name)\n\n client = ServerProxy('http://127.0.0.1:9001')\n print(client.echo('test scm'))\n</code></pre>\n \n <p><strong>Stop and delete service</strong></p>\n\n<pre><code>import pysc\n\nservice_name = 'test_xmlrpc_server'\n\npysc.stop(service_name)\npysc.delete(service_name)\n</code></pre>\n</blockquote>\n\n\n\n<pre><code>pip install pysc\n</code></pre>\n" }, { "answer_id": 44820139, "author": "Seckin Sanli", "author_id": 8230298, "author_profile": "https://Stackoverflow.com/users/8230298", "pm_score": 5, "selected": false, "text": "<p>Step by step explanation how to make it work :</p>\n\n<p>1- First create a python file according to the basic skeleton mentioned above. And save it to a path for example : \"c:\\PythonFiles\\AppServerSvc.py\"</p>\n\n<pre><code>import win32serviceutil\nimport win32service\nimport win32event\nimport servicemanager\nimport socket\n\n\nclass AppServerSvc (win32serviceutil.ServiceFramework):\n _svc_name_ = \"TestService\"\n _svc_display_name_ = \"Test Service\"\n\n\n def __init__(self,args):\n win32serviceutil.ServiceFramework.__init__(self,args)\n self.hWaitStop = win32event.CreateEvent(None,0,0,None)\n socket.setdefaulttimeout(60)\n\n def SvcStop(self):\n self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n win32event.SetEvent(self.hWaitStop)\n\n def SvcDoRun(self):\n servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,\n servicemanager.PYS_SERVICE_STARTED,\n (self._svc_name_,''))\n self.main()\n\n def main(self):\n # Your business logic or call to any class should be here\n # this time it creates a text.txt and writes Test Service in a daily manner \n f = open('C:\\\\test.txt', 'a')\n rc = None\n while rc != win32event.WAIT_OBJECT_0:\n f.write('Test Service \\n')\n f.flush()\n # block for 24*60*60 seconds and wait for a stop event\n # it is used for a one-day loop\n rc = win32event.WaitForSingleObject(self.hWaitStop, 24 * 60 * 60 * 1000)\n f.write('shut down \\n')\n f.close()\n\nif __name__ == '__main__':\n win32serviceutil.HandleCommandLine(AppServerSvc)\n</code></pre>\n\n<p>2 - On this step we should register our service. </p>\n\n<p>Run command prompt as <strong>administrator</strong> and type as: </p>\n\n<blockquote>\n <p>sc create TestService binpath= \"C:\\Python36\\Python.exe c:\\PythonFiles\\AppServerSvc.py\" DisplayName= \"TestService\" start= auto</p>\n</blockquote>\n\n<p>the first argument of <strong>binpath</strong> is the <strong>path of python.exe</strong> </p>\n\n<p>second argument of <strong>binpath</strong> is <strong>the path of your python file</strong> that we created already</p>\n\n<p>Don't miss that you should put one space after every \"<strong>=</strong>\" sign. </p>\n\n<p>Then if everything is ok, you should see </p>\n\n<blockquote>\n <p>[SC] CreateService SUCCESS</p>\n</blockquote>\n\n<p>Now your python service is installed as windows service now. You can see it in Service Manager and registry under : </p>\n\n<p>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\TestService</p>\n\n<p>3- Ok now. You can start your service on service manager. </p>\n\n<p>You can execute every python file that provides this service skeleton. </p>\n" }, { "answer_id": 46450007, "author": "Adriano P", "author_id": 8221383, "author_profile": "https://Stackoverflow.com/users/8221383", "pm_score": 6, "selected": false, "text": "<p>The simplest way is to use the: <strong>NSSM - the Non-Sucking Service Manager.</strong> Just download and unzip to a location of your choosing. It's a self-contained utility, around 300KB (much less than installing the entire pywin32 suite just for this purpose) and no &quot;installation&quot; is needed. The zip contains a 64-bit and a 32-bit version of the utility. Either should work well on current systems (you can use the 32-bit version to manage services on 64-bit systems).</p>\n<h3>GUI approach</h3>\n<p><strong>1 - install the python program as a service. Open a Win prompt as admin</strong></p>\n<pre><code>c:\\&gt;nssm.exe install WinService\n</code></pre>\n<p><strong>2 - On NSSM´s GUI console:</strong></p>\n<p>path: C:\\Python27\\Python27.exe</p>\n<p>Startup directory: C:\\Python27</p>\n<p>Arguments: c:\\WinService.py</p>\n<p><strong>3 - check the created services on services.msc</strong></p>\n<h3>Scripting approach (no GUI)</h3>\n<p>This is handy if your service should be part of an automated, non-interactive procedure, that may be beyond your control, such as a batch or installer script. It is assumed that the commands are executed with administrative privileges.</p>\n<p>For convenience the commands are described here by simply referring to the utility as <code>nssm.exe</code>. It is advisable, however, to refer to it more explicitly in scripting with its full path <code>c:\\path\\to\\nssm.exe</code>, since it's a self-contained executable that may be located in a private path that the system is not aware of.</p>\n<p><strong>1. Install the service</strong></p>\n<p>You must specify a name for the service, the path to the proper Python executable, and the path to the script:</p>\n<pre><code>nssm.exe install ProjectService &quot;c:\\path\\to\\python.exe&quot; &quot;c:\\path\\to\\project\\app\\main.py&quot;\n</code></pre>\n<p>More explicitly:</p>\n<pre><code>nssm.exe install ProjectService \nnssm.exe set ProjectService Application &quot;c:\\path\\to\\python.exe&quot;\nnssm.exe set ProjectService AppParameters &quot;c:\\path\\to\\project\\app\\main.py&quot;\n</code></pre>\n<p>Alternatively you may want your Python app to be started as a Python module. One easy approach is to tell nssm that it needs to change to the proper starting directory, as you would do yourself when launching from a command shell:</p>\n<pre><code>nssm.exe install ProjectService &quot;c:\\path\\to\\python.exe&quot; &quot;-m app.main&quot;\nnssm.exe set ProjectService AppDirectory &quot;c:\\path\\to\\project&quot;\n</code></pre>\n<p>This approach works well with virtual environments and self-contained (embedded) Python installs. Just make sure to have properly resolved any path issues in those environments with the usual methods. nssm has a way to set environment variables (e.g. PYTHONPATH) if needed, and can also launch batch scripts.</p>\n<p><strong>2. To start the service</strong></p>\n<pre><code>nssm.exe start ProjectService \n</code></pre>\n<p><strong>3. To stop the service</strong></p>\n<pre><code>nssm.exe stop ProjectService\n</code></pre>\n<p><strong>4. To remove the service</strong>, specify the <code>confirm</code> parameter to skip the interactive confirmation.</p>\n<pre><code>nssm.exe remove ProjectService confirm\n</code></pre>\n" }, { "answer_id": 52780201, "author": "flam3", "author_id": 1407255, "author_profile": "https://Stackoverflow.com/users/1407255", "pm_score": 2, "selected": false, "text": "<p>I started hosting as a service with <a href=\"https://stackoverflow.com/a/32440/1407255\">pywin32</a>.</p>\n\n<p>Everything was well but I met the problem that service was not able to start within 30 seconds (default timeout for Windows) on system startup. It was critical for me because Windows startup took place simultaneous on several virtual machines hosted on one physical machine, and IO load was huge.\nError messages were:</p>\n\n<p><code>Error 1053: The service did not respond to the start or control request in a timely fashion.</code></p>\n\n<p><code>Error 7009: Timeout (30000 milliseconds) waiting for the &lt;ServiceName&gt; service to connect.</code></p>\n\n<p>I fought a lot with pywin, but ended up with using NSSM as it was proposed <a href=\"https://stackoverflow.com/a/24996607/1407255\">in this answer</a>. It was very easy to migrate to it.</p>\n" }, { "answer_id": 53240642, "author": "ndemou", "author_id": 1011025, "author_profile": "https://Stackoverflow.com/users/1011025", "pm_score": 1, "selected": false, "text": "<p>The accepted answer using <code>win32serviceutil</code> works but is complicated and makes debugging and changes harder. It is <strong><em>far</em></strong> easier to use NSSM (<a href=\"https://nssm.cc\" rel=\"nofollow noreferrer\">the Non-Sucking Service Manager)</a>. You write and comfortably debug a normal python program and when it finally works you use NSSM to install it as a service in less than a minute:</p>\n\n<p>From an elevated (admin) command prompt you run <code>nssm.exe install NameOfYourService</code> and you fill-in these options:</p>\n\n<ul>\n<li><strong>path</strong>: (the path to python.exe e.g. <code>C:\\Python27\\Python.exe</code>)</li>\n<li><strong>Arguments</strong>: (the path to your python script, e.g. <code>c:\\path\\to\\program.py</code>)</li>\n</ul>\n\n<p>By the way, if your program prints useful messages that you want to keep in a log file NSSM can also handle this and a lot more for you.</p>\n" }, { "answer_id": 56451724, "author": "coder", "author_id": 10534497, "author_profile": "https://Stackoverflow.com/users/10534497", "pm_score": 3, "selected": false, "text": "<p><strong><a href=\"https://nssm.cc/download\" rel=\"nofollow noreferrer\">nssm</a> in python 3+</strong></p>\n\n<p>(I converted my .py file to .exe with <a href=\"https://www.pyinstaller.org/downloads.html\" rel=\"nofollow noreferrer\">pyinstaller</a>)</p>\n\n<p>nssm:\nas said before</p>\n\n<ul>\n<li>run nssm install {ServiceName}</li>\n<li><p><strong>On NSSM´s console:</strong></p>\n\n<p><strong>path: <em>path\\to\\your\\program.exe</em></strong></p>\n\n<p><strong>Startup directory: <em>path\\to\\your\\ #same as the path but without your program.exe</em></strong></p>\n\n<p><strong>Arguments: empty</strong></p></li>\n</ul>\n\n<p><strong>If you don't want to convert your project to .exe</strong> </p>\n\n<ul>\n<li>create a .bat file with <code>python {{your python.py file name}}</code></li>\n<li>and set the path to the .bat file</li>\n</ul>\n" }, { "answer_id": 59923084, "author": "Alias_Knagg", "author_id": 2156089, "author_profile": "https://Stackoverflow.com/users/2156089", "pm_score": 2, "selected": false, "text": "<h1>A complete pywin32 example using loop or subthread</h1>\n<p>After working on this on and off for a few days, here is the answer I would have wished to find, using pywin32 to keep it nice and self contained.</p>\n<p>This is complete working code for one loop-based and one thread-based solution.\nIt may work on both python 2 and 3, although I've only tested the latest version on 2.7 and Win7. The loop should be good for polling code, and the tread should work with more server-like code. It seems to work nicely with the <a href=\"https://docs.pylonsproject.org/projects/waitress/en/latest/\" rel=\"nofollow noreferrer\">waitress</a> wsgi server that does not have a standard way to shut down gracefully.</p>\n<p>I would also like to note that there seems to be loads of examples out there, like <a href=\"https://www.thepythoncorner.com/2018/08/how-to-create-a-windows-service-in-python/\" rel=\"nofollow noreferrer\">this</a> that are almost useful, but in reality misleading, because they have cut and pasted other examples blindly. I could be wrong. but why create an event if you never wait for it?</p>\n<p>That said I still feel I'm on somewhat shaky ground here, especially with regards to how clean the exit from the thread version is, but at least I believe there are nothing <em>misleading</em> here.</p>\n<p>To run simply copy the code to a file and follow the instructions.</p>\n<h3>update:</h3>\n<p>Use a simple flag to terminate thread. The important bit is that &quot;thread done&quot; prints.<br />\nFor a more elaborate example exiting from an uncooperative server thread see my <a href=\"https://stackoverflow.com/questions/59893782/how-to-exit-cleanly-from-flask-and-waitress-running-as-a-windows-pywin32-service\">post about the waitress wsgi server</a>.</p>\n<pre><code># uncomment mainthread() or mainloop() call below\n# run without parameters to see HandleCommandLine options\n# install service with &quot;install&quot; and remove with &quot;remove&quot;\n# run with &quot;debug&quot; to see print statements\n# with &quot;start&quot; and &quot;stop&quot; watch for files to appear\n# check Windows EventViever for log messages\n\nimport socket\nimport sys\nimport threading\nimport time\nfrom random import randint\nfrom os import path\n\nimport servicemanager\nimport win32event\nimport win32service\nimport win32serviceutil\n# see http://timgolden.me.uk/pywin32-docs/contents.html for details\n\n\ndef dummytask_once(msg='once'):\n fn = path.join(path.dirname(__file__),\n '%s_%s.txt' % (msg, randint(1, 10000)))\n with open(fn, 'w') as fh:\n print(fn)\n fh.write('')\n\n\ndef dummytask_loop():\n global do_run\n while do_run:\n dummytask_once(msg='loop')\n time.sleep(3)\n\n\nclass MyThread(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n\n def run(self):\n global do_run\n do_run = True\n print('thread start\\n')\n dummytask_loop()\n print('thread done\\n')\n\n def exit(self):\n global do_run\n do_run = False\n\n\nclass SMWinservice(win32serviceutil.ServiceFramework):\n _svc_name_ = 'PyWinSvc'\n _svc_display_name_ = 'Python Windows Service'\n _svc_description_ = 'An example of a windows service in Python'\n\n @classmethod\n def parse_command_line(cls):\n win32serviceutil.HandleCommandLine(cls)\n\n def __init__(self, args):\n win32serviceutil.ServiceFramework.__init__(self, args)\n self.stopEvt = win32event.CreateEvent(None, 0, 0, None) # create generic event\n socket.setdefaulttimeout(60)\n\n def SvcStop(self):\n servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,\n servicemanager.PYS_SERVICE_STOPPED,\n (self._svc_name_, ''))\n self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n win32event.SetEvent(self.stopEvt) # raise event\n\n def SvcDoRun(self):\n servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,\n servicemanager.PYS_SERVICE_STARTED,\n (self._svc_name_, ''))\n # UNCOMMENT ONE OF THESE\n # self.mainthread()\n # self.mainloop()\n\n # Wait for stopEvt indefinitely after starting thread.\n def mainthread(self):\n print('main start')\n self.server = MyThread()\n self.server.start()\n print('wait for win32event')\n win32event.WaitForSingleObject(self.stopEvt, win32event.INFINITE)\n self.server.exit()\n print('wait for thread')\n self.server.join()\n print('main done')\n\n # Wait for stopEvt event in loop.\n def mainloop(self):\n print('loop start')\n rc = None\n while rc != win32event.WAIT_OBJECT_0:\n dummytask_once()\n rc = win32event.WaitForSingleObject(self.stopEvt, 3000)\n print('loop done')\n\n\nif __name__ == '__main__':\n SMWinservice.parse_command_line()\n</code></pre>\n" }, { "answer_id": 60775892, "author": "gunarajulu renganathan", "author_id": 13095056, "author_profile": "https://Stackoverflow.com/users/13095056", "pm_score": -1, "selected": false, "text": "<p><a href=\"https://www.chrisumbel.com/article/windows_services_in_python\" rel=\"nofollow noreferrer\">https://www.chrisumbel.com/article/windows_services_in_python</a></p>\n\n<ol>\n<li><p>Follow up the PySvc.py</p></li>\n<li><p>changing the dll folder </p></li>\n</ol>\n\n<p>I know this is old but I was stuck on this forever. For me, this specific problem was solved by copying this file - pywintypes36.dll</p>\n\n<p>From -> Python36\\Lib\\site-packages\\pywin32_system32</p>\n\n<p>To -> Python36\\Lib\\site-packages\\win32</p>\n\n<pre><code>setx /M PATH \"%PATH%;C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32;C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\Scripts;C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\site-packages\\pywin32_system32;C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\site-packages\\win32\n</code></pre>\n\n<ol start=\"3\">\n<li>changing the path to python folder by</li>\n</ol>\n\n<p><code>cd C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32</code></p>\n\n<ol start=\"4\">\n<li><code>NET START PySvc</code></li>\n<li><code>NET STOP PySvc</code></li>\n</ol>\n" }, { "answer_id": 64637599, "author": "Russell McDonell", "author_id": 12791160, "author_profile": "https://Stackoverflow.com/users/12791160", "pm_score": 2, "selected": false, "text": "<p>This answer is plagiarizer from several sources on StackOverflow - most of them above, but I've forgotten the others - sorry. It's simple and scripts run &quot;as is&quot;. For releases you test you script, then copy it to the server and Stop/Start the associated service. And it should work for all scripting languages (Python, Perl, node.js), plus batch scripts such as GitBash, PowerShell, even old DOS bat scripts.\npyGlue is the glue that sits between Windows Services and your script.</p>\n<pre><code>'''\nA script to create a Windows Service, which, when started, will run an executable with the specified parameters.\nOptionally, you can also specify a startup directory\n\nTo use this script you MUST define (in class Service)\n1. A name for your service (short - preferably no spaces)\n2. A display name for your service (the name visibile in Windows Services)\n3. A description for your service (long details visible when you inspect the service in Windows Services)\n4. The full path of the executable (usually C:/Python38/python.exe or C:WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe\n5. The script which Python or PowerShell will run(or specify None if your executable is standalone - in which case you don't need pyGlue)\n6. The startup directory (or specify None)\n7. Any parameters for your script (or for your executable if you have no script)\n\nNOTE: This does not make a portable script.\nThe associated '_svc_name.exe' in the dist folder will only work if the executable,\n(and any optional startup directory) actually exist in those locations on the target system\n\nUsage: 'pyGlue.exe [options] install|update|remove|start [...]|stop|restart [...]|debug [...]'\nOptions for 'install' and 'update' commands only:\n --username domain\\\\username : The Username the service is to run under\n --password password : The password for the username\n --startup [manual|auto|disabled|delayed] : How the service starts, default = manual\n --interactive : Allow the service to interact with the desktop.\n --perfmonini file: .ini file to use for registering performance monitor data\n --perfmondll file: .dll file to use when querying the service for performance data, default = perfmondata.dll\nOptions for 'start' and 'stop' commands only:\n --wait seconds: Wait for the service to actually start or stop.\n If you specify --wait with the 'stop' option, the service and all dependent services will be stopped,\n each waiting the specified period.\n'''\n\n# Import all the modules that make life easy\nimport servicemanager\nimport socket\nimport sys\nimport win32event\nimport win32service\nimport win32serviceutil\nimport win32evtlogutil\nimport os\nfrom logging import Formatter, Handler\nimport logging\nimport subprocess\n\n\n# Define the win32api class\nclass Service (win32serviceutil.ServiceFramework):\n # The following variable are edited by the build.sh script\n _svc_name_ = &quot;TestService&quot;\n _svc_display_name_ = &quot;Test Service&quot;\n _svc_description_ = &quot;Test Running Python Scripts as a Service&quot;\n service_exe = 'c:/Python27/python.exe'\n service_script = None\n service_params = []\n service_startDir = None\n\n # Initialize the service\n def __init__(self, args):\n win32serviceutil.ServiceFramework.__init__(self, args)\n self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)\n self.configure_logging()\n socket.setdefaulttimeout(60)\n\n # Configure logging to the WINDOWS Event logs\n def configure_logging(self):\n self.formatter = Formatter('%(message)s')\n self.handler = logHandler()\n self.handler.setFormatter(self.formatter)\n self.logger = logging.getLogger()\n self.logger.addHandler(self.handler)\n self.logger.setLevel(logging.INFO)\n\n # Stop the service\n def SvcStop(self):\n self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n win32event.SetEvent(self.hWaitStop)\n\n # Run the service\n def SvcDoRun(self):\n self.main()\n\n # This is the service\n def main(self):\n\n # Log that we are starting\n servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED,\n (self._svc_name_, ''))\n\n # Fire off the real process that does the real work\n logging.info('%s - about to call Popen() to run %s %s %s', self._svc_name_, self.service_exe, self.service_script, self.service_params)\n self.process = subprocess.Popen([self.service_exe, self.service_script] + self.service_params, shell=False, cwd=self.service_startDir)\n logging.info('%s - started process %d', self._svc_name_, self.process.pid)\n\n # Wait until WINDOWS kills us - retrigger the wait for stop every 60 seconds\n rc = None\n while rc != win32event.WAIT_OBJECT_0:\n rc = win32event.WaitForSingleObject(self.hWaitStop, (1 * 60 * 1000))\n\n # Shut down the real process and exit\n logging.info('%s - is terminating process %d', self._svc_name_, self.process.pid)\n self.process.terminate()\n logging.info('%s - is exiting', self._svc_name_)\n\n\nclass logHandler(Handler):\n '''\nEmit a log record to the WINDOWS Event log\n '''\n\n def emit(self, record):\n servicemanager.LogInfoMsg(record.getMessage())\n\n\n# The main code\nif __name__ == '__main__':\n '''\nCreate a Windows Service, which, when started, will run an executable with the specified parameters.\n '''\n\n # Check that configuration contains valid values just in case this service has accidentally\n # been moved to a server where things are in different places\n if not os.path.isfile(Service.service_exe):\n print('Executable file({!s}) does not exist'.format(Service.service_exe), file=sys.stderr)\n sys.exit(0)\n if not os.access(Service.service_exe, os.X_OK):\n print('Executable file({!s}) is not executable'.format(Service.service_exe), file=sys.stderr)\n sys.exit(0)\n # Check that any optional startup directory exists\n if (Service.service_startDir is not None) and (not os.path.isdir(Service.service_startDir)):\n print('Start up directory({!s}) does not exist'.format(Service.service_startDir), file=sys.stderr)\n sys.exit(0)\n\n if len(sys.argv) == 1:\n servicemanager.Initialize()\n servicemanager.PrepareToHostSingle(Service)\n servicemanager.StartServiceCtrlDispatcher()\n else:\n # install/update/remove/start/stop/restart or debug the service\n # One of those command line options must be specified\n win32serviceutil.HandleCommandLine(Service)\n</code></pre>\n<p>Now there's a bit of editing and you don't want all your services called 'pyGlue'. So there's a script (build.sh) to plug in the bits and create a customized 'pyGlue' and create an '.exe'. It is this '.exe' which gets installed as a Windows Service. Once installed you can set it to run automatically.</p>\n<pre><code>#!/bin/sh\n# This script build a Windows Service that will install/start/stop/remove a service that runs a script\n# That is, executes Python to run a Python script, or PowerShell to run a PowerShell script, etc\n\nif [ $# -lt 6 ]; then\n echo &quot;Usage: build.sh Name Display Description Executable Script StartupDir [Params]...&quot;\n exit 0\nfi\n\nname=$1\ndisplay=$2\ndesc=$3\nexe=$4\nscript=$5\nstartDir=$6\nshift; shift; shift; shift; shift; shift\nparams=\nwhile [ $# -gt 0 ]; do\n if [ &quot;${params}&quot; != &quot;&quot; ]; then\n params=&quot;${params}, &quot;\n fi\n params=&quot;${params}'$1'&quot;\n shift\ndone\n\ncat pyGlue.py | sed -e &quot;s/pyGlue/${name}/g&quot; | \\\n sed -e &quot;/_svc_name_ =/s?=.*?= '${name}'?&quot; | \\\n sed -e &quot;/_svc_display_name_ =/s?=.*?= '${display}'?&quot; | \\\n sed -e &quot;/_svc_description_ =/s?=.*?= '${desc}'?&quot; | \\\n sed -e &quot;/service_exe =/s?=.*?= '$exe'?&quot; | \\\n sed -e &quot;/service_script =/s?=.*?= '$script'?&quot; | \\\n sed -e &quot;/service_params =/s?=.*?= [${params}]?&quot; | \\\n sed -e &quot;/service_startDir =/s?=.*?= '${startDir}'?&quot; &gt; ${name}.py\n\ncxfreeze ${name}.py --include-modules=win32timezone\n</code></pre>\n<p>Installation - copy the '.exe' the server and the script to the specified folder. Run the '.exe', as Administrator, with the 'install' option. Open Windows Services, as Adminstrator, and start you service. For upgrade, just copy the new version of the script and Stop/Start the service.</p>\n<p>Now every server is different - different installations of Python, different folder structures. I maintain a folder for every server, with a copy of pyGlue.py and build.sh. And I create a 'serverBuild.sh' script for rebuilding all the service on that server.</p>\n<pre><code># A script to build all the script based Services on this PC\nsh build.sh AutoCode 'AutoCode Medical Documents' 'Autocode Medical Documents to SNOMED_CT and AIHW codes' C:/Python38/python.exe autocode.py C:/Users/russell/Documents/autocoding -S -T\n</code></pre>\n" }, { "answer_id": 72627675, "author": "Matthias Luh", "author_id": 2738240, "author_profile": "https://Stackoverflow.com/users/2738240", "pm_score": 1, "selected": false, "text": "<p>This doesn't answer the original question, but might help other people that want to automatically start a Python script at Windows startup:\nHave a look at the <a href=\"https://en.wikipedia.org/wiki/Windows_Task_Scheduler\" rel=\"nofollow noreferrer\">Windows Task Scheduler</a> instead, it is way easier if you just want to start a script after boot without all the service functionality of a Windows Service.</p>\n<p>Create a new task, select &quot;At startup&quot; as trigger, &quot;Start program&quot; as action with &quot;C:\\Python39\\python.exe&quot; as the program (or wherever your python.exe is) and the full path to your script (&quot;C:...\\my_dir\\xyz.py&quot;) as argument (you can use &quot; if the path contains spaces).\nYou can also select the path of your script (without the .py file, e.g. &quot;C:...\\my_dir&quot;) for &quot;start in&quot; if you use relative paths in your script, e.g. for logging.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service. I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to daemonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services. **Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)?** I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines. *Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: **How is Windows aware of my service? Can I manage it with the native Windows utilities?** **What is the equivalent of putting a start/stop script in /etc/init.d?***
Yes you can. I do it using the pythoncom libraries that come included with [ActivePython](http://www.activestate.com/Products/activepython/index.mhtml) or can be installed with [pywin32](https://sourceforge.net/projects/pywin32/) (Python for Windows extensions). This is a basic skeleton for a simple service: ``` import win32serviceutil import win32service import win32event import servicemanager import socket class AppServerSvc (win32serviceutil.ServiceFramework): _svc_name_ = "TestService" _svc_display_name_ = "Test Service" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main() def main(self): pass if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) ``` Your code would go in the `main()` method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the `SvcStop` method
32,414
<p>We are currently working in a private beta and so are still in the process of making fairly rapid changes, although obviously as usage is starting to ramp up, we will be slowing down this process. That being said, one issue we are running into is that after we push out an update with new JavaScript files, the client browsers still use the cached version of the file and they do not see the update. Obviously, on a support call, we can simply inform them to do a <kbd>ctrl</kbd><kbd>F5</kbd> refresh to ensure that they get the up-to-date files from the server, but it would be preferable to handle this before that time.</p> <p>Our current thought is to simply attach a version number onto the name of the JavaScript files and then when changes are made, increment the version on the script and update all references. This definitely gets the job done, but updating the references on each release could get cumbersome.</p> <p>As I'm sure we're not the first ones to deal with this, I figured I would throw it out to the community. How are you ensuring clients update their cache when you update your code? If you're using the method described above, are you using a process that simplifies the change?</p>
[ { "answer_id": 32427, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 10, "selected": true, "text": "<p>As far as I know a common solution is to add a <code>?&lt;version&gt;</code> to the script's src link.</p>\n\n<p>For instance:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"myfile.js?1500\"&gt;&lt;/script&gt;\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>I assume at this point that there isn't a better way than find-replace to increment these \"version numbers\" in all of the script tags?</p>\n</blockquote>\n\n<p>You might have a version control system do that for you? Most version control systems have a way to automatically inject the revision number on check-in for instance.</p>\n\n<p>It would look something like this:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"myfile.js?$$REVISION$$\"&gt;&lt;/script&gt;\n</code></pre>\n\n<hr>\n\n<p>Of course, there are always better solutions like <a href=\"http://blog.greenfelt.net/2009/09/01/caching-javascript-safely/\" rel=\"noreferrer\">this one</a>.</p>\n" }, { "answer_id": 32450, "author": "AdamB", "author_id": 2176, "author_profile": "https://Stackoverflow.com/users/2176", "pm_score": 2, "selected": false, "text": "<p>My colleague just found a reference to that method right after I posted (in reference to css) at <a href=\"http://www.stefanhayden.com/blog/2006/04/03/css-caching-hack/\" rel=\"nofollow noreferrer\">http://www.stefanhayden.com/blog/2006/04/03/css-caching-hack/</a>. Good to see that others are using it and it seems to work. I assume at this point that there isn't a better way than find-replace to increment these \"version numbers\" in all of the script tags?</p>\n" }, { "answer_id": 83853, "author": "Richard Turner", "author_id": 12559, "author_profile": "https://Stackoverflow.com/users/12559", "pm_score": 2, "selected": false, "text": "<p>One solution is to append a query string with a timestamp in it to the URL when fetching the resource. This takes advantage of the fact that a browser will not cache resources fetched from URLs with query strings in them.</p>\n\n<p>You probably don't want the browser not to cache these resources at all though; it's more likely that you want them cached, but you want the browser to fetch a new version of the file when it is made available.</p>\n\n<p>The most common solution seems to be to embed a timestamp or revision number in the file name itself. This is a little more work, because your code needs to be modified to request the correct files, but it means that, e.g. version 7 of your <code>snazzy_javascript_file.js</code> (i.e. <code>snazzy_javascript_file_7.js</code>) is cached on the browser until you release version 8, and then your code changes to fetch <code>snazzy_javascript_file_8.js</code> instead.</p>\n" }, { "answer_id": 84770, "author": "pcorcoran", "author_id": 15992, "author_profile": "https://Stackoverflow.com/users/15992", "pm_score": 0, "selected": false, "text": "<p>Simplest solution? Don't let the browser cache at all. Append the current time (in ms) as a query.</p>\n\n<p>(You are still in beta, so you could make a reasonable case for not optimizing for performance. But YMMV here.)</p>\n" }, { "answer_id": 84835, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>If you're generating the page that links to the JS files a simple solution is appending the file's last modification timestamp to the generated links. </p>\n\n<p>This is very similar to Huppie's answer, but works in version control systems without keyword substitution. It's also better than append the current time, since that would prevent caching even when the file didn't change at all.</p>\n" }, { "answer_id": 84846, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 7, "selected": false, "text": "<p>Appending the current time to the URL is indeed a common solution. However, you can also manage this at the web server level, if you want to. The server can be configured to send different HTTP headers for javascript files. </p>\n\n<p>For example, to force the file to be cached for no longer than 1 day, you would send:</p>\n\n<pre><code>Cache-Control: max-age=86400, must-revalidate\n</code></pre>\n\n<p>For beta, if you want to force the user to always get the latest, you would use:</p>\n\n<pre><code>Cache-Control: no-cache, must-revalidate\n</code></pre>\n" }, { "answer_id": 84871, "author": "Echo says Reinstate Monica", "author_id": 13778, "author_profile": "https://Stackoverflow.com/users/13778", "pm_score": 4, "selected": false, "text": "<p>Not all browsers cache files with <strong>'?'</strong> in it. What I did to make sure it was cached as much as possible, I included the version in the filename. </p>\n\n<p>So instead of <code>stuff.js?123</code>, I did <code>stuff_123.js</code> </p>\n\n<p>I used <code>mod_redirect</code>(I think) in apache to to <code>have stuff_*.js</code> to go <code>stuff.js</code></p>\n" }, { "answer_id": 857557, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The advantage of using a <code>file.js?V=1</code> over a <code>fileV1.js</code> is that you do not need to store multiple versions of the JavaScript files on the server.</p>\n\n<p>The trouble I see with <code>file.js?V=1</code> is that you may have dependant code in another JavaScript file that breaks when using the new version of the library utilities.</p>\n\n<p>For the sake of backwards compatibility, I think it is much better to use <code>jQuery.1.3.js</code> for your new pages and let existing pages use <code>jQuery.1.1.js</code>, until you are ready to upgrade the older pages, if necessary.</p>\n" }, { "answer_id": 4293901, "author": "Derek Adair", "author_id": 231435, "author_profile": "https://Stackoverflow.com/users/231435", "pm_score": 2, "selected": false, "text": "<p>Use a version <code>GET</code> variable to prevent browser caching.</p>\n\n<p>Appending <code>?v=AUTO_INCREMENT_VERSION</code> to the end of your url prevents browser caching - avoiding any and all cached scripts.</p>\n" }, { "answer_id": 7671705, "author": "Hắc Huyền Minh", "author_id": 1020600, "author_profile": "https://Stackoverflow.com/users/1020600", "pm_score": 6, "selected": false, "text": "<p>Google Page-Speed: Don't include a query string in the URL for static resources.\nMost proxies, most notably Squid up through version 3.0, do not cache resources with a \"?\" in their URL even if a Cache-control: public header is present in the response. To enable proxy caching for these resources, remove query strings from references to static resources, and instead encode the parameters into the file names themselves. </p>\n\n<p>In this case, you can include the version into URL ex: <a href=\"http://abc.com/\">http://abc.com/</a><strong>v1.2</strong>/script.js and use apache mod_rewrite to redirect the link to <a href=\"http://abc.com/script.js\">http://abc.com/script.js</a>. When you change the version, client browser will update the new file.</p>\n" }, { "answer_id": 12757339, "author": "Trent", "author_id": 110226, "author_profile": "https://Stackoverflow.com/users/110226", "pm_score": 2, "selected": false, "text": "<p>Athough it is framework specific, Django 1.4 has <a href=\"https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#django.contrib.staticfiles.storage.CachedStaticFilesStorage\" rel=\"nofollow noreferrer\" title=\"this functionality\">the staticfiles app functionality</a> which works in a similar fashion to the 'greenfelt' site in the <a href=\"https://stackoverflow.com/a/32427/110226\">above answer</a></p>\n" }, { "answer_id": 14672139, "author": "user1944129", "author_id": 1944129, "author_profile": "https://Stackoverflow.com/users/1944129", "pm_score": 3, "selected": false, "text": "<p>In <strong>PHP</strong>:</p>\n\n<pre><code>function latest_version($file_name){\n echo $file_name.\"?\".filemtime($_SERVER['DOCUMENT_ROOT'] .$file_name);\n}\n</code></pre>\n\n<p>In <strong>HTML</strong>:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"&lt;?php latest_version('/a-o/javascript/almanacka.js'); ?&gt;\"&gt;&lt; /script&gt;\n</code></pre>\n\n<p><strong>How it works:</strong></p>\n\n<p>In HTML, write the <code>filepath</code> and name as you wold do, but in the function only.\nPHP gets the <code>filetime</code> of the file and returns the <code>filepath+name+\"?\"+time</code> of latest change </p>\n" }, { "answer_id": 18033575, "author": "Ivan Kochurkin", "author_id": 1046374, "author_profile": "https://Stackoverflow.com/users/1046374", "pm_score": 3, "selected": false, "text": "<p>For ASP.NET I suppose next solution with advanced options (debug/release mode, versions):</p>\n\n<p>Js or Css files included by such way:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"Scripts/exampleScript&lt;%=Global.JsPostfix%&gt;\" /&gt;\n&lt;link rel=\"stylesheet\" type=\"text/css\" href=\"Css/exampleCss&lt;%=Global.CssPostfix%&gt;\" /&gt;\n</code></pre>\n\n<p>Global.JsPostfix and Global.CssPostfix is calculated by the following way in Global.asax:</p>\n\n<pre><code>protected void Application_Start(object sender, EventArgs e)\n{\n ...\n string jsVersion = ConfigurationManager.AppSettings[\"JsVersion\"];\n bool updateEveryAppStart = Convert.ToBoolean(ConfigurationManager.AppSettings[\"UpdateJsEveryAppStart\"]);\n int buildNumber = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Revision;\n JsPostfix = \"\";\n#if !DEBUG\n JsPostfix += \".min\";\n#endif \n JsPostfix += \".js?\" + jsVersion + \"_\" + buildNumber;\n if (updateEveryAppStart)\n {\n Random rand = new Random();\n JsPosfix += \"_\" + rand.Next();\n }\n ...\n}\n</code></pre>\n" }, { "answer_id": 21297413, "author": "Ravi Ram", "author_id": 665387, "author_profile": "https://Stackoverflow.com/users/665387", "pm_score": 4, "selected": false, "text": "<p>For ASP.NET pages I am using the following</p>\n\n<p><strong>BEFORE</strong></p>\n\n<pre><code>&lt;script src=\"/Scripts/pages/common.js\" type=\"text/javascript\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p><strong>AFTER (force reload)</strong></p>\n\n<pre><code>&lt;script src=\"/Scripts/pages/common.js?ver&lt;%=DateTime.Now.Ticks.ToString()%&gt;\" type=\"text/javascript\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>Adding the DateTime.Now.Ticks works very well.</p>\n" }, { "answer_id": 25316713, "author": "amos", "author_id": 319034, "author_profile": "https://Stackoverflow.com/users/319034", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p>This usage has been deprected:\n <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache</a></p>\n</blockquote>\n\n<p>This answer is only 6 years late, but I don't see this answer in many places... HTML5 has introduced <a href=\"http://www.w3schools.com/html/html5_app_cache.asp\" rel=\"nofollow noreferrer\" title=\"Application Cache\">Application Cache</a> which is used to solve this problem. I was finding that new server code I was writing was crashing old javascript stored in people's browsers, so I wanted to find a way to expire their javascript. Use a manifest file that looks like this:</p>\n\n<pre><code>CACHE MANIFEST\n# Aug 14, 2014\n/mycode.js\n\nNETWORK:\n*\n</code></pre>\n\n<p>and generate this file with a new time stamp every time you want users to update their cache. As a side note, if you add this, the browser will <em>not</em> reload (even when a user refreshes the page) until the manifest tells it to.</p>\n" }, { "answer_id": 33058872, "author": "Michael Franz", "author_id": 4479748, "author_profile": "https://Stackoverflow.com/users/4479748", "pm_score": 2, "selected": false, "text": "<p>The jQuery function getScript can also be used to ensure that a js file is indeed loaded every time the page is loaded.</p>\n\n<p>This is how I did it:</p>\n\n<pre><code>$(document).ready(function(){\n $.getScript(\"../data/playlist.js\", function(data, textStatus, jqxhr){\n startProgram();\n });\n});\n</code></pre>\n\n<p>Check the function at <a href=\"http://api.jquery.com/jQuery.getScript/\" rel=\"nofollow\">http://api.jquery.com/jQuery.getScript/</a></p>\n\n<p>By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested.</p>\n" }, { "answer_id": 34032995, "author": "Erik Corona", "author_id": 5531314, "author_profile": "https://Stackoverflow.com/users/5531314", "pm_score": 5, "selected": false, "text": "<p>How about adding the filesize as a load parameter?</p>\n\n<pre><code>&lt;script type='text/javascript' src='path/to/file/mylibrary.js?filever=&lt;?=filesize('path/to/file/mylibrary.js')?&gt;'&gt;&lt;/script&gt;\n</code></pre>\n\n<p>So every time you update the file the \"filever\" parameter changes.</p>\n\n<p>How about when you update the file and your update results in the same file size? what are the odds?</p>\n" }, { "answer_id": 41501905, "author": "Goran Siriev", "author_id": 5917218, "author_profile": "https://Stackoverflow.com/users/5917218", "pm_score": 1, "selected": false, "text": "<p>One simple way.\nEdit htaccess</p>\n\n<pre><code>RewriteEngine On\nRewriteBase /\nRewriteCond %{REQUEST_URI} \\.(jpe?g|bmp|png|gif|css|js|mp3|ogg)$ [NC]\nRewriteCond %{QUERY_STRING} !^(.+?&amp;v33|)v=33[^&amp;]*(?:&amp;(.*)|)$ [NC]\nRewriteRule ^ %{REQUEST_URI}?v=33 [R=301,L]\n</code></pre>\n" }, { "answer_id": 44835940, "author": "ccherwin", "author_id": 3320423, "author_profile": "https://Stackoverflow.com/users/3320423", "pm_score": 2, "selected": false, "text": "<p>Cache Busting in ASP.NET Core via a tag helper will handle this for you and allow your browser to keep cached scripts/css until the file changes. Simply add the tag helper asp-append-version=\"true\" to your script (js) or link (css) tag:</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"~/css/site.min.css\" asp-append-version=\"true\"/&gt;\n</code></pre>\n\n<p>Dave Paquette has a good example and explanation of cache busting here (bottom of page) <a href=\"http://www.davepaquette.com/archive/2015/05/06/link-and-script-tag-helpers-in-mvc6.aspx\" rel=\"nofollow noreferrer\">Cache Busting</a> </p>\n" }, { "answer_id": 47174803, "author": "Aman Singh", "author_id": 2570255, "author_profile": "https://Stackoverflow.com/users/2570255", "pm_score": 3, "selected": false, "text": "<p>We have been creating a SaaS for users and providing them a script to attach in their website page, and it was not possible to attach a version with the script as user will attach the script to their website for functionalities and i can't force them to change the version each time we update the script</p>\n\n<p>So, we found a way to load the newer version of the script each time user calls the original script</p>\n\n<p><em>the script link provided to user</em></p>\n\n<pre><code>&lt;script src=\"https://thesaasdomain.com/somejsfile.js\" data-ut=\"user_token\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p><em>the script file</em></p>\n\n<pre><code>if($('script[src^=\"https://thesaasdomain.com/somejsfile.js?\"]').length !== 0) {\n init();\n} else {\n loadScript(\"https://thesaasdomain.com/somejsfile.js?\" + guid());\n}\n\nvar loadscript = function(scriptURL) {\n var head = document.getElementsByTagName('head')[0];\n var script = document.createElement('script');\n script.type = 'text/javascript';\n script.src = scriptURL;\n head.appendChild(script);\n}\n\nvar guid = function() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r &amp; 0x3 | 0x8);\n return v.toString(16);\n });\n}\n\nvar init = function() {\n // our main code\n}\n</code></pre>\n\n<p><strong>Explanation:</strong></p>\n\n<p>The user have attached the script provided to them in their website and we checked for the unique token attached with the script exists or not using jQuery selector and if not then load it dynamically with newer token (or version)</p>\n\n<p>This is call the same script twice which could be a performance issue, but it really solves the problem of forcing the script to not load from the cache without putting the version in the actual script link given to the user or client</p>\n\n<blockquote>\n <p>Disclaimer: Do not use if performance is a big issue in your case.</p>\n</blockquote>\n" }, { "answer_id": 52535465, "author": "schrodinger's code", "author_id": 142372, "author_profile": "https://Stackoverflow.com/users/142372", "pm_score": 4, "selected": false, "text": "<p>The common practice nowadays is to generate a content hash code as part of the file name to force the browser especially IE to reload the javascript files or css files. </p>\n\n<p>For example, </p>\n\n<p>vendor.<strong>a7561fb0e9a071baadb9</strong>.js<br>\nmain.<strong>b746e3eb72875af2caa9</strong>.js</p>\n\n<p>It is generally the job for the build tools such as webpack. Here is more <a href=\"https://webpack.js.org/guides/caching/#output-filenames\" rel=\"noreferrer\">details</a> if anyone wants to try out if you are using webpack.</p>\n" }, { "answer_id": 53721063, "author": "dragonal", "author_id": 7376037, "author_profile": "https://Stackoverflow.com/users/7376037", "pm_score": 2, "selected": false, "text": "<p>In asp.net mvc you can use <strong>@DateTime.UtcNow.ToString()</strong> for js file version number. Version number auto change with date and you force clients browser to refresh automatically js file. I using this method and this is work well.</p>\n\n<pre><code>&lt;script src=\"~/JsFilePath/[email protected]()\"&gt;&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 54941810, "author": "H.Ostwal", "author_id": 7750626, "author_profile": "https://Stackoverflow.com/users/7750626", "pm_score": 0, "selected": false, "text": "<p>Below worked for me: </p>\n\n<pre><code>&lt;head&gt;\n&lt;meta charset=\"UTF-8\"&gt;\n&lt;meta http-equiv=\"cache-control\" content=\"no-cache, must-revalidate, post-check=0, pre-check=0\" /&gt;\n&lt;meta http-equiv=\"cache-control\" content=\"max-age=0\" /&gt;\n&lt;meta http-equiv=\"expires\" content=\"0\" /&gt;\n&lt;meta http-equiv=\"expires\" content=\"Tue, 01 Jan 1980 1:00:00 GMT\" /&gt;\n&lt;meta http-equiv=\"pragma\" content=\"no-cache\" /&gt;\n&lt;/head&gt;\n</code></pre>\n" }, { "answer_id": 58064317, "author": "Megan", "author_id": 11364541, "author_profile": "https://Stackoverflow.com/users/11364541", "pm_score": 2, "selected": false, "text": "<p>location.reload(true);</p>\n\n<p>see <a href=\"https://www.w3schools.com/jsref/met_loc_reload.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/jsref/met_loc_reload.asp</a></p>\n\n<p>I dynamically call this line of code in order to ensure that javascript has been re-retrieved from the web server instead of from the browser's cache in order to escape this problem.</p>\n" }, { "answer_id": 62428811, "author": "Mohamad Hamouday", "author_id": 4110122, "author_profile": "https://Stackoverflow.com/users/4110122", "pm_score": 1, "selected": false, "text": "<p>You can add file version to your file name so it will be like:</p>\n\n<pre><code>https://www.example.com/script_fv25.js\n</code></pre>\n\n<p>fv25 => file version nr. 25</p>\n\n<p>And in your .htaccess put this block which will delete the version part from link:</p>\n\n<pre><code>RewriteEngine On\nRewriteRule (.*)_fv\\d+\\.(js|css|txt|jpe?g|png|svg|ico|gif) $1.$2 [L]\n</code></pre>\n\n<p>so the final link will be:</p>\n\n<pre><code>https://www.example.com/script.js\n</code></pre>\n" }, { "answer_id": 63309105, "author": "Luis Lobo", "author_id": 11212275, "author_profile": "https://Stackoverflow.com/users/11212275", "pm_score": 1, "selected": false, "text": "<p>FRONT-END OPTION</p>\n<p>I made this code <strong>specifically</strong> for those who can't change any settings on the backend. In this case the best way to prevent a very long cache is with:</p>\n<pre><code>new Date().getTime()\n</code></pre>\n<p>However, for most programmers the cache can be a few minutes or hours so the simple code above ends up forcing all users to download &quot;the each page browsed&quot;. To specify how long this item will remain without reloading I made this code and left several examples below:</p>\n<pre><code>// cache-expires-after.js v1\nfunction cacheExpiresAfter(delay = 1, prefix = '', suffix = '') { // seconds\n let now = new Date().getTime().toString();\n now = now.substring(now.length - 11, 10); // remove decades and milliseconds\n now = parseInt(now / delay).toString();\n return prefix + now + suffix;\n};\n\n// examples (of the delay argument):\n// the value changes every 1 second\nvar cache = cacheExpiresAfter(1);\n// see the sync\nsetInterval(function(){\n console.log(cacheExpiresAfter(1), new Date().getSeconds() + 's');\n}, 1000);\n\n// the value changes every 1 minute\nvar cache = cacheExpiresAfter(60);\n// see the sync\nsetInterval(function(){\n console.log(cacheExpiresAfter(60), new Date().getMinutes() + 'm:' + new Date().getSeconds() + 's');\n}, 1000);\n\n// the value changes every 5 minutes\nvar cache = cacheExpiresAfter(60 * 5); // OR 300\n\n// the value changes every 1 hour\nvar cache = cacheExpiresAfter(60 * 60); // OR 3600\n\n// the value changes every 3 hours\nvar cache = cacheExpiresAfter(60 * 60 * 3); // OR 10800\n\n// the value changes every 1 day\nvar cache = cacheExpiresAfter(60 * 60 * 24); // OR 86400\n\n// usage example:\nlet head = document.head || document.getElementsByTagName('head')[0];\nlet script = document.createElement('script');\nscript.setAttribute('src', '//unpkg.com/[email protected]/dist/sweetalert.min.js' + cacheExpiresAfter(60 * 5, '?'));\nhead.append(script);\n\n// this works?\nlet waitSwal = setInterval(function() {\n if (window.swal) {\n clearInterval(waitSwal);\n swal('Script successfully injected', script.outerHTML);\n };\n}, 100);\n</code></pre>\n" }, { "answer_id": 65130064, "author": "Hans-Peter Stricker", "author_id": 363429, "author_profile": "https://Stackoverflow.com/users/363429", "pm_score": -1, "selected": false, "text": "<p>A simple trick that works fine for me to prevent conflicts between older and newer javascript files. That means: If there is a conflict and some error occurs, the user will be prompted to press Ctrl-F5.</p>\n<p>At the top of the page add something like</p>\n<pre><code>&lt;h1 id=&quot;welcome&quot;&gt; Welcome to this page &lt;span style=&quot;color:red&quot;&gt;... press Ctrl-F5&lt;/span&gt;&lt;/h1&gt;\n</code></pre>\n<p>looking like</p>\n<p><a href=\"https://i.stack.imgur.com/yiqlQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yiqlQ.png\" alt=\"enter image description here\" /></a></p>\n<p>Let this line of javascript be the last to be executed when loading the page:</p>\n<pre><code>document.getElementById(&quot;welcome&quot;).innerHTML = &quot;Welcome to this page&quot;\n</code></pre>\n<p>In case that no error occurs the welcome greeting above will hardly be visible and almost immediately be replaced by</p>\n<p><a href=\"https://i.stack.imgur.com/IVakd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IVakd.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 66656955, "author": "Darshan Jain", "author_id": 5840973, "author_profile": "https://Stackoverflow.com/users/5840973", "pm_score": 0, "selected": false, "text": "<p>If you are using PHP and Javascript then the following should work for you especially in the situation where you are doing multiple times changes on the file. So, every time you cannot change its version. So, the idea is to create a random number in PHP and then assign it as a version of the JS file.</p>\n<pre><code>$fileVersion = rand();\n&lt;script src=&quot;addNewStudent.js?v=&lt;?php echo $fileVersion; ?&gt;&quot;&gt;&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 73223699, "author": "Ingo", "author_id": 2278668, "author_profile": "https://Stackoverflow.com/users/2278668", "pm_score": -1, "selected": false, "text": "<p>You can do this with .htaccess</p>\n<p>Add into your .htaccess file the following lines:</p>\n<pre><code># DISABLE CACHING\n&lt;IfModule mod_headers.c&gt;\n &lt;FilesMatch &quot;\\.js$&quot;&gt;\n Header set Cache-Control &quot;no-store, max-age=0&quot;\n &lt;/FilesMatch&gt;\n&lt;/IfModule&gt;\n</code></pre>\n" }, { "answer_id": 73327865, "author": "Reggie Pinkham", "author_id": 2927114, "author_profile": "https://Stackoverflow.com/users/2927114", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;script&gt; \n var version = new Date().getTime(); \n var script = document.createElement(&quot;script&quot;); \n script.src = &quot;app.js?=&quot; + version; \n document.body.appendChild(script); \n&lt;/script&gt;\n</code></pre>\n<p>Feel free to delete this if someone's already posted it somewhere in the plethora of answers above.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2176/" ]
We are currently working in a private beta and so are still in the process of making fairly rapid changes, although obviously as usage is starting to ramp up, we will be slowing down this process. That being said, one issue we are running into is that after we push out an update with new JavaScript files, the client browsers still use the cached version of the file and they do not see the update. Obviously, on a support call, we can simply inform them to do a `ctrl``F5` refresh to ensure that they get the up-to-date files from the server, but it would be preferable to handle this before that time. Our current thought is to simply attach a version number onto the name of the JavaScript files and then when changes are made, increment the version on the script and update all references. This definitely gets the job done, but updating the references on each release could get cumbersome. As I'm sure we're not the first ones to deal with this, I figured I would throw it out to the community. How are you ensuring clients update their cache when you update your code? If you're using the method described above, are you using a process that simplifies the change?
As far as I know a common solution is to add a `?<version>` to the script's src link. For instance: ``` <script type="text/javascript" src="myfile.js?1500"></script> ``` --- > > I assume at this point that there isn't a better way than find-replace to increment these "version numbers" in all of the script tags? > > > You might have a version control system do that for you? Most version control systems have a way to automatically inject the revision number on check-in for instance. It would look something like this: ``` <script type="text/javascript" src="myfile.js?$$REVISION$$"></script> ``` --- Of course, there are always better solutions like [this one](http://blog.greenfelt.net/2009/09/01/caching-javascript-safely/).
32,428
<p>I've created an assembly and referenced it in my Reporting Services report. I've tested the report locally (works), and I then uploaded the report to a report server (doesn't work).</p> <p>Here is the error that is thrown by the custom code I've written.</p> <blockquote> <p>System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. at System.Security.CodeAccessSecurityEngine.CheckNReturnSO(PermissionToken permToken, CodeAccessPermission demand, StackCrawlMark&amp; stackMark, Int32 unrestrictedOverride, Int32 create) at System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission cap, StackCrawlMark&amp; stackMark) at System.Security.CodeAccessPermission.Assert() at [Snipped Method Name] at ReportExprHostImpl.CustomCodeProxy.[Snipped Method Name] The action that failed was: Demand The type of the first permission that failed was: System.Security.Permissions.SecurityPermission The Zone of the assembly that failed was: MyComputer</p> </blockquote> <p>This project is something I inherited, and I'm not intimately familiar with it. Although I do have the code (now), so I can at least work with it :)</p> <p>I believe the code that is failing is this:</p> <pre><code> Dim fio As System.Security.Permissions.FileIOPermission = New System.Security.Permissions.FileIOPermission(Security.Permissions.PermissionState.Unrestricted) fio.Assert() </code></pre> <p>However, this kind of stuff is everywhere too:</p> <pre><code>Private Declare Function CryptHashData Lib "advapi32.dll" (ByVal hhash As Integer, ByVal pbData As String, ByVal dwDataLen As Integer, ByVal dwFlags As Integer) As Integer </code></pre> <p>I can see either of these being things that Reporting Services would not accommodate out of the box.</p>
[ { "answer_id": 37379, "author": "Ian Robinson", "author_id": 326, "author_profile": "https://Stackoverflow.com/users/326", "pm_score": 4, "selected": true, "text": "<p>This is how I was able to solve the issue:</p>\n\n<ul>\n<li>strongly sign the custom assembly in question</li>\n<li><p>modify the rssrvpolicy.config file to add permissions for the assembly</p>\n\n<pre><code> &lt;CodeGroup\n class=\"UnionCodeGroup\"\n version=\"1\"\n PermissionSetName=\"FullTrust\"\n Name=\"Test\"\n Description=\"This code group grants the Test code full trust. \"&gt;\n &lt;IMembershipCondition\n class=\"StrongNameMembershipCondition\"\n version=\"1\"\n PublicKeyBlob=\"0024000004800000940100000602000000240000575341310004000001000100ab4b135615ca6dfd586aa0c5807b3e07fa7a02b3f376c131e0442607de792a346e64710e82c833b42c672680732f16193ba90b2819a77fa22ac6d41559724b9c253358614c270c651fad5afe9a0f8cbd1e5e79f35e0f04cb3e3b020162ac86f633cf0d205263280e3400d1a5b5781bf6bd12f97917dcdde3c8d03ee61ccba2c0\"\n /&gt;\n &lt;/CodeGroup&gt;\n</code></pre></li>\n</ul>\n\n<p>Side note: here is a great way to get the public key blob of your assembly\n<a href=\"http://www.andrewconnell.com/blog/archive/2006/09/15/4587.aspx\" rel=\"noreferrer\">VS trick for obtaining the public key token and blob of a signed assembly</a>. </p>\n" }, { "answer_id": 5516520, "author": "Noorani raza", "author_id": 687994, "author_profile": "https://Stackoverflow.com/users/687994", "pm_score": 4, "selected": false, "text": "<pre><code>&lt;system.web&gt;\n\n&lt;trust level=\"Full\"/&gt;\n\n&lt;/system.web&gt;\n</code></pre>\n\n<p>try this in web.config</p>\n" }, { "answer_id": 29919076, "author": "user3085636", "author_id": 3085636, "author_profile": "https://Stackoverflow.com/users/3085636", "pm_score": 0, "selected": false, "text": "<p>Run your service in administrator mode</p>\n" }, { "answer_id": 54830270, "author": "Neil Schurrer", "author_id": 6104737, "author_profile": "https://Stackoverflow.com/users/6104737", "pm_score": 0, "selected": false, "text": "<pre><code> &lt;CodeGroup class=\"FirstMatchCodeGroup\" version=\"1\" PermissionSetName=\"FullTrust\"&gt;\n</code></pre>\n\n<p>For me, the solution was changing the above line in the <code>rssrvpolicy.config</code> from <code>\"None\"</code> to <code>\"FullTrust\"</code>.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326/" ]
I've created an assembly and referenced it in my Reporting Services report. I've tested the report locally (works), and I then uploaded the report to a report server (doesn't work). Here is the error that is thrown by the custom code I've written. > > System.Security.SecurityException: > Request for the permission of type > 'System.Security.Permissions.SecurityPermission, > mscorlib, Version=2.0.0.0, > Culture=neutral, > PublicKeyToken=b77a5c561934e089' > failed. at > System.Security.CodeAccessSecurityEngine.CheckNReturnSO(PermissionToken > permToken, CodeAccessPermission > demand, StackCrawlMark& stackMark, > Int32 unrestrictedOverride, Int32 > create) at > System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission > cap, StackCrawlMark& stackMark) at > System.Security.CodeAccessPermission.Assert() > at [Snipped Method Name] at > ReportExprHostImpl.CustomCodeProxy.[Snipped Method Name] The action that failed was: > Demand The type of the first > permission that failed was: > System.Security.Permissions.SecurityPermission > The Zone of the assembly that failed > was: MyComputer > > > This project is something I inherited, and I'm not intimately familiar with it. Although I do have the code (now), so I can at least work with it :) I believe the code that is failing is this: ``` Dim fio As System.Security.Permissions.FileIOPermission = New System.Security.Permissions.FileIOPermission(Security.Permissions.PermissionState.Unrestricted) fio.Assert() ``` However, this kind of stuff is everywhere too: ``` Private Declare Function CryptHashData Lib "advapi32.dll" (ByVal hhash As Integer, ByVal pbData As String, ByVal dwDataLen As Integer, ByVal dwFlags As Integer) As Integer ``` I can see either of these being things that Reporting Services would not accommodate out of the box.
This is how I was able to solve the issue: * strongly sign the custom assembly in question * modify the rssrvpolicy.config file to add permissions for the assembly ``` <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="FullTrust" Name="Test" Description="This code group grants the Test code full trust. "> <IMembershipCondition class="StrongNameMembershipCondition" version="1" PublicKeyBlob="0024000004800000940100000602000000240000575341310004000001000100ab4b135615ca6dfd586aa0c5807b3e07fa7a02b3f376c131e0442607de792a346e64710e82c833b42c672680732f16193ba90b2819a77fa22ac6d41559724b9c253358614c270c651fad5afe9a0f8cbd1e5e79f35e0f04cb3e3b020162ac86f633cf0d205263280e3400d1a5b5781bf6bd12f97917dcdde3c8d03ee61ccba2c0" /> </CodeGroup> ``` Side note: here is a great way to get the public key blob of your assembly [VS trick for obtaining the public key token and blob of a signed assembly](http://www.andrewconnell.com/blog/archive/2006/09/15/4587.aspx).
32,433
<p>This query works great:</p> <pre><code>var pageObject = (from op in db.ObjectPermissions join pg in db.Pages on op.ObjectPermissionName equals page.PageName where pg.PageID == page.PageID select op) .SingleOrDefault(); </code></pre> <p>I get a new type with my 'op' fields. Now I want to retrieve my 'pg' fields as well, but</p> <pre><code>select op, pg).SingleOrDefault(); </code></pre> <p>doesn't work.</p> <p>How can I select everything from both tables so that they appear in my new pageObject type?</p>
[ { "answer_id": 32445, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>You must create a new anonymous type:</p>\n\n<pre><code> select new { op, pg }\n</code></pre>\n\n<p>Refer to the official <a href=\"http://msdn.microsoft.com/en-us/library/bb397696.aspx\" rel=\"nofollow noreferrer\">guide</a>.</p>\n" }, { "answer_id": 32449, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 1, "selected": false, "text": "<p>change </p>\n\n<pre><code>select op) \n</code></pre>\n\n<p>to</p>\n\n<pre><code>select new { op, pg })\n</code></pre>\n" }, { "answer_id": 32465, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 8, "selected": true, "text": "<p>You can use anonymous types for this, i.e.:</p>\n\n<pre><code>var pageObject = (from op in db.ObjectPermissions\n join pg in db.Pages on op.ObjectPermissionName equals page.PageName\n where pg.PageID == page.PageID\n select new { pg, op }).SingleOrDefault();\n</code></pre>\n\n<p>This will make pageObject into an IEnumerable of an anonymous type so AFAIK you won't be able to pass it around to other methods, however if you're simply obtaining data to play with in the method you're currently in it's perfectly fine. You can also name properties in your anonymous type, i.e.:-</p>\n\n<pre><code>var pageObject = (from op in db.ObjectPermissions\n join pg in db.Pages on op.ObjectPermissionName equals page.PageName\n where pg.PageID == page.PageID\n select new\n {\n PermissionName = pg, \n ObjectPermission = op\n }).SingleOrDefault();\n</code></pre>\n\n<p>This will enable you to say:-</p>\n\n<pre><code>if (pageObject.PermissionName.FooBar == \"golden goose\") Application.Exit();\n</code></pre>\n\n<p>For example :-)</p>\n" }, { "answer_id": 144219, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 3, "selected": false, "text": "<p>If you don't want to use anonymous types b/c let's say you're passing the object to another method, you can use the LoadWith load option to load associated data. It requires that your tables are associated either through foreign keys or in your Linq-to-SQL dbml model.</p>\n\n<pre><code>db.DeferredLoadingEnabled = false;\nDataLoadOptions dlo = new DataLoadOptions();\ndlo.LoadWith&lt;ObjectPermissions&gt;(op =&gt; op.Pages)\ndb.LoadOptions = dlo;\n\nvar pageObject = from op in db.ObjectPermissions\n select op;\n\n// no join needed\n</code></pre>\n\n<p>Then you can call </p>\n\n<pre><code>pageObject.Pages.PageID\n</code></pre>\n\n<p>Depending on what your data looks like, you'd probably want to do this the other way around,</p>\n\n<pre><code>DataLoadOptions dlo = new DataLoadOptions();\ndlo.LoadWith&lt;Pages&gt;(p =&gt; p.ObjectPermissions)\ndb.LoadOptions = dlo;\n\nvar pageObject = from p in db.Pages\n select p;\n\n// no join needed\n\nvar objectPermissionName = pageObject.ObjectPermissions.ObjectPermissionName;\n</code></pre>\n" }, { "answer_id": 10050917, "author": "daviddeath", "author_id": 1277335, "author_profile": "https://Stackoverflow.com/users/1277335", "pm_score": 2, "selected": false, "text": "<p>If the anonymous type causes trouble for you, you can create a simple data class:</p>\n\n<pre><code>public class PermissionsAndPages\n{\n public ObjectPermissions Permissions {get;set}\n public Pages Pages {get;set}\n}\n</code></pre>\n\n<p>and then in your query:</p>\n\n<pre><code>select new PermissionsAndPages { Permissions = op, Page = pg };\n</code></pre>\n\n<p>Then you can pass this around:</p>\n\n<pre><code>return queryResult.SingleOrDefault(); // as PermissionsAndPages\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047/" ]
This query works great: ``` var pageObject = (from op in db.ObjectPermissions join pg in db.Pages on op.ObjectPermissionName equals page.PageName where pg.PageID == page.PageID select op) .SingleOrDefault(); ``` I get a new type with my 'op' fields. Now I want to retrieve my 'pg' fields as well, but ``` select op, pg).SingleOrDefault(); ``` doesn't work. How can I select everything from both tables so that they appear in my new pageObject type?
You can use anonymous types for this, i.e.: ``` var pageObject = (from op in db.ObjectPermissions join pg in db.Pages on op.ObjectPermissionName equals page.PageName where pg.PageID == page.PageID select new { pg, op }).SingleOrDefault(); ``` This will make pageObject into an IEnumerable of an anonymous type so AFAIK you won't be able to pass it around to other methods, however if you're simply obtaining data to play with in the method you're currently in it's perfectly fine. You can also name properties in your anonymous type, i.e.:- ``` var pageObject = (from op in db.ObjectPermissions join pg in db.Pages on op.ObjectPermissionName equals page.PageName where pg.PageID == page.PageID select new { PermissionName = pg, ObjectPermission = op }).SingleOrDefault(); ``` This will enable you to say:- ``` if (pageObject.PermissionName.FooBar == "golden goose") Application.Exit(); ``` For example :-)
32,460
<p>Here's the situation: I need to bind a WPF <code>FixedPage</code> against a <code>DataRow</code>. Bindings don't work against <code>DataRows</code>; they work against <code>DataRowViews</code>. I need to do this in the most generic way possible, as I know nothing about and have no control over what is in the <code>DataRow</code>. </p> <p>What I need is to be able to get a <code>DataRowView</code> for a given <code>DataRow</code>. I can't use the <code>Find()</code> method on the <code>DefaultView</code> because that takes a key, and there is no guarantee the table will have a primary key set.</p> <p>Does anybody have a suggestion as to the best way to go around this? </p>
[ { "answer_id": 32483, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>row.Table.DefaultView[row.Table.Rows.IndexOf(row)]\n</code></pre>\n\n<p>This is an okay answer. But if you find yourself in this situation, you should consider learning more about DataViews and how they are used, then refactor your code to be view-centric rather than table-centric.</p>\n" }, { "answer_id": 6989851, "author": "Joel Barsotti", "author_id": 37154, "author_profile": "https://Stackoverflow.com/users/37154", "pm_score": 4, "selected": true, "text": "<p>Not Exactly a sexy piece of code but their doesn't seem to be an automated way to find the row without just looping the table.</p>\n\n<pre><code> DataRowView newRowView = null;\n foreach (DataRowView tempRowView in myDataTable.DefaultView)\n {\n if (tempRowView.Row == rowToMatch)\n newRowView = tempRowView;\n }\n if (newRow != null)\n UseNewRowView(newRowView);\n else\n HandleRowNotFound();\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Here's the situation: I need to bind a WPF `FixedPage` against a `DataRow`. Bindings don't work against `DataRows`; they work against `DataRowViews`. I need to do this in the most generic way possible, as I know nothing about and have no control over what is in the `DataRow`. What I need is to be able to get a `DataRowView` for a given `DataRow`. I can't use the `Find()` method on the `DefaultView` because that takes a key, and there is no guarantee the table will have a primary key set. Does anybody have a suggestion as to the best way to go around this?
Not Exactly a sexy piece of code but their doesn't seem to be an automated way to find the row without just looping the table. ``` DataRowView newRowView = null; foreach (DataRowView tempRowView in myDataTable.DefaultView) { if (tempRowView.Row == rowToMatch) newRowView = tempRowView; } if (newRow != null) UseNewRowView(newRowView); else HandleRowNotFound(); ```
32,462
<p>So I've got a hobby site I'm working on. I've got items that are tagged and I want to associate those items with photos from Flickr. Even with restrictive searches, I might get results numbering in the thousands.</p> <p>Requirements:</p> <ol> <li>I want to display between 10-20 pictures but I want to randomize the photos each time. </li> <li>I don't want to hit Flickr every time a page request is made. </li> <li>Not every Flickr photo with the same tags as my item will be relevant.</li> </ol> <p>How should I store that number of results and how would I determine which ones are relevant?</p>
[ { "answer_id": 32483, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>row.Table.DefaultView[row.Table.Rows.IndexOf(row)]\n</code></pre>\n\n<p>This is an okay answer. But if you find yourself in this situation, you should consider learning more about DataViews and how they are used, then refactor your code to be view-centric rather than table-centric.</p>\n" }, { "answer_id": 6989851, "author": "Joel Barsotti", "author_id": 37154, "author_profile": "https://Stackoverflow.com/users/37154", "pm_score": 4, "selected": true, "text": "<p>Not Exactly a sexy piece of code but their doesn't seem to be an automated way to find the row without just looping the table.</p>\n\n<pre><code> DataRowView newRowView = null;\n foreach (DataRowView tempRowView in myDataTable.DefaultView)\n {\n if (tempRowView.Row == rowToMatch)\n newRowView = tempRowView;\n }\n if (newRow != null)\n UseNewRowView(newRowView);\n else\n HandleRowNotFound();\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2863/" ]
So I've got a hobby site I'm working on. I've got items that are tagged and I want to associate those items with photos from Flickr. Even with restrictive searches, I might get results numbering in the thousands. Requirements: 1. I want to display between 10-20 pictures but I want to randomize the photos each time. 2. I don't want to hit Flickr every time a page request is made. 3. Not every Flickr photo with the same tags as my item will be relevant. How should I store that number of results and how would I determine which ones are relevant?
Not Exactly a sexy piece of code but their doesn't seem to be an automated way to find the row without just looping the table. ``` DataRowView newRowView = null; foreach (DataRowView tempRowView in myDataTable.DefaultView) { if (tempRowView.Row == rowToMatch) newRowView = tempRowView; } if (newRow != null) UseNewRowView(newRowView); else HandleRowNotFound(); ```
32,537
<p>For scripting languages, what is the most effective way to utilize a console when developing? Are there ways to be more productive with a console than a "compile and run" only language?</p> <p>Added clarification: I am thinking more along the lines of Ruby, Python, Boo, etc. Languages that are used for full blown apps, but also have a way to run small snippets of code in a console.</p>
[ { "answer_id": 32557, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 1, "selected": false, "text": "<p>I think it depends on the console. The usefulness of a CMD console on windows pails in comparison to a Powershell console.</p>\n" }, { "answer_id": 32588, "author": "Pat", "author_id": 36, "author_profile": "https://Stackoverflow.com/users/36", "pm_score": 0, "selected": false, "text": "<p>I've added a shortcut to my Control-Shift-C key combination to bring up my Visual Studio 2008 Console. This alone has saved me countless seconds when needing to register a dll or do any other command. I imagine if you leverage this with another command tool and you may have some massive productivity increases.</p>\n" }, { "answer_id": 32599, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 0, "selected": false, "text": "<p>Are you kidding?</p>\n\n<p>In my Linux environment, the console is my lifeblood. I'm proficient in bash scripting, so to me a console is very much like sitting in a REPL for Python or Lisp. You can quite literally do anything.</p>\n\n<p>I actually write tools used by my team in bash, and the console is the perfect place to do that development. I really only need an editor as a backing store for things as I figure them out.</p>\n" }, { "answer_id": 32686, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>I am thinking more along the lines of Ruby, ...</p>\n</blockquote>\n\n<p>Well for Ruby the <code>irb</code> interactive prompt is a great tool for \"practicing\" something simple. Here are the things I'll mention about the irb to give you an idea of effective use:</p>\n\n<ul>\n<li><p><em>Automation</em>. You are allowed a <code>.irbrc</code> file that will be automatically executed when launching irb. That means you can load your favorite libraries or do <em>whatever</em> you want in full Ruby automatically. To see what I mean check out some of the ones at <a href=\"https://web.archive.org/web/20110824004021/http://dotfiles.org:80/.irbrc\" rel=\"nofollow noreferrer\">dotfiles.org</a>.</p></li>\n<li><p><em>Autocompletion</em>. That even makes writing code easier. Can't remember that string method to remove newlines? <code>\"\".ch&lt;tab&gt;</code> produces chop and chomp. <em>NOTE: you have to enable autocompletion for irb yourself</em></p></li>\n<li><p><em>Divide and Conquer</em>. irb makes the small things really easy. If you're writing a function to manipulate strings, the ability to test the code interactively right in the prompt saves a lot of time! For instance you can just open up irb and start running functions on an example string and have working and tested code already ready for your library/program. </p></li>\n<li><p><em>Learning, Experimenting, and Hacking</em>. Something like this would take a very long time to test in C/C++, even Java. If you tried testing them all at once you might seg-fault and have to start over.</p>\n\n<p>Here I'm just learning how the <code>String#[]</code> function works.</p>\n\n<pre><code>joe[~]$ irb\n&gt;&gt; \"12341:asdf\"[/\\d+/]\n# =&gt; \"12341\" \n&gt;&gt; \"12341:asdf\"[/\\d*/]\n# =&gt; \"12341\" \n&gt;&gt; \"12341:asdf\"[0..5]\n# =&gt; \"12341:\" \n&gt;&gt; \"12341:asdf\"[0...5]\n# =&gt; \"12341\" \n&gt;&gt; \"12341:asdf\"[0, ':']\nTypeError: can't convert String into Integer\n from (irb):5:in `[]'\n from (irb):5\n&gt;&gt; \"12341:asdf\"[0, 5]\n# =&gt; \"12341\" \n</code></pre></li>\n<li><p><em>Testing and Benchmarking</em>. Now they are nice and easy to perform. <a href=\"http://ozmm.org/posts/time_in_irb.html\" rel=\"nofollow noreferrer\">Here</a> is someone's idea to emulate the Unix <code>time</code> function for quick benchmarking. Just add it to your <code>.irbrc</code> file and its always there!</p></li>\n<li><p><em>Debugging</em> - I haven't used this much myself but there is always the ability to debug code <a href=\"https://web.archive.org/web/20080912141043/http://www.rubycentral.com:80/pickaxe/trouble.html\" rel=\"nofollow noreferrer\">like this</a>. Or pull out some code and run it in the irb to see what its actually doing.</p></li>\n</ul>\n\n<p>I'm sure I'm missing some things but I hit on my favorite points. You really have zero limitation in shells so you're limited only by what you can think of doing. I almost always have a few shells running. Bash, Javascript, and Ruby's irb to name a few. I use them for a lot of things!</p>\n" }, { "answer_id": 36446, "author": "asussex", "author_id": 3796, "author_profile": "https://Stackoverflow.com/users/3796", "pm_score": 1, "selected": false, "text": "<p>You didn't say what OS you're using but on Linux I been using a tabbed window manager (<a href=\"http://www.suckless.org/wmii/\" rel=\"nofollow noreferrer\">wmii</a>) for a year or so and it has radically changed the way I use applications - consoles or otherwise.</p>\n\n<p>I often have four or more consoles and other apps on a virtual desktop and with wmii I don't have to fiddle with resizing windows to line everything up just so. I can trivially rearrange them into vertical columns, stack them up vertically, have them share equal amounts of vertical or horizontal space, and move them between screens.</p>\n\n<p>Say you open two consoles on your desktop. You'd get this (with apologies for the cronkey artwork):</p>\n\n<pre><code> ----------------\n| |\n| 1 |\n| |\n ----------------\n ----------------\n| |\n| 2 |\n| |\n ----------------\n</code></pre>\n\n<p>Now I want them side-by-side. I enter SHIFT-ALT-L in window 2 to move it rightwards and create two columns:</p>\n\n<pre><code> ------- -------\n| || |\n| || |\n| 1 || 2 |\n| || |\n| || |\n ------- -------\n</code></pre>\n\n<p>Now I could open another console and get</p>\n\n<pre><code> ------- -------\n| || 2 |\n| || |\n| | -------\n| 1 | -------\n| || 3 |\n| || |\n ------- -------\n</code></pre>\n\n<p>Then I want to temporarily view console 3 full-height, so I hit ALT-s in it and get:</p>\n\n<pre><code> ------- -------\n| | -------\n| || |\n| 1 || 3 |\n| || |\n| || |\n ------- -------\n</code></pre>\n\n<p>Consoles 2 and 3 are stacked up now.</p>\n\n<p>I could also give windows tags. For example, in console 2 I could say ALT-SHIFT-twww+dev and that console would be visible in the 'www' and 'dev' virtual desktops. (The desktops are created if they don't already exist.) Even better, the console can be in a different visual configuration (e.g., stacked and full-screen) on each of those desktops.</p>\n\n<p>Anyway, I can't do tabbed window managers justice here. I don't know if it's relevant to your environment but if you get the chance to try this way of working you probably won't look back.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2001/" ]
For scripting languages, what is the most effective way to utilize a console when developing? Are there ways to be more productive with a console than a "compile and run" only language? Added clarification: I am thinking more along the lines of Ruby, Python, Boo, etc. Languages that are used for full blown apps, but also have a way to run small snippets of code in a console.
> > I am thinking more along the lines of Ruby, ... > > > Well for Ruby the `irb` interactive prompt is a great tool for "practicing" something simple. Here are the things I'll mention about the irb to give you an idea of effective use: * *Automation*. You are allowed a `.irbrc` file that will be automatically executed when launching irb. That means you can load your favorite libraries or do *whatever* you want in full Ruby automatically. To see what I mean check out some of the ones at [dotfiles.org](https://web.archive.org/web/20110824004021/http://dotfiles.org:80/.irbrc). * *Autocompletion*. That even makes writing code easier. Can't remember that string method to remove newlines? `"".ch<tab>` produces chop and chomp. *NOTE: you have to enable autocompletion for irb yourself* * *Divide and Conquer*. irb makes the small things really easy. If you're writing a function to manipulate strings, the ability to test the code interactively right in the prompt saves a lot of time! For instance you can just open up irb and start running functions on an example string and have working and tested code already ready for your library/program. * *Learning, Experimenting, and Hacking*. Something like this would take a very long time to test in C/C++, even Java. If you tried testing them all at once you might seg-fault and have to start over. Here I'm just learning how the `String#[]` function works. ``` joe[~]$ irb >> "12341:asdf"[/\d+/] # => "12341" >> "12341:asdf"[/\d*/] # => "12341" >> "12341:asdf"[0..5] # => "12341:" >> "12341:asdf"[0...5] # => "12341" >> "12341:asdf"[0, ':'] TypeError: can't convert String into Integer from (irb):5:in `[]' from (irb):5 >> "12341:asdf"[0, 5] # => "12341" ``` * *Testing and Benchmarking*. Now they are nice and easy to perform. [Here](http://ozmm.org/posts/time_in_irb.html) is someone's idea to emulate the Unix `time` function for quick benchmarking. Just add it to your `.irbrc` file and its always there! * *Debugging* - I haven't used this much myself but there is always the ability to debug code [like this](https://web.archive.org/web/20080912141043/http://www.rubycentral.com:80/pickaxe/trouble.html). Or pull out some code and run it in the irb to see what its actually doing. I'm sure I'm missing some things but I hit on my favorite points. You really have zero limitation in shells so you're limited only by what you can think of doing. I almost always have a few shells running. Bash, Javascript, and Ruby's irb to name a few. I use them for a lot of things!
32,540
<p>How is your javaScript code organized? Does it follow patterns like MVC, or something else? </p> <p>I've been working on a side project for some time now, and the further I get, the more my webpage has turned into a full-featured application. Right now, I'm sticking with <a href="http://jquery.com" rel="noreferrer">jQuery</a>, however, the logic on the page is growing to a point where some organization, or dare I say it, "architecture" is needed. My first approach is "MVC-ish":</p> <ul> <li>The 'model' is a JSON tree that gets extended with helpers</li> <li>The view is the DOM plus classes that tweak it</li> <li>The controller is the object where I connect events handling and kick off view or model manipulation</li> </ul> <p>I'm very interested, however, in how other people have built more substantial javaScript apps. I'm not interested in GWT, or other server-oriented approaches... just in the approach of "javaScript + &lt;generic web service-y thingy here&gt;"</p> <p>Note: earlier I said javaScript "is not really OO, not really functional". This, I think, distracted everyone. Let's put it this way, because javaScript is unique in many ways, and I'm coming from a strongly-typed background, I don't want to force paradigms I know but were developed in very different languages.</p>
[ { "answer_id": 32594, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 4, "selected": true, "text": "<p>..but Javascript has many facets that <strong>are</strong> OO.</p>\n\n<p>Consider this:</p>\n\n<pre><code>var Vehicle = jQuery.Class.create({ \n init: function(name) { this.name = name; } \n});\n\nvar Car = Vehicle.extend({ \n fillGas: function(){ \n this.gas = 100; \n } \n});\n</code></pre>\n\n<p>I've used this technique to create page-level javascript classes that have their own state, this helps keep it contained (and I often identify areas that I can reuse and put into other classes).</p>\n\n<p>This is also especially useful when you have components/server controls that have their own script to execute, but when you might have multiple instances on the same page. This keeps the state separate.</p>\n" }, { "answer_id": 32602, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 1, "selected": false, "text": "<p>Not 100% sure what you mean here, but I will say that after doing ASP.NET for the last 6 years, my web pages are now mostly driven by JavaScript once the basic page rendering is done by the server. I use JSON for everything (have been for about 3 years now) and use <a href=\"http://www.mochikit.com\" rel=\"nofollow noreferrer\"><strong>MochiKit</strong></a> for my client-side needs.</p>\n\n<p>By the way, JavaScript <em>is</em> OO, but since it uses prototypical inheritance, people don't give it credit in that way. I would also argue that it is functional as well, it all depends on how you write it. If you are really interested in functional programming styles, check out <a href=\"http://www.mochikit.com\" rel=\"nofollow noreferrer\"><strong>MochiKit</strong></a> - you may like it; it leans quite a bit towards the functional programming side of JavaScript.</p>\n" }, { "answer_id": 35177, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 2, "selected": false, "text": "<p>MochiKit is great -- and was my first love, so-to-speak, as far as js libraries go. But I found that while MochiKit has very expressive syntax, it didn't feel nearly as comfortable to me as Prototype/Scriptaculous or jQuery did for me.</p>\n\n<p>I think if you know or like python, then MochiKit is a good tool for you.</p>\n" }, { "answer_id": 62770, "author": "Tristan Juricek", "author_id": 3436, "author_profile": "https://Stackoverflow.com/users/3436", "pm_score": 2, "selected": false, "text": "<p>Thank you all kindly for your answers. After some time, I'd like to post what I've learned so far.</p>\n\n<p>So far, I see a very large difference the approach using something like <a href=\"http://extjs.com\" rel=\"nofollow noreferrer\">Ext</a>, and others like <a href=\"http://ui.jquery.com\" rel=\"nofollow noreferrer\">JQuery UI</a>, <a href=\"http://script.aculo.us\" rel=\"nofollow noreferrer\">Scriptaculous</a>, <a href=\"http://mochikit.org\" rel=\"nofollow noreferrer\">MochiKit</a>, etc. </p>\n\n<p>With Ext, the HTML is just a single placeholder - UI goes here. From then on, <b>everything</b> is described in JavaScript. DOM interaction is minimized under another (perhaps stronger) API layer.</p>\n\n<p>With the other kits, I find myself starting by doing a bit of HTML design, and then extending the DOM directly with snazzy effects, or just replacing the form input here, an addition there.</p>\n\n<p>The major differences start to happen as I need to deal with event handling, etc. As modules need to \"talk\" to each other, I find myself needing to step away from the DOM, abstracting it away in pieces.</p>\n\n<p>I note that many of these libraries also include some interesting modularization techniques as well. A very clear description is contributed on the Ext website, which includes <a href=\"http://extjs.com/learn/Manual:Basic_Application_Design\" rel=\"nofollow noreferrer\">a fancy way to \"protect\" your code with modules</a>. </p>\n\n<p>A new player I haven completely evaluated is <a href=\"http://sproutcore.com\" rel=\"nofollow noreferrer\">Sproutcore</a>. It seems like Ext in approach, where the DOM is hidden, and you mostly want to deal with the project's API.</p>\n" }, { "answer_id": 62961, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Tristan, you will find that when you try to architecture JavaScript as an MVC application it tends to come up short in one area -- the model. The most difficult area to deal with is the model because the data does not persist throughout the application, and by nature the models seem to change on the client-side pretty consistently. You could standardize how you pass and receive data from the server, but then at that point the model does not really belong to JavaScript -- it belongs to your server-side application.</p>\n\n<p>I did see one attempt awhile back where someone created a framework for modeling data in JavaScript, much like the way SQLite belongs to the application. It was like Model.select( \"Product\" ) and Model.update( \"Product\", \"Some data...\" ). It was basically an object notation that held a bunch of data to manage the state of the current page. However, the minute you refresh, all that data is lost. I'm probably off on the syntax, but you get the point.</p>\n\n<p>If you are using jQuery, then Ben's approach is really the best. Extend the jQuery object with your functions and properties, and then compartmentalize your \"controllers\". I usually do this by putting them into separate source files, and loading them on a section-by-section basis. For instance, if it were an e-commerce site, I might have a JS file full of controllers that handle functionality for the checkout process. This tends to keep things lightweight and easy to manage.</p>\n" }, { "answer_id": 190378, "author": "Tahir Akhtar", "author_id": 18027, "author_profile": "https://Stackoverflow.com/users/18027", "pm_score": 2, "selected": false, "text": "<p>Just a quick clarification. </p>\n\n<p>It is perfectly feasible to write GWT apps that are not server-oriented. I am assuming that from Server-Oriented you mean GWT RPC that needs java based back-end. </p>\n\n<p>I have written GWT apps that are very \"MVC-ish\" on the client side alone. </p>\n\n<ul>\n<li>The model was an object graph. Although you code in Java, at runtime the objects are in javascript with no need of any JVM in either client or server-side. GWT also supports JSON with complete parsing and manipulation support. You can connect to JSON webservices easily, see <a href=\"http://code.google.com/support/bin/answer.py?answer=65632&amp;topic=11368\" rel=\"nofollow noreferrer\">2</a> for a JSON mashup example. </li>\n<li>View was composed of standard GWT widgets (plus some of our own composite widgets)</li>\n<li>Controller layer was neatly separated from View via Observer pattern.</li>\n</ul>\n\n<p>If your \"strongly-typed\" background is with Java or similar language, I think you should seriously consider GWT for large projects. For small projects I usually prefer jQuery. Upcoming <a href=\"http://code.google.com/p/gwtquery/\" rel=\"nofollow noreferrer\">GWTQuery</a> that works with GWT 1.5 may change that though not in near future because of abundance of plugins for jQuery.</p>\n" }, { "answer_id": 1316984, "author": "Justin Meyer", "author_id": 161238, "author_profile": "https://Stackoverflow.com/users/161238", "pm_score": 2, "selected": false, "text": "<p>JavaScriptMVC is a great choice for organizing and developing a large scale JS application.</p>\n\n<p>The architecture design very well thought out. There are 4 things you will ever do with JavaScript:</p>\n\n<ol>\n<li>Respond to an event </li>\n<li>Request Data / Manipulate Services (Ajax) </li>\n<li>Add domain specific information to the ajax response. </li>\n<li>Update the DOM</li>\n</ol>\n\n<p>JMVC splits these into the Model, View, Controller pattern.</p>\n\n<p>First, and probably the most important advantage, is the Controller. Controllers use event delegation, so instead of attaching events, you simply create rules for your page. They also use the name of the Controller to limit the scope of what the controller works on. This makes your code deterministic, meaning if you see an event happen in a '#todos' element you know there has to be a todos controller.</p>\n\n<pre><code>$.Controller.extend('TodosController',{\n 'click' : function(el, ev){ ... },\n '.delete mouseover': function(el, ev){ ...}\n '.drag draginit' : function(el, ev, drag){ ...}\n})\n</code></pre>\n\n<p>Next comes the model. JMVC provides a powerful Class and basic model that lets you quickly organize Ajax functionality (#2) and wrap the data with domain specific functionality (#3). When complete, you can use models from your controller like:</p>\n\n<p>Todo.findAll({after: new Date()}, myCallbackFunction);</p>\n\n<p>Finally, once your todos come back, you have to display them (#4). This is where you use JMVC's view. </p>\n\n<pre><code>'.show click' : function(el, ev){ \n Todo.findAll({after: new Date()}, this.callback('list'));\n},\nlist : function(todos){\n $('#todos').html( this.view(todos));\n}\n</code></pre>\n\n<p>In 'views/todos/list.ejs'</p>\n\n<pre><code>&lt;% for(var i =0; i &lt; this.length; i++){ %&gt;\n &lt;label&gt;&lt;%= this[i].description %&gt;&lt;/label&gt;\n&lt;%}%&gt;\n</code></pre>\n\n<p>JMVC provides a lot more than architecture. It helps you in ever part of the development cycle with:</p>\n\n<ul>\n<li>Code generators</li>\n<li>Integrated Browser, Selenium, and Rhino Testing</li>\n<li>Documentation</li>\n<li>Script compression</li>\n<li>Error reporting</li>\n</ul>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3436/" ]
How is your javaScript code organized? Does it follow patterns like MVC, or something else? I've been working on a side project for some time now, and the further I get, the more my webpage has turned into a full-featured application. Right now, I'm sticking with [jQuery](http://jquery.com), however, the logic on the page is growing to a point where some organization, or dare I say it, "architecture" is needed. My first approach is "MVC-ish": * The 'model' is a JSON tree that gets extended with helpers * The view is the DOM plus classes that tweak it * The controller is the object where I connect events handling and kick off view or model manipulation I'm very interested, however, in how other people have built more substantial javaScript apps. I'm not interested in GWT, or other server-oriented approaches... just in the approach of "javaScript + <generic web service-y thingy here>" Note: earlier I said javaScript "is not really OO, not really functional". This, I think, distracted everyone. Let's put it this way, because javaScript is unique in many ways, and I'm coming from a strongly-typed background, I don't want to force paradigms I know but were developed in very different languages.
..but Javascript has many facets that **are** OO. Consider this: ``` var Vehicle = jQuery.Class.create({ init: function(name) { this.name = name; } }); var Car = Vehicle.extend({ fillGas: function(){ this.gas = 100; } }); ``` I've used this technique to create page-level javascript classes that have their own state, this helps keep it contained (and I often identify areas that I can reuse and put into other classes). This is also especially useful when you have components/server controls that have their own script to execute, but when you might have multiple instances on the same page. This keeps the state separate.
32,541
<p>Anybody have a good example how to deep clone a WPF object, preserving databindings?</p> <hr> <p>The marked answer is the first part.</p> <p>The second part is that you have to create an ExpressionConverter and inject it into the serialization process. Details for this are here:<br> <a href="http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2801571" rel="noreferrer">http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2801571</a></p>
[ { "answer_id": 32575, "author": "Arcturus", "author_id": 900, "author_profile": "https://Stackoverflow.com/users/900", "pm_score": 0, "selected": false, "text": "<p>How about:</p>\n\n<pre><code> public static T DeepClone&lt;T&gt;(T from)\n {\n using (MemoryStream s = new MemoryStream())\n {\n BinaryFormatter f = new BinaryFormatter();\n f.Serialize(s, from);\n s.Position = 0;\n object clone = f.Deserialize(s);\n\n return (T)clone;\n }\n }\n</code></pre>\n\n<p>Of course this deep clones any object, and it might not be the fastest solution in town, but it has the least maintenance... :)</p>\n" }, { "answer_id": 33036, "author": "Alan Le", "author_id": 1133, "author_profile": "https://Stackoverflow.com/users/1133", "pm_score": 7, "selected": true, "text": "<p>The simplest way that I've done it is to use a XamlWriter to save the WPF object as a string. The Save method will serialize the object and all of its children in the logical tree. Now you can create a new object and load it with a XamlReader.</p>\n\n<p>ex:\nWrite the object to xaml (let's say the object was a Grid control):</p>\n\n<pre><code>string gridXaml = XamlWriter.Save(myGrid);\n</code></pre>\n\n<p>Load it into a new object:</p>\n\n<pre><code>StringReader stringReader = new StringReader(gridXaml);\nXmlReader xmlReader = XmlReader.Create(stringReader);\nGrid newGrid = (Grid)XamlReader.Load(xmlReader);\n</code></pre>\n" }, { "answer_id": 4973369, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>In .NET 4.0, the new xaml serialization stack makes this MUCH easier.</p>\n\n<pre><code>var sb = new StringBuilder();\nvar writer = XmlWriter.Create(sb, new XmlWriterSettings\n{\n Indent = true,\n ConformanceLevel = ConformanceLevel.Fragment,\n OmitXmlDeclaration = true,\n NamespaceHandling = NamespaceHandling.OmitDuplicates, \n});\nvar mgr = new XamlDesignerSerializationManager(writer);\n\n// HERE BE MAGIC!!!\nmgr.XamlWriterMode = XamlWriterMode.Expression;\n// THERE WERE MAGIC!!!\n\nSystem.Windows.Markup.XamlWriter.Save(this, mgr);\nreturn sb.ToString();\n</code></pre>\n" }, { "answer_id": 14740448, "author": "John Zabroski", "author_id": 1040437, "author_profile": "https://Stackoverflow.com/users/1040437", "pm_score": 3, "selected": false, "text": "<p>There are some great answers here. Very helpful. I had tried various approaches for copying Binding information, including the approach outlined in <a href=\"http://pjlcon.wordpress.com/2011/01/14/change-a-wpf-binding-from-sync-to-async-programatically/\" rel=\"noreferrer\">http://pjlcon.wordpress.com/2011/01/14/change-a-wpf-binding-from-sync-to-async-programatically/</a> but the information here is the best on the Internet!</p>\n\n<p>I created a re-usable extension method for dealing with InvalidOperationException “Binding cannot be changed after it has been used.” In my scenario, I was maintaining some code somebody wrote, and after a major DevExpress DXGrid framework upgrade, it no longer worked. The following solved my problem perfectly. The part of the code where I return the object could be nicer, and I will re-factor that later.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Extension methods for the WPF Binding class.\n/// &lt;/summary&gt;\npublic static class BindingExtensions\n{\n public static BindingBase CloneViaXamlSerialization(this BindingBase binding)\n {\n var sb = new StringBuilder();\n var writer = XmlWriter.Create(sb, new XmlWriterSettings\n {\n Indent = true,\n ConformanceLevel = ConformanceLevel.Fragment,\n OmitXmlDeclaration = true,\n NamespaceHandling = NamespaceHandling.OmitDuplicates,\n });\n var mgr = new XamlDesignerSerializationManager(writer);\n\n // HERE BE MAGIC!!!\n mgr.XamlWriterMode = XamlWriterMode.Expression;\n // THERE WERE MAGIC!!!\n\n System.Windows.Markup.XamlWriter.Save(binding, mgr);\n StringReader stringReader = new StringReader(sb.ToString());\n XmlReader xmlReader = XmlReader.Create(stringReader);\n object newBinding = (object)XamlReader.Load(xmlReader);\n if (newBinding == null)\n {\n throw new ArgumentNullException(\"Binding could not be cloned via Xaml Serialization Stack.\");\n }\n\n if (newBinding is Binding)\n {\n return (Binding)newBinding;\n }\n else if (newBinding is MultiBinding)\n {\n return (MultiBinding)newBinding;\n }\n else if (newBinding is PriorityBinding)\n {\n return (PriorityBinding)newBinding;\n }\n else\n {\n throw new InvalidOperationException(\"Binding could not be cast.\");\n }\n }\n}\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Anybody have a good example how to deep clone a WPF object, preserving databindings? --- The marked answer is the first part. The second part is that you have to create an ExpressionConverter and inject it into the serialization process. Details for this are here: <http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2801571>
The simplest way that I've done it is to use a XamlWriter to save the WPF object as a string. The Save method will serialize the object and all of its children in the logical tree. Now you can create a new object and load it with a XamlReader. ex: Write the object to xaml (let's say the object was a Grid control): ``` string gridXaml = XamlWriter.Save(myGrid); ``` Load it into a new object: ``` StringReader stringReader = new StringReader(gridXaml); XmlReader xmlReader = XmlReader.Create(stringReader); Grid newGrid = (Grid)XamlReader.Load(xmlReader); ```
32,550
<p>When writing a SQL statement in SQL Server 2005, does the READUNCOMMITTED query hint imply NOLOCK or do I have to specify it manually too?</p> <p>So is:</p> <pre><code>With (NoLock, ReadUnCommitted) </code></pre> <p>the same as:</p> <pre><code>With (ReadUnCommitted) </code></pre>
[ { "answer_id": 32556, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": -1, "selected": false, "text": "<p>I think you can say that</p>\n\n<p>ReadUnCommitted has the abilities of NoLock</p>\n\n<p>However you cannot say that</p>\n\n<p>NoLock has the abilities of ReadUnCommitted</p>\n" }, { "answer_id": 32559, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 1, "selected": false, "text": "<p>According to Kalen Delaney...</p>\n\n<p>The NOLOCK hint has nothing to do with the index options. The hint tells SQL\nServer not to request locks when doing SELECT operations, so there will be\nno conflict with data that is already locked. The index options just tell\nSQL Server that this level of locking is allowed, when locking is going to\noccur. For example, if ALLOW_ROW_LOCKS was off, the only possible locks\nwould be page or table locks. The index options don't force locks to be\nheld, they just control the possible size of the locks.</p>\n\n<p>In answer to the question in your subject, the NOLOCK hint and the\nREADUNCOMMITTED hint are equivalent.</p>\n" }, { "answer_id": 33332, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 2, "selected": true, "text": "<p>Yes they are one and the same</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
When writing a SQL statement in SQL Server 2005, does the READUNCOMMITTED query hint imply NOLOCK or do I have to specify it manually too? So is: ``` With (NoLock, ReadUnCommitted) ``` the same as: ``` With (ReadUnCommitted) ```
Yes they are one and the same
32,586
<p>Is there an easy way to discover a File's creation time with Java? The File class only has a method to get the "last modified" time. According to some resources I found on Google, the File class doesn't provide a getCreationTime() method because not all file systems support the idea of a creation time.</p> <p>The only working solution I found involes shelling out the the command line and executing the "dir" command, which looks like it outputs the file's creation time. I guess this works, I only need to support Windows, but it seems very error prone to me.</p> <p>Are there any third party libraries that provide the info I need?</p> <p><strong>Update:</strong> In the end, I don't think it's worth it for me to buy the third party library, but their API does seem pretty good so it's probably a good choice for anyone else that has this problem. </p>
[ { "answer_id": 32712, "author": "Joseph Gordon", "author_id": 1741, "author_profile": "https://Stackoverflow.com/users/1741", "pm_score": 1, "selected": false, "text": "<p>I like the answer on <a href=\"http://www.jguru.com/faq/view.jsp?EID=1297118\" rel=\"nofollow noreferrer\">jGuru</a> that lists the option of using <a href=\"http://en.wikipedia.org/wiki/Java_Native_Interface\" rel=\"nofollow noreferrer\">JNI</a> to get the answer. This might prove to be faster than shelling out and you may encounter other situations such as this that need to be implemented specifically for windows.</p>\n\n<p>Also, if you ever need to port to a different platform, then you can port your library as well and just have it return -1 for the answer to this question on *ix.</p>\n" }, { "answer_id": 2193954, "author": "Kothar", "author_id": 37416, "author_profile": "https://Stackoverflow.com/users/37416", "pm_score": 2, "selected": false, "text": "<p>I've been investigating this myself, but I need something that will work across Windows/*nix platforms.</p>\n\n<p>One SO post includes some links to <a href=\"https://stackoverflow.com/questions/1088113/is-there-a-java-library-of-unix-functions\">Posix JNI implementations</a>.</p>\n\n<ul>\n<li><a href=\"http://kenai.com/projects/jna-posix\" rel=\"nofollow noreferrer\">JNA-POSIX</a></li>\n<li><a href=\"http://www.bmsi.com/java/posix/\" rel=\"nofollow noreferrer\">POSIX for Java</a></li>\n</ul>\n\n<p>In particular, JNA-POSIX implements <a href=\"http://kenai.com/projects/jna-posix/sources/mercurial/content/src/org/jruby/ext/posix/FileStat.java?rev=59\" rel=\"nofollow noreferrer\">methods for getting file stats</a> with implementations for <a href=\"http://kenai.com/projects/jna-posix/sources/mercurial/content/src/org/jruby/ext/posix/WindowsFileStat.java?rev=59\" rel=\"nofollow noreferrer\">Windows</a>, BSD, Solaris, Linux and OSX.</p>\n\n<p>All in all it looks very promising, so I'll be trying it out on my own project very soon.</p>\n" }, { "answer_id": 3350512, "author": "LiuYan 刘研", "author_id": 404192, "author_profile": "https://Stackoverflow.com/users/404192", "pm_score": 3, "selected": false, "text": "<p>I've wrote a small test class some days ago, wish it can help you:</p>\n\n<pre><code>// Get/Set windows file CreationTime/LastWriteTime/LastAccessTime\n// Test with jna-3.2.7\n// [http://maclife.net/wiki/index.php?title=Java_get_and_set_windows_system_file_creation_time_via_JNA_(Java_Native_Access)][1]\n\nimport java.io.*;\nimport java.nio.*;\nimport java.util.Date;\n\n// Java Native Access library: jna.dev.java.net\nimport com.sun.jna.*;\nimport com.sun.jna.ptr.*;\nimport com.sun.jna.win32.*;\nimport com.sun.jna.platform.win32.*;\n\npublic class WindowsFileTime\n{\n public static final int GENERIC_READ = 0x80000000;\n //public static final int GENERIC_WRITE = 0x40000000; // defined in com.sun.jna.platform.win32.WinNT\n public static final int GENERIC_EXECUTE = 0x20000000;\n public static final int GENERIC_ALL = 0x10000000;\n\n // defined in com.sun.jna.platform.win32.WinNT\n //public static final int CREATE_NEW = 1;\n //public static final int CREATE_ALWAYS = 2;\n //public static final int OPEN_EXISTING = 3;\n //public static final int OPEN_ALWAYS = 4;\n //public static final int TRUNCATE_EXISTING = 5;\n\n public interface MoreKernel32 extends Kernel32\n {\n static final MoreKernel32 instance = (MoreKernel32)Native.loadLibrary (\"kernel32\", MoreKernel32.class, W32APIOptions.DEFAULT_OPTIONS);\n boolean GetFileTime (WinNT.HANDLE hFile, WinBase.FILETIME lpCreationTime, WinBase.FILETIME lpLastAccessTime, WinBase.FILETIME lpLastWriteTime);\n boolean SetFileTime (WinNT.HANDLE hFile, final WinBase.FILETIME lpCreationTime, final WinBase.FILETIME lpLastAccessTime, final WinBase.FILETIME lpLastWriteTime);\n }\n\n static MoreKernel32 win32 = MoreKernel32.instance;\n //static Kernel32 _win32 = (Kernel32)win32;\n\n static WinBase.FILETIME _creationTime = new WinBase.FILETIME ();\n static WinBase.FILETIME _lastWriteTime = new WinBase.FILETIME ();\n static WinBase.FILETIME _lastAccessTime = new WinBase.FILETIME ();\n\n static boolean GetFileTime (String sFileName, Date creationTime, Date lastWriteTime, Date lastAccessTime)\n {\n WinNT.HANDLE hFile = OpenFile (sFileName, GENERIC_READ); // may be WinNT.GENERIC_READ in future jna version.\n if (hFile == WinBase.INVALID_HANDLE_VALUE) return false;\n\n boolean rc = win32.GetFileTime (hFile, _creationTime, _lastAccessTime, _lastWriteTime);\n if (rc)\n {\n if (creationTime != null) creationTime.setTime (_creationTime.toLong());\n if (lastAccessTime != null) lastAccessTime.setTime (_lastAccessTime.toLong());\n if (lastWriteTime != null) lastWriteTime.setTime (_lastWriteTime.toLong());\n }\n else\n {\n int iLastError = win32.GetLastError();\n System.out.print (\"获取文件时间失败,错误码:\" + iLastError + \" \" + GetWindowsSystemErrorMessage (iLastError));\n }\n win32.CloseHandle (hFile);\n return rc;\n }\n static boolean SetFileTime (String sFileName, final Date creationTime, final Date lastWriteTime, final Date lastAccessTime)\n {\n WinNT.HANDLE hFile = OpenFile (sFileName, WinNT.GENERIC_WRITE);\n if (hFile == WinBase.INVALID_HANDLE_VALUE) return false;\n\n ConvertDateToFILETIME (creationTime, _creationTime);\n ConvertDateToFILETIME (lastWriteTime, _lastWriteTime);\n ConvertDateToFILETIME (lastAccessTime, _lastAccessTime);\n\n //System.out.println (\"creationTime: \" + creationTime);\n //System.out.println (\"lastWriteTime: \" + lastWriteTime);\n //System.out.println (\"lastAccessTime: \" + lastAccessTime);\n\n //System.out.println (\"_creationTime: \" + _creationTime);\n //System.out.println (\"_lastWriteTime: \" + _lastWriteTime);\n //System.out.println (\"_lastAccessTime: \" + _lastAccessTime);\n\n boolean rc = win32.SetFileTime (hFile, creationTime==null?null:_creationTime, lastAccessTime==null?null:_lastAccessTime, lastWriteTime==null?null:_lastWriteTime);\n if (! rc)\n {\n int iLastError = win32.GetLastError();\n System.out.print (\"设置文件时间失败,错误码:\" + iLastError + \" \" + GetWindowsSystemErrorMessage (iLastError));\n }\n win32.CloseHandle (hFile);\n return rc;\n }\n static void ConvertDateToFILETIME (Date date, WinBase.FILETIME ft)\n {\n if (ft != null)\n {\n long iFileTime = 0;\n if (date != null)\n {\n iFileTime = WinBase.FILETIME.dateToFileTime (date);\n ft.dwHighDateTime = (int)((iFileTime &gt;&gt; 32) &amp; 0xFFFFFFFFL);\n ft.dwLowDateTime = (int)(iFileTime &amp; 0xFFFFFFFFL);\n }\n else\n {\n ft.dwHighDateTime = 0;\n ft.dwLowDateTime = 0;\n }\n }\n }\n\n static WinNT.HANDLE OpenFile (String sFileName, int dwDesiredAccess)\n {\n WinNT.HANDLE hFile = win32.CreateFile (\n sFileName,\n dwDesiredAccess,\n 0,\n null,\n WinNT.OPEN_EXISTING,\n 0,\n null\n );\n if (hFile == WinBase.INVALID_HANDLE_VALUE)\n {\n int iLastError = win32.GetLastError();\n System.out.print (\" 打开文件失败,错误码:\" + iLastError + \" \" + GetWindowsSystemErrorMessage (iLastError));\n }\n return hFile;\n }\n static String GetWindowsSystemErrorMessage (int iError)\n {\n char[] buf = new char[255];\n CharBuffer bb = CharBuffer.wrap (buf);\n //bb.clear ();\n //PointerByReference pMsgBuf = new PointerByReference ();\n int iChar = win32.FormatMessage (\n WinBase.FORMAT_MESSAGE_FROM_SYSTEM\n //| WinBase.FORMAT_MESSAGE_IGNORE_INSERTS\n //|WinBase.FORMAT_MESSAGE_ALLOCATE_BUFFER\n ,\n null,\n iError,\n 0x0804,\n bb, buf.length,\n //pMsgBuf, 0,\n null\n );\n //for (int i=0; i&lt;iChar; i++)\n //{\n // System.out.print (\" \");\n // System.out.print (String.format(\"%02X\", buf[i]&amp;0xFFFF));\n //}\n bb.limit (iChar);\n //System.out.print (bb);\n //System.out.print (pMsgBuf.getValue().getString(0));\n //win32.LocalFree (pMsgBuf.getValue());\n return bb.toString ();\n }\n\n public static void main (String[] args) throws Exception\n {\n if (args.length == 0)\n {\n System.out.println (\"获取 Windows 的文件时间(创建时间、最后修改时间、最后访问时间)\");\n System.out.println (\"用法:\");\n System.out.println (\" java -cp .;..;jna.jar;platform.jar WindowsFileTime [文件名1] [文件名2]...\");\n return;\n }\n\n boolean rc;\n java.sql.Timestamp ct = new java.sql.Timestamp(0);\n java.sql.Timestamp wt = new java.sql.Timestamp(0);\n java.sql.Timestamp at = new java.sql.Timestamp(0);\n\n for (String sFileName : args)\n {\n System.out.println (\"文件 \" + sFileName);\n\n rc = GetFileTime (sFileName, ct, wt, at);\n if (rc)\n {\n System.out.println (\" 创建时间:\" + ct);\n System.out.println (\" 修改时间:\" + wt);\n System.out.println (\" 访问时间:\" + at);\n }\n else\n {\n //System.out.println (\"GetFileTime 失败\");\n }\n\n\n //wt.setTime (System.currentTimeMillis());\n wt = java.sql.Timestamp.valueOf(\"2010-07-23 00:00:00\");\n rc = SetFileTime (sFileName, null, wt, null);\n if (rc)\n {\n System.out.println (\"SetFileTime (最后修改时间) 成功\");\n }\n else\n {\n //System.out.println (\"SetFileTime 失败\");\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 6185263, "author": "Kamal", "author_id": 777363, "author_profile": "https://Stackoverflow.com/users/777363", "pm_score": 2, "selected": false, "text": "<pre><code>import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\n\npublic class CreateDateInJava {\n public static void main(String args[]) {\n try {\n\n // get runtime environment and execute child process\n Runtime systemShell = Runtime.getRuntime();\n BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));\n System.out.println(\"Enter filename: \");\n String fname = (String) br1.readLine();\n Process output = systemShell.exec(\"cmd /c dir \\\"\" + fname + \"\\\" /tc\");\n\n System.out.println(output);\n // open reader to get output from process\n BufferedReader br = new BufferedReader(new InputStreamReader(output.getInputStream()));\n\n String out = \"\";\n String line = null;\n\n int step = 1;\n while ((line = br.readLine()) != null) {\n if (step == 6) {\n out = line;\n }\n step++;\n }\n\n // display process output\n try {\n out = out.replaceAll(\" \", \"\");\n System.out.println(\"CreationDate: \" + out.substring(0, 10));\n System.out.println(\"CreationTime: \" + out.substring(10, 16) + \"m\");\n } catch (StringIndexOutOfBoundsException se) {\n System.out.println(\"File not found\");\n }\n } catch (IOException ioe) {\n System.err.println(ioe);\n } catch (Throwable t) {\n t.printStackTrace();\n }\n }\n}\n\n/**\nD:\\Foldername\\Filename.Extension\n\nEx:\nEnter Filename :\nD:\\Kamal\\Test.txt\nCreationDate: 02/14/2011\nCreationTime: 12:59Pm\n\n*/\n</code></pre>\n" }, { "answer_id": 14287216, "author": "Peter", "author_id": 777443, "author_profile": "https://Stackoverflow.com/users/777443", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://www.javaxt.com\" rel=\"nofollow\">javaxt-core</a> library includes a File class that can be used to retrieve file attributes, including the creation time. Example:</p>\n\n<pre><code>javaxt.io.File file = new javaxt.io.File(\"/temp/file.txt\");\nSystem.out.println(\"Created: \" + file.getCreationTime());\nSystem.out.println(\"Accessed: \" + file.getLastAccessTime());\nSystem.out.println(\"Modified: \" + file.getLastModifiedTime());\n</code></pre>\n\n<p>Works with Java 1.5 and up.</p>\n" }, { "answer_id": 16969301, "author": "ajon", "author_id": 1068058, "author_profile": "https://Stackoverflow.com/users/1068058", "pm_score": 4, "selected": false, "text": "<p>With the release of Java 7 there is a built-in way to do this:</p>\n\n<pre><code>Path path = Paths.get(\"path/to/file\");\nBasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);\nFileTime creationTime = attributes.creationTime();\n</code></pre>\n\n<p>It is important to note that not all operating systems provide this information. I believe in those instances this returns the mtime which is the last modified time.</p>\n\n<p>Windows does provide creation time.</p>\n" }, { "answer_id": 32771938, "author": "Jorgesys", "author_id": 250260, "author_profile": "https://Stackoverflow.com/users/250260", "pm_score": 0, "selected": false, "text": "<p>This is a basic example in <code>Java</code>, using <a href=\"https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/BasicFileAttributes.html\" rel=\"nofollow\"><strong><code>BasicFileAttributes</code></strong></a> class:</p>\n\n<pre><code> Path path = Paths.get(\"C:\\\\Users\\\\jorgesys\\\\workspaceJava\\\\myfile.txt\");\n BasicFileAttributes attr;\n try {\n attr = Files.readAttributes(path, BasicFileAttributes.class);\n System.out.println(\"File creation time: \" + attr.creationTime());\n } catch (IOException e) {\n System.out.println(\"oops un error! \" + e.getMessage());\n }\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471/" ]
Is there an easy way to discover a File's creation time with Java? The File class only has a method to get the "last modified" time. According to some resources I found on Google, the File class doesn't provide a getCreationTime() method because not all file systems support the idea of a creation time. The only working solution I found involes shelling out the the command line and executing the "dir" command, which looks like it outputs the file's creation time. I guess this works, I only need to support Windows, but it seems very error prone to me. Are there any third party libraries that provide the info I need? **Update:** In the end, I don't think it's worth it for me to buy the third party library, but their API does seem pretty good so it's probably a good choice for anyone else that has this problem.
With the release of Java 7 there is a built-in way to do this: ``` Path path = Paths.get("path/to/file"); BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class); FileTime creationTime = attributes.creationTime(); ``` It is important to note that not all operating systems provide this information. I believe in those instances this returns the mtime which is the last modified time. Windows does provide creation time.
32,621
<p>I'm trying to find the latitude and longitude of the corners of my map while in birdseye view. I want to be able to plot pins on the map, but I have hundreds of thousands of addresses that I want to be able to limit to the ones that need to show on the map.</p> <p>In normal view, VEMap.GetMapView().TopLeftLatLong and .BottomRightLatLong return the coordinates I need; but in Birdseye view they return blank (or encrypted values). The SDK recommends using VEBirdseyeScene.GetBoundingRectangle(), but this returns bounds of up to two miles from the center of my scene which in major cities still returns way too many addresses.</p> <p>In previous versions of the VE Control, there was an undocumented VEDecoder object I could use to decrypt the LatLong values for the birdseye scenes, but this object seems to have disappeared (probably been renamed). How can I decode these values in version 6.1?</p>
[ { "answer_id": 33238, "author": "MartinHN", "author_id": 2972, "author_profile": "https://Stackoverflow.com/users/2972", "pm_score": 0, "selected": false, "text": "<p>According to <a href=\"http://dev.live.com/virtualearth/sdk/\" rel=\"nofollow noreferrer\">http://dev.live.com/virtualearth/sdk/</a> this should do the trick:</p>\n\n<pre><code>function GetInfo() \n{\n alert('The latitude,longitude at the center of the map is: '+map.GetCenter()); \n}\n</code></pre>\n" }, { "answer_id": 39986, "author": "Soldarnal", "author_id": 3420, "author_profile": "https://Stackoverflow.com/users/3420", "pm_score": 2, "selected": false, "text": "<p>From the VEMap.GetCenter Method documentation:</p>\n\n<blockquote>\n <p>This method returns null when the map\n style is set to VEMapStyle.Birdseye or\n VEMapStyle.BirdseyeHybrid.</p>\n</blockquote>\n\n<p>Here is what I've found, though:</p>\n\n<pre><code>var northWestLL = (new _xy1).Decode(map.GetMapView().TopLeftLatLong);\nvar southEastLL = (new _xy1).Decode(map.GetMapView().BottomRightLatLong);\n</code></pre>\n\n<p>The (new _xy1) seems to work the same as the old undocumented VEDecoder object.</p>\n" }, { "answer_id": 67303, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 3, "selected": true, "text": "<p>Here's the code for getting the Center Lat/Long point of the map. This method works in both Road/Aerial and Birdseye/Oblique map styles.</p>\n\n<pre><code>function GetCenterLatLong()\n {\n //Check if in Birdseye or Oblique Map Style\n if (map.GetMapStyle() == VEMapStyle.Birdseye || map.GetMapStyle() == VEMapStyle.BirdseyeHybrid)\n {\n //IN Birdseye or Oblique Map Style\n\n\n //Get the BirdseyeScene being displayed\n var birdseyeScene = map.GetBirdseyeScene();\n\n\n //Get approximate center coordinate of the map\n var x = birdseyeScene.GetWidth() / 2;\n var y = birdseyeScene.GetHeight() / 2;\n\n // Get the Lat/Long \n var center = birdseyeScene.PixelToLatLong(new VEPixel(x,y), map.GetZoomLevel());\n\n // Convert the BirdseyeScene LatLong to a normal LatLong we can use\n return (new _xy1).Decode(center);\n }\n else\n {\n // NOT in Birdseye or Oblique Map Style\n return map.GetCenter();\n }\n } \n</code></pre>\n\n<p>This code was copied from here:\n<a href=\"http://pietschsoft.com/post/2008/06/Virtual-Earth-Get-Center-LatLong-When-In-Birdseye-or-Oblique-Map-Style.aspx\" rel=\"nofollow noreferrer\">http://pietschsoft.com/post/2008/06/Virtual-Earth-Get-Center-LatLong-When-In-Birdseye-or-Oblique-Map-Style.aspx</a></p>\n" }, { "answer_id": 860198, "author": "Jason", "author_id": 7391, "author_profile": "https://Stackoverflow.com/users/7391", "pm_score": 2, "selected": false, "text": "<p>It always seems to me that the example solutions for this issue only find the centre of the current map on the screen, as if that is always the place you're going to click! Anyway, I wrote this little function to get the actual pixel location that you clicked on the screen and return a VELatLong for that. So far it seems pretty accurate (even though I see this as one big, horrible hack - but it's not like we have a choice at the moment).</p>\n\n<p>It takes a VEPixel as input, which is the x and y coordinates of where you clicked on the map. You can get that easily enough on the mouse event passed to the onclick handler for the map.</p>\n\n<pre><code>function getBirdseyeViewLatLong(vePixel)\n{\n var be = map.GetBirdseyeScene();\n\n var centrePixel = be.LatLongToPixel(map.GetCenter(), map.GetZoomLevel());\n\n var currentPixelWidth = be.GetWidth();\n var currentPixelHeight = be.GetHeight();\n\n var mapDiv = document.getElementById(\"map\");\n var mapDivPixelWidth = mapDiv.offsetWidth;\n var mapDivPixelHeight = mapDiv.offsetHeight;\n\n var xScreenPixel = centrePixel.x - (mapDivPixelWidth / 2) + vePixel.x;\n var yScreenPixel = centrePixel.y - (mapDivPixelHeight / 2) + vePixel.y;\n\n var position = be.PixelToLatLong(new VEPixel(xScreenPixel, yScreenPixel), map.GetZoomLevel())\n return (new _xy1).Decode(position);\n}\n</code></pre>\n" }, { "answer_id": 1089877, "author": "itchi", "author_id": 86017, "author_profile": "https://Stackoverflow.com/users/86017", "pm_score": 0, "selected": false, "text": "<p>An interesting point in the Bing Maps Terms of Use..\n<a href=\"http://www.microsoft.com/maps/product/terms.html\" rel=\"nofollow noreferrer\">http://www.microsoft.com/maps/product/terms.html</a></p>\n\n<p><em>Restriction on use of Bird’s eye aerial imagery:\nYou may not reveal latitude, longitude, altitude or other metadata;</em> </p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3420/" ]
I'm trying to find the latitude and longitude of the corners of my map while in birdseye view. I want to be able to plot pins on the map, but I have hundreds of thousands of addresses that I want to be able to limit to the ones that need to show on the map. In normal view, VEMap.GetMapView().TopLeftLatLong and .BottomRightLatLong return the coordinates I need; but in Birdseye view they return blank (or encrypted values). The SDK recommends using VEBirdseyeScene.GetBoundingRectangle(), but this returns bounds of up to two miles from the center of my scene which in major cities still returns way too many addresses. In previous versions of the VE Control, there was an undocumented VEDecoder object I could use to decrypt the LatLong values for the birdseye scenes, but this object seems to have disappeared (probably been renamed). How can I decode these values in version 6.1?
Here's the code for getting the Center Lat/Long point of the map. This method works in both Road/Aerial and Birdseye/Oblique map styles. ``` function GetCenterLatLong() { //Check if in Birdseye or Oblique Map Style if (map.GetMapStyle() == VEMapStyle.Birdseye || map.GetMapStyle() == VEMapStyle.BirdseyeHybrid) { //IN Birdseye or Oblique Map Style //Get the BirdseyeScene being displayed var birdseyeScene = map.GetBirdseyeScene(); //Get approximate center coordinate of the map var x = birdseyeScene.GetWidth() / 2; var y = birdseyeScene.GetHeight() / 2; // Get the Lat/Long var center = birdseyeScene.PixelToLatLong(new VEPixel(x,y), map.GetZoomLevel()); // Convert the BirdseyeScene LatLong to a normal LatLong we can use return (new _xy1).Decode(center); } else { // NOT in Birdseye or Oblique Map Style return map.GetCenter(); } } ``` This code was copied from here: <http://pietschsoft.com/post/2008/06/Virtual-Earth-Get-Center-LatLong-When-In-Birdseye-or-Oblique-Map-Style.aspx>
32,637
<p>I am consuming the Twitter API and want to convert all URLs to hyperlinks. </p> <p>What is the most effective way you've come up with to do this?</p> <p>from</p> <pre><code>string myString = "This is my tweet check it out http://tinyurl.com/blah"; </code></pre> <p>to</p> <pre><code>This is my tweet check it out &lt;a href="http://tinyurl.com/blah"&gt;http://tinyurl.com/&gt;blah&lt;/a&gt; </code></pre>
[ { "answer_id": 32648, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 6, "selected": true, "text": "<p>Regular expressions are probably your friend for this kind of task:</p>\n\n<pre><code>Regex r = new Regex(@\"(https?://[^\\s]+)\");\nmyString = r.Replace(myString, \"&lt;a href=\\\"$1\\\"&gt;$1&lt;/a&gt;\");\n</code></pre>\n\n<p>The regular expression for matching URLs might need a bit of work.</p>\n" }, { "answer_id": 32665, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 3, "selected": false, "text": "<p>This is actually an ugly problem. URLs can contain (and end with) punctuation, so it can be difficult to determine where a URL actually ends, when it's embedded in normal text. For example:</p>\n\n<pre><code>http://example.com/.\n</code></pre>\n\n<p>is a valid URL, but it could just as easily be the end of a sentence:</p>\n\n<pre><code>I buy all my witty T-shirts from http://example.com/.\n</code></pre>\n\n<p>You can't simply parse until a space is found, because then you'll keep the period as part of the URL. You also can't simply parse until a period or a space is found, because periods are extremely common in URLs.</p>\n\n<p>Yes, regex is your friend here, but constructing the appropriate regex is the hard part.</p>\n\n<p>Check out this as well: <a href=\"http://www.west-wind.com/WebLog/posts/9779.aspx\" rel=\"noreferrer\">Expanding URLs with Regex in .NET</a>.</p>\n" }, { "answer_id": 32693, "author": "RedWolves", "author_id": 648, "author_profile": "https://Stackoverflow.com/users/648", "pm_score": 3, "selected": false, "text": "<p>I did this exact same thing with <a href=\"http://ralphwhitbeck.com/2007/11/20/PullingTwitterUpdatesWithJSONAndJQuery.aspx\" rel=\"nofollow noreferrer\">jquery consuming the JSON API</a> here is the linkify function:</p>\n\n<pre><code>String.prototype.linkify = function() {\n return this.replace(/[A-Za-z]+:\\/\\/[A-Za-z0-9-_]+\\.[A-Za-z0-9-_:%&amp;\\?\\/.=]+/, function(m) {\n return m.link(m);\n });\n };\n</code></pre>\n" }, { "answer_id": 2661465, "author": "winfred", "author_id": 319042, "author_profile": "https://Stackoverflow.com/users/319042", "pm_score": 1, "selected": false, "text": "<p>/cheer for RedWolves</p>\n\n<blockquote>\n <p>from: this.replace(/[A-Za-z]+://[A-Za-z0-9-<em>]+.[A-Za-z0-9-</em>:%&amp;\\?/.=]+/, function(m){...</p>\n \n <p>see: /[A-Za-z]+://[A-Za-z0-9-<em>]+.[A-Za-z0-9-</em>:%&amp;\\?/.=]+/</p>\n</blockquote>\n\n<p>There's the code for the addresses \"anyprotocol\"://\"anysubdomain/domain\".\"anydomainextension and address\", </p>\n\n<p>and it's a perfect example for other uses of string manipulation. you can slice and dice at will with .replace and insert proper \"a href\"s where needed.</p>\n\n<p>I used jQuery to change the attributes of these links to \"target=_blank\" easily in my content-loading logic even though the .link method doesn't let you customize them.</p>\n\n<p>I personally love tacking on a custom method to the string object for on the fly string-filtering (the String.prototype.linkify declaration), but I'm not sure how that would play out in a large-scale environment where you'd have to organize 10+ custom linkify-like functions. I think you'd definitely have to do something else with your code structure at that point.</p>\n\n<p>Maybe a vet will stumble along here and enlighten us.</p>\n" }, { "answer_id": 9139800, "author": "herry", "author_id": 932213, "author_profile": "https://Stackoverflow.com/users/932213", "pm_score": 1, "selected": false, "text": "<p>You can add some more control on this by using MatchEvaluator delegate function with regular expression:\nsuppose i have this string:</p>\n\n<pre>find more on http://www.stackoverflow.com </pre>\n\n<p>now try this code</p>\n\n<pre><code>private void ModifyString()\n{\n string input = \"find more on http://www.authorcode.com \";\n Regex regx = new Regex(@\"\\b((http|https|ftp|mailto)://)?(www.)+[\\w-]+(/[\\w- ./?%&amp;=]*)?\");\n string result = regx.Replace(input, new MatchEvaluator(ReplaceURl));\n}\n\nstatic string ReplaceURl(Match m)\n{\n string x = m.ToString();\n x = \"&lt; a href=\\\"\" + x + \"\\\"&gt;\" + x + \"&lt;/a&gt;\";\n return x;\n}\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2347826/" ]
I am consuming the Twitter API and want to convert all URLs to hyperlinks. What is the most effective way you've come up with to do this? from ``` string myString = "This is my tweet check it out http://tinyurl.com/blah"; ``` to ``` This is my tweet check it out <a href="http://tinyurl.com/blah">http://tinyurl.com/>blah</a> ```
Regular expressions are probably your friend for this kind of task: ``` Regex r = new Regex(@"(https?://[^\s]+)"); myString = r.Replace(myString, "<a href=\"$1\">$1</a>"); ``` The regular expression for matching URLs might need a bit of work.
32,640
<p>So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET".</p> <p>I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest.</p> <p>I'm using latest version of rhino mocks</p>
[ { "answer_id": 32672, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 7, "selected": true, "text": "<p>Using MoQ it looks something like this:</p>\n\n<pre><code>var request = new Mock&lt;HttpRequestBase&gt;();\nrequest.Expect(r =&gt; r.HttpMethod).Returns(\"GET\");\nvar mockHttpContext = new Mock&lt;HttpContextBase&gt;();\nmockHttpContext.Expect(c =&gt; c.Request).Returns(request.Object);\nvar controllerContext = new ControllerContext(mockHttpContext.Object\n, new RouteData(), new Mock&lt;ControllerBase&gt;().Object);\n</code></pre>\n\n<p>I think the Rhino Mocks syntax is similar.</p>\n" }, { "answer_id": 33597, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 0, "selected": false, "text": "<p>I find that long mocking procedure to be too much friction.</p>\n\n<p>The best way we have found - using ASP.NET MVC on a real project - is to abstract the HttpContext to an IWebContext interface that simply passes through. Then you can mock the IWebContext with no pain.</p>\n\n<p>Here is an <a href=\"http://code.google.com/p/tarantino/source/browse/trunk/src/Tarantino.Core/Commons/Services/Web/IWebContext.cs\" rel=\"nofollow noreferrer\">example</a></p>\n" }, { "answer_id": 33798, "author": "Dane O'Connor", "author_id": 1946, "author_profile": "https://Stackoverflow.com/users/1946", "pm_score": 4, "selected": false, "text": "<p>Here's a snippet from Jason's link. Its the same as Phil's method but uses rhino. </p>\n\n<p><em>Note: mockHttpContext.Request is stubbed to return mockRequest <strong>before</strong> mockRequest's internals are stubbed out. I believe this order is required.</em></p>\n\n<pre><code>// create a fake web context\nvar mockHttpContext = MockRepository.GenerateMock&lt;HttpContextBase&gt;();\nvar mockRequest = MockRepository.GenerateMock&lt;HttpRequestBase&gt;();\nmockHttpContext.Stub(x =&gt; x.Request).Return(mockRequest);\n\n// tell the mock to return \"GET\" when HttpMethod is called\nmockRequest.Stub(x =&gt; x.HttpMethod).Return(\"GET\"); \n\nvar controller = new AccountController();\n\n// assign the fake context\nvar context = new ControllerContext(mockHttpContext, \n new RouteData(), \n controller);\ncontroller.ControllerContext = context;\n\n// act\n...\n</code></pre>\n" }, { "answer_id": 220113, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>i've finished with this spec</p>\n\n<pre><code>public abstract class Specification &lt;C&gt; where C: Controller\n{\n protected C controller;\n\n HttpContextBase mockHttpContext;\n HttpRequestBase mockRequest;\n\n protected Exception ExceptionThrown { get; private set; }\n\n [SetUp]\n public void Setup()\n {\n mockHttpContext = MockRepository.GenerateMock&lt;HttpContextBase&gt;();\n mockRequest = MockRepository.GenerateMock&lt;HttpRequestBase&gt;();\n\n mockHttpContext.Stub(x =&gt; x.Request).Return(mockRequest);\n mockRequest.Stub(x =&gt; x.HttpMethod).Return(\"GET\");\n\n\n EstablishContext();\n SetHttpContext();\n\n try\n {\n When();\n }\n catch (Exception exc)\n {\n ExceptionThrown = exc;\n }\n }\n\n protected void SetHttpContext()\n {\n var context = new ControllerContext(mockHttpContext, new RouteData(), controller);\n controller.ControllerContext = context;\n }\n\n protected T Mock&lt;T&gt;() where T: class\n {\n return MockRepository.GenerateMock&lt;T&gt;();\n }\n\n protected abstract void EstablishContext();\n protected abstract void When();\n\n [TearDown]\n public virtual void TearDown()\n {\n }\n} \n</code></pre>\n\n<p>and the juice is here </p>\n\n<pre><code>[TestFixture]\npublic class When_invoking_ManageUsersControllers_Update :Specification &lt;ManageUsersController&gt;\n{\n private IUserRepository userRepository;\n FormCollection form;\n\n ActionResult result;\n User retUser;\n\n protected override void EstablishContext()\n {\n userRepository = Mock&lt;IUserRepository&gt;();\n controller = new ManageUsersController(userRepository);\n\n retUser = new User();\n userRepository.Expect(x =&gt; x.GetById(5)).Return(retUser);\n userRepository.Expect(x =&gt; x.Update(retUser));\n\n form = new FormCollection();\n form[\"IdUser\"] = 5.ToString();\n form[\"Name\"] = 5.ToString();\n form[\"Surename\"] = 5.ToString();\n form[\"Login\"] = 5.ToString();\n form[\"Password\"] = 5.ToString();\n }\n\n protected override void When()\n {\n result = controller.Edit(5, form);\n }\n\n [Test]\n public void is_retrieved_before_update_original_user()\n {\n userRepository.AssertWasCalled(x =&gt; x.GetById(5));\n userRepository.AssertWasCalled(x =&gt; x.Update(retUser));\n }\n}\n</code></pre>\n\n<p>enjoy</p>\n" }, { "answer_id": 491798, "author": "RoyOsherove", "author_id": 18426, "author_profile": "https://Stackoverflow.com/users/18426", "pm_score": 3, "selected": false, "text": "<p>Or you can do this with Typemock Isolator with no need to send in a fake controller at all:</p>\n\n<pre><code>Isolate.WhenCalled(()=&gt;HttpContext.Request.HttpMethod).WillReturn(\"Get\");\n</code></pre>\n" }, { "answer_id": 1959077, "author": "Gabe Moothart", "author_id": 13356, "author_profile": "https://Stackoverflow.com/users/13356", "pm_score": 3, "selected": false, "text": "<p>The procedure for this seems to have changed slightly in MVC2 (I'm using RC1). Phil Haack's solution doesn't work for me if the action requires a specific method (<code>[HttpPost]</code>, <code>[HttpGet]</code>). Spelunking around in Reflector, it looks like the method for verifying these attributes has changed. MVC now checks <code>request.Headers</code>, <code>request.Form</code>, and <code>request.QueryString</code> for a <code>X-HTTP-Method-Override</code> value.</p>\n\n<p>If you add mocks for these properties, it works:</p>\n\n<pre><code>var request = new Mock&lt;HttpRequestBase&gt;();\nrequest.Setup(r =&gt; r.HttpMethod).Returns(\"POST\");\nrequest.Setup(r =&gt; r.Headers).Returns(new NameValueCollection());\nrequest.Setup(r =&gt; r.Form).Returns(new NameValueCollection());\nrequest.Setup(r =&gt; r.QueryString).Returns(new NameValueCollection());\n\nvar mockHttpContext = new Mock&lt;HttpContextBase&gt;();\nmockHttpContext.Expect(c =&gt; c.Request).Returns(request.Object);\nvar controllerContext = new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock&lt;ControllerBase&gt;().Object);\n</code></pre>\n" }, { "answer_id": 15016922, "author": "Maksym Kozlenko", "author_id": 171847, "author_profile": "https://Stackoverflow.com/users/171847", "pm_score": 5, "selected": false, "text": "<p>Here is a sample unit test class using MsTest and Moq which mocks HttpRequest and HttpResponse objects. (.NET 4.0, ASP.NET MVC 3.0 )</p>\n\n<p>Controller action get value from request and sets http header in response objects. Other http context objects could be mocked up in similar way</p>\n\n<pre><code>[TestClass]\npublic class MyControllerTest\n{\n protected Mock&lt;HttpContextBase&gt; HttpContextBaseMock;\n protected Mock&lt;HttpRequestBase&gt; HttpRequestMock;\n protected Mock&lt;HttpResponseBase&gt; HttpResponseMock;\n\n [TestInitialize]\n public void TestInitialize()\n {\n HttpContextBaseMock = new Mock&lt;HttpContextBase&gt;();\n HttpRequestMock = new Mock&lt;HttpRequestBase&gt;();\n HttpResponseMock = new Mock&lt;HttpResponseBase&gt;();\n HttpContextBaseMock.SetupGet(x =&gt; x.Request).Returns(HttpRequestMock.Object);\n HttpContextBaseMock.SetupGet(x =&gt; x.Response).Returns(HttpResponseMock.Object);\n }\n\n protected MyController SetupController()\n {\n var routes = new RouteCollection();\n var controller = new MyController();\n controller.ControllerContext = new ControllerContext(HttpContextBaseMock.Object, new RouteData(), controller);\n controller.Url = new UrlHelper(new RequestContext(HttpContextBaseMock.Object, new RouteData()), routes);\n return controller;\n }\n\n [TestMethod]\n public void IndexTest()\n {\n HttpRequestMock.Setup(x =&gt; x[\"x\"]).Returns(\"1\");\n HttpResponseMock.Setup(x =&gt; x.AddHeader(\"name\", \"value\"));\n\n var controller = SetupController();\n var result = controller.Index();\n Assert.AreEqual(\"1\", result.Content);\n\n HttpRequestMock.VerifyAll();\n HttpResponseMock.VerifyAll();\n }\n}\n\npublic class MyController : Controller\n{\n public ContentResult Index()\n {\n var x = Request[\"x\"];\n Response.AddHeader(\"name\", \"value\");\n return Content(x);\n }\n}\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET". I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest. I'm using latest version of rhino mocks
Using MoQ it looks something like this: ``` var request = new Mock<HttpRequestBase>(); request.Expect(r => r.HttpMethod).Returns("GET"); var mockHttpContext = new Mock<HttpContextBase>(); mockHttpContext.Expect(c => c.Request).Returns(request.Object); var controllerContext = new ControllerContext(mockHttpContext.Object , new RouteData(), new Mock<ControllerBase>().Object); ``` I think the Rhino Mocks syntax is similar.
32,649
<p>When making changes using <code>SubmitChanges()</code>, LINQ sometimes dies with a <code>ChangeConflictException</code> exception with the error message <code>Row not found or changed</code>, without any indication of either the row that has the conflict or the fields with changes that are in conflict, when another user has changed some data in that row.</p> <p>Is there any way to determine which row has a conflict and which fields they occur in, and also is there a way of getting LINQ to ignore the issue and simply commit the data regardless?</p> <p>Additionally, does anybody know whether this exception occurs when <em>any</em> data in the row has changed, or only when data has been changed in a field that LINQ is attempting to alter?</p>
[ { "answer_id": 32703, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 2, "selected": false, "text": "<p>I've gotten this error in a circumstance completely unrelated to what the error message describes.</p>\n\n<p>What I did was load a LINQ object via one DataContext, and then tried to SubmitChanges() for the object via a different DataContext - gave this exact same error.</p>\n\n<p>What I had to do was call DataContext.Table.Attach(myOldObject), and then call SubmitChanges(), worked like a charm.</p>\n\n<p>Worth a look, especially if you're of the opinion that there really shouldn't be any conflicts at all.</p>\n" }, { "answer_id": 32705, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 6, "selected": true, "text": "<p>Here's a way to see where the conflicts are (this is an MSDN example, so you'll need to heavily customize):</p>\n\n<pre><code>try\n{\n db.SubmitChanges(ConflictMode.ContinueOnConflict);\n}\ncatch (ChangeConflictException e)\n{\n Console.WriteLine(\"Optimistic concurrency error.\");\n Console.WriteLine(e.Message);\n Console.ReadLine();\n foreach (ObjectChangeConflict occ in db.ChangeConflicts)\n {\n MetaTable metatable = db.Mapping.GetTable(occ.Object.GetType());\n Customer entityInConflict = (Customer)occ.Object;\n Console.WriteLine(\"Table name: {0}\", metatable.TableName);\n Console.Write(\"Customer ID: \");\n Console.WriteLine(entityInConflict.CustomerID);\n foreach (MemberChangeConflict mcc in occ.MemberConflicts)\n {\n object currVal = mcc.CurrentValue;\n object origVal = mcc.OriginalValue;\n object databaseVal = mcc.DatabaseValue;\n MemberInfo mi = mcc.Member;\n Console.WriteLine(\"Member: {0}\", mi.Name);\n Console.WriteLine(\"current value: {0}\", currVal);\n Console.WriteLine(\"original value: {0}\", origVal);\n Console.WriteLine(\"database value: {0}\", databaseVal);\n }\n }\n}\n</code></pre>\n\n<p>To make it ignore the problem and commit anyway:</p>\n\n<pre><code>db.SubmitChanges(ConflictMode.ContinueOnConflict);\n</code></pre>\n" }, { "answer_id": 32708, "author": "vzczc", "author_id": 224, "author_profile": "https://Stackoverflow.com/users/224", "pm_score": 4, "selected": false, "text": "<p>These (which you could add in a partial class to your datacontext might help you understand how this works:</p>\n\n<pre><code>public void SubmitKeepChanges()\n{\n try\n {\n this.SubmitChanges(ConflictMode.ContinueOnConflict);\n }\n catch (ChangeConflictException e)\n {\n foreach (ObjectChangeConflict occ in this.ChangeConflicts)\n {\n //Keep current values that have changed, \n//updates other values with database values\n\n occ.Resolve(RefreshMode.KeepChanges);\n }\n }\n}\n\npublic void SubmitOverwrite()\n{\n try\n {\n this.SubmitChanges(ConflictMode.ContinueOnConflict);\n }\n catch (ChangeConflictException e)\n {\n foreach (ObjectChangeConflict occ in this.ChangeConflicts)\n {\n // All database values overwrite current values with \n//values from database\n\n occ.Resolve(RefreshMode.OverwriteCurrentValues);\n }\n }\n}\n\npublic void SubmitKeepCurrent()\n{\n try\n {\n this.SubmitChanges(ConflictMode.ContinueOnConflict);\n }\n catch (ChangeConflictException e)\n {\n foreach (ObjectChangeConflict occ in this.ChangeConflicts)\n {\n //Swap the original values with the values retrieved from the database. No current value is modified\n occ.Resolve(RefreshMode.KeepCurrentValues);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 33482, "author": "liammclennan", "author_id": 2785, "author_profile": "https://Stackoverflow.com/users/2785", "pm_score": -1, "selected": false, "text": "<p>\"and also is there a way of getting LINQ to ignore the issue and simply commit the data regardless?\"</p>\n\n<p>You can set the 'Update Check' property on your entity to 'Never' to stop that field being used for optimistic concurrency checking.</p>\n\n<p>You can also use:</p>\n\n<pre><code>db.SubmitChanges(ConflictMode.ContinueOnConflict)\n</code></pre>\n" }, { "answer_id": 84185, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 2, "selected": false, "text": "<p>The error \"Row not found or changed\" also will appear sometimes when the columns or types in the O/R-Designer do not match the columns in the SQL database, especially if one column is NULLable in SQL but not nullable in the O/R-Designer.</p>\n\n<p>So check if your table mapping in the O/R-Designer matches your SQL database!</p>\n" }, { "answer_id": 12487195, "author": "Mark", "author_id": 9976, "author_profile": "https://Stackoverflow.com/users/9976", "pm_score": 2, "selected": false, "text": "<p>Thanks to @vzczc. I found the example you gave very helpful but that I needed to call SubmitChanges again after resolving. Here are my modified methods - hope it helps someone.</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Submits changes and, if there are any conflicts, the database changes are auto-merged for \n /// members that client has not modified (client wins, but database changes are preserved if possible)\n /// &lt;/summary&gt;\n public void SubmitKeepChanges()\n {\n this.Submit(RefreshMode.KeepChanges);\n }\n\n /// &lt;summary&gt;\n /// Submits changes and, if there are any conflicts, simply overwrites what is in the database (client wins).\n /// &lt;/summary&gt;\n public void SubmitOverwriteDatabase()\n {\n this.Submit(RefreshMode.KeepCurrentValues);\n }\n\n /// &lt;summary&gt;\n /// Submits changes and, if there are any conflicts, all database values overwrite\n /// current values (client loses).\n /// &lt;/summary&gt;\n public void SubmitUseDatabase()\n {\n this.Submit(RefreshMode.OverwriteCurrentValues);\n }\n\n /// &lt;summary&gt;\n /// Submits the changes using the specified refresh mode.\n /// &lt;/summary&gt;\n /// &lt;param name=\"refreshMode\"&gt;The refresh mode.&lt;/param&gt;\n private void Submit(RefreshMode refreshMode)\n {\n bool moreToSubmit = true;\n do\n {\n try\n {\n this.SubmitChanges(ConflictMode.ContinueOnConflict);\n moreToSubmit = false;\n }\n catch (ChangeConflictException)\n {\n foreach (ObjectChangeConflict occ in this.ChangeConflicts)\n {\n occ.Resolve(refreshMode);\n }\n }\n }\n while (moreToSubmit);\n\n }\n</code></pre>\n" }, { "answer_id": 54920592, "author": "Herman Van Der Blom", "author_id": 2111313, "author_profile": "https://Stackoverflow.com/users/2111313", "pm_score": 0, "selected": false, "text": "<p><strong>row not found or changed is most of times a concurrency problem</strong></p>\n\n<p>If a different user is changing the same record those errors popup because the record is already changed by that other user. So when you want to eliminate those errors you should handle concurrency in your application. If you handle concurrency well you won't get these errors anymore. The above code samples are a way to handle concurrency errors. Whats missing is that in case of a concurrency error you should put a <code>refresh</code> variable in those methods so when <code>refresh</code> is <code>true</code> the data needs to be refreshed on screen after the update so you will also see the update made by the other user.</p>\n\n<pre><code> /// &lt;remarks&gt;\n /// linq has optimistic concurrency, so objects can be changed by other users, while\n /// submitted keep database changes but make sure users changes are also submitted\n /// and refreshed with the changes already made by other users.\n /// &lt;/remarks&gt;\n /// &lt;returns&gt;return if a refresh is needed.&lt;/returns&gt;\n public bool SubmitKeepChanges()\n {\n // try to submit changes to the database.\n bool refresh = false;\n try\n {\n base.SubmitChanges(ConflictMode.ContinueOnConflict);\n }\n\n /* \n * assume a \"row not found or changed\" exception, if thats the case:\n * - keep the database changes already made by other users and make sure\n * - this users changes are also written to the database\n */\n catch (ChangeConflictException)\n {\n // show where the conflicts are in debug mode\n ShowConflicts();\n\n // get database values and combine with user changes \n base.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);\n\n // submit those combined changes again to the database.\n base.SubmitChanges();\n\n // a refresh is needed\n refresh = true;\n }\n\n // return if a refresh is needed.\n return refresh;\n }\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3394/" ]
When making changes using `SubmitChanges()`, LINQ sometimes dies with a `ChangeConflictException` exception with the error message `Row not found or changed`, without any indication of either the row that has the conflict or the fields with changes that are in conflict, when another user has changed some data in that row. Is there any way to determine which row has a conflict and which fields they occur in, and also is there a way of getting LINQ to ignore the issue and simply commit the data regardless? Additionally, does anybody know whether this exception occurs when *any* data in the row has changed, or only when data has been changed in a field that LINQ is attempting to alter?
Here's a way to see where the conflicts are (this is an MSDN example, so you'll need to heavily customize): ``` try { db.SubmitChanges(ConflictMode.ContinueOnConflict); } catch (ChangeConflictException e) { Console.WriteLine("Optimistic concurrency error."); Console.WriteLine(e.Message); Console.ReadLine(); foreach (ObjectChangeConflict occ in db.ChangeConflicts) { MetaTable metatable = db.Mapping.GetTable(occ.Object.GetType()); Customer entityInConflict = (Customer)occ.Object; Console.WriteLine("Table name: {0}", metatable.TableName); Console.Write("Customer ID: "); Console.WriteLine(entityInConflict.CustomerID); foreach (MemberChangeConflict mcc in occ.MemberConflicts) { object currVal = mcc.CurrentValue; object origVal = mcc.OriginalValue; object databaseVal = mcc.DatabaseValue; MemberInfo mi = mcc.Member; Console.WriteLine("Member: {0}", mi.Name); Console.WriteLine("current value: {0}", currVal); Console.WriteLine("original value: {0}", origVal); Console.WriteLine("database value: {0}", databaseVal); } } } ``` To make it ignore the problem and commit anyway: ``` db.SubmitChanges(ConflictMode.ContinueOnConflict); ```
32,664
<p>Can anyone tell me if there is a way with generics to limit a generic type argument <code>T</code> to only:</p> <ul> <li><code>Int16</code></li> <li><code>Int32</code></li> <li><code>Int64</code></li> <li><code>UInt16</code></li> <li><code>UInt32</code></li> <li><code>UInt64</code></li> </ul> <p>I'm aware of the <code>where</code> keyword, but can't find an interface for <strong>only</strong> these types,</p> <p>Something like:</p> <pre><code>static bool IntegerFunction&lt;T&gt;(T value) where T : INumeric </code></pre>
[ { "answer_id": 32687, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 7, "selected": false, "text": "<p>There's no constraint for this. It's a real issue for anyone wanting to use generics for numeric calculations.</p>\n\n<p>I'd go further and say we need</p>\n\n<pre><code>static bool GenericFunction&lt;T&gt;(T value) \n where T : operators( +, -, /, * )\n</code></pre>\n\n<p>Or even</p>\n\n<pre><code>static bool GenericFunction&lt;T&gt;(T value) \n where T : Add, Subtract\n</code></pre>\n\n<p>Unfortunately you only have interfaces, base classes and the keywords <code>struct</code> (must be value-type), <code>class</code> (must be reference type) and <code>new()</code> (must have default constructor)</p>\n\n<p>You could wrap the number in something else (similar to <code>INullable&lt;T&gt;</code>) like <a href=\"http://www.codeproject.com/KB/cs/genericnumerics.aspx\" rel=\"noreferrer\">here on codeproject</a>.</p>\n\n<hr>\n\n<p>You could apply the restriction at runtime (by reflecting for the operators or checking for types) but that does lose the advantage of having the generic in the first place.</p>\n" }, { "answer_id": 32690, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 4, "selected": false, "text": "<p>Probably the closest you can do is </p>\n\n<pre><code>static bool IntegerFunction&lt;T&gt;(T value) where T: struct\n</code></pre>\n\n<p>Not sure if you could do the following</p>\n\n<pre><code>static bool IntegerFunction&lt;T&gt;(T value) where T: struct, IComparable\n, IFormattable, IConvertible, IComparable&lt;T&gt;, IEquatable&lt;T&gt;\n</code></pre>\n\n<p>For something so specific, why not just have overloads for each type, the list is so short and it would possibly have less memory footprint.</p>\n" }, { "answer_id": 32699, "author": "Martin Marconcini", "author_id": 2684, "author_profile": "https://Stackoverflow.com/users/2684", "pm_score": 2, "selected": false, "text": "<p>I was wondering the same as samjudson, why only to integers? and if that is the case, you might want to create a helper class or something like that to hold all the types you want.</p>\n\n<p>If all you want are integers, don't use a generic, that is not generic; or better yet, reject any other type by checking its type. </p>\n" }, { "answer_id": 32727, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 4, "selected": false, "text": "<p>Unfortunately you are only able to specify struct in the where clause in this instance. It does seem strange you can't specify Int16, Int32, etc. specifically but I'm sure there's some deep implementation reason underlying the decision to not permit value types in a where clause.</p>\n\n<p>I guess the only solution is to do a runtime check which unfortunately prevents the problem being picked up at compile time. That'd go something like:-</p>\n\n<pre><code>static bool IntegerFunction&lt;T&gt;(T value) where T : struct {\n if (typeof(T) != typeof(Int16) &amp;&amp;\n typeof(T) != typeof(Int32) &amp;&amp;\n typeof(T) != typeof(Int64) &amp;&amp;\n typeof(T) != typeof(UInt16) &amp;&amp;\n typeof(T) != typeof(UInt32) &amp;&amp;\n typeof(T) != typeof(UInt64)) {\n throw new ArgumentException(\n string.Format(\"Type '{0}' is not valid.\", typeof(T).ToString()));\n }\n\n // Rest of code...\n}\n</code></pre>\n\n<p>Which is a little bit ugly I know, but at least provides the required constraints.</p>\n\n<p>I'd also look into possible performance implications for this implementation, perhaps there's a faster way out there.</p>\n" }, { "answer_id": 33383, "author": "dbkk", "author_id": 838, "author_profile": "https://Stackoverflow.com/users/838", "pm_score": 1, "selected": false, "text": "<p>What is the point of the exercise?</p>\n\n<p>As people pointed out already, you could have a non-generic function taking the largest item, and compiler will automatically convert up smaller ints for you. </p>\n\n<pre><code>static bool IntegerFunction(Int64 value) { }\n</code></pre>\n\n<p>If your function is on performance-critical path (very unlikely, IMO), you could provide overloads for all needed functions.</p>\n\n<pre><code>static bool IntegerFunction(Int64 value) { }\n...\nstatic bool IntegerFunction(Int16 value) { }\n</code></pre>\n" }, { "answer_id": 34186, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 7, "selected": false, "text": "<p>More than a decade later, this feature finally exists in <a href=\"https://devblogs.microsoft.com/dotnet/dotnet-7-generic-math/\" rel=\"nofollow noreferrer\">.NET 7</a>. The most generic interface is <code>INumber&lt;TSelf&gt;</code> rather than <code>INumeric</code> (in the <code>System.Numerics</code> namespace), and it encompasses not just integer types. To accept just integer types, consider using <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.numerics.ibinaryinteger-1?view=net-7.0\" rel=\"nofollow noreferrer\"><code>IBinaryInteger&lt;TSelf&gt;</code></a> instead. To use the example of your prototypical, mystical <code>IntegerFunction</code>:</p>\n<pre><code>static bool IntegerFunction&lt;T&gt;(T value) where T : IBinaryInteger&lt;T&gt; {\n return value &gt; T.Zero;\n}\n</code></pre>\n<pre><code>Console.WriteLine(IntegerFunction(5)); // True\nConsole.WriteLine(IntegerFunction((sbyte)-5)); // False\nConsole.WriteLine(IntegerFunction((ulong)5)); // True\n</code></pre>\n<hr />\n<p>The (now obsolete) answer below is left as a historical perspective.</p>\n<p>C# does not support this. Hejlsberg has described the reasons for not implementing the feature <a href=\"http://www.artima.com/intv/generics.html\" rel=\"nofollow noreferrer\">in an interview with Bruce Eckel</a>:</p>\n<blockquote>\n<p>And it's not clear that the added complexity is worth the small yield that you get. If something you want to do is not directly supported in the constraint system, you can do it with a factory pattern. You could have a <code>Matrix&lt;T&gt;</code>, for example, and in that <code>Matrix</code> you would like to define a dot product method. That of course that means you ultimately need to understand how to multiply two <code>T</code>s, but you can't say that as a constraint, at least not if <code>T</code> is <code>int</code>, <code>double</code>, or <code>float</code>. But what you could do is have your <code>Matrix</code> take as an argument a <code>Calculator&lt;T&gt;</code>, and in <code>Calculator&lt;T&gt;</code>, have a method called <code>multiply</code>. You go implement that and you pass it to the <code>Matrix</code>.</p>\n</blockquote>\n<p>However, this leads to fairly convoluted code, where the user has to supply their own <code>Calculator&lt;T&gt;</code> implementation, for each <code>T</code> that they want to use. As long as it doesn’t have to be extensible, i.e. if you just want to support a fixed number of types, such as <code>int</code> and <code>double</code>, you can get away with a relatively simple interface:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var mat = new Matrix&lt;int&gt;(w, h);\n</code></pre>\n<p>(<a href=\"https://gist.github.com/klmr/314d05b66c72d62bd8a184514568e22f\" rel=\"nofollow noreferrer\">Minimal implementation in a GitHub Gist.</a>)</p>\n<p>However, as soon as you want the user to be able to supply their own, custom types, you need to open up this implementation so that the user can supply their own <code>Calculator</code> instances. For instance, to instantiate a matrix that uses a custom decimal floating point implementation, <code>DFP</code>, you’d have to write this code:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var mat = new Matrix&lt;DFP&gt;(DfpCalculator.Instance, w, h);\n</code></pre>\n<p>… and implement all the members for <code>DfpCalculator : ICalculator&lt;DFP&gt;</code>.</p>\n<p>An alternative, which unfortunately shares the same limitations, is to work with policy classes, <a href=\"https://stackoverflow.com/a/4834066/1968\">as discussed in Sergey Shandar’s answer</a>.</p>\n" }, { "answer_id": 1268443, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": false, "text": "<p>This question is a bit of a FAQ one, so I'm posting this as wiki (since I've posted similar before, but this is an older one); anyway...</p>\n<p>What version of .NET are you using? If you are using .NET 3.5, then I have a <a href=\"https://jonskeet.uk/csharp/genericoperators.html\" rel=\"nofollow noreferrer\">generic operators implementation</a> in <a href=\"https://jonskeet.uk/csharp/miscutil/index.html\" rel=\"nofollow noreferrer\">MiscUtil</a> (free etc).</p>\n<p>This has methods like <code>T Add&lt;T&gt;(T x, T y)</code>, and other variants for arithmetic on different types (like <code>DateTime + TimeSpan</code>).</p>\n<p>Additionally, this works for all the inbuilt, lifted and bespoke operators, and caches the delegate for performance.</p>\n<p>Some additional background on why this is tricky is <a href=\"https://jonskeet.uk/csharp/miscutil/usage/genericoperators.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>You may also want to know that <code>dynamic</code> (4.0) sort-of solves this issue indirectly too - i.e.</p>\n<pre><code>dynamic x = ..., y = ...\ndynamic result = x + y; // does what you expect\n</code></pre>\n" }, { "answer_id": 2065410, "author": "Marc Roussel", "author_id": 250846, "author_profile": "https://Stackoverflow.com/users/250846", "pm_score": 1, "selected": false, "text": "<p>I would use a generic one which you could handle externaly...</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Generic object copy of the same type\n/// &lt;/summary&gt;\n/// &lt;typeparam name=\"T\"&gt;The type of object to copy&lt;/typeparam&gt;\n/// &lt;param name=\"ObjectSource\"&gt;The source object to copy&lt;/param&gt;\npublic T CopyObject&lt;T&gt;(T ObjectSource)\n{\n T NewObject = System.Activator.CreateInstance&lt;T&gt;();\n\n foreach (PropertyInfo p in ObjectSource.GetType().GetProperties())\n NewObject.GetType().GetProperty(p.Name).SetValue(NewObject, p.GetValue(ObjectSource, null), null);\n\n return NewObject;\n}\n</code></pre>\n" }, { "answer_id": 4188702, "author": "pomeroy", "author_id": 141635, "author_profile": "https://Stackoverflow.com/users/141635", "pm_score": 1, "selected": false, "text": "<p>This limitation affected me when I tried to overload operators for generic types; since there was no \"INumeric\" constraint, and for a bevy of other reasons the good people on stackoverflow are happy to provide, operations cannot be defined on generic types.</p>\n\n<p>I wanted something like</p>\n\n<pre><code>public struct Foo&lt;T&gt;\n{\n public T Value{ get; private set; }\n\n public static Foo&lt;T&gt; operator +(Foo&lt;T&gt; LHS, Foo&lt;T&gt; RHS)\n {\n return new Foo&lt;T&gt; { Value = LHS.Value + RHS.Value; };\n }\n}\n</code></pre>\n\n<p>I have worked around this issue using .net4 dynamic runtime typing. </p>\n\n<pre><code>public struct Foo&lt;T&gt;\n{\n public T Value { get; private set; }\n\n public static Foo&lt;T&gt; operator +(Foo&lt;T&gt; LHS, Foo&lt;T&gt; RHS)\n {\n return new Foo&lt;T&gt; { Value = LHS.Value + (dynamic)RHS.Value };\n }\n}\n</code></pre>\n\n<p>The two things about using <code>dynamic</code> are </p>\n\n<ol>\n<li>Performance. All value types get boxed.</li>\n<li>Runtime errors. You \"beat\" the compiler, but lose type safety. If the generic type doesn't have the operator defined, an exception will be thrown during execution.</li>\n</ol>\n" }, { "answer_id": 4834066, "author": "Sergey Shandar", "author_id": 374845, "author_profile": "https://Stackoverflow.com/users/374845", "pm_score": 6, "selected": false, "text": "<p>Workaround using policies:</p>\n\n<pre><code>interface INumericPolicy&lt;T&gt;\n{\n T Zero();\n T Add(T a, T b);\n // add more functions here, such as multiplication etc.\n}\n\nstruct NumericPolicies:\n INumericPolicy&lt;int&gt;,\n INumericPolicy&lt;long&gt;\n // add more INumericPolicy&lt;&gt; for different numeric types.\n{\n int INumericPolicy&lt;int&gt;.Zero() { return 0; }\n long INumericPolicy&lt;long&gt;.Zero() { return 0; }\n int INumericPolicy&lt;int&gt;.Add(int a, int b) { return a + b; }\n long INumericPolicy&lt;long&gt;.Add(long a, long b) { return a + b; }\n // implement all functions from INumericPolicy&lt;&gt; interfaces.\n\n public static NumericPolicies Instance = new NumericPolicies();\n}\n</code></pre>\n\n<p>Algorithms:</p>\n\n<pre><code>static class Algorithms\n{\n public static T Sum&lt;P, T&gt;(this P p, params T[] a)\n where P: INumericPolicy&lt;T&gt;\n {\n var r = p.Zero();\n foreach(var i in a)\n {\n r = p.Add(r, i);\n }\n return r;\n }\n\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>int i = NumericPolicies.Instance.Sum(1, 2, 3, 4, 5);\nlong l = NumericPolicies.Instance.Sum(1L, 2, 3, 4, 5);\nNumericPolicies.Instance.Sum(\"www\", \"\") // compile-time error.\n</code></pre>\n\n<p>The solution is compile-time safe. <a href=\"http://citylizard.codeplex.com/releases/view/60527\" rel=\"noreferrer\">CityLizard Framework</a> provides compiled version for .NET 4.0. The file is lib/NETFramework4.0/CityLizard.Policy.dll.</p>\n\n<p>It's also available in Nuget: <a href=\"https://www.nuget.org/packages/CityLizard/\" rel=\"noreferrer\">https://www.nuget.org/packages/CityLizard/</a>. See <strong>CityLizard.Policy.I</strong> structure.</p>\n" }, { "answer_id": 6549763, "author": "dmihailescu", "author_id": 376495, "author_profile": "https://Stackoverflow.com/users/376495", "pm_score": 2, "selected": false, "text": "<p>There is no 'good' solution for this yet. However you can narrow the type argument significantly to rule out many missfits for your hypotetical 'INumeric' constraint as Haacked has shown above.</p>\n\n<p>static bool IntegerFunction&lt;T&gt;(T value) where T: IComparable, IFormattable, IConvertible, IComparable&lt;T&gt;, IEquatable&lt;T&gt;, struct \n{... </p>\n" }, { "answer_id": 16402309, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 1, "selected": false, "text": "<p>The .NET numeric primitive types do not share any common interface that would allow them to be used for calculations. It would be possible to define your own interfaces (e.g. <code>ISignedWholeNumber</code>) which would perform such operations, define structures which contain a single <code>Int16</code>, <code>Int32</code>, etc. and implement those interfaces, and then have methods which accept generic types constrained to <code>ISignedWholeNumber</code>, but having to convert numeric values to your structure types would likely be a nuisance.</p>\n\n<p>An alternative approach would be to define static class <code>Int64Converter&lt;T&gt;</code> with a static property <code>bool Available {get;};</code> and static delegates for <code>Int64 GetInt64(T value)</code>, <code>T FromInt64(Int64 value)</code>, <code>bool TryStoreInt64(Int64 value, ref T dest)</code>. The class constructor could use be hard-coded to load delegates for known types, and possibly use Reflection to test whether type <code>T</code> implements methods with the proper names and signatures (in case it's something like a struct which contains an <code>Int64</code> and represents a number, but has a custom <code>ToString()</code> method). This approach would lose the advantages associated with compile-time type-checking, but would still manage to avoid boxing operations and each type would only have to be \"checked\" once. After that, operations associated with that type would be replaced with a delegate dispatch.</p>\n" }, { "answer_id": 16481028, "author": "Martin Mulder", "author_id": 2304116, "author_profile": "https://Stackoverflow.com/users/2304116", "pm_score": 2, "selected": false, "text": "<p>I created a little library functionality to solve these problems:</p>\n\n<p>Instead of:</p>\n\n<pre><code>public T DifficultCalculation&lt;T&gt;(T a, T b)\n{\n T result = a * b + a; // &lt;== WILL NOT COMPILE!\n return result;\n}\nConsole.WriteLine(DifficultCalculation(2, 3)); // Should result in 8.\n</code></pre>\n\n<p>You could write:</p>\n\n<pre><code>public T DifficultCalculation&lt;T&gt;(Number&lt;T&gt; a, Number&lt;T&gt; b)\n{\n Number&lt;T&gt; result = a * b + a;\n return (T)result;\n}\nConsole.WriteLine(DifficultCalculation(2, 3)); // Results in 8.\n</code></pre>\n\n<p>You can find the source code here: <a href=\"https://codereview.stackexchange.com/questions/26022/improvement-requested-for-generic-calculator-and-generic-number\">https://codereview.stackexchange.com/questions/26022/improvement-requested-for-generic-calculator-and-generic-number</a></p>\n" }, { "answer_id": 22425077, "author": "Jeroen Vannevel", "author_id": 1864167, "author_profile": "https://Stackoverflow.com/users/1864167", "pm_score": 7, "selected": false, "text": "<p>Considering the popularity of this question and the interest behind such a function I am surprised to see that there is no answer involving T4 yet.</p>\n\n<p>In this sample code I will demonstrate a very simple example of how you can use the powerful templating engine to do what the compiler pretty much does behind the scenes with generics.</p>\n\n<p>Instead of going through hoops and sacrificing compile-time certainty you can simply generate the function you want for every type you like and use that accordingly (at compile time!).</p>\n\n<p>In order to do this: </p>\n\n<ul>\n<li>Create a new <em>Text Template</em> file called <em>GenericNumberMethodTemplate.tt</em>. </li>\n<li>Remove the auto-generated code (you'll keep most of it, but some isn't needed).</li>\n<li>Add the following snippet:</li>\n</ul>\n\n<pre class=\"lang-none prettyprint-override\"><code>&lt;#@ template language=\"C#\" #&gt;\n&lt;#@ output extension=\".cs\" #&gt;\n&lt;#@ assembly name=\"System.Core\" #&gt;\n\n&lt;# Type[] types = new[] {\n typeof(Int16), typeof(Int32), typeof(Int64),\n typeof(UInt16), typeof(UInt32), typeof(UInt64)\n };\n#&gt;\n\nusing System;\npublic static class MaxMath {\n &lt;# foreach (var type in types) { \n #&gt;\n public static &lt;#= type.Name #&gt; Max (&lt;#= type.Name #&gt; val1, &lt;#= type.Name #&gt; val2) {\n return val1 &gt; val2 ? val1 : val2;\n }\n &lt;#\n } #&gt;\n}\n</code></pre>\n\n<p>That's it. You're done now.</p>\n\n<p>Saving this file will automatically compile it to this source file:</p>\n\n<pre><code>using System;\npublic static class MaxMath {\n public static Int16 Max (Int16 val1, Int16 val2) {\n return val1 &gt; val2 ? val1 : val2;\n }\n public static Int32 Max (Int32 val1, Int32 val2) {\n return val1 &gt; val2 ? val1 : val2;\n }\n public static Int64 Max (Int64 val1, Int64 val2) {\n return val1 &gt; val2 ? val1 : val2;\n }\n public static UInt16 Max (UInt16 val1, UInt16 val2) {\n return val1 &gt; val2 ? val1 : val2;\n }\n public static UInt32 Max (UInt32 val1, UInt32 val2) {\n return val1 &gt; val2 ? val1 : val2;\n }\n public static UInt64 Max (UInt64 val1, UInt64 val2) {\n return val1 &gt; val2 ? val1 : val2;\n }\n}\n</code></pre>\n\n<p>In your <code>main</code> method you can verify that you have compile-time certainty:</p>\n\n<pre><code>namespace TTTTTest\n{\n class Program\n {\n static void Main(string[] args)\n {\n long val1 = 5L;\n long val2 = 10L;\n Console.WriteLine(MaxMath.Max(val1, val2));\n Console.Read();\n }\n }\n}\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/300td.png\" alt=\"enter image description here\"></p>\n\n<p>I'll get ahead of one remark: no, this is not a violation of the DRY principle. The DRY principle is there to prevent people from duplicating code in multiple places that would cause the application to become hard to maintain.</p>\n\n<p>This is not at all the case here: if you want a change then you can just change the template (a single source for all your generation!) and it's done.</p>\n\n<p>In order to use it with your own custom definitions, add a namespace declaration (make sure it's the same one as the one where you'll define your own implementation) to your generated code and mark the class as <code>partial</code>. Afterwards, add these lines to your template file so it will be included in the eventual compilation:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&lt;#@ import namespace=\"TheNameSpaceYouWillUse\" #&gt;\n&lt;#@ assembly name=\"$(TargetPath)\" #&gt;\n</code></pre>\n\n<p>Let's be honest: This is pretty cool.</p>\n\n<p>Disclaimer: this sample has been heavily influenced by <a href=\"http://www.manning.com/hazzard/\" rel=\"noreferrer\">Metaprogramming in .NET by Kevin Hazzard and Jason Bock, Manning Publications</a>.</p>\n" }, { "answer_id": 27627106, "author": "Rob Deary", "author_id": 1977538, "author_profile": "https://Stackoverflow.com/users/1977538", "pm_score": 3, "selected": false, "text": "<p>There is no way to restrict templates to types, but you can define different actions based on the type. As part of a generic numeric package, I needed a generic class to add two values. </p>\n\n<pre><code> class Something&lt;TCell&gt;\n {\n internal static TCell Sum(TCell first, TCell second)\n {\n if (typeof(TCell) == typeof(int))\n return (TCell)((object)(((int)((object)first)) + ((int)((object)second))));\n\n if (typeof(TCell) == typeof(double))\n return (TCell)((object)(((double)((object)first)) + ((double)((object)second))));\n\n return second;\n }\n }\n</code></pre>\n\n<p>Note that the typeofs are evaluated at compile time, so the if statements would be removed by the compiler. The compiler also removes spurious casts. So Something would resolve in the compiler to </p>\n\n<pre><code> internal static int Sum(int first, int second)\n {\n return first + second;\n }\n</code></pre>\n" }, { "answer_id": 45775531, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>If you are using .NET 4.0 and later then you can just use <strong>dynamic</strong> as method argument and check <strong>in runtime</strong> that the passed <strong>dynamic</strong> argument type is numeric/integer type.</p>\n\n<p>If the type of the passed <strong>dynamic</strong> is <strong>not</strong> numeric/integer type then throw exception.</p>\n\n<p>An example <strong>short</strong> code that implements the idea is something like:</p>\n\n<pre><code>using System;\npublic class InvalidArgumentException : Exception\n{\n public InvalidArgumentException(string message) : base(message) {}\n}\npublic class InvalidArgumentTypeException : InvalidArgumentException\n{\n public InvalidArgumentTypeException(string message) : base(message) {}\n}\npublic class ArgumentTypeNotIntegerException : InvalidArgumentTypeException\n{\n public ArgumentTypeNotIntegerException(string message) : base(message) {}\n}\npublic static class Program\n{\n private static bool IntegerFunction(dynamic n)\n {\n if (n.GetType() != typeof(Int16) &amp;&amp;\n n.GetType() != typeof(Int32) &amp;&amp;\n n.GetType() != typeof(Int64) &amp;&amp;\n n.GetType() != typeof(UInt16) &amp;&amp;\n n.GetType() != typeof(UInt32) &amp;&amp;\n n.GetType() != typeof(UInt64))\n throw new ArgumentTypeNotIntegerException(\"argument type is not integer type\");\n //code that implements IntegerFunction goes here\n }\n private static void Main()\n {\n Console.WriteLine(\"{0}\",IntegerFunction(0)); //Compiles, no run time error and first line of output buffer is either \"True\" or \"False\" depends on the code that implements \"Program.IntegerFunction\" static method.\n Console.WriteLine(\"{0}\",IntegerFunction(\"string\")); //Also compiles but it is run time error and exception of type \"ArgumentTypeNotIntegerException\" is thrown here.\n Console.WriteLine(\"This is the last Console.WriteLine output\"); //Never reached and executed due the run time error and the exception thrown on the second line of Program.Main static method.\n }\n</code></pre>\n\n<p>Of course that this solution works in run time only but never in compile time.</p>\n\n<p>If you want a solution that always works in compile time and never in run time then you will have to wrap the <strong>dynamic</strong> with a public struct/class whose overloaded <strong>public</strong> constructors accept arguments of the desired types only and give the struct/class appropriate name.</p>\n\n<p>It makes sense that the wrapped <strong>dynamic</strong> is always <strong>private</strong> member of the class/struct and it is the only member of the struct/class and the name of the only member of the struct/class is \"value\".</p>\n\n<p>You will also have to define and implement <strong>public</strong> methods and/or operators that work with the desired types for the private dynamic member of the class/struct if necessary.</p>\n\n<p>It also makes sense that the struct/class has <strong>special/unique</strong> constructor that accepts <strong>dynamic</strong> as argument that initializes it's only private dynamic member called \"value\" but the <strong>modifier</strong> of this constructor is <strong>private</strong> of course.</p>\n\n<p>Once the class/struct is ready define the argument's type of IntegerFunction to be that class/struct that has been defined.</p>\n\n<p>An example <strong>long</strong> code that implements the idea is something like:</p>\n\n<pre><code>using System;\npublic struct Integer\n{\n private dynamic value;\n private Integer(dynamic n) { this.value = n; }\n public Integer(Int16 n) { this.value = n; }\n public Integer(Int32 n) { this.value = n; }\n public Integer(Int64 n) { this.value = n; }\n public Integer(UInt16 n) { this.value = n; }\n public Integer(UInt32 n) { this.value = n; }\n public Integer(UInt64 n) { this.value = n; }\n public Integer(Integer n) { this.value = n.value; }\n public static implicit operator Int16(Integer n) { return n.value; }\n public static implicit operator Int32(Integer n) { return n.value; }\n public static implicit operator Int64(Integer n) { return n.value; }\n public static implicit operator UInt16(Integer n) { return n.value; }\n public static implicit operator UInt32(Integer n) { return n.value; }\n public static implicit operator UInt64(Integer n) { return n.value; }\n public static Integer operator +(Integer x, Int16 y) { return new Integer(x.value + y); }\n public static Integer operator +(Integer x, Int32 y) { return new Integer(x.value + y); }\n public static Integer operator +(Integer x, Int64 y) { return new Integer(x.value + y); }\n public static Integer operator +(Integer x, UInt16 y) { return new Integer(x.value + y); }\n public static Integer operator +(Integer x, UInt32 y) { return new Integer(x.value + y); }\n public static Integer operator +(Integer x, UInt64 y) { return new Integer(x.value + y); }\n public static Integer operator -(Integer x, Int16 y) { return new Integer(x.value - y); }\n public static Integer operator -(Integer x, Int32 y) { return new Integer(x.value - y); }\n public static Integer operator -(Integer x, Int64 y) { return new Integer(x.value - y); }\n public static Integer operator -(Integer x, UInt16 y) { return new Integer(x.value - y); }\n public static Integer operator -(Integer x, UInt32 y) { return new Integer(x.value - y); }\n public static Integer operator -(Integer x, UInt64 y) { return new Integer(x.value - y); }\n public static Integer operator *(Integer x, Int16 y) { return new Integer(x.value * y); }\n public static Integer operator *(Integer x, Int32 y) { return new Integer(x.value * y); }\n public static Integer operator *(Integer x, Int64 y) { return new Integer(x.value * y); }\n public static Integer operator *(Integer x, UInt16 y) { return new Integer(x.value * y); }\n public static Integer operator *(Integer x, UInt32 y) { return new Integer(x.value * y); }\n public static Integer operator *(Integer x, UInt64 y) { return new Integer(x.value * y); }\n public static Integer operator /(Integer x, Int16 y) { return new Integer(x.value / y); }\n public static Integer operator /(Integer x, Int32 y) { return new Integer(x.value / y); }\n public static Integer operator /(Integer x, Int64 y) { return new Integer(x.value / y); }\n public static Integer operator /(Integer x, UInt16 y) { return new Integer(x.value / y); }\n public static Integer operator /(Integer x, UInt32 y) { return new Integer(x.value / y); }\n public static Integer operator /(Integer x, UInt64 y) { return new Integer(x.value / y); }\n public static Integer operator %(Integer x, Int16 y) { return new Integer(x.value % y); }\n public static Integer operator %(Integer x, Int32 y) { return new Integer(x.value % y); }\n public static Integer operator %(Integer x, Int64 y) { return new Integer(x.value % y); }\n public static Integer operator %(Integer x, UInt16 y) { return new Integer(x.value % y); }\n public static Integer operator %(Integer x, UInt32 y) { return new Integer(x.value % y); }\n public static Integer operator %(Integer x, UInt64 y) { return new Integer(x.value % y); }\n public static Integer operator +(Integer x, Integer y) { return new Integer(x.value + y.value); }\n public static Integer operator -(Integer x, Integer y) { return new Integer(x.value - y.value); }\n public static Integer operator *(Integer x, Integer y) { return new Integer(x.value * y.value); }\n public static Integer operator /(Integer x, Integer y) { return new Integer(x.value / y.value); }\n public static Integer operator %(Integer x, Integer y) { return new Integer(x.value % y.value); }\n public static bool operator ==(Integer x, Int16 y) { return x.value == y; }\n public static bool operator !=(Integer x, Int16 y) { return x.value != y; }\n public static bool operator ==(Integer x, Int32 y) { return x.value == y; }\n public static bool operator !=(Integer x, Int32 y) { return x.value != y; }\n public static bool operator ==(Integer x, Int64 y) { return x.value == y; }\n public static bool operator !=(Integer x, Int64 y) { return x.value != y; }\n public static bool operator ==(Integer x, UInt16 y) { return x.value == y; }\n public static bool operator !=(Integer x, UInt16 y) { return x.value != y; }\n public static bool operator ==(Integer x, UInt32 y) { return x.value == y; }\n public static bool operator !=(Integer x, UInt32 y) { return x.value != y; }\n public static bool operator ==(Integer x, UInt64 y) { return x.value == y; }\n public static bool operator !=(Integer x, UInt64 y) { return x.value != y; }\n public static bool operator ==(Integer x, Integer y) { return x.value == y.value; }\n public static bool operator !=(Integer x, Integer y) { return x.value != y.value; }\n public override bool Equals(object obj) { return this == (Integer)obj; }\n public override int GetHashCode() { return this.value.GetHashCode(); }\n public override string ToString() { return this.value.ToString(); }\n public static bool operator &gt;(Integer x, Int16 y) { return x.value &gt; y; }\n public static bool operator &lt;(Integer x, Int16 y) { return x.value &lt; y; }\n public static bool operator &gt;(Integer x, Int32 y) { return x.value &gt; y; }\n public static bool operator &lt;(Integer x, Int32 y) { return x.value &lt; y; }\n public static bool operator &gt;(Integer x, Int64 y) { return x.value &gt; y; }\n public static bool operator &lt;(Integer x, Int64 y) { return x.value &lt; y; }\n public static bool operator &gt;(Integer x, UInt16 y) { return x.value &gt; y; }\n public static bool operator &lt;(Integer x, UInt16 y) { return x.value &lt; y; }\n public static bool operator &gt;(Integer x, UInt32 y) { return x.value &gt; y; }\n public static bool operator &lt;(Integer x, UInt32 y) { return x.value &lt; y; }\n public static bool operator &gt;(Integer x, UInt64 y) { return x.value &gt; y; }\n public static bool operator &lt;(Integer x, UInt64 y) { return x.value &lt; y; }\n public static bool operator &gt;(Integer x, Integer y) { return x.value &gt; y.value; }\n public static bool operator &lt;(Integer x, Integer y) { return x.value &lt; y.value; }\n public static bool operator &gt;=(Integer x, Int16 y) { return x.value &gt;= y; }\n public static bool operator &lt;=(Integer x, Int16 y) { return x.value &lt;= y; }\n public static bool operator &gt;=(Integer x, Int32 y) { return x.value &gt;= y; }\n public static bool operator &lt;=(Integer x, Int32 y) { return x.value &lt;= y; }\n public static bool operator &gt;=(Integer x, Int64 y) { return x.value &gt;= y; }\n public static bool operator &lt;=(Integer x, Int64 y) { return x.value &lt;= y; }\n public static bool operator &gt;=(Integer x, UInt16 y) { return x.value &gt;= y; }\n public static bool operator &lt;=(Integer x, UInt16 y) { return x.value &lt;= y; }\n public static bool operator &gt;=(Integer x, UInt32 y) { return x.value &gt;= y; }\n public static bool operator &lt;=(Integer x, UInt32 y) { return x.value &lt;= y; }\n public static bool operator &gt;=(Integer x, UInt64 y) { return x.value &gt;= y; }\n public static bool operator &lt;=(Integer x, UInt64 y) { return x.value &lt;= y; }\n public static bool operator &gt;=(Integer x, Integer y) { return x.value &gt;= y.value; }\n public static bool operator &lt;=(Integer x, Integer y) { return x.value &lt;= y.value; }\n public static Integer operator +(Int16 x, Integer y) { return new Integer(x + y.value); }\n public static Integer operator +(Int32 x, Integer y) { return new Integer(x + y.value); }\n public static Integer operator +(Int64 x, Integer y) { return new Integer(x + y.value); }\n public static Integer operator +(UInt16 x, Integer y) { return new Integer(x + y.value); }\n public static Integer operator +(UInt32 x, Integer y) { return new Integer(x + y.value); }\n public static Integer operator +(UInt64 x, Integer y) { return new Integer(x + y.value); }\n public static Integer operator -(Int16 x, Integer y) { return new Integer(x - y.value); }\n public static Integer operator -(Int32 x, Integer y) { return new Integer(x - y.value); }\n public static Integer operator -(Int64 x, Integer y) { return new Integer(x - y.value); }\n public static Integer operator -(UInt16 x, Integer y) { return new Integer(x - y.value); }\n public static Integer operator -(UInt32 x, Integer y) { return new Integer(x - y.value); }\n public static Integer operator -(UInt64 x, Integer y) { return new Integer(x - y.value); }\n public static Integer operator *(Int16 x, Integer y) { return new Integer(x * y.value); }\n public static Integer operator *(Int32 x, Integer y) { return new Integer(x * y.value); }\n public static Integer operator *(Int64 x, Integer y) { return new Integer(x * y.value); }\n public static Integer operator *(UInt16 x, Integer y) { return new Integer(x * y.value); }\n public static Integer operator *(UInt32 x, Integer y) { return new Integer(x * y.value); }\n public static Integer operator *(UInt64 x, Integer y) { return new Integer(x * y.value); }\n public static Integer operator /(Int16 x, Integer y) { return new Integer(x / y.value); }\n public static Integer operator /(Int32 x, Integer y) { return new Integer(x / y.value); }\n public static Integer operator /(Int64 x, Integer y) { return new Integer(x / y.value); }\n public static Integer operator /(UInt16 x, Integer y) { return new Integer(x / y.value); }\n public static Integer operator /(UInt32 x, Integer y) { return new Integer(x / y.value); }\n public static Integer operator /(UInt64 x, Integer y) { return new Integer(x / y.value); }\n public static Integer operator %(Int16 x, Integer y) { return new Integer(x % y.value); }\n public static Integer operator %(Int32 x, Integer y) { return new Integer(x % y.value); }\n public static Integer operator %(Int64 x, Integer y) { return new Integer(x % y.value); }\n public static Integer operator %(UInt16 x, Integer y) { return new Integer(x % y.value); }\n public static Integer operator %(UInt32 x, Integer y) { return new Integer(x % y.value); }\n public static Integer operator %(UInt64 x, Integer y) { return new Integer(x % y.value); }\n public static bool operator ==(Int16 x, Integer y) { return x == y.value; }\n public static bool operator !=(Int16 x, Integer y) { return x != y.value; }\n public static bool operator ==(Int32 x, Integer y) { return x == y.value; }\n public static bool operator !=(Int32 x, Integer y) { return x != y.value; }\n public static bool operator ==(Int64 x, Integer y) { return x == y.value; }\n public static bool operator !=(Int64 x, Integer y) { return x != y.value; }\n public static bool operator ==(UInt16 x, Integer y) { return x == y.value; }\n public static bool operator !=(UInt16 x, Integer y) { return x != y.value; }\n public static bool operator ==(UInt32 x, Integer y) { return x == y.value; }\n public static bool operator !=(UInt32 x, Integer y) { return x != y.value; }\n public static bool operator ==(UInt64 x, Integer y) { return x == y.value; }\n public static bool operator !=(UInt64 x, Integer y) { return x != y.value; }\n public static bool operator &gt;(Int16 x, Integer y) { return x &gt; y.value; }\n public static bool operator &lt;(Int16 x, Integer y) { return x &lt; y.value; }\n public static bool operator &gt;(Int32 x, Integer y) { return x &gt; y.value; }\n public static bool operator &lt;(Int32 x, Integer y) { return x &lt; y.value; }\n public static bool operator &gt;(Int64 x, Integer y) { return x &gt; y.value; }\n public static bool operator &lt;(Int64 x, Integer y) { return x &lt; y.value; }\n public static bool operator &gt;(UInt16 x, Integer y) { return x &gt; y.value; }\n public static bool operator &lt;(UInt16 x, Integer y) { return x &lt; y.value; }\n public static bool operator &gt;(UInt32 x, Integer y) { return x &gt; y.value; }\n public static bool operator &lt;(UInt32 x, Integer y) { return x &lt; y.value; }\n public static bool operator &gt;(UInt64 x, Integer y) { return x &gt; y.value; }\n public static bool operator &lt;(UInt64 x, Integer y) { return x &lt; y.value; }\n public static bool operator &gt;=(Int16 x, Integer y) { return x &gt;= y.value; }\n public static bool operator &lt;=(Int16 x, Integer y) { return x &lt;= y.value; }\n public static bool operator &gt;=(Int32 x, Integer y) { return x &gt;= y.value; }\n public static bool operator &lt;=(Int32 x, Integer y) { return x &lt;= y.value; }\n public static bool operator &gt;=(Int64 x, Integer y) { return x &gt;= y.value; }\n public static bool operator &lt;=(Int64 x, Integer y) { return x &lt;= y.value; }\n public static bool operator &gt;=(UInt16 x, Integer y) { return x &gt;= y.value; }\n public static bool operator &lt;=(UInt16 x, Integer y) { return x &lt;= y.value; }\n public static bool operator &gt;=(UInt32 x, Integer y) { return x &gt;= y.value; }\n public static bool operator &lt;=(UInt32 x, Integer y) { return x &lt;= y.value; }\n public static bool operator &gt;=(UInt64 x, Integer y) { return x &gt;= y.value; }\n public static bool operator &lt;=(UInt64 x, Integer y) { return x &lt;= y.value; }\n}\npublic static class Program\n{\n private static bool IntegerFunction(Integer n)\n {\n //code that implements IntegerFunction goes here\n //note that there is NO code that checks the type of n in rum time, because it is NOT needed anymore \n }\n private static void Main()\n {\n Console.WriteLine(\"{0}\",IntegerFunction(0)); //compile error: there is no overloaded METHOD for objects of type \"int\" and no implicit conversion from any object, including \"int\", to \"Integer\" is known.\n Console.WriteLine(\"{0}\",IntegerFunction(new Integer(0))); //both compiles and no run time error\n Console.WriteLine(\"{0}\",IntegerFunction(\"string\")); //compile error: there is no overloaded METHOD for objects of type \"string\" and no implicit conversion from any object, including \"string\", to \"Integer\" is known.\n Console.WriteLine(\"{0}\",IntegerFunction(new Integer(\"string\"))); //compile error: there is no overloaded CONSTRUCTOR for objects of type \"string\"\n }\n}\n</code></pre>\n\n<p>Note that in order to use <strong>dynamic</strong> in your code you must <strong>Add Reference</strong> to <strong>Microsoft.CSharp</strong></p>\n\n<p>If the version of the .NET framework is below/under/lesser than 4.0 and <strong>dynamic</strong> is undefined in that version then you will have to use <strong>object</strong> instead and do casting to the integer type, which is trouble, so I recommend that you use at least .NET 4.0 or newer if you can so you can use <strong>dynamic</strong> instead of <strong>object</strong>.</p>\n" }, { "answer_id": 53663980, "author": "user276648", "author_id": 276648, "author_profile": "https://Stackoverflow.com/users/276648", "pm_score": 0, "selected": false, "text": "<p>If all you want is use <strong>one numeric type</strong>, you could consider creating something similar to an alias in C++ with <code>using</code>.</p>\n\n<p>So instead of having the very generic</p>\n\n<pre><code>T ComputeSomething&lt;T&gt;(T value1, T value2) where T : INumeric { ... }\n</code></pre>\n\n<p>you could have</p>\n\n<pre><code>using MyNumType = System.Double;\nT ComputeSomething&lt;MyNumType&gt;(MyNumType value1, MyNumType value2) { ... }\n</code></pre>\n\n<p>That might allow you to easily go from <code>double</code> to <code>int</code> or others if needed, but you wouldn't be able to use <code>ComputeSomething</code> with <code>double</code> and <code>int</code> in the same program.</p>\n\n<p>But why not replace all <code>double</code> to <code>int</code> then? Because your method may want to use a <code>double</code> whether the input is <code>double</code> or <code>int</code>. The alias allows you to know exactly which variable uses the <em>dynamic</em> type.</p>\n" }, { "answer_id": 53703357, "author": "DrGriff", "author_id": 584714, "author_profile": "https://Stackoverflow.com/users/584714", "pm_score": 2, "selected": false, "text": "<p>I had a similar situation where I needed to handle numeric types and strings; seems a bit of a bizarre mix but there you go.</p>\n\n<p>Again, like many people I looked at constraints and came up with a bunch of interfaces that it had to support. However, a) it wasn't 100% watertight and b), anyone new looking at this long list of constraints would be immediately very confused.</p>\n\n<p>So, my approach was to put all my logic into a generic method with no constraints, but to make that generic method private. I then exposed it with public methods, one explicitly handling the type I wanted to handle - to my mind, the code is clean and explicit, e.g.</p>\n\n<pre><code>public static string DoSomething(this int input, ...) =&gt; DoSomethingHelper(input, ...);\npublic static string DoSomething(this decimal input, ...) =&gt; DoSomethingHelper(input, ...);\npublic static string DoSomething(this double input, ...) =&gt; DoSomethingHelper(input, ...);\npublic static string DoSomething(this string input, ...) =&gt; DoSomethingHelper(input, ...);\n\nprivate static string DoSomethingHelper&lt;T&gt;(this T input, ....)\n{\n // complex logic\n}\n</code></pre>\n" }, { "answer_id": 59991325, "author": "TylerBrinkley", "author_id": 8137269, "author_profile": "https://Stackoverflow.com/users/8137269", "pm_score": 2, "selected": false, "text": "<p>Unfortunately .NET doesn't provide a way to do that natively.</p>\n\n<p>To address this issue I created the OSS library <a href=\"https://github.com/TylerBrinkley/Genumerics\" rel=\"nofollow noreferrer\">Genumerics</a> which provides most standard numeric operations for the following built-in numeric types and their nullable equivalents with the ability to add support for other numeric types.</p>\n\n<p><code>sbyte</code>, <code>byte</code>, <code>short</code>, <code>ushort</code>, <code>int</code>, <code>uint</code>, <code>long</code>, <code>ulong</code>, <code>float</code>, <code>double</code>, <code>decimal</code>, and <code>BigInteger</code></p>\n\n<p>The performance is equivalent to a numeric type specific solution allowing you to create efficient generic numeric algorithms.</p>\n\n<p>Here's an example of the code usage.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static T Sum(T[] items)\n{\n T sum = Number.Zero&lt;T&gt;();\n foreach (T item in items)\n {\n sum = Number.Add(sum, item);\n }\n return sum;\n}\n</code></pre>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static T SumAlt(T[] items)\n{\n // implicit conversion to Number&lt;T&gt;\n Number&lt;T&gt; sum = Number.Zero&lt;T&gt;();\n foreach (T item in items)\n {\n // operator support\n sum += item;\n }\n // implicit conversion to T\n return sum;\n}\n</code></pre>\n" }, { "answer_id": 60022011, "author": "Vlad", "author_id": 1544015, "author_profile": "https://Stackoverflow.com/users/1544015", "pm_score": 5, "selected": false, "text": "<p>Beginning with C# 7.3, you can use closer <strong>approximation</strong> - the <strong>unmanaged constraint</strong> to specify that a type parameter is a non-pointer, non-nullable <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/unmanaged-types\" rel=\"noreferrer\">unmanaged</a> type.</p>\n<pre><code>class SomeGeneric&lt;T&gt; where T : unmanaged\n{\n//...\n}\n</code></pre>\n<p>The unmanaged constraint implies the struct constraint and can't be combined with either the struct or new() constraints.</p>\n<p>A type is an unmanaged type if it's any of the following types:</p>\n<ul>\n<li>sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool</li>\n<li>Any enum type</li>\n<li>Any pointer type</li>\n<li>Any user-defined struct type that contains fields of unmanaged types only and, in C# 7.3 and earlier, is not a constructed type (a type that includes at least one type argument)</li>\n</ul>\n<p>To restrict further and eliminate pointer and user-defined types that do not implement IComparable add <strong>IComparable</strong> (but enum is still derived from IComparable, so restrict enum by adding IEquatable &lt; T &gt;, you can go further depending on your circumstances and add additional interfaces. unmanaged allows to keep this list shorter):</p>\n<pre><code> class SomeGeneric&lt;T&gt; where T : unmanaged, IComparable, IEquatable&lt;T&gt;\n {\n //...\n }\n</code></pre>\n<p>But this doesn't prevent from DateTime instantiation.</p>\n" }, { "answer_id": 62211277, "author": "Arman Ebrahimpour", "author_id": 9212040, "author_profile": "https://Stackoverflow.com/users/9212040", "pm_score": 4, "selected": false, "text": "<p>Topic is old but for future readers:</p>\n\n<p>This feature is tightly related to <code>Discriminated Unions</code> which is not implemented in C# so far. I found its issue here:</p>\n\n<p><a href=\"https://github.com/dotnet/csharplang/issues/113\" rel=\"noreferrer\">https://github.com/dotnet/csharplang/issues/113</a></p>\n\n<p>This issue is still open and feature has been planned for <code>C# 10</code></p>\n\n<p>So still we have to wait a bit more, but after releasing you can do it this way:</p>\n\n<pre><code>static bool IntegerFunction&lt;T&gt;(T value) where T : Int16 | Int32 | Int64 | ...\n</code></pre>\n" }, { "answer_id": 68753665, "author": "Dan", "author_id": 4601149, "author_profile": "https://Stackoverflow.com/users/4601149", "pm_score": 5, "selected": true, "text": "<p>This constraint exists in .Net 7.</p>\n<p>Check out this <a href=\"https://devblogs.microsoft.com/dotnet/dotnet-7-generic-math/\" rel=\"nofollow noreferrer\">.NET Blog post</a> and the <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/generics/math\" rel=\"nofollow noreferrer\">actual documentation</a>.</p>\n<p>Starting in .NET 7, you can make use of interfaces such as <code>INumber</code> and <code>IFloatingPoint</code> to create programs such as:</p>\n<pre><code>using System.Numerics;\n\nConsole.WriteLine(Sum(1, 2, 3, 4, 5));\nConsole.WriteLine(Sum(10.541, 2.645));\nConsole.WriteLine(Sum(1.55f, 5, 9.41f, 7));\n\nstatic T Sum&lt;T&gt;(params T[] numbers) where T : INumber&lt;T&gt;\n{\n T result = T.Zero;\n\n foreach (T item in numbers)\n {\n result += item;\n }\n\n return result;\n}\n</code></pre>\n<p><code>INumber</code> is in the <code>System.Numerics</code> namespace.</p>\n<p>There are also interfaces such as <code>IAdditionOperators</code> and <code>IComparisonOperators</code> so you can make use of specific operators generically.</p>\n" }, { "answer_id": 69288660, "author": "lonix", "author_id": 9971404, "author_profile": "https://Stackoverflow.com/users/9971404", "pm_score": 0, "selected": false, "text": "<p>All numeric types <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/types#value-types\" rel=\"nofollow noreferrer\">are structs</a> which implement <code>IComparable, IComparable&lt;T&gt;, IConvertible, IEquatable&lt;T&gt;, IFormattable</code>. However, so does <code>DateTime</code>.</p>\n<p>So this generic extension method is possible:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static bool IsNumeric&lt;T&gt;(this T value) where T : struct, IComparable, IComparable&lt;T&gt;, IConvertible, IEquatable&lt;T&gt;, IFormattable =&gt;\n typeof(T) != typeof(DateTime);\n</code></pre>\n<p>But it will fail for a struct that implements those interfaces, e.g.:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public struct Foo : IComparable, IComparable&lt;Foo&gt;, IConvertible, IEquatable&lt;Foo&gt;, IFormattable { /* ... */ }\n</code></pre>\n<p>This non-generic alternative is less performant, but guaranteed to work:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static bool IsNumeric(this Type type) =&gt;\n type == typeof(sbyte) || type == typeof(byte) ||\n type == typeof(short) || type == typeof(ushort) ||\n type == typeof(int) || type == typeof(uint) ||\n type == typeof(long) || type == typeof(ulong) ||\n type == typeof(float) ||\n type == typeof(double) ||\n type == typeof(decimal);\n</code></pre>\n" }, { "answer_id": 70046713, "author": "asaf92", "author_id": 6104191, "author_profile": "https://Stackoverflow.com/users/6104191", "pm_score": 2, "selected": false, "text": "<p>.NET 6 has this functionality a preview feature:</p>\n<p><a href=\"https://devblogs.microsoft.com/dotnet/preview-features-in-net-6-generic-math/#generic-math\" rel=\"nofollow noreferrer\">https://devblogs.microsoft.com/dotnet/preview-features-in-net-6-generic-math/#generic-math</a></p>\n<p>An example from the article:</p>\n<pre><code>static T Add&lt;T&gt;(T left, T right)\n where T : INumber&lt;T&gt;\n{\n return left + right;\n}\n</code></pre>\n<p><code>INumber</code> is an interface that implements other interfaces, such as <code>IAdditionOperators</code> which allows the generic <code>+</code> usage. This is possible now because of another preview feature which is the static abstracts in interfaces, because the <code>+</code> operator overload is a static method:</p>\n<pre><code>/// &lt;summary&gt;Defines a mechanism for computing the sum of two values.&lt;/summary&gt;\n/// &lt;typeparam name=&quot;TSelf&quot;&gt;The type that implements this interface.&lt;/typeparam&gt;\n/// &lt;typeparam name=&quot;TOther&quot;&gt;The type that will be added to &lt;typeparamref name=&quot;TSelf&quot; /&gt;.&lt;/typeparam&gt;\n/// &lt;typeparam name=&quot;TResult&quot;&gt;The type that contains the sum of &lt;typeparamref name=&quot;TSelf&quot; /&gt; and &lt;typeparamref name=&quot;TOther&quot; /&gt;.&lt;/typeparam&gt;\n[RequiresPreviewFeatures(Number.PreviewFeatureMessage, Url = Number.PreviewFeatureUrl)]\npublic interface IAdditionOperators&lt;TSelf, TOther, TResult&gt;\n where TSelf : IAdditionOperators&lt;TSelf, TOther, TResult&gt;\n{\n /// &lt;summary&gt;Adds two values together to compute their sum.&lt;/summary&gt;\n /// &lt;param name=&quot;left&quot;&gt;The value to which &lt;paramref name=&quot;right&quot; /&gt; is added.&lt;/param&gt;\n /// &lt;param name=&quot;right&quot;&gt;The value which is added to &lt;paramref name=&quot;left&quot; /&gt;.&lt;/param&gt;\n /// &lt;returns&gt;The sum of &lt;paramref name=&quot;left&quot; /&gt; and &lt;paramref name=&quot;right&quot; /&gt;.&lt;/returns&gt;\n static abstract TResult operator +(TSelf left, TOther right);\n}\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1736/" ]
Can anyone tell me if there is a way with generics to limit a generic type argument `T` to only: * `Int16` * `Int32` * `Int64` * `UInt16` * `UInt32` * `UInt64` I'm aware of the `where` keyword, but can't find an interface for **only** these types, Something like: ``` static bool IntegerFunction<T>(T value) where T : INumeric ```
This constraint exists in .Net 7. Check out this [.NET Blog post](https://devblogs.microsoft.com/dotnet/dotnet-7-generic-math/) and the [actual documentation](https://learn.microsoft.com/en-us/dotnet/standard/generics/math). Starting in .NET 7, you can make use of interfaces such as `INumber` and `IFloatingPoint` to create programs such as: ``` using System.Numerics; Console.WriteLine(Sum(1, 2, 3, 4, 5)); Console.WriteLine(Sum(10.541, 2.645)); Console.WriteLine(Sum(1.55f, 5, 9.41f, 7)); static T Sum<T>(params T[] numbers) where T : INumber<T> { T result = T.Zero; foreach (T item in numbers) { result += item; } return result; } ``` `INumber` is in the `System.Numerics` namespace. There are also interfaces such as `IAdditionOperators` and `IComparisonOperators` so you can make use of specific operators generically.
32,694
<p>I'm trying to use <strong>NIS</strong> for authentication on a st of machines. I had to change one of the user ID numbers for a user account on the NIS server (I changed the userid for <code>username</code> from 500 to 509 to avoid a conflict with a local user account with id 500 on the clients). The problem is that it has not updated properly on the client. </p> <p>In particular, if I do <code>ypcat passwd | grep username</code>, I get the up-to-date info:</p> <pre><code>username:*hidden*:509:509:User Name:/home/username:/bin/bash </code></pre> <p>But if I do, <code>ypmatch username passwd</code>, it says:</p> <pre><code>username:*hidden*:500:500:User Name:/home/username:/bin/bash </code></pre> <p>This means that when the user logs onto one of the clients, it has the wrong userid, which causes all sorts of problems. I've done <code>"cd /var/yp; make"</code> on the server, and <code>"service ypbind restart"</code> on the client, but that hasn't fixed the problem. Does anybody know what would be causing this and how I can somehow force a refresh on the client? (I'm running Fedora 8 on both client and server).</p>
[ { "answer_id": 32770, "author": "Lorin Hochstein", "author_id": 742, "author_profile": "https://Stackoverflow.com/users/742", "pm_score": 1, "selected": false, "text": "<p>OK, I found the problem, I also had to restart the NIS service on the server to get it to refresh everything (<code>\"service ypserv restart\"</code>)</p>\n" }, { "answer_id": 33434, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>hmm, you're not supposed to have to restart the ypserver to have updates take effect; the <em>make</em> in /var/yp ought to do the trick. you might want to check the Makefile in /var/yp to be sure it's triggering on the right conditions (namely, passwd.by* should check the timestamp on /etc/passwd in some fashion, versus its current table. the process used to go through a passwd.time rule on the NIS server i ran, back in the dark ages). killing and restarting your nis server can have funky effects on (particularly non-linux) clients, so be careful doing it willy-nilly.</p>\n" }, { "answer_id": 3687735, "author": "John O", "author_id": 444677, "author_profile": "https://Stackoverflow.com/users/444677", "pm_score": 2, "selected": false, "text": "<p>Encountered same problem - RHEL 5.5. Change (any) source map, then run make. ypcat shows the changed info, ypmatch does not. Anything that needs to actually --use-- the new map fails. As per last post, restarting ypserv makes all OK. After days of testing, running strace, etc. I found that ypserv has a \"file handle cache\" controlled by the \"file:\" entry in /etc/ypserv.conf --- the default value is 30. Change this to 0 and everything works following the make. </p>\n\n<p>Shouldn't have to do this --- Per the manpage for ypserv.conf... </p>\n\n<p>\"There was one big change between ypserv 1.1 and ypserv 1.2. Since version 1.2, the file handles are cached. This means you have to call makedbm always with the -c option if you create new maps. Make sure, you are using the new /var/yp/Makefile from ypserv 1.2 or later, or add the -c flag to makedbm in the Makefile. If you don't do that, ypserv will continue to use the old maps, and not the updated one.\"</p>\n\n<p>The makefile <strong>DOES</strong> use \"makedbm -c\", but still ypserv uses the old (cached) map.</p>\n\n<p>Answer: Don't cache the file handles, e.g. set \"files: 0\" in ypserv.conf</p>\n" }, { "answer_id": 12900738, "author": "Bradley Kreider", "author_id": 268907, "author_profile": "https://Stackoverflow.com/users/268907", "pm_score": 3, "selected": false, "text": "<p>John O pointed me in the right direction. </p>\n\n<p>He is right. If you set \"files: 0\" in /etc/ypserv.conf, you can get ypserv to not cache files. If you have to restart ypserv after each make, this is the problem.</p>\n\n<p>The real solution is to look in /var/log/messages for this error: </p>\n\n<pre><code>ypserv[]: refused connect from 127.0.0.1 to procedure ypproc_clear (,;0)\n</code></pre>\n\n<p>makedbm -c means: send YPPROC_CLEAR to the local ypserv. The error message in the log means that CLEAR message is getting denied. You need to add 127.0.0.1 to /var/yp/securenets. </p>\n" }, { "answer_id": 41453662, "author": "Parthasarathi Sahu", "author_id": 7371642, "author_profile": "https://Stackoverflow.com/users/7371642", "pm_score": 0, "selected": false, "text": "<p>it is because of the nscd daemon.\nset the time to live value to 60 in /etc/nscd.conf for passwd session. It will work</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
I'm trying to use **NIS** for authentication on a st of machines. I had to change one of the user ID numbers for a user account on the NIS server (I changed the userid for `username` from 500 to 509 to avoid a conflict with a local user account with id 500 on the clients). The problem is that it has not updated properly on the client. In particular, if I do `ypcat passwd | grep username`, I get the up-to-date info: ``` username:*hidden*:509:509:User Name:/home/username:/bin/bash ``` But if I do, `ypmatch username passwd`, it says: ``` username:*hidden*:500:500:User Name:/home/username:/bin/bash ``` This means that when the user logs onto one of the clients, it has the wrong userid, which causes all sorts of problems. I've done `"cd /var/yp; make"` on the server, and `"service ypbind restart"` on the client, but that hasn't fixed the problem. Does anybody know what would be causing this and how I can somehow force a refresh on the client? (I'm running Fedora 8 on both client and server).
John O pointed me in the right direction. He is right. If you set "files: 0" in /etc/ypserv.conf, you can get ypserv to not cache files. If you have to restart ypserv after each make, this is the problem. The real solution is to look in /var/log/messages for this error: ``` ypserv[]: refused connect from 127.0.0.1 to procedure ypproc_clear (,;0) ``` makedbm -c means: send YPPROC\_CLEAR to the local ypserv. The error message in the log means that CLEAR message is getting denied. You need to add 127.0.0.1 to /var/yp/securenets.
32,717
<p>I just finished setting up an out-of-place build system for our existing C++ code using inherited property sheets, a feature that seems to be specific to the Visual C++ product. Building out-of-place requires that many of the project settings be changed, and the inherited property sheets allowed me to change all the necessary settings just by attaching a property sheet to the project. I am migrating our team from C++/MFC for UI to C# and WPF, but I need to provide the same out-of-place build functionality, hopefully with the same convenience. I cannot seem to find a way to do this with C# projects - I first looked to see if I could reference an MsBuild targets file, but could not find a way to do this. I know I could just use MsBuild for the whole thing, but that seems more complicated than necessary. Is there a way I can define a macro for a directory and use it in the output path, for example?</p>
[ { "answer_id": 32879, "author": "John Smithers", "author_id": 1069, "author_profile": "https://Stackoverflow.com/users/1069", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Is there a way I can define a macro for a directory and use it in the output path </p>\n</blockquote>\n\n<p>Have you looked at the pre-build and post-build events of a project?</p>\n" }, { "answer_id": 33159, "author": "Brian Stewart", "author_id": 3114, "author_profile": "https://Stackoverflow.com/users/3114", "pm_score": 0, "selected": false, "text": "<p>Actually, pre-build and post-build events seem to be solely a place to add batch-file type commands. This would not help me to set up standard build directories for our projects, unfortunately. And having these events create <strong>batch files</strong> seems like a very 1980's approach for a modern language like C#, IMO. </p>\n\n<p>After digging some more, and experimenting, I have found that you can add an &lt;Import&gt; directive into your .csproj file. When you do this, the IDE pops up a warning dialog that there is an unsafe entry point in your project - but you can ignore this, and you can make it not appear at all by editing a registry entry, evidently. So this would give me a way to get the variables containing the directory paths I need into the .csproj file. </p>\n\n<p>Now to get the Output Path to refer to it - unfortunately when you add a string like \"$(MySpecialPath)/Debug\" to the Output Path field, and save the project, the $ and () chars are converted to hex, and your file get's put in a Debug directory under a directory named \"$(MySpecialPath)\". Arrgghh. If you edit the .csproj file in a text editor, you can set this correctly however, and it seems to work as long as the &lt;Import&gt; tag appears before the &lt;PropertyGroup&gt; containing the Output Path. </p>\n\n<p>So I think the solution for me will be to create a standard OurTeam.targets MsBuild file in a standard location, add an installer for changing the registry so it doesn't flag warnings, and then create custom project templates that &lt;Import&gt; this file, and also set the Output Path to use the properties defined in the OurTeam.targets file. Sadly, this is more work and a less elegant solution than the property sheet inheritance mechanism in C++.</p>\n" }, { "answer_id": 188237, "author": "akmad", "author_id": 1314, "author_profile": "https://Stackoverflow.com/users/1314", "pm_score": 3, "selected": true, "text": "<p>I'm not quite sure what an \"out-of-place\" build system is, but if you just need the ability to copy the compiled files (or other resources) to other directories you can do so by tying into the MSBuild build targets.</p>\n\n<p>In our projects we move the compiled dlls into lib folders and put the files into the proper locations after a build is complete. To do this we've created a custom build .target file that creates the <code>Target</code>'s, <code>Property</code>'s, and <code>ItemGroup</code>'s that we then use to populate our external output folder.</p>\n\n<p>Our custom targets file looks a bit like this:</p>\n\n<pre><code>&lt;Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"&gt;\n &lt;PropertyGroup&gt;\n &lt;ProjectName&gt;TheProject&lt;/ProjectName&gt;\n &lt;ProjectDepthPath&gt;..\\..\\&lt;/ProjectDepthPath&gt;\n &lt;ProjectsLibFolder&gt;..\\..\\lib\\&lt;/ProjectsLibFolder&gt;\n\n &lt;LibFolder&gt;$(ProjectsLibFolder)$(ProjectName)\\$(Configuration)\\&lt;/LibFolder&gt;\n &lt;/PropertyGroup&gt;\n\n &lt;Target Name=\"DeleteLibFiles\"&gt;\n &lt;Delete Files=\"@(LibFiles-&gt; '$(ProjectDepthPath)$(LibFolder)%(filename)%(extension)')\" TreatErrorsAsWarnings=\"true\" /&gt;\n &lt;/Target&gt;\n &lt;Target Name=\"CopyLibFiles\"&gt;\n &lt;Copy SourceFiles=\"@(LibFiles)\" DestinationFolder=\"$(ProjectDepthPath)$(LibFolder)\" SkipUnchangedFiles=\"True\" /&gt;\n &lt;/Target&gt;\n\n &lt;ItemGroup&gt;\n &lt;LibFiles Include=\" \"&gt;\n &lt;Visible&gt;false&lt;/Visible&gt;\n &lt;/LibFiles&gt;\n &lt;/ItemGroup&gt;\n&lt;/Project&gt;\n</code></pre>\n\n<p>The .csproj file in Visual Studio then integrates with this custom target file:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;Project ToolsVersion=\"3.5\" ... &gt;\n ...\n &lt;Import Project=\"..\\..\\..\\..\\build\\OurBuildTargets.targets\" /&gt;\n &lt;ItemGroup&gt;\n &lt;LibFiles Include=\"$(OutputPath)$(AssemblyName).dll\"&gt;\n &lt;Visible&gt;false&lt;/Visible&gt;\n &lt;/LibFiles&gt;\n &lt;/ItemGroup&gt;\n &lt;Target Name=\"BeforeClean\" DependsOnTargets=\"DeleteLibFiles\" /&gt;\n &lt;Target Name=\"AfterBuild\" DependsOnTargets=\"CopyLibFiles\" /&gt;\n&lt;/Project&gt;\n</code></pre>\n\n<p>In a nutshell, this build script first tells MSBuild to load our custom build script, then adds the compiled file to the <code>LibFiles</code> ItemGroup, and lastly ties our custom build targets, <code>DeleteLibFiles</code> and <code>CopyLibFiles</code>, into the build process. We set this up for each project in our solution so only the files that are updated get deleted/copied and each project is responsible for it's own files (dlls, images, etc).</p>\n\n<p>I hope this helps. I apologize if I misunderstood what you mean by out-of-place build system and this is completely useless to you!</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114/" ]
I just finished setting up an out-of-place build system for our existing C++ code using inherited property sheets, a feature that seems to be specific to the Visual C++ product. Building out-of-place requires that many of the project settings be changed, and the inherited property sheets allowed me to change all the necessary settings just by attaching a property sheet to the project. I am migrating our team from C++/MFC for UI to C# and WPF, but I need to provide the same out-of-place build functionality, hopefully with the same convenience. I cannot seem to find a way to do this with C# projects - I first looked to see if I could reference an MsBuild targets file, but could not find a way to do this. I know I could just use MsBuild for the whole thing, but that seems more complicated than necessary. Is there a way I can define a macro for a directory and use it in the output path, for example?
I'm not quite sure what an "out-of-place" build system is, but if you just need the ability to copy the compiled files (or other resources) to other directories you can do so by tying into the MSBuild build targets. In our projects we move the compiled dlls into lib folders and put the files into the proper locations after a build is complete. To do this we've created a custom build .target file that creates the `Target`'s, `Property`'s, and `ItemGroup`'s that we then use to populate our external output folder. Our custom targets file looks a bit like this: ``` <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <ProjectName>TheProject</ProjectName> <ProjectDepthPath>..\..\</ProjectDepthPath> <ProjectsLibFolder>..\..\lib\</ProjectsLibFolder> <LibFolder>$(ProjectsLibFolder)$(ProjectName)\$(Configuration)\</LibFolder> </PropertyGroup> <Target Name="DeleteLibFiles"> <Delete Files="@(LibFiles-> '$(ProjectDepthPath)$(LibFolder)%(filename)%(extension)')" TreatErrorsAsWarnings="true" /> </Target> <Target Name="CopyLibFiles"> <Copy SourceFiles="@(LibFiles)" DestinationFolder="$(ProjectDepthPath)$(LibFolder)" SkipUnchangedFiles="True" /> </Target> <ItemGroup> <LibFiles Include=" "> <Visible>false</Visible> </LibFiles> </ItemGroup> </Project> ``` The .csproj file in Visual Studio then integrates with this custom target file: ``` <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" ... > ... <Import Project="..\..\..\..\build\OurBuildTargets.targets" /> <ItemGroup> <LibFiles Include="$(OutputPath)$(AssemblyName).dll"> <Visible>false</Visible> </LibFiles> </ItemGroup> <Target Name="BeforeClean" DependsOnTargets="DeleteLibFiles" /> <Target Name="AfterBuild" DependsOnTargets="CopyLibFiles" /> </Project> ``` In a nutshell, this build script first tells MSBuild to load our custom build script, then adds the compiled file to the `LibFiles` ItemGroup, and lastly ties our custom build targets, `DeleteLibFiles` and `CopyLibFiles`, into the build process. We set this up for each project in our solution so only the files that are updated get deleted/copied and each project is responsible for it's own files (dlls, images, etc). I hope this helps. I apologize if I misunderstood what you mean by out-of-place build system and this is completely useless to you!
32,744
<p>For the past few weeks, I've been trying to learn about just how email works. I understand the process of a client receiving mail from a server using POP pretty well. I also understand how a client computer can use SMTP to ask an SMTP server to send a message. However, I'm still missing something...</p> <p>The way I understand it, outgoing mail has to make three trips:</p> <ol> <li>Client (gmail user using Thunderbird) to a server (Gmail)</li> <li>First server (Gmail) to second server (Hotmail)</li> <li>Second server (Hotmail) to second client (hotmail user using OS X Mail)</li> </ol> <p>As I understand it, step one uses SMTP for the client to communicate. The client authenticates itself somehow (say, with USER and PASS), and then sends a message to the gmail server.</p> <p>However, I don't understand how gmail server transfers the message to the hotmail server.</p> <p>For step three, I'm pretty sure, the hotmail server uses POP to send the message to the hotmail client (using authentication, again).</p> <p>So, the big question is: <strong>when I click send Mail sends my message to my gmail server, how does my gmail server forward the message to, say, a hotmail server so my friend can recieve it?</strong></p> <p>Thank you so much!</p> <p>~Jason</p> <hr> <p>Thanks, that's been helpful so far.</p> <p>As I understand it, the first client sends the message to the first server using SMTP, often to an address such as smtp.mail.SOMESERVER.com on port 25 (usually).</p> <p>Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy).</p> <p>Then, when the recipient asks RECEIVESERVER for its mail, using POP, s/he recieves the message... right?</p> <p>Thanks again (especially to dr-jan),</p> <p>Jason</p>
[ { "answer_id": 32754, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 3, "selected": false, "text": "<p>You're looking for the Mail Transfer Agent, Wikipedia has <a href=\"http://en.wikipedia.org/wiki/Mail_transfer_agent\" rel=\"nofollow noreferrer\">a nice article</a> on the topic.</p>\n<blockquote>\n<p>Within Internet message handling services (MHS), a message transfer agent or mail transfer agent (MTA) or mail relay is software that transfers electronic mail messages from one computer to another using a client–server application architecture. An MTA implements both the client (sending) and server (receiving) portions of the Simple Mail Transfer Protocol.</p>\n<p>The terms mail server, mail exchanger, and MX host may also refer to a computer performing the MTA function. The Domain Name System (DNS) associates a mail server to a domain with mail exchanger (MX) resource records containing the domain name of a host providing MTA services.</p>\n</blockquote>\n" }, { "answer_id": 32765, "author": "Philip Reynolds", "author_id": 1087, "author_profile": "https://Stackoverflow.com/users/1087", "pm_score": 1, "selected": false, "text": "<p>Step 2 to 3 (i.e. Gmail to Hotmail) would normally happen through SMTP (or ESMTP - extended SMTP).</p>\n\n<p>Hotmail doesn't send anything to a client via POP3. It's important to understand some of the nuances here. The client contacts Hotmail via POP3 and requests its mail. (i.e. the client initiates the discussion).</p>\n" }, { "answer_id": 32775, "author": "Ivan Bosnic", "author_id": 3221, "author_profile": "https://Stackoverflow.com/users/3221", "pm_score": 2, "selected": false, "text": "<p>The first server will look at DNS for a MX record of Hotmail server. MX is a special record that defines a mail server for a certain domain. Knowing IP address of Hotmail server, GMail server will sent the message using SMTP protocol and will wait for an answer. If Hotmail server goes down, GMail server wiil try to resend the message (it will depend on server software configuration). If the process terminates ok, then ok, if not, GMail server will notify you that he wasn´t able to deliver the message.</p>\n" }, { "answer_id": 32776, "author": "dr-jan", "author_id": 2599, "author_profile": "https://Stackoverflow.com/users/2599", "pm_score": 5, "selected": true, "text": "<p>The SMTP server at Gmail (which accepted the message from Thunderbird) will route the message to the final recipient.</p>\n\n<p>It does this by using DNS to find the MX (mail exchanger) record for the domain name part of the destination email address (hotmail.com in this example). The DNS server will return an IP address which the message should be sent to. The server at the destination IP address will hopefully be running SMTP (on the standard port 25) so it can receive the incoming messages.</p>\n\n<p>Once the message has been received by the hotmail server, it is stored until the appropriate user logs in and retrieves their messages using POP (or IMAP).</p>\n\n<p>Jason - to answer your follow up...</p>\n\n<blockquote>\n <p>Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy).</p>\n</blockquote>\n\n<p>That's correct - the domain name to send to is taken as everything after the '@' in the email address of the recipient. Often, RECEIVESERVER.com is an alias for something more specific, say something like incoming.RECEIVESERVER.com, (or, indeed, smtp.mail.RECEIVESERVER.com).</p>\n\n<p>You can use nslookup to query your local DNS servers (this works in Linux and in a Windows cmd window):</p>\n\n<pre><code>nslookup\n&gt; set type=mx\n&gt; stackoverflow.com\nServer: 158.155.25.16\nAddress: 158.155.25.16#53\n\nNon-authoritative answer:\nstackoverflow.com mail exchanger = 10 aspmx.l.google.com.\nstackoverflow.com mail exchanger = 20 alt1.aspmx.l.google.com.\nstackoverflow.com mail exchanger = 30 alt2.aspmx.l.google.com.\nstackoverflow.com mail exchanger = 40 aspmx2.googlemail.com.\nstackoverflow.com mail exchanger = 50 aspmx3.googlemail.com.\n\nAuthoritative answers can be found from:\naspmx.l.google.com internet address = 64.233.183.114\naspmx.l.google.com internet address = 64.233.183.27\n&gt; \n</code></pre>\n\n<p>This shows us that email to anyone at stackoverflow.com should be sent to one of the gmail servers shown above.</p>\n\n<p>The Wikipedia article mentioned (<a href=\"http://en.wikipedia.org/wiki/Mx_record\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Mx_record</a>) discusses the priority numbers shown above (10, 20, ..., 50).</p>\n" }, { "answer_id": 32800, "author": "Corin Blaikie", "author_id": 1736, "author_profile": "https://Stackoverflow.com/users/1736", "pm_score": 2, "selected": false, "text": "<p>If you really want to know how email works you could read the <a href=\"http://www.lesnikowski.com/mail/Rfc/rfc2821.txt\" rel=\"nofollow noreferrer\">SMTP RFC</a> or the <a href=\"http://www.lesnikowski.com/mail/Rfc/rfc1939.txt\" rel=\"nofollow noreferrer\">POP3 RFC</a>.</p>\n" }, { "answer_id": 32813, "author": "Michał Piaskowski", "author_id": 1534, "author_profile": "https://Stackoverflow.com/users/1534", "pm_score": 1, "selected": false, "text": "<p>All emails are transferred using SMTP (or ESMTP). <br>\nThe important thing to understand is that the when you send message to [email protected] this message's destination is not his PC. The destination is someguy's inbox folder at hotmail.com server. <br>\nAfter the message arrives at it's destination. The user can check if he has any new messages on his account at hotmail server and retrieve them using POP3</p>\n\n<p>Also it would be possible to send the message without using gmail server, by sending it directly from your PC to hotmail using SMTP. </p>\n" }, { "answer_id": 32867, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": false, "text": "<p>You might also be interested to know why the GMail to HotMail link uses SMTP, just like your Thunderbird client. In other words, since your client can send email via SMTP, and it can use DNS to get the MX record for hotmail.com, why doesn't it just send it there directly, skipping gmail.com altogether?</p>\n<p>There are a couple of reasons, some historical and some for security. In the original question, it was assumed that your Thunderbird client logs in with a user name and password. This is often not the case. SMTP doesn't actually require a login to send a mail. And SMTP has no way to tell who's really sending the mail. Thus, spam was born!</p>\n<p>There are, unfortunately, still many SMTP servers out there that allow anyone and everyone to connect and send mail, trusting blindly that the sender is who they claim to be. These servers are called &quot;open relays&quot; and are routinely black-listed by smarter administrators of other mail servers, because of the spam they churn out.</p>\n<p>Responsible SMTP server admins set up their server to accept mail for delivery only in special cases 1) the mail is coming from &quot;its own&quot; network, or 2) the mail is being sent to &quot;its own&quot; network, or 3) the user presents credentials that identifies him as a trusted sender. Case #1 is probably what happens when you send mail from work; your machine is on the trusted network, so you can send mail to anyone. A lot of corporate mail servers still don't require authentication, so you can impersonate anyone in your office. Fun! Case #2 is when someone sends you mail. And case #3 is probably what happens with your GMail example. You're not coming from a trusted network, you’re just out on the Internet with the spammers. But by using a password, you can prove to GMail that you are who you say you are.</p>\n<p>The historical aspect is that in the old days, the link between gmail and hotmail was likely to be intermittent. By queuing your mail up at a local server, you could wash your hands of it, knowing that when a link was established, the local server could transfer your messages to the remote server, which would hold the message until the recipient's agent picked it up.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ]
For the past few weeks, I've been trying to learn about just how email works. I understand the process of a client receiving mail from a server using POP pretty well. I also understand how a client computer can use SMTP to ask an SMTP server to send a message. However, I'm still missing something... The way I understand it, outgoing mail has to make three trips: 1. Client (gmail user using Thunderbird) to a server (Gmail) 2. First server (Gmail) to second server (Hotmail) 3. Second server (Hotmail) to second client (hotmail user using OS X Mail) As I understand it, step one uses SMTP for the client to communicate. The client authenticates itself somehow (say, with USER and PASS), and then sends a message to the gmail server. However, I don't understand how gmail server transfers the message to the hotmail server. For step three, I'm pretty sure, the hotmail server uses POP to send the message to the hotmail client (using authentication, again). So, the big question is: **when I click send Mail sends my message to my gmail server, how does my gmail server forward the message to, say, a hotmail server so my friend can recieve it?** Thank you so much! ~Jason --- Thanks, that's been helpful so far. As I understand it, the first client sends the message to the first server using SMTP, often to an address such as smtp.mail.SOMESERVER.com on port 25 (usually). Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy). Then, when the recipient asks RECEIVESERVER for its mail, using POP, s/he recieves the message... right? Thanks again (especially to dr-jan), Jason
The SMTP server at Gmail (which accepted the message from Thunderbird) will route the message to the final recipient. It does this by using DNS to find the MX (mail exchanger) record for the domain name part of the destination email address (hotmail.com in this example). The DNS server will return an IP address which the message should be sent to. The server at the destination IP address will hopefully be running SMTP (on the standard port 25) so it can receive the incoming messages. Once the message has been received by the hotmail server, it is stored until the appropriate user logs in and retrieves their messages using POP (or IMAP). Jason - to answer your follow up... > > Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy). > > > That's correct - the domain name to send to is taken as everything after the '@' in the email address of the recipient. Often, RECEIVESERVER.com is an alias for something more specific, say something like incoming.RECEIVESERVER.com, (or, indeed, smtp.mail.RECEIVESERVER.com). You can use nslookup to query your local DNS servers (this works in Linux and in a Windows cmd window): ``` nslookup > set type=mx > stackoverflow.com Server: 158.155.25.16 Address: 158.155.25.16#53 Non-authoritative answer: stackoverflow.com mail exchanger = 10 aspmx.l.google.com. stackoverflow.com mail exchanger = 20 alt1.aspmx.l.google.com. stackoverflow.com mail exchanger = 30 alt2.aspmx.l.google.com. stackoverflow.com mail exchanger = 40 aspmx2.googlemail.com. stackoverflow.com mail exchanger = 50 aspmx3.googlemail.com. Authoritative answers can be found from: aspmx.l.google.com internet address = 64.233.183.114 aspmx.l.google.com internet address = 64.233.183.27 > ``` This shows us that email to anyone at stackoverflow.com should be sent to one of the gmail servers shown above. The Wikipedia article mentioned (<http://en.wikipedia.org/wiki/Mx_record>) discusses the priority numbers shown above (10, 20, ..., 50).
32,747
<p>How do I get today's date in C# in mm/dd/yyyy format?</p> <p>I need to set a string variable to today's date (preferably without the year), but there's got to be a better way than building it month-/-day one piece at a time.</p> <p>BTW: I'm in the US so M/dd would be correct, e.g. September 11th is 9/11.</p> <p><em>Note: an answer from kronoz came in that discussed internationalization, and I thought it was awesome enough to mention since I can't make it an 'accepted' answer as well.</em></p> <p><a href="https://stackoverflow.com/questions/32747/how-do-i-get-todays-date-in-c-in-8282008-format#32819" title="kronoz&#39;s answer">kronoz's answer</a></p>
[ { "answer_id": 32749, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 9, "selected": true, "text": "<pre><code>DateTime.Now.ToString(\"M/d/yyyy\");\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx</a></p>\n" }, { "answer_id": 32751, "author": "Corin Blaikie", "author_id": 1736, "author_profile": "https://Stackoverflow.com/users/1736", "pm_score": 4, "selected": false, "text": "<pre><code>DateTime.Now.ToString(\"dd/MM/yyyy\");\n</code></pre>\n" }, { "answer_id": 32752, "author": "Josh Mein", "author_id": 2486, "author_profile": "https://Stackoverflow.com/users/2486", "pm_score": 3, "selected": false, "text": "<pre><code>DateTime.Now.Date.ToShortDateString()\n</code></pre>\n\n<p>I think this is what you are looking for</p>\n" }, { "answer_id": 32758, "author": "Corin Blaikie", "author_id": 1736, "author_profile": "https://Stackoverflow.com/users/1736", "pm_score": 3, "selected": false, "text": "<pre><code>DateTime.Now.Date.ToShortDateString()\n</code></pre>\n\n<p>is culture specific. </p>\n\n<p>It is best to stick with:</p>\n\n<pre><code>DateTime.Now.ToString(\"d/MM/yyyy\");\n</code></pre>\n" }, { "answer_id": 32759, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 2, "selected": false, "text": "<p>Or without the year:</p>\n\n<pre><code>DateTime.Now.ToString(\"M/dd\")\n</code></pre>\n" }, { "answer_id": 32760, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "<p>If you want it without the year:</p>\n\n<pre><code>DateTime.Now.ToString(\"MM/DD\");\n</code></pre>\n\n<p>DateTime.ToString() has a lot of cool format strings:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa326721.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa326721.aspx</a></p>\n" }, { "answer_id": 32764, "author": "Billy Jo", "author_id": 3447, "author_profile": "https://Stackoverflow.com/users/3447", "pm_score": 3, "selected": false, "text": "<pre><code>string today = DateTime.Today.ToString(\"M/d\");\n</code></pre>\n" }, { "answer_id": 32819, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 5, "selected": false, "text": "<p>Not to be horribly pedantic, but if you are internationalising the code it might be more useful to have the facility to get the short date for a given culture, e.g.:-</p>\n\n<pre><code>using System.Globalization;\nusing System.Threading;\n\n...\n\nvar currentCulture = Thread.CurrentThread.CurrentCulture;\ntry {\n Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(\"en-us\");\n string shortDateString = DateTime.Now.ToShortDateString();\n // Do something with shortDateString...\n} finally {\n Thread.CurrentThread.CurrentCulture = currentCulture;\n}\n</code></pre>\n\n<p>Though clearly the \"m/dd/yyyy\" approach is considerably neater!!</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
How do I get today's date in C# in mm/dd/yyyy format? I need to set a string variable to today's date (preferably without the year), but there's got to be a better way than building it month-/-day one piece at a time. BTW: I'm in the US so M/dd would be correct, e.g. September 11th is 9/11. *Note: an answer from kronoz came in that discussed internationalization, and I thought it was awesome enough to mention since I can't make it an 'accepted' answer as well.* [kronoz's answer](https://stackoverflow.com/questions/32747/how-do-i-get-todays-date-in-c-in-8282008-format#32819 "kronoz's answer")
``` DateTime.Now.ToString("M/d/yyyy"); ``` <http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx>
32,750
<p>I have a <code>byte[]</code> array, the contents of which represent a TIFF file (as in, if I write out these bytes directly to a file using the <code>BinaryWriter</code> object, it forms a perfectly valid TIFF file) and I'm trying to turn it into a System.Drawing.Image object so that I can use it for later manipulation (feeding into a multipage TIFF object)</p> <p>The problem I'm having is that the commonly accepted code for this task:</p> <pre><code> public Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms, true); return returnImage; } </code></pre> <p>doesn't work for me. The second line of the above method where it calls the <code>Image.FromStream</code> method dies at runtime, saying</p> <pre><code>Parameter Not Valid </code></pre> <p>I believe that the method is choking on the fact that this is a TIFF file but I cannot figure out how to make the <code>FromStream</code> method accept this fact.</p> <p>How do I turn a byte array of a TIFF image into an Image object?</p> <p>Also, like I said the end goal of this is to have a byte array representing a multipage TIFF file, which contains the TIFF files for which I have byte array objects of right now. If there's a much better way to go about doing this, I'm all for it.</p>
[ { "answer_id": 32841, "author": "Tim", "author_id": 1970, "author_profile": "https://Stackoverflow.com/users/1970", "pm_score": 3, "selected": true, "text": "<p><strong>Edit:</strong> The assumption below is not correct, I had a chance to fire up my IDE later and tested with and without Write and both populated the MemoryStream correctly.</p>\n\n<p>I think you need to write to your MemeoryStream first.</p>\n\n<p>As if my memory (no pun intended) serves me correctly this:</p>\n\n<pre><code>MemoryStream ms = new MemoryStream(byteArrayIn);\n</code></pre>\n\n<p>Creates a memory stream of that size.</p>\n\n<p>You then need to write your byte array contents to the memory stream:</p>\n\n<pre><code>ms.Write(byteArrayIn, 0, byteArrayIn.Length);\n</code></pre>\n\n<p>See if that fixes it.</p>\n" }, { "answer_id": 33101, "author": "Tom Kidd", "author_id": 2577, "author_profile": "https://Stackoverflow.com/users/2577", "pm_score": 2, "selected": false, "text": "<p>OK, I found the issue, and it was from a part of the code unrelated to the part of the code I was asking about. The data was being passed as a string, I was converting it to a byte array (this was a test rig so I was trying to simulate the byte array that I get in the main app), then converting that to a MemoryStream, then making an Image from that.</p>\n\n<p>What I failed to realize was that the string was Base64 encoded. Calling <code>Convert.FromBase64String()</code> caused it to turn into a byte array which wouldn't kill the <code>Image.FromStream()</code> method.</p>\n\n<p>So basically it boiled down to a stupid mistake on my part. But hey, the code above is still useful and this page will probably serve as a Google result as to how to avoid this mistake to someone else.</p>\n\n<p>Also, I found an easy way to construct a Multi-Page TIFF from my byte arrays <a href=\"http://www.dotnetmonster.com/Uwe/Forum.aspx/dotnet-csharp/70308/Craete-tiff-Image-Page-by-Page\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 21838383, "author": "Shawn Kovac", "author_id": 2840284, "author_profile": "https://Stackoverflow.com/users/2840284", "pm_score": 1, "selected": false, "text": "<p>All these were clues that helped me figure out my problem which was the same problem as the question asks. So i want to post my solution which i arrived at because of these helpful clues. Thanks for all the clues posted so far!</p>\n\n<p>As Time Saunders posted in his answer, that Write method to actually write the bytes to the memory stream is essential. That was my first mistake.</p>\n\n<p>Then my data was bad TIFF data too, but in my case, i had an extra character 13 at the beginning of my image data. Once i removed that, it all worked fine for me.</p>\n\n<p>When i read about some basic TIFF file format specs, i found that TIFF files must begin with II or MM (two bytes with values of either 73 or 77). II means little-endian byte order ('Intel byte ordering') is used. MM means big-ending ('Motorola byte ordering') is used. The next two bytes are a two byte integer value ( = Int16 in .NET) of 42, binary 101010.</p>\n\n<p>Thus a correct TIFF stream of bytes begins with the decimal byte values of: 73, 73, 42, 0 or 77, 77, 0, 42. I encourage anyone with the same problem that we experienced to inspect your TIFF data byte stream and make sure your data is valid TIFF data!</p>\n\n<p>Thanks Schnapple and Tim Saunders!!</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ]
I have a `byte[]` array, the contents of which represent a TIFF file (as in, if I write out these bytes directly to a file using the `BinaryWriter` object, it forms a perfectly valid TIFF file) and I'm trying to turn it into a System.Drawing.Image object so that I can use it for later manipulation (feeding into a multipage TIFF object) The problem I'm having is that the commonly accepted code for this task: ``` public Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms, true); return returnImage; } ``` doesn't work for me. The second line of the above method where it calls the `Image.FromStream` method dies at runtime, saying ``` Parameter Not Valid ``` I believe that the method is choking on the fact that this is a TIFF file but I cannot figure out how to make the `FromStream` method accept this fact. How do I turn a byte array of a TIFF image into an Image object? Also, like I said the end goal of this is to have a byte array representing a multipage TIFF file, which contains the TIFF files for which I have byte array objects of right now. If there's a much better way to go about doing this, I'm all for it.
**Edit:** The assumption below is not correct, I had a chance to fire up my IDE later and tested with and without Write and both populated the MemoryStream correctly. I think you need to write to your MemeoryStream first. As if my memory (no pun intended) serves me correctly this: ``` MemoryStream ms = new MemoryStream(byteArrayIn); ``` Creates a memory stream of that size. You then need to write your byte array contents to the memory stream: ``` ms.Write(byteArrayIn, 0, byteArrayIn.Length); ``` See if that fixes it.
32,824
<p>While writing a custom IHttpHandler I came across a behavior that I didn't expect concerning the HttpCachePolicy object.</p> <p>My handler calculates and sets an entity-tag (using the SetETag method on the HttpCachePolicy associated with the current response object). If I set the cache-control to public using the SetCacheability method everything works like a charm and the server sends along the e-tag header. If I set it to private the e-tag header will be suppressed.</p> <p>Maybe I just haven't looked hard enough but I haven't seen anything in the HTTP/1.1 spec that would justify this behavior. Why wouldn't you want to send E-Tag to browsers while still prohibiting proxies from storing the data?</p> <pre><code>using System; using System.Web; public class Handler : IHttpHandler { public void ProcessRequest (HttpContext ctx) { ctx.Response.Cache.SetCacheability(HttpCacheability.Private); ctx.Response.Cache.SetETag("\"static\""); ctx.Response.ContentType = "text/plain"; ctx.Response.Write("Hello World"); } public bool IsReusable { get { return true; } } } </code></pre> <p>Will return</p> <pre> Cache-Control: private Content-Type: text/plain; charset=utf-8 Content-Length: 11 </pre> <p>But if we change it to public it'll return</p> <pre> Cache-Control: public Content-Type: text/plain; charset=utf-8 Content-Length: 11 Etag: "static" </pre> <p>I've run this on the ASP.NET development server and IIS6 so far with the same results. Also I'm unable to explicitly set the ETag using</p> <pre><code>Response.AppendHeader("ETag", "static") </code></pre> <p><strong>Update</strong>: It's possible to append the ETag header manually when running in IIS7, I suspect this is caused by the tight integration between ASP.NET and the IIS7 pipeline.</p> <p><strong>Clarification</strong>: It's a long question but the core question is this: <strong>why does ASP.NET do this, how can I get around it and should I?</strong></p> <p><strong>Update</strong>: I'm going to accept <a href="https://stackoverflow.com/questions/32824/why-does-httpcacheabilityprivate-suppress-etags#34004">Tony's answer</a> since it's essentially correct (go Tony!). I found that if you want to emulate the HttpCacheability.Private fully you can set the cacheability to ServerAndPrivate but you also have call cache.<a href="http://msdn.microsoft.com/en-us/library/system.web.httpcachepolicy.setomitvarystar.aspx" rel="nofollow noreferrer">SetOmitVaryStar</a>(true) otherwise the cache will add the <strong>Vary: *</strong> header to the output and you don't want that. I'll edit that into the answer when I get edit permissions (or if you see this Tony perhaps you could edit your answer to include that call?)</p>
[ { "answer_id": 33555, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 2, "selected": false, "text": "<p>Unfortunately if you look at <code>System.Web.HttpCachePolicy.UpdateCachedHeaders()</code> in .NET Reflector you see that there's an if statement specifically checking that the Cacheability is not Private before doing any ETag stuff. In any case, I've always found that <code>Last-Modified/If-Modified-Since</code> works well for our data and is a bit easier to monitor in Fiddler anyway.</p>\n" }, { "answer_id": 34004, "author": "TonyB", "author_id": 3543, "author_profile": "https://Stackoverflow.com/users/3543", "pm_score": 5, "selected": true, "text": "<p>I think you need to use HttpCacheability.ServerAndPrivate</p>\n\n<p>That should give you cache-control: private in the headers and let you set an ETag.</p>\n\n<p>The documentation on that needs to be a bit better.</p>\n\n<p><strong>Edit:</strong> Markus found that you also have call cache.SetOmitVaryStar(true) otherwise the cache will add the Vary: * header to the output and you don't want that.</p>\n" }, { "answer_id": 9935387, "author": "Moray McConnachie", "author_id": 1302129, "author_profile": "https://Stackoverflow.com/users/1302129", "pm_score": 1, "selected": false, "text": "<p>If like me you're unhappy with the workaround mentioned here of using Cacheability.ServerAndPrivate, and you really want to use Private instead - perhaps because you are customising pages individually for users and it makes no sense to cache on the server - then at least in .NET 3.5 you can set ETag through Response.Headers.Add and this works fine. </p>\n\n<p>N.B. if you do this you have to implement the comparison of the client headers yourself and the HTTP 304 response handling - not sure if .NET takes care of this for you under normal circumstances.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2114/" ]
While writing a custom IHttpHandler I came across a behavior that I didn't expect concerning the HttpCachePolicy object. My handler calculates and sets an entity-tag (using the SetETag method on the HttpCachePolicy associated with the current response object). If I set the cache-control to public using the SetCacheability method everything works like a charm and the server sends along the e-tag header. If I set it to private the e-tag header will be suppressed. Maybe I just haven't looked hard enough but I haven't seen anything in the HTTP/1.1 spec that would justify this behavior. Why wouldn't you want to send E-Tag to browsers while still prohibiting proxies from storing the data? ``` using System; using System.Web; public class Handler : IHttpHandler { public void ProcessRequest (HttpContext ctx) { ctx.Response.Cache.SetCacheability(HttpCacheability.Private); ctx.Response.Cache.SetETag("\"static\""); ctx.Response.ContentType = "text/plain"; ctx.Response.Write("Hello World"); } public bool IsReusable { get { return true; } } } ``` Will return ``` Cache-Control: private Content-Type: text/plain; charset=utf-8 Content-Length: 11 ``` But if we change it to public it'll return ``` Cache-Control: public Content-Type: text/plain; charset=utf-8 Content-Length: 11 Etag: "static" ``` I've run this on the ASP.NET development server and IIS6 so far with the same results. Also I'm unable to explicitly set the ETag using ``` Response.AppendHeader("ETag", "static") ``` **Update**: It's possible to append the ETag header manually when running in IIS7, I suspect this is caused by the tight integration between ASP.NET and the IIS7 pipeline. **Clarification**: It's a long question but the core question is this: **why does ASP.NET do this, how can I get around it and should I?** **Update**: I'm going to accept [Tony's answer](https://stackoverflow.com/questions/32824/why-does-httpcacheabilityprivate-suppress-etags#34004) since it's essentially correct (go Tony!). I found that if you want to emulate the HttpCacheability.Private fully you can set the cacheability to ServerAndPrivate but you also have call cache.[SetOmitVaryStar](http://msdn.microsoft.com/en-us/library/system.web.httpcachepolicy.setomitvarystar.aspx)(true) otherwise the cache will add the **Vary: \*** header to the output and you don't want that. I'll edit that into the answer when I get edit permissions (or if you see this Tony perhaps you could edit your answer to include that call?)
I think you need to use HttpCacheability.ServerAndPrivate That should give you cache-control: private in the headers and let you set an ETag. The documentation on that needs to be a bit better. **Edit:** Markus found that you also have call cache.SetOmitVaryStar(true) otherwise the cache will add the Vary: \* header to the output and you don't want that.
32,845
<p>Is it "taboo" to programatically create system restore points? I would be doing this before I perform a software update. If there is a better method to create a restore point with just my software's files and data, please let me know.</p> <p>I would like a means by which I can get the user back to a known working state if everything goes kaput during an update (closes/kills the update app, power goes out, user pulls the plug, etc.)</p> <pre><code> private void CreateRestorePoint(string description) { ManagementScope oScope = new ManagementScope("\\\\localhost\\root\\default"); ManagementPath oPath = new ManagementPath("SystemRestore"); ObjectGetOptions oGetOp = new ObjectGetOptions(); ManagementClass oProcess = new ManagementClass(oScope, oPath, oGetOp); ManagementBaseObject oInParams = oProcess.GetMethodParameters("CreateRestorePoint"); oInParams["Description"] = description; oInParams["RestorePointType"] = 12; // MODIFY_SETTINGS oInParams["EventType"] = 100; ManagementBaseObject oOutParams = oProcess.InvokeMethod("CreateRestorePoint", oInParams, null); } </code></pre>
[ { "answer_id": 32854, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": -1, "selected": false, "text": "<p>I don't think a complete system restore would be a good plan. Two reasons that quickly come to mind:</p>\n\n<ul>\n<li>Wasted disk space</li>\n<li>Unintended consequences from a rollback</li>\n</ul>\n" }, { "answer_id": 32874, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 2, "selected": false, "text": "<p>No, it's not Taboo - in fact, I'd encourage it. The OS manages how much hard drive takes, and I'd put money down on Microsoft spending more money &amp; time testing System Restore than you the money &amp; time you're putting into testing your setup application.</p>\n" }, { "answer_id": 32893, "author": "Misha M", "author_id": 3467, "author_profile": "https://Stackoverflow.com/users/3467", "pm_score": 0, "selected": false, "text": "<p>Take a look at the following link: <a href=\"http://www.calumgrant.net/atomic/\" rel=\"nofollow noreferrer\">http://www.calumgrant.net/atomic/</a></p>\n\n<p>The author described \"Transactional Programming\". This is analogous to the transactions in data bases.</p>\n\n<p>Example:</p>\n\n<p>Start transaction:</p>\n\n<ol>\n<li>Step 1</li>\n<li>Step 2</li>\n<li>Encounter error during step 2</li>\n<li>Roll back to before transaction started.</li>\n</ol>\n\n<p>This is a new framework, but you can look at it more as a solution rather then using the framework.</p>\n\n<p>By using transactions, you get the \"Restore Points\" that you're looking for.</p>\n" }, { "answer_id": 32933, "author": "The How-To Geek", "author_id": 291, "author_profile": "https://Stackoverflow.com/users/291", "pm_score": 1, "selected": false, "text": "<p>If you are developing an application for Vista you can use Transactional NTFS, which supports a similar feature to what you are looking for.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Transactional_NTFS\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Transactional_NTFS</a></p>\n\n<p>Wouldn't installer packages already include this type of rollback support, though? I'm not terribly familiar with most of them so I am not sure.</p>\n\n<p>Finally, Windows will typically automatically create a restore point anytime you run a setup application.</p>\n" }, { "answer_id": 32989, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 2, "selected": false, "text": "<p>Whether it's a good idea or not really depends on how much you're doing. A full system restore point is weighty - it takes time to create, disk space to store, and gets added to the interface of restore points, possibly pushing earlier restore points out of storage.</p>\n\n<p>So, if your update is really only changing <em>your</em> application (i.e. the data it stores, the binaries that make it up, the registry entries for it), then it's not really a system level change, and I'd vote for no restore point. You can emulate the functionality by just backing up the parts you're changing, and offering a restore to backup option. My opinion is that System Restore should be to restore the system when global changes are made that might corrupt it (application install, etc).</p>\n\n<p>The counter argument that one should just use the system service doesn't hold water for me; I worry that, if you have to issue a number of updates to your application, the set of system restore points might get so large that important, real \"system wide\" updates might get pushed out, or lost in the noise.</p>\n" }, { "answer_id": 32995, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>Is it \"taboo\" to programatically create system restore points?</p>\n</blockquote>\n\n<p>No. That's why the API is there; so that you can have pseudo-atomic updates of the system.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
Is it "taboo" to programatically create system restore points? I would be doing this before I perform a software update. If there is a better method to create a restore point with just my software's files and data, please let me know. I would like a means by which I can get the user back to a known working state if everything goes kaput during an update (closes/kills the update app, power goes out, user pulls the plug, etc.) ``` private void CreateRestorePoint(string description) { ManagementScope oScope = new ManagementScope("\\\\localhost\\root\\default"); ManagementPath oPath = new ManagementPath("SystemRestore"); ObjectGetOptions oGetOp = new ObjectGetOptions(); ManagementClass oProcess = new ManagementClass(oScope, oPath, oGetOp); ManagementBaseObject oInParams = oProcess.GetMethodParameters("CreateRestorePoint"); oInParams["Description"] = description; oInParams["RestorePointType"] = 12; // MODIFY_SETTINGS oInParams["EventType"] = 100; ManagementBaseObject oOutParams = oProcess.InvokeMethod("CreateRestorePoint", oInParams, null); } ```
> > Is it "taboo" to programatically create system restore points? > > > No. That's why the API is there; so that you can have pseudo-atomic updates of the system.
32,877
<p>I've got a problem where incoming SOAP messages from one particular client are being marked as invalid and rejected by our XML firewall device. It appears extra payload data is being inserted by Visual Studio; we're thinking the extra data may be causing a problem b/c we're seeing "VsDebuggerCausalityData" in these messages but not in others sent from a different client who is not having a problem. It's a starting point, anyway.</p> <p>The question I have is how can the client remove this extra data and still run from VS? Why is VS putting it in there at all?</p> <p>Thanks.</p>
[ { "answer_id": 33312, "author": "Darryl Braaten", "author_id": 1834, "author_profile": "https://Stackoverflow.com/users/1834", "pm_score": 5, "selected": true, "text": "<p>A quick google reveals that this should get rid of it, get them to add it to the web.config or app.config for their application. </p>\n\n<pre><code>&lt;configuration&gt;\n &lt;system.diagnostics&gt;\n &lt;switches&gt;\n &lt;add name=\"Remote.Disable\" value=\"1\" /&gt;\n &lt;/switches&gt;\n &lt;/system.diagnostics&gt;\n&lt;/configuration&gt; \n</code></pre>\n\n<p>The information is debug information that the receiving service can use to help trace things back to the client. (maybe, I am guessing a little) </p>\n\n<ul>\n<li>I have proposed a follow up <a href=\"https://stackoverflow.com/questions/33334/how-do-you-find-what-debug-switches-are-available-or-given-a-switch-find-out-wh\">question</a> to determine were the magic switch actually comes from.</li>\n</ul>\n" }, { "answer_id": 3066595, "author": "ggrocco", "author_id": 369899, "author_profile": "https://Stackoverflow.com/users/369899", "pm_score": 4, "selected": false, "text": "<p>For remove 'VsDebuggerCausalityData' you need stop de Visual Studio Diagnostic for WCF using this command:</p>\n\n<p>VS 2008 -> c:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE>vsdiag_regwcf.exe -u\nVS 2010 -> c:\\Program Files\\Microsoft Visual Studio 10.0\\Common7\\IDE>vsdiag_regwcf.exe -u</p>\n\n<p>I hope this help you or other people.</p>\n" }, { "answer_id": 12289892, "author": "Jesse Chisholm", "author_id": 1456887, "author_profile": "https://Stackoverflow.com/users/1456887", "pm_score": 3, "selected": false, "text": "<p>Darryl's answer didn't work for me. Each developer has to do ggrocco's answer.</p>\n\n<p>I ended up writing a <strong>MessageInspector</strong>, and adding this code to the <strong>BeforeSendRequest</strong> method:</p>\n\n<pre><code>int limit = request.Headers.Count;\nfor(int i=0; i&lt;limit; ++i)\n{\n if (request.Headers[i].Name.Equals(\"VsDebuggerCausalityData\"))\n {\n request.Headers.RemoveAt(i);\n break;\n }\n}\n</code></pre>\n" }, { "answer_id": 26403141, "author": "Poppert", "author_id": 598630, "author_profile": "https://Stackoverflow.com/users/598630", "pm_score": 2, "selected": false, "text": "<p>Or use \"Start without debugging\" in Visual Studio.</p>\n" }, { "answer_id": 38570441, "author": "Gone Coding", "author_id": 201078, "author_profile": "https://Stackoverflow.com/users/201078", "pm_score": 4, "selected": false, "text": "<p>Based on an answer by <code>@Luiz Felipe</code> I came up with this slightly more robust solution:</p>\n\n<pre><code>var vs = client.Endpoint.EndpointBehaviors.FirstOrDefault((i) =&gt; i.GetType().Namespace == \"Microsoft.VisualStudio.Diagnostics.ServiceModelSink\");\nif (vs != null)\n{\n client.Endpoint.Behaviors.Remove(vs);\n}\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1683/" ]
I've got a problem where incoming SOAP messages from one particular client are being marked as invalid and rejected by our XML firewall device. It appears extra payload data is being inserted by Visual Studio; we're thinking the extra data may be causing a problem b/c we're seeing "VsDebuggerCausalityData" in these messages but not in others sent from a different client who is not having a problem. It's a starting point, anyway. The question I have is how can the client remove this extra data and still run from VS? Why is VS putting it in there at all? Thanks.
A quick google reveals that this should get rid of it, get them to add it to the web.config or app.config for their application. ``` <configuration> <system.diagnostics> <switches> <add name="Remote.Disable" value="1" /> </switches> </system.diagnostics> </configuration> ``` The information is debug information that the receiving service can use to help trace things back to the client. (maybe, I am guessing a little) * I have proposed a follow up [question](https://stackoverflow.com/questions/33334/how-do-you-find-what-debug-switches-are-available-or-given-a-switch-find-out-wh) to determine were the magic switch actually comes from.
32,897
<p>This question would probably apply equally as well to other languages with C-like multi-line comments. Here's the problem I'm encountering. I'm working with Java code in Eclipse, and I wanted to comment out a block of code. However, there is a string that contains the character sequence "*/", and Eclipse thinks that the comment should end there, even though it is inside a string. It gives me tons of errors and fails to build.</p> <pre><code>/* ... some Java code ... ... "... */ ..." ... ... more Java code ... */ </code></pre> <p>Does the Java specification match with Eclipse's interpretation of my multi-line comment? I would like to think that Java and/or Eclipse would account for this sort of thing.</p>
[ { "answer_id": 32916, "author": "Damien B", "author_id": 3069, "author_profile": "https://Stackoverflow.com/users/3069", "pm_score": 4, "selected": true, "text": "<p>Eclipse is correct. There is no interpretation context inside a comment (no escaping, etc). See <a href=\"http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48125\" rel=\"noreferrer\">JLS §3.7</a>.</p>\n" }, { "answer_id": 32918, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Yes, I am commenting the code out just to do a quick test. I've already tested what I needed to by commenting the code out another way; I was just curious about what appears to be an odd misfeature of Java and/or Eclipse.</p>\n" }, { "answer_id": 32927, "author": "joev", "author_id": 3449, "author_profile": "https://Stackoverflow.com/users/3449", "pm_score": 0, "selected": false, "text": "<p>A simple test shows Eclipse is correct:</p>\n\n<pre><code>public class Test {\n public static final void main(String[] args) throws Exception {\n String s = \"This is the original string.\";\n /* This is commented out.\n s = \"This is the end of a comment: */ \";\n */\n System.out.println(s);\n }\n}\n</code></pre>\n\n<p>This fails to compile with:</p>\n\n<pre><code>Test.java:5: unclosed string literal\n s = \"This is the end of a comment: */ \";\n</code></pre>\n" }, { "answer_id": 32931, "author": "axk", "author_id": 578, "author_profile": "https://Stackoverflow.com/users/578", "pm_score": 0, "selected": false, "text": "<p>I may be helpful to just do a \"batch\" multiline comment so that it comments each line with \"//\". It is Ctrl+\"/\" in Idea for commenting and uncommenting the selected lines, Eclipse should have a similar feature.</p>\n" }, { "answer_id": 32982, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 2, "selected": false, "text": "<p>In Eclipse you can highlight the part of the source code you want to comment out and use the Ctrl+/ to single-line comment every line in the highlighted section - puts a \"//\" at the beginning of the lines.</p>\n\n<p>Or if you really want to block-comment the selection use the Ctrl+Shift+/ combination. It will detect the block comments in your selection. However undoing this is harder than single-line comments.</p>\n" }, { "answer_id": 143915, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 0, "selected": false, "text": "<p>I often use only <code>//</code> for inline commments, and use <code>/* */</code> only for commenting out large blocks the way you have.</p>\n\n<p>A lot of developers will still use /* */ for inline comments, because that's what they're familiar with, but they all run into problems like this one, in C it didn't matter as much because you could #if 0 the stuff away.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This question would probably apply equally as well to other languages with C-like multi-line comments. Here's the problem I'm encountering. I'm working with Java code in Eclipse, and I wanted to comment out a block of code. However, there is a string that contains the character sequence "\*/", and Eclipse thinks that the comment should end there, even though it is inside a string. It gives me tons of errors and fails to build. ``` /* ... some Java code ... ... "... */ ..." ... ... more Java code ... */ ``` Does the Java specification match with Eclipse's interpretation of my multi-line comment? I would like to think that Java and/or Eclipse would account for this sort of thing.
Eclipse is correct. There is no interpretation context inside a comment (no escaping, etc). See [JLS §3.7](http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48125).
32,899
<p>I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [[&quot;foo&quot;, &quot;a&quot;, &quot;a&quot;,], [&quot;bar&quot;, &quot;a&quot;, &quot;b&quot;], [&quot;lee&quot;, &quot;b&quot;, &quot;b&quot;]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print &quot;test&quot;, name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
[ { "answer_id": 32939, "author": "Dmitry Mukhin", "author_id": 3448, "author_profile": "https://Stackoverflow.com/users/3448", "pm_score": 9, "selected": true, "text": "<p>This is called &quot;parametrization&quot;.</p>\n<p>There are several tools that support this approach. E.g.:</p>\n<ul>\n<li><a href=\"https://docs.pytest.org/en/latest/parametrize.html\" rel=\"noreferrer\">pytest's decorator</a></li>\n<li><a href=\"https://github.com/wolever/parameterized\" rel=\"noreferrer\">parameterized</a></li>\n</ul>\n<p>The resulting code looks like this:</p>\n<pre><code>from parameterized import parameterized\n\nclass TestSequence(unittest.TestCase):\n @parameterized.expand([\n [&quot;foo&quot;, &quot;a&quot;, &quot;a&quot;,],\n [&quot;bar&quot;, &quot;a&quot;, &quot;b&quot;],\n [&quot;lee&quot;, &quot;b&quot;, &quot;b&quot;],\n ])\n def test_sequence(self, name, a, b):\n self.assertEqual(a,b)\n</code></pre>\n<p>Which will generate the tests:</p>\n<pre class=\"lang-none prettyprint-override\"><code>test_sequence_0_foo (__main__.TestSequence) ... ok\ntest_sequence_1_bar (__main__.TestSequence) ... FAIL\ntest_sequence_2_lee (__main__.TestSequence) ... ok\n\n======================================================================\nFAIL: test_sequence_1_bar (__main__.TestSequence)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File &quot;/usr/local/lib/python2.7/site-packages/parameterized/parameterized.py&quot;, line 233, in &lt;lambda&gt;\n standalone_func = lambda *a: func(*(a + p.args), **p.kwargs)\n File &quot;x.py&quot;, line 12, in test_sequence\n self.assertEqual(a,b)\nAssertionError: 'a' != 'b'\n</code></pre>\n<p>For historical reasons I'll leave the original answer circa 2008):</p>\n<p>I use something like this:</p>\n<pre><code>import unittest\n\nl = [[&quot;foo&quot;, &quot;a&quot;, &quot;a&quot;,], [&quot;bar&quot;, &quot;a&quot;, &quot;b&quot;], [&quot;lee&quot;, &quot;b&quot;, &quot;b&quot;]]\n\nclass TestSequense(unittest.TestCase):\n pass\n\ndef test_generator(a, b):\n def test(self):\n self.assertEqual(a,b)\n return test\n\nif __name__ == '__main__':\n for t in l:\n test_name = 'test_%s' % t[0]\n test = test_generator(t[1], t[2])\n setattr(TestSequense, test_name, test)\n unittest.main()\n</code></pre>\n" }, { "answer_id": 34094, "author": "codeape", "author_id": 3571, "author_profile": "https://Stackoverflow.com/users/3571", "pm_score": 8, "selected": false, "text": "<p><strong>Using <a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"noreferrer\">unittest</a> (since 3.4)</strong></p>\n<p>Since Python 3.4, the standard library <code>unittest</code> package has the <code>subTest</code> context manager.</p>\n<p>See the documentation:</p>\n<ul>\n<li><a href=\"https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests\" rel=\"noreferrer\">26.4.7. Distinguishing test iterations using subtests</a></li>\n<li><a href=\"https://docs.python.org/3/library/unittest.html#unittest.TestCase.subTest\" rel=\"noreferrer\">subTest</a></li>\n</ul>\n<p>Example:</p>\n<pre><code>from unittest import TestCase\n\nparam_list = [('a', 'a'), ('a', 'b'), ('b', 'b')]\n\nclass TestDemonstrateSubtest(TestCase):\n def test_works_as_expected(self):\n for p1, p2 in param_list:\n with self.subTest():\n self.assertEqual(p1, p2)\n</code></pre>\n<p>You can also specify a custom message and parameter values to <code>subTest()</code>:</p>\n<pre><code>with self.subTest(msg=&quot;Checking if p1 equals p2&quot;, p1=p1, p2=p2):\n</code></pre>\n<p><strong>Using <a href=\"https://pypi.org/project/nose/\" rel=\"noreferrer\">nose</a></strong></p>\n<p>The <a href=\"https://nose.readthedocs.org/en/latest/\" rel=\"noreferrer\">nose</a> testing framework <a href=\"https://nose.readthedocs.org/en/latest/writing_tests.html#test-generators\" rel=\"noreferrer\">supports this</a>.</p>\n<p>Example (the code below is the entire contents of the file containing the test):</p>\n<pre><code>param_list = [('a', 'a'), ('a', 'b'), ('b', 'b')]\n\ndef test_generator():\n for params in param_list:\n yield check_em, params[0], params[1]\n\ndef check_em(a, b):\n assert a == b\n</code></pre>\n<p>The output of the nosetests command:</p>\n<pre class=\"lang-none prettyprint-override\"><code>&gt; nosetests -v\ntestgen.test_generator('a', 'a') ... ok\ntestgen.test_generator('a', 'b') ... FAIL\ntestgen.test_generator('b', 'b') ... ok\n\n======================================================================\nFAIL: testgen.test_generator('a', 'b')\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File &quot;/usr/lib/python2.5/site-packages/nose-0.10.1-py2.5.egg/nose/case.py&quot;, line 203, in runTest\n self.test(*self.arg)\n File &quot;testgen.py&quot;, line 7, in check_em\n assert a == b\nAssertionError\n\n----------------------------------------------------------------------\nRan 3 tests in 0.006s\n\nFAILED (failures=1)\n</code></pre>\n" }, { "answer_id": 810127, "author": "bignose", "author_id": 70157, "author_profile": "https://Stackoverflow.com/users/70157", "pm_score": 3, "selected": false, "text": "<p>You would benefit from trying the <a href=\"https://launchpad.net/testscenarios\" rel=\"noreferrer\">TestScenarios</a> library.</p>\n\n<blockquote>\n <p>testscenarios provides clean dependency injection for python unittest style tests. This can be used for interface testing (testing many implementations via a single test suite) or for classic dependency injection (provide tests with dependencies externally to the test code itself, allowing easy testing in different situations).</p>\n</blockquote>\n" }, { "answer_id": 20870875, "author": "Guy", "author_id": 1540037, "author_profile": "https://Stackoverflow.com/users/1540037", "pm_score": 6, "selected": false, "text": "<p>This can be solved elegantly using Metaclasses:</p>\n\n<pre><code>import unittest\n\nl = [[\"foo\", \"a\", \"a\",], [\"bar\", \"a\", \"b\"], [\"lee\", \"b\", \"b\"]]\n\nclass TestSequenceMeta(type):\n def __new__(mcs, name, bases, dict):\n\n def gen_test(a, b):\n def test(self):\n self.assertEqual(a, b)\n return test\n\n for tname, a, b in l:\n test_name = \"test_%s\" % tname\n dict[test_name] = gen_test(a,b)\n return type.__new__(mcs, name, bases, dict)\n\nclass TestSequence(unittest.TestCase):\n __metaclass__ = TestSequenceMeta\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n" }, { "answer_id": 23508426, "author": "Javier", "author_id": 3339058, "author_profile": "https://Stackoverflow.com/users/3339058", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://docs.python.org/2/library/unittest.html#load-tests-protocol\">load_tests</a> is a little known mechanism introduced in 2.7 to dynamically create a TestSuite. With it, you can easily create parametrized tests.</p>\n\n<p>For example:</p>\n\n<pre><code>import unittest\n\nclass GeneralTestCase(unittest.TestCase):\n def __init__(self, methodName, param1=None, param2=None):\n super(GeneralTestCase, self).__init__(methodName)\n\n self.param1 = param1\n self.param2 = param2\n\n def runTest(self):\n pass # Test that depends on param 1 and 2.\n\n\ndef load_tests(loader, tests, pattern):\n test_cases = unittest.TestSuite()\n for p1, p2 in [(1, 2), (3, 4)]:\n test_cases.addTest(GeneralTestCase('runTest', p1, p2))\n return test_cases\n</code></pre>\n\n<p>That code will run all the TestCases in the TestSuite returned by load_tests. No other tests are automatically run by the discovery mechanism.</p>\n\n<p>Alternatively, you can also use inheritance as shown in this ticket: <a href=\"http://bugs.python.org/msg151444\">http://bugs.python.org/msg151444</a></p>\n" }, { "answer_id": 25626660, "author": "Sergei Voronezhskii", "author_id": 4000827, "author_profile": "https://Stackoverflow.com/users/4000827", "pm_score": 5, "selected": false, "text": "<p>It can be done by using <a href=\"http://pytest.org\" rel=\"noreferrer\">pytest</a>. Just write the file <code>test_me.py</code> with content:</p>\n<pre class=\"lang-python prettyprint-override\"><code>import pytest\n\[email protected]('name, left, right', [['foo', 'a', 'a'],\n ['bar', 'a', 'b'],\n ['baz', 'b', 'b']])\ndef test_me(name, left, right):\n assert left == right, name\n</code></pre>\n<p>And run your test with command <code>py.test --tb=short test_me.py</code>. Then the output will look like:</p>\n<pre class=\"lang-none prettyprint-override\"><code>=========================== test session starts ============================\nplatform darwin -- Python 2.7.6 -- py-1.4.23 -- pytest-2.6.1\ncollected 3 items\n\ntest_me.py .F.\n\n================================= FAILURES =================================\n_____________________________ test_me[bar-a-b] _____________________________\ntest_me.py:8: in test_me\n assert left == right, name\nE AssertionError: bar\n==================== 1 failed, 2 passed in 0.01 seconds ====================\n</code></pre>\n<p>It is simple! Also <a href=\"http://pytest.org\" rel=\"noreferrer\">pytest</a> has more features like <code>fixtures</code>, <code>mark</code>, <code>assert</code>, etc.</p>\n" }, { "answer_id": 27250866, "author": "Maroun", "author_id": 1735406, "author_profile": "https://Stackoverflow.com/users/1735406", "pm_score": 2, "selected": false, "text": "<p>You can use the <a href=\"https://github.com/taykey/nose-ittr\" rel=\"nofollow noreferrer\">nose-ittr</a> plugin (<code>pip install nose-ittr</code>).</p>\n<p>It's very easy to integrate with existing tests, and minimal changes (if any) are required. It also supports the <em>nose</em> multiprocessing plugin.</p>\n<p>Note that you can also have a customize <code>setup</code> function per test.</p>\n<pre><code>@ittr(number=[1, 2, 3, 4])\ndef test_even(self):\n assert_equal(self.number % 2, 0)\n</code></pre>\n<p>It is also possible to pass <code>nosetest</code> parameters like with their built-in plugin <code>attrib</code>. This way you can run only a specific test with specific parameter:</p>\n<pre class=\"lang-none prettyprint-override\"><code>nosetest -a number=2\n</code></pre>\n" }, { "answer_id": 28890882, "author": "Matt", "author_id": 452274, "author_profile": "https://Stackoverflow.com/users/452274", "pm_score": 2, "selected": false, "text": "<p>I came across <a href=\"https://pypi.python.org/pypi/ParamUnittest\" rel=\"nofollow noreferrer\"><strong>ParamUnittest</strong></a> the other day when looking at the source code for <a href=\"https://pypi.python.org/pypi/radon\" rel=\"nofollow noreferrer\">radon</a> (<a href=\"https://github.com/rubik/radon/blob/master/radon/tests/test_other_metrics.py\" rel=\"nofollow noreferrer\">example usage on the GitHub repository</a>). It should work with other frameworks that extend TestCase (like Nose).</p>\n<p>Here is an example:</p>\n<pre><code>import unittest\nimport paramunittest\n\n\[email protected](\n ('1', '2'),\n #(4, 3), &lt;---- Uncomment to have a failing test\n ('2', '3'),\n (('4', ), {'b': '5'}),\n ((), {'a': 5, 'b': 6}),\n {'a': 5, 'b': 6},\n)\nclass TestBar(TestCase):\n def setParameters(self, a, b):\n self.a = a\n self.b = b\n\n def testLess(self):\n self.assertLess(self.a, self.b)\n</code></pre>\n" }, { "answer_id": 29384495, "author": "Bernhard", "author_id": 639054, "author_profile": "https://Stackoverflow.com/users/639054", "pm_score": 6, "selected": false, "text": "<p>As of Python 3.4, subtests have been introduced to <em>unittest</em> for this purpose. See <a href=\"https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests\" rel=\"noreferrer\">the documentation</a> for details. TestCase.subTest is a context manager which allows one to isolate asserts in a test so that a failure will be reported with parameter information, but it does not stop the test execution. Here's the example from the documentation:</p>\n<pre><code>class NumbersTest(unittest.TestCase):\n\ndef test_even(self):\n &quot;&quot;&quot;\n Test that numbers between 0 and 5 are all even.\n &quot;&quot;&quot;\n for i in range(0, 6):\n with self.subTest(i=i):\n self.assertEqual(i % 2, 0)\n</code></pre>\n<p>The output of a test run would be:</p>\n<pre class=\"lang-none prettyprint-override\"><code>======================================================================\nFAIL: test_even (__main__.NumbersTest) (i=1)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File &quot;subtests.py&quot;, line 32, in test_even\n self.assertEqual(i % 2, 0)\nAssertionError: 1 != 0\n\n======================================================================\nFAIL: test_even (__main__.NumbersTest) (i=3)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File &quot;subtests.py&quot;, line 32, in test_even\n self.assertEqual(i % 2, 0)\nAssertionError: 1 != 0\n\n======================================================================\nFAIL: test_even (__main__.NumbersTest) (i=5)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File &quot;subtests.py&quot;, line 32, in test_even\n self.assertEqual(i % 2, 0)\nAssertionError: 1 != 0\n</code></pre>\n<p>This is also part of <a href=\"https://pypi.python.org/pypi/unittest2\" rel=\"noreferrer\">unittest2</a>, so it is available for earlier versions of Python.</p>\n" }, { "answer_id": 29766722, "author": "Mykhaylo Kopytonenko", "author_id": 2726783, "author_profile": "https://Stackoverflow.com/users/2726783", "pm_score": 4, "selected": false, "text": "<p>Use the <a href=\"https://technomilk.wordpress.com/2012/02/12/multiplying-python-unit-test-cases-with-different-sets-of-data/\" rel=\"noreferrer\">ddt</a> library. It adds simple decorators for the test methods:</p>\n\n<pre><code>import unittest\nfrom ddt import ddt, data\nfrom mycode import larger_than_two\n\n@ddt\nclass FooTestCase(unittest.TestCase):\n\n @data(3, 4, 12, 23)\n def test_larger_than_two(self, value):\n self.assertTrue(larger_than_two(value))\n\n @data(1, -3, 2, 0)\n def test_not_larger_than_two(self, value):\n self.assertFalse(larger_than_two(value))\n</code></pre>\n\n<p>This library can be installed with <code>pip</code>. It doesn't require <code>nose</code>, and works excellent with the standard library <code>unittest</code> module.</p>\n" }, { "answer_id": 30150971, "author": "sleepycal", "author_id": 1267398, "author_profile": "https://Stackoverflow.com/users/1267398", "pm_score": 1, "selected": false, "text": "<p>Just use metaclasses, as seen here;</p>\n\n<pre><code>class DocTestMeta(type):\n \"\"\"\n Test functions are generated in metaclass due to the way some\n test loaders work. For example, setupClass() won't get called\n unless there are other existing test methods, and will also\n prevent unit test loader logic being called before the test\n methods have been defined.\n \"\"\"\n def __init__(self, name, bases, attrs):\n super(DocTestMeta, self).__init__(name, bases, attrs)\n\n def __new__(cls, name, bases, attrs):\n def func(self):\n \"\"\"Inner test method goes here\"\"\"\n self.assertTrue(1)\n\n func.__name__ = 'test_sample'\n attrs[func.__name__] = func\n return super(DocTestMeta, cls).__new__(cls, name, bases, attrs)\n\nclass ExampleTestCase(TestCase):\n \"\"\"Our example test case, with no methods defined\"\"\"\n __metaclass__ = DocTestMeta\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>test_sample (ExampleTestCase) ... OK\n</code></pre>\n" }, { "answer_id": 31161347, "author": "Kirill Ermolov", "author_id": 4990113, "author_profile": "https://Stackoverflow.com/users/4990113", "pm_score": 2, "selected": false, "text": "<p>I use metaclasses and decorators for generate tests. You can check my implementation <a href=\"https://github.com/erm0l0v/python_wrap_cases\" rel=\"nofollow noreferrer\">python_wrap_cases</a>. This library doesn't require any test frameworks.</p>\n<p>Your example:</p>\n<pre><code>import unittest\nfrom python_wrap_cases import wrap_case\n\n\n@wrap_case\nclass TestSequence(unittest.TestCase):\n\n @wrap_case(&quot;foo&quot;, &quot;a&quot;, &quot;a&quot;)\n @wrap_case(&quot;bar&quot;, &quot;a&quot;, &quot;b&quot;)\n @wrap_case(&quot;lee&quot;, &quot;b&quot;, &quot;b&quot;)\n def testsample(self, name, a, b):\n print &quot;test&quot;, name\n self.assertEqual(a, b)\n</code></pre>\n<p>Console output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>testsample_u'bar'_u'a'_u'b' (tests.example.test_stackoverflow.TestSequence) ... test bar\nFAIL\ntestsample_u'foo'_u'a'_u'a' (tests.example.test_stackoverflow.TestSequence) ... test foo\nok\ntestsample_u'lee'_u'b'_u'b' (tests.example.test_stackoverflow.TestSequence) ... test lee\nok\n</code></pre>\n<p>Also you may use <em>generators</em>. For example this code generate all possible combinations of tests with arguments <code>a__list</code> and <code>b__list</code></p>\n<pre><code>import unittest\nfrom python_wrap_cases import wrap_case\n\n\n@wrap_case\nclass TestSequence(unittest.TestCase):\n\n @wrap_case(a__list=[&quot;a&quot;, &quot;b&quot;], b__list=[&quot;a&quot;, &quot;b&quot;])\n def testsample(self, a, b):\n self.assertEqual(a, b)\n</code></pre>\n<p>Console output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>testsample_a(u'a')_b(u'a') (tests.example.test_stackoverflow.TestSequence) ... ok\ntestsample_a(u'a')_b(u'b') (tests.example.test_stackoverflow.TestSequence) ... FAIL\ntestsample_a(u'b')_b(u'a') (tests.example.test_stackoverflow.TestSequence) ... FAIL\ntestsample_a(u'b')_b(u'b') (tests.example.test_stackoverflow.TestSequence) ... ok\n</code></pre>\n" }, { "answer_id": 33884166, "author": "Javier", "author_id": 3339058, "author_profile": "https://Stackoverflow.com/users/3339058", "pm_score": 3, "selected": false, "text": "<p>There's also <a href=\"https://pypi.python.org/pypi/hypothesis\" rel=\"nofollow noreferrer\">Hypothesis</a> which adds fuzz or property based testing.</p>\n<p>This is a very powerful testing method.</p>\n" }, { "answer_id": 34382688, "author": "Max Malysh", "author_id": 1977620, "author_profile": "https://Stackoverflow.com/users/1977620", "pm_score": 1, "selected": false, "text": "<p>You can use <code>TestSuite</code> and custom <code>TestCase</code> classes. </p>\n\n<pre><code>import unittest\n\nclass CustomTest(unittest.TestCase):\n def __init__(self, name, a, b):\n super().__init__()\n self.name = name\n self.a = a\n self.b = b\n\n def runTest(self):\n print(\"test\", self.name)\n self.assertEqual(self.a, self.b)\n\nif __name__ == '__main__':\n suite = unittest.TestSuite()\n suite.addTest(CustomTest(\"Foo\", 1337, 1337))\n suite.addTest(CustomTest(\"Bar\", 0xDEAD, 0xC0DE))\n unittest.TextTestRunner().run(suite)\n</code></pre>\n" }, { "answer_id": 36788233, "author": "Danielle Weisz", "author_id": 6239458, "author_profile": "https://Stackoverflow.com/users/6239458", "pm_score": 1, "selected": false, "text": "<p>I'd been having trouble with a very particular style of parameterized tests. All our Selenium tests can run locally, but they also should be able to be run remotely against several platforms on SauceLabs. Basically, I wanted to take a large amount of already-written test cases and parameterize them with the fewest changes to code possible. Furthermore, I needed to be able to pass the parameters into the setUp method, something which I haven't seen any solutions for elsewhere.</p>\n\n<p>Here's what I've come up with:</p>\n\n<pre><code>import inspect\nimport types\n\ntest_platforms = [\n {'browserName': \"internet explorer\", 'platform': \"Windows 7\", 'version': \"10.0\"},\n {'browserName': \"internet explorer\", 'platform': \"Windows 7\", 'version': \"11.0\"},\n {'browserName': \"firefox\", 'platform': \"Linux\", 'version': \"43.0\"},\n]\n\n\ndef sauce_labs():\n def wrapper(cls):\n return test_on_platforms(cls)\n return wrapper\n\n\ndef test_on_platforms(base_class):\n for name, function in inspect.getmembers(base_class, inspect.isfunction):\n if name.startswith('test_'):\n for platform in test_platforms:\n new_name = '_'.join(list([name, ''.join(platform['browserName'].title().split()), platform['version']]))\n new_function = types.FunctionType(function.__code__, function.__globals__, new_name,\n function.__defaults__, function.__closure__)\n setattr(new_function, 'platform', platform)\n setattr(base_class, new_name, new_function)\n delattr(base_class, name)\n\n return base_class\n</code></pre>\n\n<p>With this, all I had to do was add a simple decorator @sauce_labs() to each regular old TestCase, and now when running them, they're wrapped up and rewritten, so that all the test methods are parameterized and renamed. LoginTests.test_login(self) runs as LoginTests.test_login_internet_explorer_10.0(self), LoginTests.test_login_internet_explorer_11.0(self), and LoginTests.test_login_firefox_43.0(self), and each one has the parameter self.platform to decide what browser/platform to run against, even in LoginTests.setUp, which is crucial for my task since that's where the connection to SauceLabs is initialized.</p>\n\n<p>Anyway, I hope this might be of help to someone looking to do a similar \"global\" parameterization of their tests!</p>\n" }, { "answer_id": 37470261, "author": "pptime", "author_id": 2590401, "author_profile": "https://Stackoverflow.com/users/2590401", "pm_score": -1, "selected": false, "text": "<p>Besides using setattr, we can use <em>load_tests</em> with Python 3.2 and later.</p>\n<pre><code>class Test(unittest.TestCase):\n pass\n\ndef _test(self, file_name):\n open(file_name, 'r') as f:\n self.assertEqual('test result',f.read())\n\ndef _generate_test(file_name):\n def test(self):\n _test(self, file_name)\n return test\n\ndef _generate_tests():\n for file in files:\n file_name = os.path.splitext(os.path.basename(file))[0]\n setattr(Test, 'test_%s' % file_name, _generate_test(file))\n\ntest_cases = (Test,)\n\ndef load_tests(loader, tests, pattern):\n _generate_tests()\n suite = TestSuite()\n for test_class in test_cases:\n tests = loader.loadTestsFromTestCase(test_class)\n suite.addTests(tests)\n return suite\n\nif __name__ == '__main__':\n _generate_tests()\n unittest.main()\n</code></pre>\n" }, { "answer_id": 38726022, "author": "S.Arora", "author_id": 6665372, "author_profile": "https://Stackoverflow.com/users/6665372", "pm_score": -1, "selected": false, "text": "<p>Following is my solution. I find this useful when:</p>\n<ol>\n<li><p>Should work for unittest.Testcase and unittest discover</p>\n</li>\n<li><p>Have a set of tests to be run for different parameter settings.</p>\n</li>\n<li><p>Very simple and no dependency on other packages</p>\n<pre><code> import unittest\n\n class BaseClass(unittest.TestCase):\n def setUp(self):\n self.param = 2\n self.base = 2\n\n def test_me(self):\n self.assertGreaterEqual(5, self.param+self.base)\n\n def test_me_too(self):\n self.assertLessEqual(3, self.param+self.base)\n\n\n class Child_One(BaseClass):\n def setUp(self):\n BaseClass.setUp(self)\n self.param = 4\n\n\n class Child_Two(BaseClass):\n def setUp(self):\n BaseClass.setUp(self)\n self.param = 1\n</code></pre>\n</li>\n</ol>\n" }, { "answer_id": 39350898, "author": "mop", "author_id": 1791024, "author_profile": "https://Stackoverflow.com/users/1791024", "pm_score": 1, "selected": false, "text": "<p>This solution works with <code>unittest</code> and <code>nose</code> for Python 2 and Python 3:</p>\n\n<pre><code>#!/usr/bin/env python\nimport unittest\n\ndef make_function(description, a, b):\n def ghost(self):\n self.assertEqual(a, b, description)\n print(description)\n ghost.__name__ = 'test_{0}'.format(description)\n return ghost\n\n\nclass TestsContainer(unittest.TestCase):\n pass\n\ntestsmap = {\n 'foo': [1, 1],\n 'bar': [1, 2],\n 'baz': [5, 5]}\n\ndef generator():\n for name, params in testsmap.iteritems():\n test_func = make_function(name, params[0], params[1])\n setattr(TestsContainer, 'test_{0}'.format(name), test_func)\n\ngenerator()\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n" }, { "answer_id": 41010565, "author": "Arindam Roychowdhury", "author_id": 1076965, "author_profile": "https://Stackoverflow.com/users/1076965", "pm_score": 2, "selected": false, "text": "<pre><code>import unittest\n\ndef generator(test_class, a, b):\n def test(self):\n self.assertEqual(a, b)\n return test\n\ndef add_test_methods(test_class):\n # The first element of list is variable &quot;a&quot;, then variable &quot;b&quot;, then name of test case that will be used as suffix.\n test_list = [[2,3, 'one'], [5,5, 'two'], [0,0, 'three']]\n for case in test_list:\n test = generator(test_class, case[0], case[1])\n setattr(test_class, &quot;test_%s&quot; % case[2], test)\n\n\nclass TestAuto(unittest.TestCase):\n def setUp(self):\n print 'Setup'\n pass\n\n def tearDown(self):\n print 'TearDown'\n pass\n\n_add_test_methods(TestAuto) # It's better to start with underscore so it is not detected as a test itself\n\nif __name__ == '__main__':\n unittest.main(verbosity=1)\n</code></pre>\n<p>RESULT:</p>\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt;\nSetup\nFTearDown\nSetup\nTearDown\n.Setup\nTearDown\n.\n======================================================================\nFAIL: test_one (__main__.TestAuto)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File &quot;D:/inchowar/Desktop/PyTrash/test_auto_3.py&quot;, line 5, in test\n self.assertEqual(a, b)\nAssertionError: 2 != 3\n\n----------------------------------------------------------------------\nRan 3 tests in 0.019s\n\nFAILED (failures=1)\n</code></pre>\n" }, { "answer_id": 43851514, "author": "Patrick Ohly", "author_id": 222305, "author_profile": "https://Stackoverflow.com/users/222305", "pm_score": 0, "selected": false, "text": "<p>The metaclass-based answers still work in Python 3, but instead of the <code>__metaclass__</code> attribute, one has to use the <code>metaclass</code> parameter, as in:</p>\n<pre><code>class ExampleTestCase(TestCase,metaclass=DocTestMeta):\n pass\n</code></pre>\n" }, { "answer_id": 45570424, "author": "YvesgereY", "author_id": 995896, "author_profile": "https://Stackoverflow.com/users/995896", "pm_score": 1, "selected": false, "text": "<p>Meta-programming is fun, but it can get in the way. Most solutions here make it difficult to:</p>\n<ul>\n<li>selectively launch a test</li>\n<li>point back to the code given the test's name</li>\n</ul>\n<p>So, my first suggestion is to follow the simple/explicit path (works with any test runner):</p>\n<pre><code>import unittest\n\nclass TestSequence(unittest.TestCase):\n\n def _test_complex_property(self, a, b):\n self.assertEqual(a,b)\n\n def test_foo(self):\n self._test_complex_property(&quot;a&quot;, &quot;a&quot;)\n def test_bar(self):\n self._test_complex_property(&quot;a&quot;, &quot;b&quot;)\n def test_lee(self):\n self._test_complex_property(&quot;b&quot;, &quot;b&quot;)\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n<p>Since we shouldn't repeat ourselves, my second suggestion builds on <a href=\"https://stackoverflow.com/questions/32899/how-do-you-generate-dynamic-parameterized-unit-tests-in-python/23508426#23508426\">Javier's answer</a>: embrace property based testing. Hypothesis library:</p>\n<ul>\n<li><p>is &quot;more relentlessly devious about test case generation than us mere humans&quot;</p>\n</li>\n<li><p>will provide simple count-examples</p>\n</li>\n<li><p>works with any test runner</p>\n</li>\n<li><p>has many more interesting features (statistics, additional test output, ...)</p>\n<p>class TestSequence(unittest.TestCase):</p>\n<pre><code> @given(st.text(), st.text())\n def test_complex_property(self, a, b):\n self.assertEqual(a,b)\n</code></pre>\n</li>\n</ul>\n<p>To test your specific examples, just add:</p>\n<pre><code> @example(&quot;a&quot;, &quot;a&quot;)\n @example(&quot;a&quot;, &quot;b&quot;)\n @example(&quot;b&quot;, &quot;b&quot;)\n</code></pre>\n<p>To run only one particular example, you can comment out the other examples (provided example will be run first). You may want to use <code>@given(st.nothing())</code>. Another option is to replace the whole block by:</p>\n<pre><code> @given(st.just(&quot;a&quot;), st.just(&quot;b&quot;))\n</code></pre>\n<p>OK, you don't have distinct test names. But maybe you just need:</p>\n<ul>\n<li>a descriptive name of the property under test.</li>\n<li>which input leads to failure (falsifying example).</li>\n</ul>\n<p><a href=\"http://hypothesis.works/articles/how-not-to-die-hard-with-hypothesis\" rel=\"nofollow noreferrer\">Funnier example</a></p>\n" }, { "answer_id": 48452127, "author": "hhquark", "author_id": 5932228, "author_profile": "https://Stackoverflow.com/users/5932228", "pm_score": 0, "selected": false, "text": "<p>I had trouble making these work for <code>setUpClass</code>.</p>\n<p>Here's a version of <a href=\"https://stackoverflow.com/a/23508426/5932228\">Javier's answer</a> that gives <code>setUpClass</code> access to dynamically allocated attributes.</p>\n<pre><code>import unittest\n\n\nclass GeneralTestCase(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n print ''\n print cls.p1\n print cls.p2\n\n def runTest1(self):\n self.assertTrue((self.p2 - self.p1) == 1)\n\n def runTest2(self):\n self.assertFalse((self.p2 - self.p1) == 2)\n\n\ndef load_tests(loader, tests, pattern):\n test_cases = unittest.TestSuite()\n for p1, p2 in [(1, 2), (3, 4)]:\n clsname = 'TestCase_{}_{}'.format(p1, p2)\n dct = {\n 'p1': p1,\n 'p2': p2,\n }\n cls = type(clsname, (GeneralTestCase,), dct)\n test_cases.addTest(cls('runTest1'))\n test_cases.addTest(cls('runTest2'))\n return test_cases\n</code></pre>\n<h3>Outputs</h3>\n<pre class=\"lang-none prettyprint-override\"><code>1\n2\n..\n3\n4\n..\n----------------------------------------------------------------------\nRan 4 tests in 0.000s\n\nOK\n</code></pre>\n" }, { "answer_id": 57378023, "author": "bcdan", "author_id": 3325465, "author_profile": "https://Stackoverflow.com/users/3325465", "pm_score": 1, "selected": false, "text": "<p>I have found that this works well for my purposes, especially if I need to generate tests that do slightly difference processes on a collection of data.</p>\n\n<pre><code>import unittest\n\ndef rename(newName):\n def renamingFunc(func):\n func.__name__ == newName\n return func\n return renamingFunc\n\nclass TestGenerator(unittest.TestCase):\n\n TEST_DATA = {}\n\n @classmethod\n def generateTests(cls):\n for dataName, dataValue in TestGenerator.TEST_DATA:\n for func in cls.getTests(dataName, dataValue):\n setattr(cls, \"test_{:s}_{:s}\".format(func.__name__, dataName), func)\n\n @classmethod\n def getTests(cls):\n raise(NotImplementedError(\"This must be implemented\"))\n\nclass TestCluster(TestGenerator):\n\n TEST_CASES = []\n\n @staticmethod\n def getTests(dataName, dataValue):\n\n def makeTest(case):\n\n @rename(\"{:s}\".format(case[\"name\"]))\n def test(self):\n # Do things with self, case, data\n pass\n\n return test\n\n return [makeTest(c) for c in TestCluster.TEST_CASES]\n\nTestCluster.generateTests()\n</code></pre>\n\n<p>The <code>TestGenerator</code> class can be used to spawn different sets of test cases like <code>TestCluster</code>.</p>\n\n<p><code>TestCluster</code> can be thought of as an implementation of the <code>TestGenerator</code> interface.</p>\n" }, { "answer_id": 58974546, "author": "thangaraj1980", "author_id": 2707200, "author_profile": "https://Stackoverflow.com/users/2707200", "pm_score": -1, "selected": false, "text": "<pre><code>import unittest\n\ndef generator(test_class, a, b,c,d,name):\n def test(self):\n print('Testexecution=',name)\n print('a=',a)\n print('b=',b)\n print('c=',c)\n print('d=',d)\n\n return test\n\ndef add_test_methods(test_class):\n test_list = [[3,3,5,6, 'one'], [5,5,8,9, 'two'], [0,0,5,6, 'three'],[0,0,2,3,'Four']]\n for case in test_list:\n print('case=',case[0], case[1],case[2],case[3],case[4])\n test = generator(test_class, case[0], case[1],case[2],case[3],case[4])\n setattr(test_class, &quot;test_%s&quot; % case[4], test)\n\n\nclass TestAuto(unittest.TestCase):\n def setUp(self):\n print ('Setup')\n pass\n\n def tearDown(self):\n print ('TearDown')\n pass\n\nadd_test_methods(TestAuto)\n\nif __name__ == '__main__':\n unittest.main(verbosity=1)\n</code></pre>\n" }, { "answer_id": 62476654, "author": "Eric Cousineau", "author_id": 7829525, "author_profile": "https://Stackoverflow.com/users/7829525", "pm_score": 2, "selected": false, "text": "<p>This is effectively the same as <code>parameterized</code> as mentioned in a previous answer, but specific to <code>unittest</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def sub_test(param_list):\n &quot;&quot;&quot;Decorates a test case to run it as a set of subtests.&quot;&quot;&quot;\n\n def decorator(f):\n\n @functools.wraps(f)\n def wrapped(self):\n for param in param_list:\n with self.subTest(**param):\n f(self, **param)\n\n return wrapped\n\n return decorator\n</code></pre>\n<p>Example usage:</p>\n<pre><code>class TestStuff(unittest.TestCase):\n @sub_test([\n dict(arg1='a', arg2='b'),\n dict(arg1='x', arg2='y'),\n ])\n def test_stuff(self, arg1, arg2):\n ...\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/720/" ]
I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this: ``` import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() ``` The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?
This is called "parametrization". There are several tools that support this approach. E.g.: * [pytest's decorator](https://docs.pytest.org/en/latest/parametrize.html) * [parameterized](https://github.com/wolever/parameterized) The resulting code looks like this: ``` from parameterized import parameterized class TestSequence(unittest.TestCase): @parameterized.expand([ ["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"], ]) def test_sequence(self, name, a, b): self.assertEqual(a,b) ``` Which will generate the tests: ```none test_sequence_0_foo (__main__.TestSequence) ... ok test_sequence_1_bar (__main__.TestSequence) ... FAIL test_sequence_2_lee (__main__.TestSequence) ... ok ====================================================================== FAIL: test_sequence_1_bar (__main__.TestSequence) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/parameterized/parameterized.py", line 233, in <lambda> standalone_func = lambda *a: func(*(a + p.args), **p.kwargs) File "x.py", line 12, in test_sequence self.assertEqual(a,b) AssertionError: 'a' != 'b' ``` For historical reasons I'll leave the original answer circa 2008): I use something like this: ``` import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequense(unittest.TestCase): pass def test_generator(a, b): def test(self): self.assertEqual(a,b) return test if __name__ == '__main__': for t in l: test_name = 'test_%s' % t[0] test = test_generator(t[1], t[2]) setattr(TestSequense, test_name, test) unittest.main() ```
32,937
<p>In C# is there a shorthand way to write this:</p> <pre><code>public static bool IsAllowed(int userID) { return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...); } </code></pre> <p>Like:</p> <pre><code>public static bool IsAllowed(int userID) { return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...); } </code></pre> <p>I know I could also use switch, but there are probably 50 or so functions like this I have to write (porting a classic ASP site over to ASP.NET) so I'd like to keep them as short as possible.</p>
[ { "answer_id": 32942, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": false, "text": "<p>I would encapsulate the list of allowed IDs as <em>data</em> not <em>code</em>. Then it's source can be changed easily later on.</p>\n\n<pre><code>List&lt;int&gt; allowedIDs = ...;\n\npublic bool IsAllowed(int userID)\n{\n return allowedIDs.Contains(userID);\n}\n</code></pre>\n\n<p>If using .NET 3.5, you can use <code>IEnumerable</code> instead of <code>List</code> thanks to extension methods.</p>\n\n<p>(This function shouldn't be static. See this posting: <a href=\"https://stackoverflow.com/questions/30998/using-too-much-static-bad-or-good#31004\">using too much static bad or good ?</a>.)</p>\n" }, { "answer_id": 32944, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 2, "selected": false, "text": "<p>How about something like this:</p>\n\n<pre><code>public static bool IsAllowed(int userID) {\n List&lt;int&gt; IDs = new List&lt;string&gt; { 1,2,3,4,5 };\n return IDs.Contains(userID);\n}\n</code></pre>\n\n<p>(You could of course change the static status, initialize the IDs class in some other place, use an IEnumerable&lt;>, etc, based on your needs. The main point is that the closest equivalent to the <em>in</em> operator in SQL is the Collection.Contains() function.)</p>\n" }, { "answer_id": 32950, "author": "Pauly", "author_id": 3460, "author_profile": "https://Stackoverflow.com/users/3460", "pm_score": 1, "selected": false, "text": "<p>Are permissions user-id based? If so, you may end up with a better solution by going to role based permissions. Or you may end up having to edit that method quite frequently to add additional users to the \"allowed users\" list.</p>\n\n<p>For example, \n enum UserRole {\n User, Administrator, LordEmperor\n }</p>\n\n<pre><code>class User {\n public UserRole Role{get; set;}\n public string Name {get; set;}\n public int UserId {get; set;}\n}\n\npublic static bool IsAllowed(User user) {\n return user.Role == UserRole.LordEmperor;\n}\n</code></pre>\n" }, { "answer_id": 33014, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 0, "selected": false, "text": "<p>A nice little trick is to sort of reverse the way you usually use .Contains(), like:-</p>\n\n<pre><code>public static bool IsAllowed(int userID) {\n return new int[] { Personnel.JaneDoe, Personnel.JohnDoe }.Contains(userID);\n}\n</code></pre>\n\n<p>Where you can put as many entries in the array as you like.</p>\n\n<p>If the Personnel.x is an enum you'd have some casting issues with this (and with the original code you posted), and in that case it'd be easier to use:-</p>\n\n<pre><code>public static bool IsAllowed(int userID) {\n return Enum.IsDefined(typeof(Personnel), userID);\n}\n</code></pre>\n" }, { "answer_id": 33015, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Here's the closest that I can think of:</p>\n\n<pre><code>using System.Linq;\npublic static bool IsAllowed(int userID)\n{\n return new Personnel[]\n { Personnel.JohnDoe, Personnel.JaneDoe }.Contains((Personnel)userID);\n}\n</code></pre>\n" }, { "answer_id": 33018, "author": "Adam", "author_id": 3142, "author_profile": "https://Stackoverflow.com/users/3142", "pm_score": 0, "selected": false, "text": "<p>Just another syntax idea:</p>\n\n<pre><code>return new [] { Personnel.JohnDoe, Personnel.JaneDoe }.Contains(userID);\n</code></pre>\n" }, { "answer_id": 33024, "author": "Chad Boyer", "author_id": 3135, "author_profile": "https://Stackoverflow.com/users/3135", "pm_score": 0, "selected": false, "text": "<p>Can you write an iterator for Personnel.</p>\n\n<pre><code>public static bool IsAllowed(int userID)\n{\n return (Personnel.Contains(userID))\n}\n\npublic bool Contains(int userID) : extends Personnel (i think that is how it is written)\n{\n foreach (int id in Personnel)\n if (id == userid)\n return true;\n return false;\n}\n</code></pre>\n" }, { "answer_id": 33234, "author": "Jon Sagara", "author_id": 731, "author_profile": "https://Stackoverflow.com/users/731", "pm_score": 5, "selected": true, "text": "<p>How about this?</p>\n\n<pre><code>public static class Extensions\n{\n public static bool In&lt;T&gt;(this T testValue, params T[] values)\n {\n return values.Contains(testValue);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Personnel userId = Personnel.JohnDoe;\n\nif (userId.In(Personnel.JohnDoe, Personnel.JaneDoe))\n{\n // Do something\n}\n</code></pre>\n\n<p>I can't claim credit for this, but I also can't remember where I saw it. So, credit to you, anonymous Internet stranger.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1302/" ]
In C# is there a shorthand way to write this: ``` public static bool IsAllowed(int userID) { return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...); } ``` Like: ``` public static bool IsAllowed(int userID) { return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...); } ``` I know I could also use switch, but there are probably 50 or so functions like this I have to write (porting a classic ASP site over to ASP.NET) so I'd like to keep them as short as possible.
How about this? ``` public static class Extensions { public static bool In<T>(this T testValue, params T[] values) { return values.Contains(testValue); } } ``` Usage: ``` Personnel userId = Personnel.JohnDoe; if (userId.In(Personnel.JohnDoe, Personnel.JaneDoe)) { // Do something } ``` I can't claim credit for this, but I also can't remember where I saw it. So, credit to you, anonymous Internet stranger.
33,048
<p>Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do you test this observer with rSpec?</p>
[ { "answer_id": 33869, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 4, "selected": false, "text": "<p>Disclaimer: I've never actually done this on a production site, but it looks like a reasonable way would be to use mock objects, <code>should_receive</code> and friends, and invoke methods on the observer directly</p>\n\n<p>Given the following model and observer:</p>\n\n<pre><code>class Person &lt; ActiveRecord::Base\n def set_status( new_status )\n # do whatever\n end\nend\n\nclass PersonObserver &lt; ActiveRecord::Observer\n def after_save(person)\n person.set_status(\"aha!\")\n end\nend\n</code></pre>\n\n<p>I would write a spec like this (I ran it, and it passes)</p>\n\n<pre><code>describe PersonObserver do\n before :each do\n @person = stub_model(Person)\n @observer = PersonObserver.instance\n end\n\n it \"should invoke after_save on the observed object\" do\n @person.should_receive(:set_status).with(\"aha!\")\n @observer.after_save(@person)\n end\nend\n</code></pre>\n" }, { "answer_id": 130114, "author": "Pete", "author_id": 13472, "author_profile": "https://Stackoverflow.com/users/13472", "pm_score": 6, "selected": true, "text": "<p>You are on the right track, but I have run into a number of frustrating unexpected message errors when using rSpec, observers, and mock objects. When I am spec testing my model, I don't want to have to handle observer behavior in my message expectations. </p>\n\n<p>In your example, there isn't a really good way to spec \"set_status\" on the model without knowledge of what the observer is going to do to it. </p>\n\n<p>Therefore, I like to use the <a href=\"http://patmaddox.com/2007/11/23/better-rails-testing-decoupling-observers/\" rel=\"noreferrer\">\"No Peeping Toms\" plugin.</a> Given your code above and using the No Peeping Toms plugin, I would spec the model like this: </p>\n\n<pre><code>describe Person do \n it \"should set status correctly\" do \n @p = Person.new(:status =&gt; \"foo\")\n @p.set_status(\"bar\")\n @p.save\n @p.status.should eql(\"bar\")\n end\nend\n</code></pre>\n\n<p>You can spec your model code without having to worry that there is an observer out there that is going to come in and clobber your value. You'd spec that separately in the person_observer_spec like this: </p>\n\n<pre><code>describe PersonObserver do\n it \"should clobber the status field\" do \n @p = mock_model(Person, :status =&gt; \"foo\")\n @obs = PersonObserver.instance\n @p.should_receive(:set_status).with(\"aha!\")\n @obs.after_save\n end\nend \n</code></pre>\n\n<p>If you REALLY REALLY want to test the coupled Model and Observer class, you can do it like this:</p>\n\n<pre><code>describe Person do \n it \"should register a status change with the person observer turned on\" do\n Person.with_observers(:person_observer) do\n lambda { @p = Person.new; @p.save }.should change(@p, :status).to(\"aha!)\n end\n end\nend\n</code></pre>\n\n<p>99% of the time, I'd rather spec test with the observers turned off. It's just easier that way. </p>\n" }, { "answer_id": 5555454, "author": "William Dix", "author_id": 663243, "author_profile": "https://Stackoverflow.com/users/663243", "pm_score": 2, "selected": false, "text": "<p>no_peeping_toms is now a gem and can be found here: <a href=\"https://github.com/patmaddox/no-peeping-toms\" rel=\"nofollow\">https://github.com/patmaddox/no-peeping-toms</a></p>\n" }, { "answer_id": 5930831, "author": "Sujoy Gupta", "author_id": 634977, "author_profile": "https://Stackoverflow.com/users/634977", "pm_score": 2, "selected": false, "text": "<p>If you want to test that the observer observes the correct model and receives the notification as expected, here is an example using RR.</p>\n\n<p>your_model.rb:</p>\n\n<pre><code>class YourModel &lt; ActiveRecord::Base\n ...\nend\n</code></pre>\n\n<p>your_model_observer.rb:</p>\n\n<pre><code>class YourModelObserver &lt; ActiveRecord::Observer\n def after_create\n ...\n end\n\n def custom_notification\n ...\n end\nend\n</code></pre>\n\n<p>your_model_observer_spec.rb:</p>\n\n<pre><code>before do\n @observer = YourModelObserver.instance\n @model = YourModel.new\nend\n\nit \"acts on the after_create notification\"\n mock(@observer).after_create(@model)\n @model.save!\nend\n\nit \"acts on the custom notification\"\n mock(@observer).custom_notification(@model)\n @model.send(:notify, :custom_notification)\nend\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2569/" ]
Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do you test this observer with rSpec?
You are on the right track, but I have run into a number of frustrating unexpected message errors when using rSpec, observers, and mock objects. When I am spec testing my model, I don't want to have to handle observer behavior in my message expectations. In your example, there isn't a really good way to spec "set\_status" on the model without knowledge of what the observer is going to do to it. Therefore, I like to use the ["No Peeping Toms" plugin.](http://patmaddox.com/2007/11/23/better-rails-testing-decoupling-observers/) Given your code above and using the No Peeping Toms plugin, I would spec the model like this: ``` describe Person do it "should set status correctly" do @p = Person.new(:status => "foo") @p.set_status("bar") @p.save @p.status.should eql("bar") end end ``` You can spec your model code without having to worry that there is an observer out there that is going to come in and clobber your value. You'd spec that separately in the person\_observer\_spec like this: ``` describe PersonObserver do it "should clobber the status field" do @p = mock_model(Person, :status => "foo") @obs = PersonObserver.instance @p.should_receive(:set_status).with("aha!") @obs.after_save end end ``` If you REALLY REALLY want to test the coupled Model and Observer class, you can do it like this: ``` describe Person do it "should register a status change with the person observer turned on" do Person.with_observers(:person_observer) do lambda { @p = Person.new; @p.save }.should change(@p, :status).to("aha!) end end end ``` 99% of the time, I'd rather spec test with the observers turned off. It's just easier that way.
33,055
<p>I'm new to SVN and I'd like to know what methods are available for backing up repositories in a Windows environment?</p>
[ { "answer_id": 33062, "author": "Misha M", "author_id": 3467, "author_profile": "https://Stackoverflow.com/users/3467", "pm_score": 2, "selected": false, "text": "<p>I like to just copy the entire repo directory to my backup location. That way, if something happens, you can just copy the directory back and be ready to go immediately.</p>\n\n<p>Just make sure to preserve permissions, if needed. Usually, this is only a concern on Linux machines.</p>\n" }, { "answer_id": 33064, "author": "Nicolai Reuschling", "author_id": 2569, "author_profile": "https://Stackoverflow.com/users/2569", "pm_score": 8, "selected": true, "text": "<p>You could use something like (Linux):</p>\n\n<pre><code>svnadmin dump repositorypath | gzip &gt; backupname.svn.gz\n</code></pre>\n\n<p>Since Windows does not support GZip it is just:</p>\n\n<pre><code>svnadmin dump repositorypath &gt; backupname.svn\n</code></pre>\n" }, { "answer_id": 33068, "author": "RobotCaleb", "author_id": 1621, "author_profile": "https://Stackoverflow.com/users/1621", "pm_score": 3, "selected": false, "text": "<ul>\n<li><p>You can create a repository backup (<em>dump</em>) with <a href=\"http://svnbook.red-bean.com/en/1.7/svn.ref.svnadmin.c.dump.html\" rel=\"nofollow noreferrer\"><code>svnadmin dump</code></a>.</p></li>\n<li><p>You can then import it in using <a href=\"http://svnbook.red-bean.com/en/1.7/svn.ref.svnadmin.c.load.html\" rel=\"nofollow noreferrer\"><code>svnadmin load</code></a>.</p></li>\n</ul>\n\n<p>Detailed reference in the SVNBook:\n<a href=\"http://svnbook.red-bean.com/en/1.7/svn.reposadmin.maint.html#svn.reposadmin.maint.migrate.svnadmin\" rel=\"nofollow noreferrer\">\"Repository data migration using svnadmin\"</a></p>\n" }, { "answer_id": 33072, "author": "Adam", "author_id": 3142, "author_profile": "https://Stackoverflow.com/users/3142", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://svnbook.red-bean.com/nightly/en/svn.ref.svnadmin.c.hotcopy.html\" rel=\"noreferrer\">svnadmin hotcopy</a></p>\n\n<pre><code>svnadmin hotcopy REPOS_PATH NEW_REPOS_PATH\n</code></pre>\n\n<blockquote>\n <p>This subcommand makes a full “hot” backup of your repository, including all hooks, configuration files, and, of course, database files. </p>\n</blockquote>\n" }, { "answer_id": 33082, "author": "Kevin Dente", "author_id": 9, "author_profile": "https://Stackoverflow.com/users/9", "pm_score": 5, "selected": false, "text": "<p>There's a hotbackup.py script available on the Subversion web site that's quite handy for automating backups.</p>\n\n<p><a href=\"http://svn.apache.org/repos/asf/subversion/trunk/tools/backup/hot-backup.py.in\" rel=\"noreferrer\">http://svn.apache.org/repos/asf/subversion/trunk/tools/backup/hot-backup.py.in</a></p>\n" }, { "answer_id": 33088, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 2, "selected": false, "text": "<p>If you are using the FSFS repository format (the default), then you can copy the repository itself to make a backup. With the older BerkleyDB system, the repository is not platform independent and you would generally want to use svnadmin dump.</p>\n\n<p>The <a href=\"http://svnbook.red-bean.com/en/1.8/svn.reposadmin.maint.html#svn.reposadmin.maint.backup\" rel=\"nofollow noreferrer\">svnbook documentation topic for backup</a> recommends the <code>svnadmin hotcopy</code> command, as it will take care of issues like files in use and such.</p>\n" }, { "answer_id": 33114, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 7, "selected": false, "text": "<p>We use svnadmin hotcopy, e.g.:</p>\n\n<pre><code>svnadmin hotcopy C:\\svn\\repo D:\\backups\\svn\\repo\n</code></pre>\n\n<p>As per <a href=\"http://svnbook.red-bean.com/nightly/en/svn.ref.svnadmin.c.hotcopy.html\" rel=\"noreferrer\">the book</a>:</p>\n\n<blockquote>\n <p>You can run this command at any time and make a safe copy of the repository, regardless of whether other processes are using the repository.</p>\n</blockquote>\n\n<p>You can of course ZIP (preferably 7-Zip) the backup copy. IMHO It's the most straightforward of the backup options: in case of disaster there's little to do other than unzip it back into position.</p>\n" }, { "answer_id": 33190, "author": "Tom Mayfield", "author_id": 2314, "author_profile": "https://Stackoverflow.com/users/2314", "pm_score": 4, "selected": false, "text": "<p>I use <a href=\"http://svn.apache.org/repos/asf/subversion/trunk/notes/svnsync.txt\" rel=\"noreferrer\">svnsync</a>, which sets up a remote server as a mirror/slave. We had a server go down two weeks ago, and I was able to switch the slave into primary position quite easily (only had to reset the UUID on the slave repository to the original).</p>\n\n<p>Another benefit is that the sync can be run by a middle-man, rather than as a task on either server. I've had a client to two VPNs sync a repository between them.</p>\n" }, { "answer_id": 37554, "author": "quick_dry", "author_id": 3716, "author_profile": "https://Stackoverflow.com/users/3716", "pm_score": 0, "selected": false, "text": "<p>as others have said, hot-backup.py from the Subversion team has some nice features over just plain <code>svnadmin hotcopy</code></p>\n\n<p>I run a scheduled task on a python script that spiders for all my repositories on the machine, and uses hotbackup to keep several days worth of hotcopies (paranoid of corruption) and an <code>svnadmin svndump</code> on a remote machine. Restoration is really easy from that - so far.</p>\n" }, { "answer_id": 717473, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Here is a Perl script that will:</p>\n\n<ol>\n<li>Backup the repo</li>\n<li>Copy it to another server via SCP</li>\n<li>Retrieve the backup</li>\n<li>Create a test repository from the backup</li>\n<li>Do a test checkout</li>\n<li>Email you with any errors (via cron)</li>\n</ol>\n\n<p>The script:</p>\n\n<pre><code>my $svn_repo = \"/var/svn\"; \nmy $bkup_dir = \"/home/backup_user/backups\";\nmy $bkup_file = \"my_backup-\";\nmy $tmp_dir = \"/home/backup_user/tmp\"; \nmy $bkup_svr = \"my.backup.com\";\nmy $bkup_svr_login = \"backup\";\n\n$bkup_file = $bkup_file . `date +%Y%m%d-%H%M`;\nchomp $bkup_file;\nmy $youngest = `svnlook youngest $svn_repo`;\nchomp $youngest;\n\nmy $dump_command = \"svnadmin -q dump $svn_repo &gt; $bkup_dir/$bkup_file \";\nprint \"\\nDumping Subversion repo $svn_repo to $bkup_file...\\n\";\nprint `$dump_command`;\nprint \"Backing up through revision $youngest... \\n\";\nprint \"\\nCompressing dump file...\\n\";\nprint `gzip -9 $bkup_dir/$bkup_file\\n`;\nchomp $bkup_file;\nmy $zipped_file = $bkup_dir . \"/\" . $bkup_file . \".gz\";\nprint \"\\nCreated $zipped_file\\n\";\nprint `scp $zipped_file $bkup_svr_login\\@$bkup_svr:/home/backup/`;\nprint \"\\n$bkup_file.gz transfered to $bkup_svr\\n\";\n\n#Test Backup\nprint \"\\n---------------------------------------\\n\";\nprint \"Testing Backup\";\nprint \"\\n---------------------------------------\\n\";\nprint \"Downloading $bkup_file.gz from $bkup_svr\\n\";\nprint `scp $bkup_svr_login\\@$bkup_svr:/home/backup/$bkup_file.gz $tmp_dir/`;\nprint \"Unzipping $bkup_file.gz\\n\";\nprint `gunzip $tmp_dir/$bkup_file.gz`;\nprint \"Creating test repository\\n\";\nprint `svnadmin create $tmp_dir/test_repo`;\nprint \"Loading repository\\n\";\nprint `svnadmin -q load $tmp_dir/test_repo &lt; $tmp_dir/$bkup_file`;\nprint \"Checking out repository\\n\";\nprint `svn -q co file://$tmp_dir/test_repo $tmp_dir/test_checkout`;\nprint \"Cleaning up\\n\";\nprint `rm -f $tmp_dir/$bkup_file`;\nprint `rm -rf $tmp_dir/test_checkout`;\nprint `rm -rf $tmp_dir/test_repo`;\n</code></pre>\n\n<p><a href=\"http://blog.markwshead.com/101/backing-up-subversion-automatically/\" rel=\"noreferrer\">Script source and more details about the rational for this type of backup.</a></p>\n" }, { "answer_id": 790664, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>For the daily and full backup solution just use the <a href=\"http://www.randombugs.com/linux/subversion-backup.html\" rel=\"nofollow noreferrer\">SVN backup scripts here</a>.</p>\n" }, { "answer_id": 2961039, "author": "Uwe Keim", "author_id": 107625, "author_profile": "https://Stackoverflow.com/users/107625", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://code.google.com/p/dotsvntools/\" rel=\"noreferrer\">svnbackup</a> over at Google Code, a .NET console application.</p>\n" }, { "answer_id": 5846792, "author": "Jose Manuel Ojeda", "author_id": 731858, "author_profile": "https://Stackoverflow.com/users/731858", "pm_score": 2, "selected": false, "text": "<p>there are 2 main methods to backup a svn server, first is hotcopy that will create a copy of your repository files, the main problem with this approach is that it saves data about the underlying file system, so you may have some difficulties trying to repostore this kind of backup in another svn server kind or another machine.\nthere is another type of backup called dump, this backup wont save any information of the underlying file system and its potable to any kind of SVN server based in tigiris.org subversion.</p>\n\n<p>about the backup tool you can use the svnadmin tool(it is able to do hotcopy and dump) from the command prompt, this console resides in the same directory where your svn server lives or you can google for svn backup tools.</p>\n\n<p>my recommendation is that you do both kinds of backups and get them out of the office to your email acount, amazon s3 service, ftp, or azure services, that way you will have a securityy backup without having to host the svn server somewhere out of your office.</p>\n" }, { "answer_id": 6168209, "author": "Nitin Verma", "author_id": 565859, "author_profile": "https://Stackoverflow.com/users/565859", "pm_score": 1, "selected": false, "text": "<p>I have compiled the steps I followed for the purpose of taking a backup of the remote SVN\nrepository of my project.</p>\n\n<pre><code>install svk (http://svk.bestpractical.com/view/SVKWin32)\n\ninstall svn (http://sourceforge.net/projects/win32svn/files/1.6.16/Setup-Subversion-1.6.16.msi/download)\n\nsvk mirror //local &lt;remote repository URL&gt;\n\nsvk sync //local\n</code></pre>\n\n<p>This takes time and says that it is fetching the logs from repository. It creates a set of files inside <code>C:\\Documents and Settings\\nverma\\.svk\\local</code>.</p>\n\n<p>To update this local repository with the latest set of changes from the remote one, just run the previous command from time to time.</p>\n\n<p>Now you can play with your local repository (<code>/home/user/.svk/local</code> in this example) as if it were a normal SVN repository!</p>\n\n<p>The only problem with this approach is that the local repository is created with a revision increments by the actual revision in the remote repository. As someone wrote:</p>\n\n<blockquote>\n <p>The svk miror command generates a commit in the just created repository. So all the commits created by the subsequent sync will have revision numbers incremented by one as compared to the remote public repository.</p>\n</blockquote>\n\n<p>But, this was OK for me as I only wanted some backup of the remote repository time to time, nothing else.</p>\n\n<p>Verification:</p>\n\n<p>To verify, use the SVN client with the local repository like this:</p>\n\n<pre><code>svn checkout \"file:///C:/Documents and Settings\\nverma/.svk/local/\" &lt;local-dir-path-to-checkout-onto&gt;\n</code></pre>\n\n<p>This command then goes to checkout the latest revision from the local repository. At the end it says <code>Checked out revision N</code>. This <code>N</code> was one more than the actual revision found in the remote repository (due to the problem mentioned above).</p>\n\n<p>To verify that svk also brought all the history, the SVN checkout was run with various older revisions using <code>-r</code> with 2, 10, 50 etc. Then the files in <code>&lt;local-dir-path-to-checkout-onto&gt;</code> were confirmed to be from that revision.</p>\n\n<p>At the end, zip the directory <code>C:/Documents and Settings\\nverma/.svk/local/</code> and store the zip somewhere. Keep doing this regularly.</p>\n" }, { "answer_id": 8668396, "author": "RoughPlace", "author_id": 468083, "author_profile": "https://Stackoverflow.com/users/468083", "pm_score": 2, "selected": false, "text": "<pre><code>@echo off\nset hour=%time:~0,2%\nif \"%hour:~0,1%\"==\" \" set hour=0%time:~1,1%\nset folder=%date:~6,4%%date:~3,2%%date:~0,2%%hour%%time:~3,2%\n\necho Performing Backup\nmd \"\\\\HOME\\Development\\Backups\\SubVersion\\%folder%\"\n\nsvnadmin dump \"C:\\Users\\Yakyb\\Desktop\\MainRepositary\\Jake\" | \"C:\\Program Files\\7-Zip\\7z.exe\" a \"\\\\HOME\\Development\\Backups\\SubVersion\\%folder%\\Jake.7z\" -sibackupname.svn\n</code></pre>\n\n<p>This is the Batch File i have running that performs my Backups</p>\n" }, { "answer_id": 11868183, "author": "atx", "author_id": 1585221, "author_profile": "https://Stackoverflow.com/users/1585221", "pm_score": 3, "selected": false, "text": "<p>Basically it's safe to copy the repository folder if the svn server is stopped. (source: <a href=\"https://groups.google.com/forum/?fromgroups#!topic/visualsvn/i_55khUBrys%5B1-25%5D\" rel=\"noreferrer\">https://groups.google.com/forum/?fromgroups#!topic/visualsvn/i_55khUBrys%5B1-25%5D</a> )</p>\n\n<p>So if you're allowed to stop the server, do it and just copy the repository, either with some script or a backup tool. Cobian Backup fits here nicely as it can stop and start services automatically, and it can do incremental backups so you're only backing up parts of repository that have changed recently (useful if the repository is large and you're backing up to remote location).</p>\n\n<p>Example:</p>\n\n<ol>\n<li>Install Cobian Backup</li>\n<li><p>Add a backup task:</p>\n\n<ul>\n<li><p>Set source to repository folder (e.g. <code>C:\\Repositories\\</code>),</p></li>\n<li><p>Add pre-backup event <code>\"STOP_SERVICE\"</code> VisualSVN,</p></li>\n<li><p>Add post-backup event, <code>\"START_SERVICE\"</code> VisualSVN,</p></li>\n<li><p>Set other options as needed. <em>We've set up incremental backups including removal of old ones, backup schedule, destination, compression incl. archive splitting etc.</em></p></li>\n</ul></li>\n<li><p>Profit!</p></li>\n</ol>\n" }, { "answer_id": 20362633, "author": "ajdev8", "author_id": 1610035, "author_profile": "https://Stackoverflow.com/users/1610035", "pm_score": 2, "selected": false, "text": "<p>For hosted repositories you can since svn version 1.7 use <a href=\"http://svnbook.red-bean.com/en/1.7/svn.ref.svnrdump.html\" rel=\"nofollow\"><code>svnrdump</code></a>, which is analogous to <code>svnadmin dump</code> for local repositories. This <a href=\"https://help.cloudforge.com/entries/22410698-Exporting-a-CloudForge-Repository-Using-svnrdump\" rel=\"nofollow\">article</a> provides a nice walk-through, which essentially boils down to:</p>\n\n<pre><code>svnrdump dump /URL/to/remote/repository &gt; myRepository.dump\n</code></pre>\n\n<p>After you have downloaded the dump file you can import it locally </p>\n\n<pre><code>svnadmin load /path/to/local/repository &lt; myRepository.dump\n</code></pre>\n\n<p>or upload it to the host of your choice.</p>\n" }, { "answer_id": 23921878, "author": "Suppaman", "author_id": 3685361, "author_profile": "https://Stackoverflow.com/users/3685361", "pm_score": 2, "selected": false, "text": "<p>Here a GUI Windows tool for make a dump of local and remote subversion repositories:</p>\n\n<p><a href=\"https://falsinsoft-software.blogspot.com/p/svn-backup-tool.html\" rel=\"nofollow noreferrer\">https://falsinsoft-software.blogspot.com/p/svn-backup-tool.html</a></p>\n\n<p>The tool description says:</p>\n\n<p><em>This simply tool allow to make a dump backup of a local and remote subversion repository. The software work in the same way of the \"svnadmin\" but is not a GUI frontend over it. Instead use directly the subversion libraries for allow to create dump in standalone mode without any other additional tool.</em> </p>\n\n<p>Hope this help...</p>\n" }, { "answer_id": 27154329, "author": "Aamir Shahzad", "author_id": 2159585, "author_profile": "https://Stackoverflow.com/users/2159585", "pm_score": 0, "selected": false, "text": "<p><strong>1.1 Create Dump from SVN (Subversion) repository</strong></p>\n\n<pre><code>svnadmin dump /path/to/reponame &gt; /path/to/reponame.dump\n</code></pre>\n\n<p><strong>Real example</strong></p>\n\n<pre><code>svnadmin dump /var/www/svn/testrepo &gt; /backups/testrepo.dump\n</code></pre>\n\n<p><strong>1.2 Gzip Created Dump</strong></p>\n\n<pre><code>gzip -9 /path/to/reponame.dump\n</code></pre>\n\n<p><strong>Real example</strong></p>\n\n<pre><code>gzip -9 /backups/testrepo.dump\n</code></pre>\n\n<p><strong>1.3 SVN Dump and Gzip Dump with One-liner</strong></p>\n\n<pre><code>svnadmin dump /path/to/reponame | gzip -9 &gt; /path/to/reponame.dump.gz\n</code></pre>\n\n<p><strong>Real example</strong></p>\n\n<pre><code>svnadmin dump /var/www/svn/testrepo |Â gzip -9 &gt; /backups/testrepo.dump.gz\n</code></pre>\n\n<p>How to Backup (dump) and Restore (load) SVN (Subversion) repository on Linux.<br>\n<strong>Ref:</strong> <a href=\"http://www.if-not-true-then-false.com/2012/svn-subversion-backup-and-restore/\" rel=\"nofollow\">svn subversion backup andrestore</a></p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3396/" ]
I'm new to SVN and I'd like to know what methods are available for backing up repositories in a Windows environment?
You could use something like (Linux): ``` svnadmin dump repositorypath | gzip > backupname.svn.gz ``` Since Windows does not support GZip it is just: ``` svnadmin dump repositorypath > backupname.svn ```
33,063
<p>I have a big string (let's call it a CSV file, though it isn't actually one, it'll just be easier for now) that I have to parse in C# code.<br> The first step of the parsing process splits the file into individual lines by just using a <code>StreamReader</code> object and calling <code>ReadLine</code> until it's through the file. However, any given line might contain a quoted (in single quotes) literal with embedded newlines. I need to find those newlines and convert them temporarily into some other kind of token or escape sequence until I've split the file into an array of lines..then I can change them back. </p> <p>Example input data: </p> <pre><code>1,2,10,99,'Some text without a newline', true, false, 90 2,1,11,98,'This text has an embedded newline and continues here', true, true, 90 </code></pre> <p>I could write all of the C# code needed to do this by using <code>string.IndexOf</code> to find the quoted sections and look within them for newlines, but I'm thinking a Regex might be a better choice (i.e. <a href="http://regex.info/blog/2006-09-15/247" rel="nofollow noreferrer">now I have two problems</a>)</p>
[ { "answer_id": 33074, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "<p><strong>EDIT:</strong> Sorry, I've misinterpreted your post. If you're looking for a regex, then here is one:</p>\n\n<pre><code>content = Regex.Replace(content, \"'([^']*)\\n([^']*)'\", \"'\\1TOKEN\\2'\");\n</code></pre>\n\n<p>There might be edge cases and that two problems but I think it should be ok most of the time. What the Regex does is that it first finds any pair of single quotes that has \\n between it and replace that \\n with TOKEN preserving any text in-between.</p>\n\n<p>But still, I'd go state machine like what @bryansh explained below.</p>\n" }, { "answer_id": 33075, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 1, "selected": false, "text": "<p>What if you got the whole file into a variable then split that based on non-quoted newlines?</p>\n" }, { "answer_id": 33112, "author": "bryansh", "author_id": 211367, "author_profile": "https://Stackoverflow.com/users/211367", "pm_score": 3, "selected": true, "text": "<p>Since this isn't a true CSV file, does it have any sort of schema?</p>\n\n<p>From your example, it looks like you have:\nint, int, int, int, string , bool, bool, int</p>\n\n<p>With that making up your record / object.</p>\n\n<p>Assuming that your data is well formed (I don't know enough about your source to know how valid this assumption is); you could:</p>\n\n<ol>\n<li>Read your line.</li>\n<li>Use a state machine to parse your data.</li>\n<li>If your line ends, and you're parsing a string, read the next line..and keep parsing.</li>\n</ol>\n\n<p>I'd avoid using a regex if possible.</p>\n" }, { "answer_id": 33172, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 2, "selected": false, "text": "<p>State-machines for doing such a job are made easy using C# 2.0 iterators. Here's hopefully the last CSV parser I'll ever write. The whole file is treated as a enumerable bunch of enumerable strings, i.e. rows/columns. IEnumerable is great because it can then be processed by LINQ operators.</p>\n\n<pre><code>public class CsvParser\n{\n public char FieldDelimiter { get; set; }\n\n public CsvParser()\n : this(',')\n {\n }\n\n public CsvParser(char fieldDelimiter)\n {\n FieldDelimiter = fieldDelimiter;\n }\n\n public IEnumerable&lt;IEnumerable&lt;string&gt;&gt; Parse(string text)\n {\n return Parse(new StringReader(text));\n }\n public IEnumerable&lt;IEnumerable&lt;string&gt;&gt; Parse(TextReader reader)\n {\n while (reader.Peek() != -1)\n yield return parseLine(reader);\n }\n\n IEnumerable&lt;string&gt; parseLine(TextReader reader)\n {\n bool insideQuotes = false;\n StringBuilder item = new StringBuilder();\n\n while (reader.Peek() != -1)\n {\n char ch = (char)reader.Read();\n char? nextCh = reader.Peek() &gt; -1 ? (char)reader.Peek() : (char?)null;\n\n if (!insideQuotes &amp;&amp; ch == FieldDelimiter)\n {\n yield return item.ToString();\n item.Length = 0;\n }\n else if (!insideQuotes &amp;&amp; ch == '\\r' &amp;&amp; nextCh == '\\n') //CRLF\n {\n reader.Read(); // skip LF\n break;\n }\n else if (!insideQuotes &amp;&amp; ch == '\\n') //LF for *nix-style line endings\n break;\n else if (ch == '\"' &amp;&amp; nextCh == '\"') // escaped quotes \"\"\n {\n item.Append('\"');\n reader.Read(); // skip next \"\n }\n else if (ch == '\"')\n insideQuotes = !insideQuotes;\n else\n item.Append(ch);\n }\n // last one\n yield return item.ToString();\n }\n\n}\n</code></pre>\n\n<p>Note that the file is read character by character with the code deciding when newlines are to be treated as row delimiters or part of a quoted string.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2187/" ]
I have a big string (let's call it a CSV file, though it isn't actually one, it'll just be easier for now) that I have to parse in C# code. The first step of the parsing process splits the file into individual lines by just using a `StreamReader` object and calling `ReadLine` until it's through the file. However, any given line might contain a quoted (in single quotes) literal with embedded newlines. I need to find those newlines and convert them temporarily into some other kind of token or escape sequence until I've split the file into an array of lines..then I can change them back. Example input data: ``` 1,2,10,99,'Some text without a newline', true, false, 90 2,1,11,98,'This text has an embedded newline and continues here', true, true, 90 ``` I could write all of the C# code needed to do this by using `string.IndexOf` to find the quoted sections and look within them for newlines, but I'm thinking a Regex might be a better choice (i.e. [now I have two problems](http://regex.info/blog/2006-09-15/247))
Since this isn't a true CSV file, does it have any sort of schema? From your example, it looks like you have: int, int, int, int, string , bool, bool, int With that making up your record / object. Assuming that your data is well formed (I don't know enough about your source to know how valid this assumption is); you could: 1. Read your line. 2. Use a state machine to parse your data. 3. If your line ends, and you're parsing a string, read the next line..and keep parsing. I'd avoid using a regex if possible.
33,073
<p>How do I make <code>diff</code> ignore temporary files like <code>foo.c~</code>? Is there a configuration file that will make ignoring temporaries the default?</p> <p>More generally: what's the best way to generate a "clean" patch off a tarball? I do this rarely enough (submitting a bug fix to an OSS project by email) that I always struggle with it...</p> <p>EDIT: OK, the short answer is</p> <pre><code>diff -ruN -x *~ ... </code></pre> <p>Is there a better answer? E.g., can this go in a configuration file?</p>
[ { "answer_id": 33085, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 3, "selected": true, "text": "<p>This doesn't strictly answer your question, but you can avoid the problem by configuring Emacs to use a specific directory to keep the backup files in. There are different implementations for Emacs or XEmacs.</p>\n\n<p>In GNU Emacs</p>\n\n<pre>\n (defvar user-temporary-file-directory\n (concat temporary-file-directory user-login-name \"/\"))\n (make-directory user-temporary-file-directory t)\n (setq backup-by-copying t)\n (setq backup-directory-alist\n `((\".\" . ,user-temporary-file-directory)\n (,tramp-file-name-regexp nil)))\n (setq auto-save-list-file-prefix\n (concat user-temporary-file-directory \".auto-saves-\"))\n (setq auto-save-file-name-transforms\n `((\".*\" ,user-temporary-file-directory t)))\n</pre>\n\n<p>In XEmacs</p>\n\n<pre>\n (require 'auto-save) \n (require 'backup-dir) \n\n (defvar user-temporary-file-directory\n (concat (temp-directory) \"/\" (user-login-name)))\n (make-directory user-temporary-file-directory t)\n (setq backup-by-copying t)\n (setq auto-save-directory user-temporary-file-directory)\n (setq auto-save-list-file-prefix \n (concat user-temporary-file-directory \".auto-saves-\"))\n (setq bkup-backup-directory-info\n `((t ,user-temporary-file-directory full-path)))\n</pre>\n\n<p>You can also remove them all with a simple find command</p>\n\n<pre>\n find . -name “*~” -delete\n</pre>\n\n<p>Note that the asterisk and tilde are in double quotes to stop the shell expanding them.</p>\n\n<p>By the way, these aren't strictly <em>temporary</em> files. They are a backup of the previous version of the file, so you can manually \"undo\" your last edit at any time in the future. </p>\n" }, { "answer_id": 33098, "author": "Fernando Barrocal", "author_id": 2274, "author_profile": "https://Stackoverflow.com/users/2274", "pm_score": 0, "selected": false, "text": "<p>You can create a small sunction/script to it, like:</p>\n\n<pre><code>#!/bin/bash\nolddir=\"/tmp/old\"\nnewdir=\"/tmp/new\"\n\npushd $newdir\nfor files in $(find . -name \\*.c)\ndo\n diff $olddir/$file $newdir/$file\ndone\npopd\n</code></pre>\n\n<p>This is only one way to script this. The simple way. But I think you got the idea.</p>\n\n<p>Other suggestion is configuring in emacs a backup dir, so your backup files go always to the same place, outside your work dir!</p>\n" }, { "answer_id": 1099613, "author": "rnsanchez", "author_id": 72689, "author_profile": "https://Stackoverflow.com/users/72689", "pm_score": 2, "selected": false, "text": "<p>You can create an ignore file, like this:</p>\n\n<pre><code>core.*\n*~\n*.o\n*.a\n*.so\n&lt;more file patterns you want to skip&gt;\n</code></pre>\n\n<p>and then run <code>diff</code> with <code>-X</code> option, like this:</p>\n\n<pre><code>diff -X ignore-file &lt;other diff options you use/need&gt; path1 path2\n</code></pre>\n\n<p>There used to be a .diffignore file \"close\" to the Linux kernel (maybe an informal file), but I couldn't find it anymore. Usually you keep using this ignore-file, just adding new patterns you want to ignore.</p>\n" }, { "answer_id": 26330661, "author": "Bret Weinraub", "author_id": 869942, "author_profile": "https://Stackoverflow.com/users/869942", "pm_score": 0, "selected": false, "text": "<p>The poster has listed this as the 'short answer':</p>\n\n<pre><code>diff -ruN -x *~ ...\n</code></pre>\n\n<p>but feeding this to shell will cause the * to be globbed before diff is invoked.</p>\n\n<p>This is better:</p>\n\n<pre><code>diff -r -x '*~' dir1 dir2\n</code></pre>\n\n<p>I omit the -u and -N flags as those are matters of taste and not relevant to the question at hand.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
How do I make `diff` ignore temporary files like `foo.c~`? Is there a configuration file that will make ignoring temporaries the default? More generally: what's the best way to generate a "clean" patch off a tarball? I do this rarely enough (submitting a bug fix to an OSS project by email) that I always struggle with it... EDIT: OK, the short answer is ``` diff -ruN -x *~ ... ``` Is there a better answer? E.g., can this go in a configuration file?
This doesn't strictly answer your question, but you can avoid the problem by configuring Emacs to use a specific directory to keep the backup files in. There are different implementations for Emacs or XEmacs. In GNU Emacs ``` (defvar user-temporary-file-directory (concat temporary-file-directory user-login-name "/")) (make-directory user-temporary-file-directory t) (setq backup-by-copying t) (setq backup-directory-alist `(("." . ,user-temporary-file-directory) (,tramp-file-name-regexp nil))) (setq auto-save-list-file-prefix (concat user-temporary-file-directory ".auto-saves-")) (setq auto-save-file-name-transforms `((".*" ,user-temporary-file-directory t))) ``` In XEmacs ``` (require 'auto-save) (require 'backup-dir) (defvar user-temporary-file-directory (concat (temp-directory) "/" (user-login-name))) (make-directory user-temporary-file-directory t) (setq backup-by-copying t) (setq auto-save-directory user-temporary-file-directory) (setq auto-save-list-file-prefix (concat user-temporary-file-directory ".auto-saves-")) (setq bkup-backup-directory-info `((t ,user-temporary-file-directory full-path))) ``` You can also remove them all with a simple find command ``` find . -name “*~” -delete ``` Note that the asterisk and tilde are in double quotes to stop the shell expanding them. By the way, these aren't strictly *temporary* files. They are a backup of the previous version of the file, so you can manually "undo" your last edit at any time in the future.
33,080
<p>In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window.</p> <p>I need an auto-height for the object. The DIV starts about 300px from the top screen, and its height should make it stretch to the bottom of the browser screen. I have a max height for the container DIV, so there would have to be minimum-height for the div. I believe I can just restrict that in CSS, and use Javascript to handle the resizing of the DIV.</p> <p>My javascript isn't nearly as good as it should be. Is there an easy script I could write that would do this for me?</p> <p>Edit: The DIV houses a control that does it's own overflow handling (implements its own scroll bar).</p>
[ { "answer_id": 33096, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": false, "text": "<p>What should happen in the case of overflow? If you want it to just get to the bottom of the window, use absolute positioning:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>div {\n position: absolute;\n top: 300px;\n bottom: 0px;\n left: 30px;\n right: 30px;\n}\n</code></pre>\n\n<p>This will put the DIV 30px in from each side, 300px from the top of the screen, and flush with the bottom. Add an <code>overflow:auto;</code> to handle cases where the content is larger than the div.\n<hr/>\nEdit: @Whoever marked this down, an explanation would be nice... Is something wrong with the answer?</p>\n" }, { "answer_id": 33124, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 0, "selected": false, "text": "<p>If I understand what you're asking, this should do the trick:</p>\n\n<pre><code>// the more standards compliant browsers (mozilla/netscape/opera/IE7) use \n// window.innerWidth and window.innerHeight\n\nvar windowHeight;\n\nif (typeof window.innerWidth != 'undefined')\n{\n windowHeight = window.innerHeight;\n}\n// IE6 in standards compliant mode (i.e. with a valid doctype as the first \n// line in the document)\nelse if (typeof document.documentElement != 'undefined'\n &amp;&amp; typeof document.documentElement.clientWidth != 'undefined' \n &amp;&amp; document.documentElement.clientWidth != 0)\n{\n windowHeight = document.documentElement.clientHeight;\n}\n// older versions of IE\nelse\n{\n windowHeight = document.getElementsByTagName('body')[0].clientHeight;\n}\n\ndocument.getElementById(\"yourDiv\").height = windowHeight - 300 + \"px\";\n</code></pre>\n" }, { "answer_id": 33129, "author": "Toran Billups", "author_id": 2701, "author_profile": "https://Stackoverflow.com/users/2701", "pm_score": 3, "selected": false, "text": "<p><code>document.getElementById('myDiv').style.height = 500;</code></p>\n\n<p>This is the very basic JS code required to adjust the height of your object dynamically. I just did this very thing where I had some auto height property, but when I add some content via <code>XMLHttpRequest</code> I needed to resize my parent div and this offsetheight property did the trick in IE6/7 and FF3</p>\n" }, { "answer_id": 33147, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 6, "selected": true, "text": "<p>Try this simple, specific function:</p>\n\n<pre><code>function resizeElementHeight(element) {\n var height = 0;\n var body = window.document.body;\n if (window.innerHeight) {\n height = window.innerHeight;\n } else if (body.parentElement.clientHeight) {\n height = body.parentElement.clientHeight;\n } else if (body &amp;&amp; body.clientHeight) {\n height = body.clientHeight;\n }\n element.style.height = ((height - element.offsetTop) + \"px\");\n}\n</code></pre>\n\n<p>It does not depend on the current distance from the top of the body being specified (in case your 300px changes).</p>\n\n<hr>\n\n<p>EDIT: By the way, you would want to call this on that div every time the user changed the browser's size, so you would need to wire up the event handler for that, of course.</p>\n" }, { "answer_id": 1718904, "author": "Shanti", "author_id": 209155, "author_profile": "https://Stackoverflow.com/users/209155", "pm_score": 0, "selected": false, "text": "<p>With minor corrections:</p>\n\n<pre><code>function rearrange()\n{\nvar windowHeight;\n\nif (typeof window.innerWidth != 'undefined')\n{\n windowHeight = window.innerHeight;\n}\n// IE6 in standards compliant mode (i.e. with a valid doctype as the first\n// line in the document)\nelse if (typeof document.documentElement != 'undefined'\n &amp;&amp; typeof document.documentElement.clientWidth != 'undefined'\n &amp;&amp; document.documentElement.clientWidth != 0)\n{\n windowHeight = document.documentElement.clientHeight;\n}\n// older versions of IE\nelse\n{\n windowHeight = document.getElementsByTagName('body')[0].clientHeight;\n}\n\ndocument.getElementById(\"foobar\").style.height = (windowHeight - document.getElementById(\"foobar\").offsetTop - 6)+ \"px\";\n}\n</code></pre>\n" }, { "answer_id": 26062700, "author": "RawBits", "author_id": 2023816, "author_profile": "https://Stackoverflow.com/users/2023816", "pm_score": 0, "selected": false, "text": "<p>Simplest I could come up...</p>\n\n<pre><code>function resizeResizeableHeight() {\n $('.resizableHeight').each( function() {\n $(this).outerHeight( $(this).parent().height() - ( $(this).offset().top - ( $(this).parent().offset().top + parseInt( $(this).parent().css('padding-top') ) ) ) )\n });\n}\n</code></pre>\n\n<p>Now all you have to do is add the resizableHeight class to everything you want to autosize (to it's parent).</p>\n" }, { "answer_id": 40434747, "author": "mwag", "author_id": 3160967, "author_profile": "https://Stackoverflow.com/users/3160967", "pm_score": 0, "selected": false, "text": "<p>inspired by @jason-bunting, same thing for either height or width:</p>\n\n<pre><code>function resizeElementDimension(element, doHeight) {\n dim = (doHeight ? 'Height' : 'Width')\n ref = (doHeight ? 'Top' : 'Left')\n\n var x = 0;\n var body = window.document.body;\n if(window['inner' + dim])\n x = window['inner' + dim]\n else if (body.parentElement['client' + dim])\n x = body.parentElement['client' + dim]\n else if (body &amp;&amp; body['client' + dim])\n x = body['client' + dim]\n\n element.style[dim.toLowerCase()] = ((x - element['offset' + ref]) + \"px\");\n}\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1226/" ]
In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window. I need an auto-height for the object. The DIV starts about 300px from the top screen, and its height should make it stretch to the bottom of the browser screen. I have a max height for the container DIV, so there would have to be minimum-height for the div. I believe I can just restrict that in CSS, and use Javascript to handle the resizing of the DIV. My javascript isn't nearly as good as it should be. Is there an easy script I could write that would do this for me? Edit: The DIV houses a control that does it's own overflow handling (implements its own scroll bar).
Try this simple, specific function: ``` function resizeElementHeight(element) { var height = 0; var body = window.document.body; if (window.innerHeight) { height = window.innerHeight; } else if (body.parentElement.clientHeight) { height = body.parentElement.clientHeight; } else if (body && body.clientHeight) { height = body.clientHeight; } element.style.height = ((height - element.offsetTop) + "px"); } ``` It does not depend on the current distance from the top of the body being specified (in case your 300px changes). --- EDIT: By the way, you would want to call this on that div every time the user changed the browser's size, so you would need to wire up the event handler for that, of course.
33,089
<p>I'm using the <a href="http://msdn.microsoft.com/en-us/library/ms178329.aspx" rel="nofollow noreferrer">ASP.NET Login Controls</a> and <a href="http://msdn.microsoft.com/en-us/library/aa480476.aspx" rel="nofollow noreferrer">Forms Authentication</a> for membership/credentials for an ASP.NET web application. It keeps redirecting to a Login.aspx page at the root of my application that does not exist. My login page is within a folder.</p>
[ { "answer_id": 33092, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 1, "selected": false, "text": "<p>I found the answer at <a href=\"http://www.codersource.net/asp_net_forms_authentication.aspx\" rel=\"nofollow noreferrer\">CoderSource.net</a>. I had to put the correct path into my web.config file.</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;configuration&gt;\n &lt;system.web&gt;\n ...\n &lt;!--\n The &lt;authentication&gt; section enables configuration \n of the security authentication mode used by \n ASP.NET to identify an incoming user. \n --&gt;\n &lt;authentication mode=\"Forms\"&gt;\n &lt;forms loginUrl=\"~/FolderName/Login.aspx\" /&gt;\n &lt;/authentication&gt;\n ...\n &lt;/system.web&gt;\n ...\n&lt;/configuration&gt;\n</code></pre>\n" }, { "answer_id": 33106, "author": "Ryan Sampson", "author_id": 1375, "author_profile": "https://Stackoverflow.com/users/1375", "pm_score": 4, "selected": true, "text": "<p>Use the LoginUrl property for the forms item?</p>\n\n<pre><code>&lt;authentication mode=\"Forms\"&gt;\n &lt;forms defaultUrl=\"~/Default.aspx\" loginUrl=\"~/login.aspx\" timeout=\"1440\" &gt;&lt;/forms&gt;\n&lt;/authentication&gt;\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
I'm using the [ASP.NET Login Controls](http://msdn.microsoft.com/en-us/library/ms178329.aspx) and [Forms Authentication](http://msdn.microsoft.com/en-us/library/aa480476.aspx) for membership/credentials for an ASP.NET web application. It keeps redirecting to a Login.aspx page at the root of my application that does not exist. My login page is within a folder.
Use the LoginUrl property for the forms item? ``` <authentication mode="Forms"> <forms defaultUrl="~/Default.aspx" loginUrl="~/login.aspx" timeout="1440" ></forms> </authentication> ```
33,103
<p>I've noticed that some sites (usually banks) suppress the ability to paste text into text fields. How is this done? I know that JavaScript can be used to swallow the keyboard shortcut for paste, but what about the right-click menu item?</p>
[ { "answer_id": 33130, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 4, "selected": true, "text": "<p>Probably using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.onpaste\" rel=\"nofollow noreferrer\"><code>onpaste</code></a> event, and either <code>return false</code> from it or use <code>e.preventDefault()</code> on the Event object.</p>\n\n<p>Note that <code>onpaste</code> is <em>non standard</em>, don't rely on it for production sites, because it will not be there forever.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(document).on(\"paste\",function(e){\r\n console.log(\"paste\")\r\n e.preventDefault()\r\n return false;\r\n})</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 37108, "author": "LucaM", "author_id": 3511, "author_profile": "https://Stackoverflow.com/users/3511", "pm_score": 2, "selected": false, "text": "<p>Even if it is somewhat possible to intercept the paste event in many browsers (but not all as shown at the link on the previous answer), that is quite unreliable and posible not complete (depending on the browser / OS it may be possible to do the paste operation in different ways that may not be trappable by javascript code).</p>\n\n<p><a href=\"http://discerning.com/topics/software/ttw.html#copy_and_paste\" rel=\"nofollow noreferrer\" title=\"Here\">Here</a> is a collection of notes regarding paste (and copy) in the context of rich text editors that may be applied also elsewhere.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1450/" ]
I've noticed that some sites (usually banks) suppress the ability to paste text into text fields. How is this done? I know that JavaScript can be used to swallow the keyboard shortcut for paste, but what about the right-click menu item?
Probably using the [`onpaste`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.onpaste) event, and either `return false` from it or use `e.preventDefault()` on the Event object. Note that `onpaste` is *non standard*, don't rely on it for production sites, because it will not be there forever. ```js $(document).on("paste",function(e){ console.log("paste") e.preventDefault() return false; }) ```
33,115
<p>Does C# have the notion of private / protected inheritance, and if not, why?</p> <p><strong>C++</strong></p> <pre> <code> class Foo : private Bar { public: ... }; </code> </pre> <p><strong>C#</strong></p> <pre> <code> public abstract NServlet class : private System.Web.UI.Page { // error "type expected" } </code> </pre> <p>I am implementing a "servlet like" concept in an .aspx page and I don't want the concrete class to have the ability to see the internals of the System.Web.UI.Page base.</p>
[ { "answer_id": 33128, "author": "Chris Karcher", "author_id": 2773, "author_profile": "https://Stackoverflow.com/users/2773", "pm_score": 1, "selected": false, "text": "<p>No, public inheritance only.</p>\n" }, { "answer_id": 33142, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 1, "selected": false, "text": "<p>You probably want a ServletContainer class that gets hooked up with a NServlet implementation. In my book, not allowing private / protected inheritance is not really a big deal and keeps the language less confusing - with LINQ etc. we allready have enough stuff to remember.</p>\n" }, { "answer_id": 33151, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": -1, "selected": false, "text": "<p>No it doesn't. What would the benefit be of allowing this type of restriction?</p>\n" }, { "answer_id": 33152, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 3, "selected": false, "text": "<p>You can hide inherited APIs from being publicly visible by declaring that same member in your class as private, and using the new keyword. See <a href=\"http://msdn.microsoft.com/en-us/library/aa691135.aspx\" rel=\"noreferrer\">Hiding through Inheritance</a> from MSDN.</p>\n" }, { "answer_id": 33155, "author": "Joel Martinez", "author_id": 3433, "author_profile": "https://Stackoverflow.com/users/3433", "pm_score": 2, "selected": false, "text": "<p>If you want the NServlet class to not know anything about the Page, you should look into using the Adapter pattern. Write a page that will host an instance of the NServlet class. Depending on what exactly you're doing, you could then write a wide array of classes that only know about the base class NServlet without having to pollute your API with asp.net page members.</p>\n" }, { "answer_id": 33180, "author": "Brian Stewart", "author_id": 3114, "author_profile": "https://Stackoverflow.com/users/3114", "pm_score": 4, "selected": false, "text": "<p>C# allows public inheritance only. C++ allowed all three kinds. Public inheritance implied an \"IS-A\" type of relationship, and private inheritance implied a \"Is-Implemented-In-Terms-Of\" kind of relationship. Since layering (or composition) accomplished this in an arguably simpler fashion, private inheritance was only used when absolutely required by protected members or virtual functions required it - according to Scott Meyers in Effective C++, Item 42. </p>\n\n<p>My guess would be that the authors of C# did not feel this additional method of implementing one class in terms of another was necessary.</p>\n" }, { "answer_id": 33182, "author": "Chris Karcher", "author_id": 2773, "author_profile": "https://Stackoverflow.com/users/2773", "pm_score": 2, "selected": false, "text": "<p>@bdukes:\nKeep in mind that you aren't <strong>truly</strong> hiding the member. E.g.:</p>\n\n<pre><code>class Base\n{\n public void F() {}\n}\nclass Derived : Base\n{\n new private void F() {}\n}\n\nBase o = new Derived();\no.F(); // works\n</code></pre>\n\n<p>But this accomplishes the same as private inheritance in C++, which is what the questioner wanted.</p>\n" }, { "answer_id": 2321706, "author": "Nick Alexeev", "author_id": 279844, "author_profile": "https://Stackoverflow.com/users/279844", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>No it doesn't. What would the benefit be of allowing this type of restriction?</p>\n</blockquote>\n\n<p>Private and protected inheritance is good for encapsulation (information hiding). Protected* inheritance is supported in C++, although it isn’t in Java. Here’s an example from my project where it would be useful.</p>\n\n<p>There is a base class in as 3rd party framework**. It has dozens of settings plus properties and methods for manipulating them. The base class doesn’t make a lot of checking when individual settings are assigned, but it will generate an exception later if it encounters an unacceptable combination.</p>\n\n<p>I’m making a child class with methods for assigning these settings (e.g. example, assigning carefully crafted settings from a file). It would be nice to deny the rest of the code (outside my child class) the ability to manipulate individual settings and mess them up.</p>\n\n<p>That said, I think in C++ (which, again, supports private and protected inheritance) it's possible to cast the child class up to parent and get access to parent's public members. (See also <a href=\"https://stackoverflow.com/questions/33115/does-c-have-the-notion-of-private-and-protected-inheritance/33182#33182\">Chris Karcher's post</a>) Still, protected inheritance improves information hiding. If members of a class B1 need to be truly hidden within other classes C1 and C2, it can be arranged by making a protected variable of a class B1 within C1 and C2. Protected instance of B1 will be available to children of C1 and C2. Of course, this approach by itself doesn't provide polymorphism between C1 and C2. But polymorphism can be added (if desired) by inheriting C1 and C2 from a common interface I1.</p>\n\n<p>*** For brevity will use \"protected\" instead of \"private and protected\".</p>\n\n<p>** National Instruments Measurement Studio in my case.</p>\n\n<ul>\n<li>Nick</li>\n</ul>\n" }, { "answer_id": 11171448, "author": "ulatekh", "author_id": 603828, "author_profile": "https://Stackoverflow.com/users/603828", "pm_score": 1, "selected": false, "text": "<p>I know this is an old question, but I've run into this issue several times while writing C#, and I want to know...why not just use an interface?</p>\n\n<p>When you create your subclass of the 3rd party framework's class, also have it implement a public interface. Then define that interface to include only the methods that you want the client to access. Then, when the client requests an instance of that class, give them an instance of that interface instead.</p>\n\n<p>That seems to be the C#-accepted way of doing these sorts of things.</p>\n\n<p>The first time I did this was when I realized that the C# standard library didn't have a read-only variant of a dictionary. I wanted to provide access to a dictionary, but didn't want to give the client the ability to change items in the dictionary. So I defined a \"class DictionaryEx&lt;K,V,IV&gt; : Dictionary&lt;K,V&gt;, IReadOnlyDictionary&lt;K,IV&gt; where V : IV\" where K is the key type, V is the real value type, and IV is an interface to the V type that prevents changes. The implementation of DictionaryEx was mostly straightforward; the only difficult part was creating a ReadOnlyEnumerator class, but even that didn't take very long.</p>\n\n<p>The only drawback I can see to this approach is if the client tries to dynamically cast your public interface to the related subclass. To stop this, make your class internal. If your client casts your public interface to the original base class, I think it'd be pretty clear to them that they're taking their life in their own hands. :-)</p>\n" }, { "answer_id": 32614798, "author": "franckspike", "author_id": 1368184, "author_profile": "https://Stackoverflow.com/users/1368184", "pm_score": 1, "selected": false, "text": "<p><strong>First solution:</strong></p>\n\n<p><strong>protected internal</strong> acts as public in the same assembly and protected on other assemblies.</p>\n\n<p>You would need to change the access modifier of each members of the class which are not to be exposed through inheritance.</p>\n\n<p>It is a bit restrictive though that this solution <strong>requires and forces the class to be inherited</strong> to be used by another assembly. Thus the choice of being used only by inheritance or not is taken by the unknowing parent... normally the children are more knowing of the architecture...</p>\n\n<p>Not a perfect solution but might be a better <strong>alternative to adding an interface to hide methods</strong> and still leaving the possibility of using the parent methods to be hidden though the child class because you might not easily be able to force the use of the interface.</p>\n\n<hr>\n\n<p><strong>Problem:</strong></p>\n\n<p>The <strong>protected</strong> and <strong>private</strong> access modifiers <strong>cannot</strong> be used for methods that are <strong>implement</strong>ing <strong>interfaces</strong>. That means that the protected internal solution cannot be used for interface implemented methods. This is a big restriction.</p>\n\n<hr>\n\n<p><strong>Final solution:</strong></p>\n\n<p>I fell back to the <strong>interface</strong> solution <strong>to hide methods</strong>.</p>\n\n<p>The problem with it was to be able to force the use of the interface so that members to be hidden are ALWAYS hidden and then definitely avoiding mistakes.</p>\n\n<p>To <strong>force using only the interface</strong>, just <strong>make the constructors protected</strong> and <strong>add a static method for construction</strong> (I named it New). This static New method is in fact a factory function and it <strong>returns the interface</strong>. So the rest of the code has to use the interface only!</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
Does C# have the notion of private / protected inheritance, and if not, why? **C++** ``` class Foo : private Bar { public: ... }; ``` **C#** ``` public abstract NServlet class : private System.Web.UI.Page { // error "type expected" } ``` I am implementing a "servlet like" concept in an .aspx page and I don't want the concrete class to have the ability to see the internals of the System.Web.UI.Page base.
C# allows public inheritance only. C++ allowed all three kinds. Public inheritance implied an "IS-A" type of relationship, and private inheritance implied a "Is-Implemented-In-Terms-Of" kind of relationship. Since layering (or composition) accomplished this in an arguably simpler fashion, private inheritance was only used when absolutely required by protected members or virtual functions required it - according to Scott Meyers in Effective C++, Item 42. My guess would be that the authors of C# did not feel this additional method of implementing one class in terms of another was necessary.
33,150
<p>I am working on a Customer Server Control that extends another control. There is no problem with attaching to other controls on the form.</p> <p>in vb.net: <code>Parent.FindControl(TargetControlName)</code></p> <p>I would like to pass a method to the control in the ASPX markup. </p> <p>for example: <code>&lt;c:MyCustomerControl runat=server InitializeStuffCallback="InitializeStuff"&gt;</code></p> <p>So, I tried using reflection to access the given method name from the Parent.</p> <p>Something like (in VB)</p> <pre class="lang-vb prettyprint-override"><code>Dim pageType As Type = Page.GetType Dim CallbackMethodInfo As MethodInfo = pageType.GetMethod( "MethodName" ) 'Also tried sender.Parent.GetType.GetMethod("MethodName") sender.Parent.Parent.GetType.GetMethod("MethodName") </code></pre> <p>The method isn't found, because it just isn't apart of the Page. Where should I be looking? I'm fairly sure this is possible because I've seen other controls do similar.</p> <hr> <p>I forgot to mention, my work-around is to give the control events and attaching to them in the Code-behind.</p>
[ { "answer_id": 33163, "author": "Joel Martinez", "author_id": 3433, "author_profile": "https://Stackoverflow.com/users/3433", "pm_score": 0, "selected": false, "text": "<p>Your workaround is actually the better answer. If you have code that you must run at a certain part of your control's lifecycle, you <strong>should</strong> expose events to let the container extend the lifecycle with custom functionality.</p>\n" }, { "answer_id": 33179, "author": "Jesse Dearing", "author_id": 1804, "author_profile": "https://Stackoverflow.com/users/1804", "pm_score": 3, "selected": true, "text": "<p>If you want to be able to pass a method in the ASPX markup, you need to use the <code>Browsable</code> attribute in your code on the event.</p>\n\n<p>VB.NET</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>&lt;Browsable(True)&gt; Public Event InitializeStuffCallback\n</code></pre>\n\n<p>C#</p>\n\n<pre><code>[Browsable(true)]\npublic event EventHandler InitializeStuffCallback;\n</code></pre>\n\n<p>Reference:\n<a href=\"http://msdn.microsoft.com/en-us/library/tk67c2t8.aspx\" rel=\"nofollow noreferrer\">Design-Time Attributes for Components</a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.browsableattribute.aspx\" rel=\"nofollow noreferrer\">BrowsableAttribute Class</a></p>\n\n<p>All the events, properties, or whatever need to be in the code-behind of the control with the browsable attribute to make it so you can change it in the tag code.</p>\n" }, { "answer_id": 33187, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 2, "selected": false, "text": "<p>Normally you wouldn't need to get the method via reflection. Inside your user control, define a public event (sorry I do not know the vb syntax so this will be in c#)</p>\n\n<pre><code>public event EventHandler EventName;\n</code></pre>\n\n<p>Now, inside your aspx page, or whatever container of the user control, define a protected method that matches the EventHandler:</p>\n\n<pre><code>protected void MyCustomerControl_MethodName(object sender, EventArgs e) { }\n</code></pre>\n\n<p>Now, inside your markup, you can use</p>\n\n<pre><code>&lt;c:MyCustomerControl id=\"MyCustomerControl\" runat=server OnEventName=\"MyCustomerControl_MethodName\"&gt;\n</code></pre>\n" }, { "answer_id": 33191, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "<p>Every ASP.NET page is <strong>class of its own</strong> inherited from <code>Page</code> as in:</p>\n\n<pre><code>class MyPage : Page\n</code></pre>\n\n<p>Therefore, to find that method via Reflection, you must get the correct type, which is the type of the page class that stores the page code.</p>\n\n<p>I suppose you need to support multiple pages for this control to be instantiated in I believe you can find the child type of any instance of Page via Reflection, but I do not remember how, but you should be able to do it.</p>\n\n<p>but... like everyone else has said, such case is what <em>events</em> are for.</p>\n" }, { "answer_id": 33536, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 0, "selected": false, "text": "<p>buyutec and Jesse Dearing both have an acceptable answer.</p>\n\n<pre><code>[Browsable(true)] \n</code></pre>\n\n<p>lets you see the property in the Properties window. However, the event doesn't show up, which makes no difference to me.</p>\n\n<p>The thing I overlooked earlier was the fact that when you reference a control's even from the tag, it prep-ends On.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2017/" ]
I am working on a Customer Server Control that extends another control. There is no problem with attaching to other controls on the form. in vb.net: `Parent.FindControl(TargetControlName)` I would like to pass a method to the control in the ASPX markup. for example: `<c:MyCustomerControl runat=server InitializeStuffCallback="InitializeStuff">` So, I tried using reflection to access the given method name from the Parent. Something like (in VB) ```vb Dim pageType As Type = Page.GetType Dim CallbackMethodInfo As MethodInfo = pageType.GetMethod( "MethodName" ) 'Also tried sender.Parent.GetType.GetMethod("MethodName") sender.Parent.Parent.GetType.GetMethod("MethodName") ``` The method isn't found, because it just isn't apart of the Page. Where should I be looking? I'm fairly sure this is possible because I've seen other controls do similar. --- I forgot to mention, my work-around is to give the control events and attaching to them in the Code-behind.
If you want to be able to pass a method in the ASPX markup, you need to use the `Browsable` attribute in your code on the event. VB.NET ```vb <Browsable(True)> Public Event InitializeStuffCallback ``` C# ``` [Browsable(true)] public event EventHandler InitializeStuffCallback; ``` Reference: [Design-Time Attributes for Components](http://msdn.microsoft.com/en-us/library/tk67c2t8.aspx) and [BrowsableAttribute Class](http://msdn.microsoft.com/en-us/library/system.componentmodel.browsableattribute.aspx) All the events, properties, or whatever need to be in the code-behind of the control with the browsable attribute to make it so you can change it in the tag code.
33,199
<p>Would it be possible to print <code>Hello</code> twice using single <code>condition</code>?</p> <pre><code>if "condition" printf ("Hello"); else printf("World"); </code></pre>
[ { "answer_id": 33202, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>The <code>if</code> statement executes one or the other of the controlled statements (both <code>printf</code> in your example). No matter what you use for <code>condition</code>, that snippet will either print \"Hello\", or \"World\", but never both.</p>\n\n<p>Edit: Okay, so it's a trick question and you can put whatever you like in the condition (including a call to an entire other function that does anything you want). But that's hardly interesting. I can't believe I got downmodded for giving a correct answer.</p>\n" }, { "answer_id": 33205, "author": "scoob", "author_id": 1165587, "author_profile": "https://Stackoverflow.com/users/1165587", "pm_score": 3, "selected": false, "text": "<pre><code>if ( printf(\"Hello\")==0)\n</code></pre>\n\n<p>see\n[<a href=\"http://www.coders2020.com/what-does-printf-return]\" rel=\"nofollow noreferrer\">http://www.coders2020.com/what-does-printf-return]</a></p>\n\n<p>(matt corrected my =, thanks, C is far away)</p>\n" }, { "answer_id": 33206, "author": "Jake Pearson", "author_id": 632, "author_profile": "https://Stackoverflow.com/users/632", "pm_score": 0, "selected": false, "text": "<pre><code>if(printf(\"Hello\") == 1)\n printf(\"Hello\")\nelse\n printf(\"World\")\n</code></pre>\n" }, { "answer_id": 33208, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 7, "selected": true, "text": "<pre><code>if ( printf(\"Hello\") == 0 )\n printf (\"Hello\");\nelse\n printf (\"World\");\n</code></pre>\n\n<p>:-)</p>\n" }, { "answer_id": 33211, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 2, "selected": false, "text": "<pre><code>if (true) printf (\"Hello\"); if (false)\n printf (\"Hello\");\nelse\n printf(\"World\");\n</code></pre>\n" }, { "answer_id": 33212, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 4, "selected": false, "text": "<pre><code>\"condition\" === (printf(\"Hello\"), 0)\n</code></pre>\n\n<p>Really lame:</p>\n\n<pre><code>int main() {\n if (printf(\"Hello\"), 0)\n printf (\"Hello\");\n else\n printf(\"World\");\n}\n</code></pre>\n\n<p>I prefer the use of the comma operator because you don't have to look up the return value of <code>printf</code> in order to know what the conditional does. This increases readability and maintainability. :-)</p>\n" }, { "answer_id": 33213, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 1, "selected": false, "text": "<p>This could work:</p>\n\n<pre><code>if (printf(\"Hello\") - strlen(\"Hello\"))\n printf(\"Hello\")\nelse\n printf(\"World\")\n</code></pre>\n\n<p>This snippet emphasizes the return value of <code>printf</code>: The number of characters printed.</p>\n" }, { "answer_id": 33216, "author": "Billy Jo", "author_id": 3447, "author_profile": "https://Stackoverflow.com/users/3447", "pm_score": 0, "selected": false, "text": "<pre><code>if (printf(\"Hello\") &lt; 1)\n printf(\"Hello\");\nelse\n printf(\"World\");\n</code></pre>\n" }, { "answer_id": 33219, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>#define CONDITION (0) if (0) {} else\n</code></pre>\n\n<p>or some such.</p>\n\n<p>If you see such a question on an interview, run away as fast as you can! The team that asks such questions is bound to be unhealthy.</p>\n\n<p>Edit - I forgot to clarify - this relies on \"else\" being matched with closest open \"if\", and on the fact that it's written as \"if CONDITION\" rather than if (CONDITION) - parenthesis would make the puzzle unsolvable.</p>\n" }, { "answer_id": 33230, "author": "infralite", "author_id": 3423, "author_profile": "https://Stackoverflow.com/users/3423", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Greg wrote:</p>\n \n <blockquote>\n <p>No matter what you use for condition, that snippet will either print \"Hello\", or \"World\", but never both.</p>\n </blockquote>\n</blockquote>\n\n<p>Well, this isn't true, but why you would <em>want</em> it to print both, I can't find a use case for. It's defeating the point of having an if statement. The likely \"real\" solution is to not use an if at all. Silly interview questions... :)</p>\n" }, { "answer_id": 33253, "author": "ryan", "author_id": 2454, "author_profile": "https://Stackoverflow.com/users/2454", "pm_score": 0, "selected": false, "text": "<p>Very interesting guys, thanks for the answers. I never would have thought about putting the print statement inside the if condition.</p>\n\n<p>Here's the Java equivalent:</p>\n\n<pre><code> if ( System.out.printf(\"Hello\").equals(\"\") )\n System.out.printf(\"Hello\");\n else\n System.out.printf(\"World\");\n</code></pre>\n" }, { "answer_id": 33724, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Without knowing the return value of <code>printf</code> off the top of your head:</p>\n\n<pre><code>if (printf(\"Hello\") &amp;&amp; 0)\n printf(\"Hello\");\nelse\n printf(\"World\");\n</code></pre>\n" }, { "answer_id": 80684, "author": "GowriKumar", "author_id": 15150, "author_profile": "https://Stackoverflow.com/users/15150", "pm_score": 4, "selected": false, "text": "<p>If it is on Unix:</p>\n\n<pre><code>if (fork())\n printf (\"Hello\");\nelse\n printf(\"World\");\n</code></pre>\n\n<p>Ofcoures that doesn't guarantee the order 0f the prints</p>\n" }, { "answer_id": 784683, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Solution 1:</p>\n\n<pre><code>int main(int argc, char* argv[])\n{ \n if( argc == 2 || main( 2, NULL ) )\n {\n printf(\"Hello \"); \n }\n else\n {\n printf(\"World\\n\");\n }\n return 0;\n}\n</code></pre>\n\n<p>Solution 2 (Only for Unix and Linux):</p>\n\n<pre><code>int main(int argc, char* argv[])\n{ \n if( !fork() )\n {\n printf(\"Hello \"); \n }\n else\n {\n printf(\"World\\n\");\n }\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 1373971, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "<p>No love for <code>exit</code>?</p>\n\n<pre><code>if(printf(\"HelloWorld\"), exit(0), \"ByeBye\") \n printf (\"Hello\");\nelse\n printf (\"World\");\n</code></pre>\n" }, { "answer_id": 1774682, "author": "Adriaan Stander", "author_id": 144424, "author_profile": "https://Stackoverflow.com/users/144424", "pm_score": 0, "selected": false, "text": "<p>Dont use an if else block then.</p>\n\n<p>EDIT to Comment.</p>\n\n<p>It might then mean that the code be in both blocks, or before/after the block if it is required to run in both cases.</p>\n" }, { "answer_id": 1774683, "author": "Ed S.", "author_id": 1053, "author_profile": "https://Stackoverflow.com/users/1053", "pm_score": 2, "selected": false, "text": "<p>So... you want to execute the code inside the if block... and the code inside of the else block... of the same if/else statement? Then... you should get rid of the else and stick taht code in the if.</p>\n\n<pre><code>if something\n do_this\n do_that\nend\n</code></pre>\n\n<p>The else statement is designed to execute only if the if statement is not executed and vice-versa, that is the whole point. This is an odd question...</p>\n" }, { "answer_id": 1774688, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 1, "selected": false, "text": "<p>Just put the code before or after the if..else block.</p>\n\n<p>Alternatively, if you have an \"if, else if, else\" block where you want to execute code in some (but not all) branches, just put it in a separate function and call that function within each block.</p>\n" }, { "answer_id": 1774706, "author": "Tordek", "author_id": 77542, "author_profile": "https://Stackoverflow.com/users/77542", "pm_score": 2, "selected": false, "text": "<p>Comment the \"else\" ;)</p>\n\n<pre><code>if(foo)\n{\n bar();\n}\n//else\n{\n baz();\n}\n</code></pre>\n" }, { "answer_id": 1774711, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 4, "selected": false, "text": "<p>Buckle your seatbelts:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;setjmp.h&gt;\n\nint main()\n{\n jmp_buf env;\n\n if (!setjmp(env))\n {\n printf(\"if executed\\n\");\n longjmp(env, 1);\n }\n else\n {\n printf(\"else executed\\n\");\n }\n\n return 0;\n}\n</code></pre>\n\n<p>Prints:</p>\n\n<pre><code>if executed\nelse executed\n</code></pre>\n\n<p>Is this what you mean? I doubt it, but at least it's possible. Using <code>fork</code> you can do it also, but the branches will run in different processes.</p>\n" }, { "answer_id": 1774717, "author": "sud03r", "author_id": 91593, "author_profile": "https://Stackoverflow.com/users/91593", "pm_score": 4, "selected": false, "text": "<p>This sounds to me like some interview puzzle. I hope this is close to what you want.</p>\n\n<pre><code>\n#include &lt;stdio.h&gt;\n\nint main()\n{\n static int i = 0 ;\n if( i++==0 ? main(): 1)\n printf(\"Hello,\");\n else\n printf(\"World\\n\");\n\n return 0 ;\n}\n</code></pre>\n\n<p>prints <code>Hello, World</code></p>\n" }, { "answer_id": 1774727, "author": "rtpg", "author_id": 122757, "author_profile": "https://Stackoverflow.com/users/122757", "pm_score": 0, "selected": false, "text": "<p>use a goto, one of the single most underused keywords of our day</p>\n" }, { "answer_id": 1774757, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>The basic answer is that in the ordinary course of events you neither want to execute both the statements in the 'if' block and the 'else' block in a single pass through the code (why bother with the condition if you do) nor can you execute both sets of statements without jumping through grotesque hoops.</p>\n\n<p>Some grotesque hoops - evil code!</p>\n\n<pre><code> if (condition == true)\n {\n ...stuff...\n goto Else;\n }\n else\n {\nElse:\n ...more stuff...\n }\n</code></pre>\n\n<p>Of course, it is a plain abuse of (any) language because it is equivalent to:</p>\n\n<pre><code> if (condition == true)\n {\n ...stuff...\n }\n ...more stuff...\n</code></pre>\n\n<p>However, it might achieve what the question is asking. If you have to execute both blocks whether the condition is true or false, then things get a bit trickier.</p>\n\n<pre><code> done_then = false;\n if (condition == true)\n {\nThen:\n ...stuff...\n done_then = true;\n goto Else;\n }\n else\n {\nElse:\n ...more stuff...\n if (!done_then) goto Then;\n }\n</code></pre>\n" }, { "answer_id": 1774759, "author": "Dustin E", "author_id": 215931, "author_profile": "https://Stackoverflow.com/users/215931", "pm_score": 2, "selected": false, "text": "<pre><code>int main()\n{\n runIfElse(true);\n runIfElse(false);\n\n return 0;\n}\n\nvoid runIfElse(bool p)\n{\n if(p)\n {\n // do if\n }\n else\n {\n // do else\n }\n}\n</code></pre>\n" }, { "answer_id": 1774788, "author": "lpz", "author_id": 215987, "author_profile": "https://Stackoverflow.com/users/215987", "pm_score": 0, "selected": false, "text": "<p>Cheeting with an empty else statement:</p>\n\n<pre><code>if (condition)\n // do if stuff\nelse;\n // do else stuff\n</code></pre>\n\n<p>If you don't like the fact that else; is actually an empty else statement try this:</p>\n\n<pre><code>for (int ii=0; ii&lt;2; ii++)\n{\n if (condition &amp;&amp; !ii)\n // do if stuff\n else\n {\n // do else stuff\n break;\n }\n}\n</code></pre>\n" }, { "answer_id": 10151648, "author": "firesofmay", "author_id": 679390, "author_profile": "https://Stackoverflow.com/users/679390", "pm_score": 0, "selected": false, "text": "<p>Two possible Solutions without using printf statements :-</p>\n\n<p>First :-</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint\nmain(void)\n{\n if (!stdin || (stdin = 0, main()))\n printf(\"hello\");\n else\n printf(\"world\");\n return 0;\n}\n</code></pre>\n\n<p>Second</p>\n\n<pre><code>#include&lt;stdio.h&gt;\nvoid main()\n{\nif (1\n#define else if (1) \n)\n{ \n printf(\"hello\"); \n} \nelse\n { \n printf(\"world\"); \n}\n}\n</code></pre>\n\n<p>Reference :- <a href=\"http://ideone.com/q5Y7j\" rel=\"nofollow\">Link1</a> , <a href=\"http://codepad.org/qfS5my7p\" rel=\"nofollow\">Link2</a></p>\n" }, { "answer_id": 12060150, "author": "mafia", "author_id": 1137405, "author_profile": "https://Stackoverflow.com/users/1137405", "pm_score": -1, "selected": false, "text": "<p>The condition to this question is:</p>\n\n<pre><code> if(printf(\"hello\")? 0 : 1) { }\n</code></pre>\n" }, { "answer_id": 25564384, "author": "shiju", "author_id": 1179556, "author_profile": "https://Stackoverflow.com/users/1179556", "pm_score": 0, "selected": false, "text": "<pre><code>if (printf(\"hello\") &amp; 0)\n{\nprintf(\"hello\");\n}\nelse\n{\nprintf(\"world\");\n</code></pre>\n\n<p>No need to bother about the return value of printf.</p>\n" }, { "answer_id": 29992356, "author": "Shankha Jana", "author_id": 2550691, "author_profile": "https://Stackoverflow.com/users/2550691", "pm_score": 1, "selected": false, "text": "<pre><code> #include&lt;stdio.h&gt;\n int main()\n{\n if(! printf(\"Hello\"))\n printf (\"Hello\");\nelse\n printf (\"World\");\n return 0;\n}\n</code></pre>\n\n<p>Because Printf returns the number of character it has printed successfully. </p>\n" }, { "answer_id": 29992672, "author": "Michael Dorgan", "author_id": 527574, "author_profile": "https://Stackoverflow.com/users/527574", "pm_score": 0, "selected": false, "text": "<p>Abuse of preprocessing - with cleanup at least.</p>\n\n<pre><code>\n#define else \nif(1)\n{\n printf(\"hello\");\n}\nelse\n{\n printf(\"world\");\n}\n#undef else\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2454/" ]
Would it be possible to print `Hello` twice using single `condition`? ``` if "condition" printf ("Hello"); else printf("World"); ```
``` if ( printf("Hello") == 0 ) printf ("Hello"); else printf ("World"); ``` :-)
33,226
<p>Assuming such a query exists, I would greatly appreciate the help.</p> <p>I'm trying to develop a permissions script that will grant "select" and "references" permissions on the user tables and views in a database. My hope is that executing the "grant" commands on each element in such a set will make it easier to keep permissions current when new tables and views are added to the database.</p>
[ { "answer_id": 33266, "author": "Jas", "author_id": 777, "author_profile": "https://Stackoverflow.com/users/777", "pm_score": 0, "selected": false, "text": "<pre><code>select * from information_schema.tables\nwhere table_type = 'view'\n</code></pre>\n" }, { "answer_id": 33285, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 4, "selected": true, "text": "<pre><code>select * from information_schema.tables\nWHERE OBJECTPROPERTY(OBJECT_ID(table_name),'IsMSShipped') =0 \n</code></pre>\n\n<p>Will exclude dt_properties and system tables</p>\n\n<p>add </p>\n\n<pre><code>where table_type = 'view' \n</code></pre>\n\n<p>if you just want the view</p>\n" }, { "answer_id": 33302, "author": "karlgrz", "author_id": 318, "author_profile": "https://Stackoverflow.com/users/318", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT\n *\nFROM\n sysobjects\nWHERE\n xtype = 'V' AND\n type = 'V' AND\n category = 0\n</code></pre>\n\n<p>Here is a list of the possible values for <strong>xtype</strong>:</p>\n\n<ul>\n<li>C = CHECK constraint</li>\n<li>D = Default or DEFAULT constraint</li>\n<li>F = FOREIGN KEY constraint</li>\n<li>L = Log</li>\n<li>P = Stored procedure</li>\n<li>PK = PRIMARY KEY constraint (type is K)</li>\n<li>RF = Replication filter stored procedure</li>\n<li>S = System table</li>\n<li>TR = Trigger</li>\n<li>U = User table</li>\n<li>UQ = UNIQUE constraint (type is K)</li>\n<li>V = View</li>\n<li>X = Extended stored procedure</li>\n</ul>\n\n<p>Here are the possible values for <strong>type</strong>:</p>\n\n<ul>\n<li>C = CHECK constraint</li>\n<li>D = Default or DEFAULT constraint</li>\n<li>F = FOREIGN KEY constraint</li>\n<li>FN = Scalar function</li>\n<li>IF = Inlined table-function</li>\n<li>K = PRIMARY KEY or UNIQUE constraint</li>\n<li>L = Log</li>\n<li>P = Stored procedure</li>\n<li>R = Rule</li>\n<li>RF = Replication filter stored procedure</li>\n<li>S = System table</li>\n<li>TF = Table function</li>\n<li>TR = Trigger</li>\n<li>U = User table</li>\n<li>V = View</li>\n<li>X = Extended stored procedure</li>\n</ul>\n\n<p>Finally, the <strong>category</strong> field looks like it groups based on different types of objects. After analyzing the return resultset, the system views look to have a <strong>category</strong> = 2, whereas all of the user views have a <strong>category</strong> = 0. Hope this helps.</p>\n\n<p>For more information, visit <a href=\"http://msdn.microsoft.com/en-us/library/aa260447(SQL.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa260447(SQL.80).aspx</a></p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3475/" ]
Assuming such a query exists, I would greatly appreciate the help. I'm trying to develop a permissions script that will grant "select" and "references" permissions on the user tables and views in a database. My hope is that executing the "grant" commands on each element in such a set will make it easier to keep permissions current when new tables and views are added to the database.
``` select * from information_schema.tables WHERE OBJECTPROPERTY(OBJECT_ID(table_name),'IsMSShipped') =0 ``` Will exclude dt\_properties and system tables add ``` where table_type = 'view' ``` if you just want the view
33,233
<p>Imagine you homebrew a custom gui framework that <em>doesn't</em> use windows handles (compact framework, so please don't argue with "whys"). One of the main disadvantages of developing such a framework is that you lose compatability with the winform designer.</p> <p>So my question is to all of you who know a lot about VS customisation, would there be a clever mechanism by which one could incorperate the gui framework into the designer and get it to spit out your custom code instead of the standard windows stuff in the <code>InitialiseComponent()</code> method?</p>
[ { "answer_id": 33266, "author": "Jas", "author_id": 777, "author_profile": "https://Stackoverflow.com/users/777", "pm_score": 0, "selected": false, "text": "<pre><code>select * from information_schema.tables\nwhere table_type = 'view'\n</code></pre>\n" }, { "answer_id": 33285, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 4, "selected": true, "text": "<pre><code>select * from information_schema.tables\nWHERE OBJECTPROPERTY(OBJECT_ID(table_name),'IsMSShipped') =0 \n</code></pre>\n\n<p>Will exclude dt_properties and system tables</p>\n\n<p>add </p>\n\n<pre><code>where table_type = 'view' \n</code></pre>\n\n<p>if you just want the view</p>\n" }, { "answer_id": 33302, "author": "karlgrz", "author_id": 318, "author_profile": "https://Stackoverflow.com/users/318", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT\n *\nFROM\n sysobjects\nWHERE\n xtype = 'V' AND\n type = 'V' AND\n category = 0\n</code></pre>\n\n<p>Here is a list of the possible values for <strong>xtype</strong>:</p>\n\n<ul>\n<li>C = CHECK constraint</li>\n<li>D = Default or DEFAULT constraint</li>\n<li>F = FOREIGN KEY constraint</li>\n<li>L = Log</li>\n<li>P = Stored procedure</li>\n<li>PK = PRIMARY KEY constraint (type is K)</li>\n<li>RF = Replication filter stored procedure</li>\n<li>S = System table</li>\n<li>TR = Trigger</li>\n<li>U = User table</li>\n<li>UQ = UNIQUE constraint (type is K)</li>\n<li>V = View</li>\n<li>X = Extended stored procedure</li>\n</ul>\n\n<p>Here are the possible values for <strong>type</strong>:</p>\n\n<ul>\n<li>C = CHECK constraint</li>\n<li>D = Default or DEFAULT constraint</li>\n<li>F = FOREIGN KEY constraint</li>\n<li>FN = Scalar function</li>\n<li>IF = Inlined table-function</li>\n<li>K = PRIMARY KEY or UNIQUE constraint</li>\n<li>L = Log</li>\n<li>P = Stored procedure</li>\n<li>R = Rule</li>\n<li>RF = Replication filter stored procedure</li>\n<li>S = System table</li>\n<li>TF = Table function</li>\n<li>TR = Trigger</li>\n<li>U = User table</li>\n<li>V = View</li>\n<li>X = Extended stored procedure</li>\n</ul>\n\n<p>Finally, the <strong>category</strong> field looks like it groups based on different types of objects. After analyzing the return resultset, the system views look to have a <strong>category</strong> = 2, whereas all of the user views have a <strong>category</strong> = 0. Hope this helps.</p>\n\n<p>For more information, visit <a href=\"http://msdn.microsoft.com/en-us/library/aa260447(SQL.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa260447(SQL.80).aspx</a></p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143/" ]
Imagine you homebrew a custom gui framework that *doesn't* use windows handles (compact framework, so please don't argue with "whys"). One of the main disadvantages of developing such a framework is that you lose compatability with the winform designer. So my question is to all of you who know a lot about VS customisation, would there be a clever mechanism by which one could incorperate the gui framework into the designer and get it to spit out your custom code instead of the standard windows stuff in the `InitialiseComponent()` method?
``` select * from information_schema.tables WHERE OBJECTPROPERTY(OBJECT_ID(table_name),'IsMSShipped') =0 ``` Will exclude dt\_properties and system tables add ``` where table_type = 'view' ``` if you just want the view
33,250
<p>In one of my applications, I am querying active directory to get a list of all users below a given user (using the "Direct Reports" thing). So basically, given the name of the person, it is looked up in AD, then the Direct Reports are read. But then for every direct report, the tool needs to check the direct reports of the direct reports. Or, more abstract: The Tool will use a person as the root of the tree and then walk down the complete tree to get the names of all the leaves (can be several hundred)</p> <p>Now, my concern is obviously performance, as this needs to be done quite a few times. My idea is to manually cache that (essentially just put all the names in a long string and store that somewhere and update it once a day).</p> <p>But I just wonder if there is a more elegant way to first get the information and then cache it, possibly using something in the System.DirectoryServices Namespace?</p>
[ { "answer_id": 33299, "author": "kemiller2002", "author_id": 1942, "author_profile": "https://Stackoverflow.com/users/1942", "pm_score": 2, "selected": false, "text": "<p>Active Directory is pretty efficient at storing information and the retrieval shouldn't be that much of a performance hit. If you are really intent on storing the names, you'll probably want to store them in some sort of a tree stucture, so you can see the relationships of all the people. Depending on how the number of people, you might as well pull all the information you need daily and then query all the requests against your cached copy. </p>\n" }, { "answer_id": 36730, "author": "Phil Bennett", "author_id": 2995, "author_profile": "https://Stackoverflow.com/users/2995", "pm_score": 2, "selected": false, "text": "<p>AD does that sort of caching for you so don't worry about it unless performance becomes a problem. I have software doing this sort of thing all day long running on a corporate intranet that takes thousands of hits per hour and have never had to tune performance in this area. </p>\n" }, { "answer_id": 39091, "author": "Erick Sgarbi", "author_id": 4171, "author_profile": "https://Stackoverflow.com/users/4171", "pm_score": 3, "selected": true, "text": "<p>In order to take control over the properties that you want to be cached you can call 'RefreshCache()' passing the properties that you want to hang around:</p>\n\n<pre class=\"lang-c# prettyprint-override\"><code>System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry(); \n\n// Push the property values from AD back to cache.\n\nentry.RefreshCache(new string[] {\"cn\", \"www\" });\n</code></pre>\n" }, { "answer_id": 39099, "author": "Guy", "author_id": 993, "author_profile": "https://Stackoverflow.com/users/993", "pm_score": 2, "selected": false, "text": "<p>Depends on how up to date you want the information to be. If you <strong>must have</strong> the very latest data in your report then querying directly from AD is reasonable. And I agree that AD is quite robust, a typical dedicated AD server is actually very lightly utilised in normal day to day operations <em>but best to check with your IT department / support person.</em></p>\n\n<p>An alternative is to have a daily script to dump the AD data into a CSV file and/or import it into a SQL database. (Oracle has a SELECT CONNECT BY feature that can automatically create multi-level hierarchies within a result set. MSSQL can do a similar thing with a bit of recursion IIRC).</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
In one of my applications, I am querying active directory to get a list of all users below a given user (using the "Direct Reports" thing). So basically, given the name of the person, it is looked up in AD, then the Direct Reports are read. But then for every direct report, the tool needs to check the direct reports of the direct reports. Or, more abstract: The Tool will use a person as the root of the tree and then walk down the complete tree to get the names of all the leaves (can be several hundred) Now, my concern is obviously performance, as this needs to be done quite a few times. My idea is to manually cache that (essentially just put all the names in a long string and store that somewhere and update it once a day). But I just wonder if there is a more elegant way to first get the information and then cache it, possibly using something in the System.DirectoryServices Namespace?
In order to take control over the properties that you want to be cached you can call 'RefreshCache()' passing the properties that you want to hang around: ```c# System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry(); // Push the property values from AD back to cache. entry.RefreshCache(new string[] {"cn", "www" }); ```
33,252
<p>As a temporary stopgap until all the designers are in place we are currently hand-cranking a whole bunch of xml configuration files at work. One of the issues with this is file-versioning because people forget to update version numbers when updating the files (which is to be expected as humans generally suck at perfection).</p> <p>Therefore I figure that as we store the files in Sharepoint I should be able to write a script to pull the files down from Sharepoint, get the version number and automatically enter/update the version number from Sharepoint into the file. This means when someone wants the "latest" files they can run the script and get the latest files with the version numbers correct (there is slightly more to it than this so the reason for using the script isn't just the benefit of auto-versioning).</p> <p>Does anyone know how to get the files + version numbers from Sharepoint?</p>
[ { "answer_id": 33299, "author": "kemiller2002", "author_id": 1942, "author_profile": "https://Stackoverflow.com/users/1942", "pm_score": 2, "selected": false, "text": "<p>Active Directory is pretty efficient at storing information and the retrieval shouldn't be that much of a performance hit. If you are really intent on storing the names, you'll probably want to store them in some sort of a tree stucture, so you can see the relationships of all the people. Depending on how the number of people, you might as well pull all the information you need daily and then query all the requests against your cached copy. </p>\n" }, { "answer_id": 36730, "author": "Phil Bennett", "author_id": 2995, "author_profile": "https://Stackoverflow.com/users/2995", "pm_score": 2, "selected": false, "text": "<p>AD does that sort of caching for you so don't worry about it unless performance becomes a problem. I have software doing this sort of thing all day long running on a corporate intranet that takes thousands of hits per hour and have never had to tune performance in this area. </p>\n" }, { "answer_id": 39091, "author": "Erick Sgarbi", "author_id": 4171, "author_profile": "https://Stackoverflow.com/users/4171", "pm_score": 3, "selected": true, "text": "<p>In order to take control over the properties that you want to be cached you can call 'RefreshCache()' passing the properties that you want to hang around:</p>\n\n<pre class=\"lang-c# prettyprint-override\"><code>System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry(); \n\n// Push the property values from AD back to cache.\n\nentry.RefreshCache(new string[] {\"cn\", \"www\" });\n</code></pre>\n" }, { "answer_id": 39099, "author": "Guy", "author_id": 993, "author_profile": "https://Stackoverflow.com/users/993", "pm_score": 2, "selected": false, "text": "<p>Depends on how up to date you want the information to be. If you <strong>must have</strong> the very latest data in your report then querying directly from AD is reasonable. And I agree that AD is quite robust, a typical dedicated AD server is actually very lightly utilised in normal day to day operations <em>but best to check with your IT department / support person.</em></p>\n\n<p>An alternative is to have a daily script to dump the AD data into a CSV file and/or import it into a SQL database. (Oracle has a SELECT CONNECT BY feature that can automatically create multi-level hierarchies within a result set. MSSQL can do a similar thing with a bit of recursion IIRC).</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143/" ]
As a temporary stopgap until all the designers are in place we are currently hand-cranking a whole bunch of xml configuration files at work. One of the issues with this is file-versioning because people forget to update version numbers when updating the files (which is to be expected as humans generally suck at perfection). Therefore I figure that as we store the files in Sharepoint I should be able to write a script to pull the files down from Sharepoint, get the version number and automatically enter/update the version number from Sharepoint into the file. This means when someone wants the "latest" files they can run the script and get the latest files with the version numbers correct (there is slightly more to it than this so the reason for using the script isn't just the benefit of auto-versioning). Does anyone know how to get the files + version numbers from Sharepoint?
In order to take control over the properties that you want to be cached you can call 'RefreshCache()' passing the properties that you want to hang around: ```c# System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry(); // Push the property values from AD back to cache. entry.RefreshCache(new string[] {"cn", "www" }); ```
33,262
<p>I have a complete XML document in a string and would like a <code>Document</code> object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5)</p> <p><strong>Solution</strong> Thanks to <a href="https://stackoverflow.com/users/1322/matt-mcminn">Matt McMinn</a>, I have settled on this implementation. It has the right level of input flexibility and exception granularity for me. (It's good to know if the error came from malformed XML - <code>SAXException</code> - or just bad IO - <code>IOException</code>.)</p> <pre><code>public static org.w3c.dom.Document loadXMLFrom(String xml) throws org.xml.sax.SAXException, java.io.IOException { return loadXMLFrom(new java.io.ByteArrayInputStream(xml.getBytes())); } public static org.w3c.dom.Document loadXMLFrom(java.io.InputStream is) throws org.xml.sax.SAXException, java.io.IOException { javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException ex) { } org.w3c.dom.Document doc = builder.parse(is); is.close(); return doc; } </code></pre>
[ { "answer_id": 33283, "author": "Matt McMinn", "author_id": 1322, "author_profile": "https://Stackoverflow.com/users/1322", "pm_score": 7, "selected": true, "text": "<p>This works for me in Java 1.5 - I stripped out specific exceptions for readability.</p>\n\n<pre><code>import javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.DocumentBuilder;\nimport org.w3c.dom.Document;\nimport java.io.ByteArrayInputStream;\n\npublic Document loadXMLFromString(String xml) throws Exception\n{\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n\n factory.setNamespaceAware(true);\n DocumentBuilder builder = factory.newDocumentBuilder();\n\n return builder.parse(new ByteArrayInputStream(xml.getBytes()));\n}\n</code></pre>\n" }, { "answer_id": 33618, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 7, "selected": false, "text": "<p>Whoa there! </p>\n\n<p>There's a potentially serious problem with this code, because it ignores the character encoding specified in the <code>String</code> (which is UTF-8 by default). When you call <code>String.getBytes()</code> the platform default encoding is used to encode Unicode characters to bytes. So, the parser may think it's getting UTF-8 data when in fact it's getting EBCDIC or something&hellip; not pretty!</p>\n\n<p>Instead, use the parse method that takes an InputSource, which can be constructed with a Reader, like this:</p>\n\n<pre><code>import java.io.StringReader;\nimport org.xml.sax.InputSource;\n…\n return builder.parse(new InputSource(new StringReader(xml)));\n</code></pre>\n\n<p>It may not seem like a big deal, but ignorance of character encoding issues leads to insidious code rot akin to y2k.</p>\n" }, { "answer_id": 46121, "author": "shsteimer", "author_id": 292, "author_profile": "https://Stackoverflow.com/users/292", "pm_score": 3, "selected": false, "text": "<p>Just had a similar problem, except i needed a NodeList and not a Document, here's what I came up with. It's mostly the same solution as before, augmented to get the root element down as a NodeList and using erickson's suggestion of using an InputSource instead for character encoding issues.</p>\n\n<pre><code>private String DOC_ROOT=\"root\";\nString xml=getXmlString();\nDocument xmlDoc=loadXMLFrom(xml);\nElement template=xmlDoc.getDocumentElement();\nNodeList nodes=xmlDoc.getElementsByTagName(DOC_ROOT);\n\npublic static Document loadXMLFrom(String xml) throws Exception {\n InputSource is= new InputSource(new StringReader(xml));\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n factory.setNamespaceAware(true);\n DocumentBuilder builder = null;\n builder = factory.newDocumentBuilder();\n Document doc = builder.parse(is);\n return doc;\n }\n</code></pre>\n" }, { "answer_id": 25137190, "author": "Xavier Dury", "author_id": 599011, "author_profile": "https://Stackoverflow.com/users/599011", "pm_score": 2, "selected": false, "text": "<p>To manipulate XML in Java, I always tend to use the Transformer API:</p>\n\n<pre><code>import javax.xml.transform.Source;\nimport javax.xml.transform.TransformerException;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMResult;\nimport javax.xml.transform.stream.StreamSource;\n\npublic static Document loadXMLFrom(String xml) throws TransformerException {\n Source source = new StreamSource(new StringReader(xml));\n DOMResult result = new DOMResult();\n TransformerFactory.newInstance().newTransformer().transform(source , result);\n return (Document) result.getNode();\n} \n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
I have a complete XML document in a string and would like a `Document` object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5) **Solution** Thanks to [Matt McMinn](https://stackoverflow.com/users/1322/matt-mcminn), I have settled on this implementation. It has the right level of input flexibility and exception granularity for me. (It's good to know if the error came from malformed XML - `SAXException` - or just bad IO - `IOException`.) ``` public static org.w3c.dom.Document loadXMLFrom(String xml) throws org.xml.sax.SAXException, java.io.IOException { return loadXMLFrom(new java.io.ByteArrayInputStream(xml.getBytes())); } public static org.w3c.dom.Document loadXMLFrom(java.io.InputStream is) throws org.xml.sax.SAXException, java.io.IOException { javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException ex) { } org.w3c.dom.Document doc = builder.parse(is); is.close(); return doc; } ```
This works for me in Java 1.5 - I stripped out specific exceptions for readability. ``` import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import java.io.ByteArrayInputStream; public Document loadXMLFromString(String xml) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new ByteArrayInputStream(xml.getBytes())); } ```
33,263
<p>I'm using the <a href="http://msdn.microsoft.com/en-us/library/ms178329.aspx" rel="nofollow noreferrer">ASP.NET Login Controls</a> and <a href="http://msdn.microsoft.com/en-us/library/aa480476.aspx" rel="nofollow noreferrer">Forms Authentication</a> for membership/credentials for an ASP.NET web application.</p> <p>I've got two roles:</p> <ul> <li>Users</li> <li>Administrators</li> </ul> <p>I want pages to be viewable by four different groups:</p> <ul> <li>Everyone <em>(Default, Help)</em></li> <li>Anonymous <em>(CreateUser, Login, PasswordRecovery)</em></li> <li>Users <em>(ChangePassword, DataEntry)</em></li> <li>Administrators <em>(Report)</em></li> </ul> <p>Expanding on the example in the <a href="http://www.asp.net/learn/videos/video-45.aspx" rel="nofollow noreferrer">ASP.NET HOW DO I Video Series: Membership and Roles</a>, I've put those page files into such folders:</p> <p><img src="https://i.stack.imgur.com/Ps7sm.gif" alt="Visual Studio Solution Explorer"></p> <p>And I used the ASP.NET Web Site Administration Tool to set up access rules for each folder.</p> <p>It works but seems kludgy to me and it creates issues <a href="https://stackoverflow.com/questions/33089/how-do-i-use-aspnet-login-controls-when-my-loginaspx-is-not-at-the-root-of-my-a">when Login.aspx is not at the root</a> and with the <a href="https://stackoverflow.com/questions/33166/how-do-i-keep-my-loginaspx-pages-returnurl-parameter-from-overriding-my-aspnet">ReturnUrl parameter</a> of Login.aspx.</p> <p>Is there a better way to do this? Is there perhaps a simple way I can set permissions at the page level rather than at the folder level?</p>
[ { "answer_id": 33283, "author": "Matt McMinn", "author_id": 1322, "author_profile": "https://Stackoverflow.com/users/1322", "pm_score": 7, "selected": true, "text": "<p>This works for me in Java 1.5 - I stripped out specific exceptions for readability.</p>\n\n<pre><code>import javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.DocumentBuilder;\nimport org.w3c.dom.Document;\nimport java.io.ByteArrayInputStream;\n\npublic Document loadXMLFromString(String xml) throws Exception\n{\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n\n factory.setNamespaceAware(true);\n DocumentBuilder builder = factory.newDocumentBuilder();\n\n return builder.parse(new ByteArrayInputStream(xml.getBytes()));\n}\n</code></pre>\n" }, { "answer_id": 33618, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 7, "selected": false, "text": "<p>Whoa there! </p>\n\n<p>There's a potentially serious problem with this code, because it ignores the character encoding specified in the <code>String</code> (which is UTF-8 by default). When you call <code>String.getBytes()</code> the platform default encoding is used to encode Unicode characters to bytes. So, the parser may think it's getting UTF-8 data when in fact it's getting EBCDIC or something&hellip; not pretty!</p>\n\n<p>Instead, use the parse method that takes an InputSource, which can be constructed with a Reader, like this:</p>\n\n<pre><code>import java.io.StringReader;\nimport org.xml.sax.InputSource;\n…\n return builder.parse(new InputSource(new StringReader(xml)));\n</code></pre>\n\n<p>It may not seem like a big deal, but ignorance of character encoding issues leads to insidious code rot akin to y2k.</p>\n" }, { "answer_id": 46121, "author": "shsteimer", "author_id": 292, "author_profile": "https://Stackoverflow.com/users/292", "pm_score": 3, "selected": false, "text": "<p>Just had a similar problem, except i needed a NodeList and not a Document, here's what I came up with. It's mostly the same solution as before, augmented to get the root element down as a NodeList and using erickson's suggestion of using an InputSource instead for character encoding issues.</p>\n\n<pre><code>private String DOC_ROOT=\"root\";\nString xml=getXmlString();\nDocument xmlDoc=loadXMLFrom(xml);\nElement template=xmlDoc.getDocumentElement();\nNodeList nodes=xmlDoc.getElementsByTagName(DOC_ROOT);\n\npublic static Document loadXMLFrom(String xml) throws Exception {\n InputSource is= new InputSource(new StringReader(xml));\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n factory.setNamespaceAware(true);\n DocumentBuilder builder = null;\n builder = factory.newDocumentBuilder();\n Document doc = builder.parse(is);\n return doc;\n }\n</code></pre>\n" }, { "answer_id": 25137190, "author": "Xavier Dury", "author_id": 599011, "author_profile": "https://Stackoverflow.com/users/599011", "pm_score": 2, "selected": false, "text": "<p>To manipulate XML in Java, I always tend to use the Transformer API:</p>\n\n<pre><code>import javax.xml.transform.Source;\nimport javax.xml.transform.TransformerException;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMResult;\nimport javax.xml.transform.stream.StreamSource;\n\npublic static Document loadXMLFrom(String xml) throws TransformerException {\n Source source = new StreamSource(new StringReader(xml));\n DOMResult result = new DOMResult();\n TransformerFactory.newInstance().newTransformer().transform(source , result);\n return (Document) result.getNode();\n} \n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
I'm using the [ASP.NET Login Controls](http://msdn.microsoft.com/en-us/library/ms178329.aspx) and [Forms Authentication](http://msdn.microsoft.com/en-us/library/aa480476.aspx) for membership/credentials for an ASP.NET web application. I've got two roles: * Users * Administrators I want pages to be viewable by four different groups: * Everyone *(Default, Help)* * Anonymous *(CreateUser, Login, PasswordRecovery)* * Users *(ChangePassword, DataEntry)* * Administrators *(Report)* Expanding on the example in the [ASP.NET HOW DO I Video Series: Membership and Roles](http://www.asp.net/learn/videos/video-45.aspx), I've put those page files into such folders: ![Visual Studio Solution Explorer](https://i.stack.imgur.com/Ps7sm.gif) And I used the ASP.NET Web Site Administration Tool to set up access rules for each folder. It works but seems kludgy to me and it creates issues [when Login.aspx is not at the root](https://stackoverflow.com/questions/33089/how-do-i-use-aspnet-login-controls-when-my-loginaspx-is-not-at-the-root-of-my-a) and with the [ReturnUrl parameter](https://stackoverflow.com/questions/33166/how-do-i-keep-my-loginaspx-pages-returnurl-parameter-from-overriding-my-aspnet) of Login.aspx. Is there a better way to do this? Is there perhaps a simple way I can set permissions at the page level rather than at the folder level?
This works for me in Java 1.5 - I stripped out specific exceptions for readability. ``` import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import java.io.ByteArrayInputStream; public Document loadXMLFromString(String xml) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new ByteArrayInputStream(xml.getBytes())); } ```
33,265
<p>There are two weird operators in C#:</p> <ul> <li>the <a href="http://msdn.microsoft.com/en-us/library/6x6y6z4d.aspx" rel="noreferrer">true operator</a></li> <li>the <a href="http://msdn.microsoft.com/en-us/library/6292hy1k.aspx" rel="noreferrer">false operator</a></li> </ul> <p>If I understand this right these operators can be used in types which I want to use instead of a boolean expression and where I don't want to provide an implicit conversion to bool.</p> <p>Let's say I have a following class:</p> <pre><code> public class MyType { public readonly int Value; public MyType(int value) { Value = value; } public static bool operator true (MyType mt) { return mt.Value &gt; 0; } public static bool operator false (MyType mt) { return mt.Value &lt; 0; } } </code></pre> <p>So I can write the following code:</p> <pre><code> MyType mTrue = new MyType(100); MyType mFalse = new MyType(-100); MyType mDontKnow = new MyType(0); if (mTrue) { // Do something. } while (mFalse) { // Do something else. } do { // Another code comes here. } while (mDontKnow) </code></pre> <p>However for all the examples above only the true operator is executed. So what's the false operator in C# good for?</p> <p><em>Note: More examples can be found <a href="http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/truefalseoperatorforComplex.htm" rel="noreferrer">here</a>, <a href="http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/OverloadtrueandfalseforTwoDimension.htm" rel="noreferrer">here</a> and <a href="http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/trueandfalseoperator.htm" rel="noreferrer">here</a>.</em></p>
[ { "answer_id": 33315, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 4, "selected": false, "text": "<p>The page you link to <a href=\"http://msdn.microsoft.com/en-us/library/6x6y6z4d.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/6x6y6z4d.aspx</a> says what they were for, which was a way of handling nullable bools before nullable value types were introduced.</p>\n\n<p>I'd guess nowadays they're good for the same sort of stuff as ArrayList - i.e. absolutely nothing.</p>\n" }, { "answer_id": 33337, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 2, "selected": false, "text": "<p>It appears from the MSDN article you linked to it was provided to allow for nullable boolean types prior to the Nullable (i.e. int?, bool?, etc.) type being introducted into the language in C#2. Thus you would store an internal value indicating whether the value is true or false or null, i.e. in your example >0 for true, &lt;0 for false and ==0 for null, and then you'd get SQL-style null semantics. You would also have to implement a .IsNull method or property in order that nullity could be checked explicitly. </p>\n\n<p>Comparing to SQL, imagine a table Table with 3 rows with value Foo set to true, 3 rows with value Foo set to false and 3 rows with value Foo set to null.</p>\n\n<pre><code>SELECT COUNT(*) FROM Table WHERE Foo = TRUE OR Foo = FALSE\n6\n</code></pre>\n\n<p>In order to count all rows you'd have to do the following:-</p>\n\n<pre><code>SELECT COUNT(*) FROM Table WHERE Foo = TRUE OR Foo = FALSE OR Foo IS NULL\n9\n</code></pre>\n\n<p>This 'IS NULL' syntax would have equivilent code in your class as .IsNull().</p>\n\n<p>LINQ makes the comparison to C# even clearer:-</p>\n\n<pre><code>int totalCount = (from s in MyTypeEnumerable\n where s || !s\n select s).Count();\n</code></pre>\n\n<p>Imagining that MyTypeEnumberable has exactly the same contents of the database, i.e. 3 values equal to true, 3 values equal to false and 3 values equal to null. In this case totalCount would evaluate to 6 in this case. However, if we re-wrote the code as:-</p>\n\n<pre><code>int totalCount = (from s in MyTypeEnumerable\n where s || !s || s.IsNull()\n select s).Count();\n</code></pre>\n\n<p>Then totalCount would evaluate to 9.</p>\n\n<p>The DBNull example given in the linked MSDN article on the false operator demonstrates a class in the BCL which has this exact behaviour.</p>\n\n<p>In effect the conclusion is you shouldn't use this unless you're completely sure you want this type of behaviour, it's better to just use the far simpler nullable syntax!!</p>\n\n<p><strong>Update:</strong> I just noticed you need to manually override the logic operators !, || and &amp;&amp; to make this work properly. I believe the false operator feeds into these logical operators, i.e. indicating truth, falsity or 'otherwise'. As noted in another comment !x won't work off the bat; you have to overload !. Weirdness!</p>\n" }, { "answer_id": 33339, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 3, "selected": false, "text": "<p>AFAIK, it would be used in a test for false, such as when the <code>&amp;&amp;</code> operator comes into play. Remember, &amp;&amp; short-circuits, so in the expression</p>\n\n<pre><code>if ( mFalse &amp;&amp; mTrue) \n{\n // ... something\n}\n</code></pre>\n\n<p><code>mFalse.false()</code> is called, and upon returning <code>true</code> the expression is reduced to a call to 'mFalse.true()' (which should then return <code>false</code>, or things will get weird).</p>\n\n<p>Note that you must implement the <code>&amp;</code> operator in order for that expression to compile, since it's used if <code>mFalse.false()</code> returns <code>false</code>.</p>\n" }, { "answer_id": 33391, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 7, "selected": true, "text": "<p>You can use it to override the <code>&amp;&amp;</code> and <code>||</code> operators.</p>\n\n<p>The <code>&amp;&amp;</code> and <code>||</code> operators can't be overridden, but if you override <code>|</code>, <code>&amp;</code>, <code>true</code> and <code>false</code> in exactly the right way the compiler will call <code>|</code> and <code>&amp;</code> when you write <code>||</code> and <code>&amp;&amp;</code>.</p>\n\n<p>For example, look at this code (from <a href=\"http://ayende.com/blog/1574/nhibernate-criteria-api-operator-overloading\" rel=\"noreferrer\">http://ayende.com/blog/1574/nhibernate-criteria-api-operator-overloading</a> - where I found out about this trick; <a href=\"http://web.archive.org/web/20080613013350/http://www.ayende.com/Blog/archive/2006/08/04/7381.aspx\" rel=\"noreferrer\">archived version</a> by @BiggsTRC):</p>\n\n<pre><code>public static AbstractCriterion operator &amp;(AbstractCriterion lhs, AbstractCriterion rhs)\n{\n return new AndExpression(lhs, rhs);\n}\n\npublic static AbstractCriterion operator |(AbstractCriterion lhs, AbstractCriterion rhs)\n{\n return new OrExpression(lhs, rhs);\n}\n\npublic static bool operator false(AbstractCriterion criteria)\n{\n return false;\n}\npublic static bool operator true(AbstractCriterion criteria)\n{\n return false;\n}\n</code></pre>\n\n<p>This is obviously a side effect and not the way it's intended to be used, but it is useful.</p>\n" }, { "answer_id": 33437, "author": "Jakub Šturc", "author_id": 2361, "author_profile": "https://Stackoverflow.com/users/2361", "pm_score": 5, "selected": false, "text": "<p>Shog9 and Nir:\nthanks for your answers. Those answers pointed me to <a href=\"http://steve.emxsoftware.com/NET/Overloading+the++and++operators\" rel=\"noreferrer\">Steve Eichert article</a> and it pointed me to <a href=\"http://msdn.microsoft.com/en-us/library/aa691312.aspx\" rel=\"noreferrer\">msdn</a>:</p>\n\n<blockquote>\n <p>The operation x &amp;&amp; y is evaluated as T.false(x) ? x : T.&amp;(x, y), where T.false(x) is an invocation of the operator false declared in T, and T.&amp;(x, y) is an invocation of the selected operator &amp;. In other words, x is first evaluated and operator false is invoked on the result to determine if x is definitely false. Then, if x is definitely false, the result of the operation is the value previously computed for x. Otherwise, y is evaluated, and the selected operator &amp; is invoked on the value previously computed for x and the value computed for y to produce the result of the operation.</p>\n</blockquote>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361/" ]
There are two weird operators in C#: * the [true operator](http://msdn.microsoft.com/en-us/library/6x6y6z4d.aspx) * the [false operator](http://msdn.microsoft.com/en-us/library/6292hy1k.aspx) If I understand this right these operators can be used in types which I want to use instead of a boolean expression and where I don't want to provide an implicit conversion to bool. Let's say I have a following class: ``` public class MyType { public readonly int Value; public MyType(int value) { Value = value; } public static bool operator true (MyType mt) { return mt.Value > 0; } public static bool operator false (MyType mt) { return mt.Value < 0; } } ``` So I can write the following code: ``` MyType mTrue = new MyType(100); MyType mFalse = new MyType(-100); MyType mDontKnow = new MyType(0); if (mTrue) { // Do something. } while (mFalse) { // Do something else. } do { // Another code comes here. } while (mDontKnow) ``` However for all the examples above only the true operator is executed. So what's the false operator in C# good for? *Note: More examples can be found [here](http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/truefalseoperatorforComplex.htm), [here](http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/OverloadtrueandfalseforTwoDimension.htm) and [here](http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/trueandfalseoperator.htm).*
You can use it to override the `&&` and `||` operators. The `&&` and `||` operators can't be overridden, but if you override `|`, `&`, `true` and `false` in exactly the right way the compiler will call `|` and `&` when you write `||` and `&&`. For example, look at this code (from <http://ayende.com/blog/1574/nhibernate-criteria-api-operator-overloading> - where I found out about this trick; [archived version](http://web.archive.org/web/20080613013350/http://www.ayende.com/Blog/archive/2006/08/04/7381.aspx) by @BiggsTRC): ``` public static AbstractCriterion operator &(AbstractCriterion lhs, AbstractCriterion rhs) { return new AndExpression(lhs, rhs); } public static AbstractCriterion operator |(AbstractCriterion lhs, AbstractCriterion rhs) { return new OrExpression(lhs, rhs); } public static bool operator false(AbstractCriterion criteria) { return false; } public static bool operator true(AbstractCriterion criteria) { return false; } ``` This is obviously a side effect and not the way it's intended to be used, but it is useful.
33,301
<p>I have a JavaScript method that I need to run on one of my pages, in particular, the <code>onresize</code> event. </p> <p>However, I don't see how I can set that event from my content page. I wish I could just put it on my master page, but I don't have the need for the method to be called on all pages that use that master page.</p> <p>Any help would be appreciated.</p>
[ { "answer_id": 33440, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 3, "selected": true, "text": "<p>Place the following in your content page:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n\n// here is a cross-browser compatible way of connecting \n// handlers to events, in case you don't have one\nfunction attachEventHandler(element, eventToHandle, eventHandler) {\n if(element.attachEvent) {\n element.attachEvent(eventToHandle, eventHandler);\n } else if(element.addEventListener) {\n element.addEventListener(eventToHandle.replace(\"on\", \"\"), eventHandler, false);\n } else {\n element[eventToHandle] = eventHandler;\n }\n}\n\nattachEventHandler(window, \"onresize\", function() {\n // the code you want to run when the browser is resized\n});\n\n&lt;/script&gt;\n</code></pre>\n\n<hr>\n\n<p>That code should give you the basic idea of what you need to do. Hopefully you are using a library that already has code to help you write up event handlers and such.</p>\n" }, { "answer_id": 33603, "author": "Adhip Gupta", "author_id": 384, "author_profile": "https://Stackoverflow.com/users/384", "pm_score": 0, "selected": false, "text": "<p>How about use code like the following in your Content Page (C#)?</p>\n\n<pre><code>Page.ClientScript.RegisterStartupScript(this.GetType(), \"resizeMyPage\", \"window.onresize=function(){ resizeMyPage();}\", true);\n</code></pre>\n\n<p>Thus, you could have a <code>resizeMyPage</code> function defined somewhere in the Javascript and it would be run whenever the browser is resized!</p>\n" }, { "answer_id": 887139, "author": "Gordon Thompson", "author_id": 21299, "author_profile": "https://Stackoverflow.com/users/21299", "pm_score": 0, "selected": false, "text": "<p>I had the same problem and have come across this post :</p>\n\n<p><a href=\"http://blog.stchur.com/2006/09/06/the-ie-resize-bug-revisited/\" rel=\"nofollow noreferrer\">IE Resize Bug Revisited</a></p>\n\n<p>The above code works but IE has a problem where the onresize is triggered when the body tag changes shape. This blog gives an alternate method which works well</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1226/" ]
I have a JavaScript method that I need to run on one of my pages, in particular, the `onresize` event. However, I don't see how I can set that event from my content page. I wish I could just put it on my master page, but I don't have the need for the method to be called on all pages that use that master page. Any help would be appreciated.
Place the following in your content page: ``` <script type="text/javascript"> // here is a cross-browser compatible way of connecting // handlers to events, in case you don't have one function attachEventHandler(element, eventToHandle, eventHandler) { if(element.attachEvent) { element.attachEvent(eventToHandle, eventHandler); } else if(element.addEventListener) { element.addEventListener(eventToHandle.replace("on", ""), eventHandler, false); } else { element[eventToHandle] = eventHandler; } } attachEventHandler(window, "onresize", function() { // the code you want to run when the browser is resized }); </script> ``` --- That code should give you the basic idea of what you need to do. Hopefully you are using a library that already has code to help you write up event handlers and such.
33,334
<p>In this <a href="https://stackoverflow.com/questions/32877/how-to-remove-vsdebuggercausalitydata-data-from-soap-message">question</a> the answer was to flip on a switch that is picked up by the debugger disabling the extraneous header that was causing the problem. The Microsoft help implies these switched are user generated and does not list any switches.</p> <pre><code>&lt;configuration&gt; &lt;system.diagnostics&gt; &lt;switches&gt; &lt;add name="Remote.Disable" value="1" /&gt; &lt;/switches&gt; &lt;/system.diagnostics&gt; &lt;/configuration&gt; </code></pre> <p>What I would like to know is where the value "Remote.Disable" comes from and how find out what other things can be switched on or off. Currently it is just some config magic, and I don't like magic.</p>
[ { "answer_id": 33677, "author": "Kevin Dente", "author_id": 9, "author_profile": "https://Stackoverflow.com/users/9", "pm_score": 1, "selected": false, "text": "<p>You can use Reflector to search for uses of the Switch class and its subclasss (BooleanSwitch, TraceSwitch, etc). The various switches are hardcoded by name, so AFAIK there's no master list somewhere. </p>\n" }, { "answer_id": 33683, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 3, "selected": true, "text": "<p>As you suspected, Remote.Disable stops the app from attaching debug info to remote requests. It's defined inside the .NET framework methods that make the SOAP request.</p>\n\n<p>The basic situation is that these switches can be defined anywhere in code, you just need to create a new System.Diagnostics.BooleanSwitch with the name given and the config file can control them.</p>\n\n<p>This particular one is defined in System.ComponentModel.CompModSwitches.DisableRemoteDebugging:</p>\n\n<pre><code>public static BooleanSwitch DisableRemoteDebugging\n{\n get\n {\n if (disableRemoteDebugging == null)\n {\n disableRemoteDebugging = new BooleanSwitch(\"Remote.Disable\", \"Disable remote debugging for web methods.\");\n }\n return disableRemoteDebugging;\n }\n}\n</code></pre>\n\n<p>In your case it's probably being called from <em>System.Web.Services.Protocols.RemoteDebugger.IsClientCallOutEnabled()</em>, which is being called by <em>System.Web.Services.Protocols.WebClientProtocol.NotifyClientCallOut</em> which is in turn being called by the Invoke method of <em>System.Web.Services.Protocols.SoapHttpClientProtocol</em></p>\n\n<p>Unfortunately, to my knowledge, short of decompiling the framework &amp; seaching for </p>\n\n<pre><code>new BooleanSwitch\n</code></pre>\n\n<p>or any of the other inheritors of the <em>System.Diagnostics.Switch</em> class,\nthere's no easy way to know what switches are defined. It seems to be a case of searching msdn/google/stack overflow for the specific case</p>\n\n<p>In this case I just used Reflector &amp; searched for the Remote.Disable string</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1834/" ]
In this [question](https://stackoverflow.com/questions/32877/how-to-remove-vsdebuggercausalitydata-data-from-soap-message) the answer was to flip on a switch that is picked up by the debugger disabling the extraneous header that was causing the problem. The Microsoft help implies these switched are user generated and does not list any switches. ``` <configuration> <system.diagnostics> <switches> <add name="Remote.Disable" value="1" /> </switches> </system.diagnostics> </configuration> ``` What I would like to know is where the value "Remote.Disable" comes from and how find out what other things can be switched on or off. Currently it is just some config magic, and I don't like magic.
As you suspected, Remote.Disable stops the app from attaching debug info to remote requests. It's defined inside the .NET framework methods that make the SOAP request. The basic situation is that these switches can be defined anywhere in code, you just need to create a new System.Diagnostics.BooleanSwitch with the name given and the config file can control them. This particular one is defined in System.ComponentModel.CompModSwitches.DisableRemoteDebugging: ``` public static BooleanSwitch DisableRemoteDebugging { get { if (disableRemoteDebugging == null) { disableRemoteDebugging = new BooleanSwitch("Remote.Disable", "Disable remote debugging for web methods."); } return disableRemoteDebugging; } } ``` In your case it's probably being called from *System.Web.Services.Protocols.RemoteDebugger.IsClientCallOutEnabled()*, which is being called by *System.Web.Services.Protocols.WebClientProtocol.NotifyClientCallOut* which is in turn being called by the Invoke method of *System.Web.Services.Protocols.SoapHttpClientProtocol* Unfortunately, to my knowledge, short of decompiling the framework & seaching for ``` new BooleanSwitch ``` or any of the other inheritors of the *System.Diagnostics.Switch* class, there's no easy way to know what switches are defined. It seems to be a case of searching msdn/google/stack overflow for the specific case In this case I just used Reflector & searched for the Remote.Disable string
33,341
<p>Is there a way to hide radio buttons inside a RadioButtonList control programmatically?</p>
[ { "answer_id": 33353, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 0, "selected": false, "text": "<p>If you mean with JavaScript, and if I remember correctly, you've got to dig out the ClientID properties of each &lt;input type=\"radio\" ...&gt; tag.</p>\n" }, { "answer_id": 33357, "author": "RedWolves", "author_id": 648, "author_profile": "https://Stackoverflow.com/users/648", "pm_score": 0, "selected": false, "text": "<p>Have you tried to hide it through the itemdatabound event onload or do you need it to hide after it loads?</p>\n" }, { "answer_id": 33365, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 4, "selected": true, "text": "<p>Under the hood, you can access the attributes of the item and assign it a CSS style.</p>\n\n<p>So you should be able to then programmatically assign it by specifying:</p>\n\n<pre><code>RadioButtonList.Items(1).CssClass.Add(\"visibility\", \"hidden\")\n</code></pre>\n\n<p>and get the job done.</p>\n" }, { "answer_id": 33371, "author": "James Hall", "author_id": 514, "author_profile": "https://Stackoverflow.com/users/514", "pm_score": 0, "selected": false, "text": "<p>I haven't tested it, but I'd assume (for C#)</p>\n\n<pre><code>foreach(ListItem myItem in rbl.Items)\n{\nif(whatever condition)\nmyItem.Attributes.Add(\"visibility\",\"hidden\");\n\n}\n</code></pre>\n" }, { "answer_id": 319114, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Why not add and remove the radio buttons as needed?</p>\n\n<pre><code>RadioButtonList.Items.Add(\"Item Name\" or index);\nRadioButtonList.Items.Remove(\"Item Name\" or index);\n</code></pre>\n" }, { "answer_id": 1594238, "author": "BlueGreenWorld", "author_id": 193072, "author_profile": "https://Stackoverflow.com/users/193072", "pm_score": 1, "selected": false, "text": "<p>Try This:</p>\n\n<pre><code>RadioButtonList.Items.Remove(RadioButtonList.Items.FindByValue(\"3\"));\n</code></pre>\n" }, { "answer_id": 12178048, "author": "Airn5475", "author_id": 229897, "author_profile": "https://Stackoverflow.com/users/229897", "pm_score": 2, "selected": false, "text": "<p>Here's how you have to apply a style attribute to a listitem:</p>\n\n<p><code>RadioButtonList.Items(1).Attributes.Add(\"style\", \"display:none\")</code><br>\n- OR -<br>\n<code>RadioButtonList.Items(1).Attributes.Add(\"style\", \"visibility:hidden\")</code></p>\n" }, { "answer_id": 59497513, "author": "Sumate Mephokkij", "author_id": 10863080, "author_profile": "https://Stackoverflow.com/users/10863080", "pm_score": 0, "selected": false, "text": "<p>Another answer to not visibility inside a RadioButtonList.</p>\n\n<p>Try this code:</p>\n\n<pre><code>RadioButtonList.Items(1).CssClass.Add(\"display\", \"none\");\n</code></pre>\n\n<p>and get the job to no display RadioButtonList in layout.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/877/" ]
Is there a way to hide radio buttons inside a RadioButtonList control programmatically?
Under the hood, you can access the attributes of the item and assign it a CSS style. So you should be able to then programmatically assign it by specifying: ``` RadioButtonList.Items(1).CssClass.Add("visibility", "hidden") ``` and get the job done.
33,395
<p>I'm using the <a href="http://msdn.microsoft.com/en-us/library/ms178329.aspx" rel="nofollow noreferrer">ASP.NET Login Controls</a> and <a href="http://msdn.microsoft.com/en-us/library/aa480476.aspx" rel="nofollow noreferrer">Forms Authentication</a> for membership/credentials for an ASP.NET web application. And I'm using a <a href="http://msdn.microsoft.com/en-us/library/yy2ykkab.aspx" rel="nofollow noreferrer">site map</a> for site navigation.</p> <p>I have ASP.NET TreeView and Menu navigation controls populated using a SiteMapDataSource. But off-limits administrator-only pages are visible to non-administrator users.</p> <hr> <blockquote> <p><strong><a href="https://stackoverflow.com/users/1574/kevin-pang">Kevin Pang</a></strong> wrote:</p> <p>I'm not sure how this question is any different than your <a href="https://stackoverflow.com/questions/33263/how-do-i-best-handle-role-based-permissions-using-forms-authentication-on-my-as">other question</a>&hellip;</p> </blockquote> <p>The other question deals with assigning and maintaining permissions.</p> <p>This question just deals with presentation of navigation. Specifically TreeView and Menu controls with sitemap data sources.</p> <pre><code>&lt;asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" /&gt; &lt;asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" ShowStartingNode="False" /&gt; </code></pre> <hr> <blockquote> <p><strong><a href="https://stackoverflow.com/users/2808/nicholas">Nicholas</a></strong> wrote:</p> <p>add role="SomeRole" in the sitemap</p> </blockquote> <p>Does that only handle the display issue? Or are such page permissions enforced?</p>
[ { "answer_id": 33402, "author": "Vin", "author_id": 1747, "author_profile": "https://Stackoverflow.com/users/1747", "pm_score": 0, "selected": false, "text": "<p>I think Jeff Atwood talked about this in the <a href=\"http://herdingcode.com/?p=36\" rel=\"nofollow noreferrer\">Herding Code podcast</a>, when he was questioned about the exact same thing. Listen to it towards the last 15-20 minutes or so.</p>\n\n<p>I think in SO, the datacontext is created in the Controller class. Not sure about a lot of details here. But that's what it looked like.</p>\n" }, { "answer_id": 33405, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 4, "selected": true, "text": "<p>You pretty much need to keep the same data context available throughout the lifetime of the operations you want to perform if you're ever going to be storing changes which are to be <code>.SubmitChanges()</code>'d later, as otherwise you will lose those changes.</p>\n\n<p>If you're just querying stuff then it's fine to create them as needed, but then if later you want to <code>.SubmitChanges()</code> you'll have to refactor your code a lot, so you may as well adopt the pattern of effectively keeping the <code>datacontext</code> global throughout your app from the beginning.</p>\n\n<p>Note the data context is <em>disconnected</em>. The connection is only made when the query data is <em>enumerated</em> (not when you first run the query, it's a 'lazy' data type so only provides data when it's needed), and then closed immediately afterwards. On <code>.SubmitChanges()</code> the connection is opened to submit the changes then closed immediately afterwards. So don't think keeping the <code>datacontext</code> around keeps a connection open, it doesn't (you can hook the <code>StateChange</code> event of the connection to confirm this for yourself, that's how I'm sure).</p>\n\n<p>There is a great article over at <a href=\"http://www.west-wind.com/weblog/posts/246222.aspx\" rel=\"nofollow noreferrer\">Rick Strahl's Blog</a> which covers this topic in depth, far more than my answer here provides!!</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
I'm using the [ASP.NET Login Controls](http://msdn.microsoft.com/en-us/library/ms178329.aspx) and [Forms Authentication](http://msdn.microsoft.com/en-us/library/aa480476.aspx) for membership/credentials for an ASP.NET web application. And I'm using a [site map](http://msdn.microsoft.com/en-us/library/yy2ykkab.aspx) for site navigation. I have ASP.NET TreeView and Menu navigation controls populated using a SiteMapDataSource. But off-limits administrator-only pages are visible to non-administrator users. --- > > **[Kevin Pang](https://stackoverflow.com/users/1574/kevin-pang)** wrote: > > > I'm not sure how this question is any > different than your [other question](https://stackoverflow.com/questions/33263/how-do-i-best-handle-role-based-permissions-using-forms-authentication-on-my-as)… > > > The other question deals with assigning and maintaining permissions. This question just deals with presentation of navigation. Specifically TreeView and Menu controls with sitemap data sources. ``` <asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" /> <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" ShowStartingNode="False" /> ``` --- > > **[Nicholas](https://stackoverflow.com/users/2808/nicholas)** wrote: > > > add role="SomeRole" in the sitemap > > > Does that only handle the display issue? Or are such page permissions enforced?
You pretty much need to keep the same data context available throughout the lifetime of the operations you want to perform if you're ever going to be storing changes which are to be `.SubmitChanges()`'d later, as otherwise you will lose those changes. If you're just querying stuff then it's fine to create them as needed, but then if later you want to `.SubmitChanges()` you'll have to refactor your code a lot, so you may as well adopt the pattern of effectively keeping the `datacontext` global throughout your app from the beginning. Note the data context is *disconnected*. The connection is only made when the query data is *enumerated* (not when you first run the query, it's a 'lazy' data type so only provides data when it's needed), and then closed immediately afterwards. On `.SubmitChanges()` the connection is opened to submit the changes then closed immediately afterwards. So don't think keeping the `datacontext` around keeps a connection open, it doesn't (you can hook the `StateChange` event of the connection to confirm this for yourself, that's how I'm sure). There is a great article over at [Rick Strahl's Blog](http://www.west-wind.com/weblog/posts/246222.aspx) which covers this topic in depth, far more than my answer here provides!!
33,409
<p>I am using SQL Server 2005. I have a table with a text column and I have many rows in the table where the value of this column is not null, but it is empty. Trying to compare against '' yields this response:</p> <blockquote> <p>The data types text and varchar are incompatible in the not equal to operator.</p> </blockquote> <p>Is there a special function to determine whether the value of a text column is not null but empty?</p>
[ { "answer_id": 33415, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 0, "selected": false, "text": "<p>I would test against <a href=\"http://msdn.microsoft.com/en-us/library/ms187748.aspx\" rel=\"nofollow noreferrer\">SUBSTRING</a>(textColumn, 0, 1)</p>\n" }, { "answer_id": 33425, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 9, "selected": true, "text": "<pre><code>where datalength(mytextfield)=0\n</code></pre>\n" }, { "answer_id": 34036, "author": "Dane", "author_id": 2929, "author_profile": "https://Stackoverflow.com/users/2929", "pm_score": 5, "selected": false, "text": "<p>Actually, you just have to use the LIKE operator.</p>\n\n<pre><code>SELECT * FROM mytable WHERE mytextfield LIKE ''\n</code></pre>\n" }, { "answer_id": 35183, "author": "Tyler Gooch", "author_id": 1372, "author_profile": "https://Stackoverflow.com/users/1372", "pm_score": 0, "selected": false, "text": "<p>Are null and an empty string equivalent? If they are, I would include logic in my application (or maybe a trigger if the app is \"out-of-the-box\"?) to force the field to be either null or '', but not the other. If you went with '', then you could set the column to NOT NULL as well. Just a data-cleanliness thing.</p>\n" }, { "answer_id": 3104438, "author": "Eric", "author_id": 374536, "author_profile": "https://Stackoverflow.com/users/374536", "pm_score": 6, "selected": false, "text": "<pre><code>ISNULL(\ncase textcolum1\n WHEN '' THEN NULL\n ELSE textcolum1\nEND \n,textcolum2) textcolum1\n</code></pre>\n" }, { "answer_id": 9608085, "author": "Yoosaf Abdulla", "author_id": 676508, "author_profile": "https://Stackoverflow.com/users/676508", "pm_score": 0, "selected": false, "text": "<p>I wanted to have a predefined text(\"No Labs Available\") to be displayed if the value was null or empty and my friend helped me with this:</p>\n\n<pre><code>StrengthInfo = CASE WHEN ((SELECT COUNT(UnitsOrdered) FROM [Data_Sub_orders].[dbo].[Snappy_Orders_Sub] WHERE IdPatient = @PatientId and IdDrugService = 226)&gt; 0)\n THEN cast((S.UnitsOrdered) as varchar(50))\n ELSE 'No Labs Available'\n END\n</code></pre>\n" }, { "answer_id": 11017855, "author": "Mike Roberts", "author_id": 1454021, "author_profile": "https://Stackoverflow.com/users/1454021", "pm_score": 1, "selected": false, "text": "<p>I know this post is ancient but, I found it useful. </p>\n\n<p>It didn't resolve my issue of returning the record with a non empty text field so I thought I would add my solution.</p>\n\n<p>This is the where clause that worked for me.</p>\n\n<pre><code>WHERE xyz LIKE CAST('% %' as text)\n</code></pre>\n" }, { "answer_id": 12326533, "author": "marklark", "author_id": 462234, "author_profile": "https://Stackoverflow.com/users/462234", "pm_score": 0, "selected": false, "text": "<p>You have to do both:</p>\n\n<p><code>SELECT * FROM Table WHERE Text IS NULL or Text LIKE ''</code></p>\n" }, { "answer_id": 16915901, "author": "Pearl", "author_id": 1920827, "author_profile": "https://Stackoverflow.com/users/1920827", "pm_score": 2, "selected": false, "text": "<p>Use the IS NULL operator:</p>\n\n<pre><code>Select * from tb_Employee where ename is null\n</code></pre>\n" }, { "answer_id": 21686029, "author": "Enrique Garcia", "author_id": 1231186, "author_profile": "https://Stackoverflow.com/users/1231186", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT * FROM TABLE\nWHERE ISNULL(FIELD, '')=''\n</code></pre>\n" }, { "answer_id": 25454764, "author": "Nima", "author_id": 3715742, "author_profile": "https://Stackoverflow.com/users/3715742", "pm_score": 4, "selected": false, "text": "<p>To get only empty values (and not null values):</p>\n\n<pre><code>SELECT * FROM myTable WHERE myColumn = ''\n</code></pre>\n\n<p>To get both null and empty values:</p>\n\n<pre><code>SELECT * FROM myTable WHERE myColumn IS NULL OR myColumn = ''\n</code></pre>\n\n<p>To get only null values:</p>\n\n<pre><code>SELECT * FROM myTable WHERE myColumn IS NULL\n</code></pre>\n\n<p>To get values other than null and empty:</p>\n\n<pre><code>SELECT * FROM myTable WHERE myColumn &lt;&gt; ''\n</code></pre>\n\n<p><br>\nAnd remember use LIKE phrases only when necessary because they will degrade performance compared to other types of searches.</p>\n" }, { "answer_id": 31875178, "author": "Leo", "author_id": 4189349, "author_profile": "https://Stackoverflow.com/users/4189349", "pm_score": 0, "selected": false, "text": "<p>I know there are plenty answers with alternatives to this problem, but I just would like to put together what I found as the best solution by @Eric Z Beard &amp; @Tim Cooper with @Enrique Garcia &amp; @Uli Köhler.</p>\n\n<p>If needed to deal with the fact that space-only could be the same as empty in your use-case scenario, because the query below will return 1, not 0.</p>\n\n<pre><code>SELECT datalength(' ')\n</code></pre>\n\n<p>Therefore, I would go for something like:</p>\n\n<pre><code>SELECT datalength(RTRIM(LTRIM(ISNULL([TextColumn], ''))))\n</code></pre>\n" }, { "answer_id": 32258632, "author": "Jorgesys", "author_id": 250260, "author_profile": "https://Stackoverflow.com/users/250260", "pm_score": 1, "selected": false, "text": "<p>Use <a href=\"https://msdn.microsoft.com/en-us/library/ms173486.aspx\" rel=\"nofollow\"><strong>DATALENGTH</strong></a> method, for example:</p>\n\n<pre><code>SELECT length = DATALENGTH(myField)\nFROM myTABLE\n</code></pre>\n" }, { "answer_id": 52740656, "author": "Luiz Fernando Corrêa Leite", "author_id": 4267702, "author_profile": "https://Stackoverflow.com/users/4267702", "pm_score": 0, "selected": false, "text": "<p>try this:</p>\n\n<pre><code>select * from mytable where convert(varchar, mycolumn) = ''\n</code></pre>\n\n<p>i hope help u!</p>\n" }, { "answer_id": 56599223, "author": "Enrique Garcia", "author_id": 1231186, "author_profile": "https://Stackoverflow.com/users/1231186", "pm_score": 1, "selected": false, "text": "<p>Instead of using <code>isnull</code> use a <code>case</code>, because of performance it is better the case.</p>\n\n<pre><code>case when campo is null then '' else campo end\n</code></pre>\n\n<p>In your issue you need to do this:</p>\n\n<pre><code>case when campo is null then '' else\n case when len(campo) = 0 then '' else campo en\nend\n</code></pre>\n\n<p>Code like this:</p>\n\n<pre><code>create table #tabla(\nid int,\ncampo varchar(10)\n)\n\ninsert into #tabla\nvalues(1,null)\n\ninsert into #tabla\nvalues(2,'')\n\ninsert into #tabla\nvalues(3,null)\n\ninsert into #tabla\nvalues(4,'dato4')\n\ninsert into #tabla\nvalues(5,'dato5')\n\nselect id, case when campo is null then 'DATA NULL' else\n case when len(campo) = 0 then 'DATA EMPTY' else campo end\nend\nfrom #tabla\n\ndrop table #tabla\n</code></pre>\n" }, { "answer_id": 57628088, "author": "user11968038", "author_id": 11968038, "author_profile": "https://Stackoverflow.com/users/11968038", "pm_score": 0, "selected": false, "text": "<pre><code>DECLARE @temp as nvarchar(20)\n\nSET @temp = NULL\n--SET @temp = ''\n--SET @temp = 'Test'\n\nSELECT IIF(ISNULL(@temp,'')='','[Empty]',@temp)\n</code></pre>\n" }, { "answer_id": 68573417, "author": "Pallav Chanana", "author_id": 10538842, "author_profile": "https://Stackoverflow.com/users/10538842", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p><strong>It will do two things:</strong></p>\n<ol>\n<li>Null check and string null check</li>\n<li>Replace empty value to default value eg NA.</li>\n</ol>\n</blockquote>\n<pre><code>SELECT coalesce(NULLIF(column_name,''),'NA') as 'desired_name') from table;\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1214/" ]
I am using SQL Server 2005. I have a table with a text column and I have many rows in the table where the value of this column is not null, but it is empty. Trying to compare against '' yields this response: > > The data types text and varchar are incompatible in the not equal to operator. > > > Is there a special function to determine whether the value of a text column is not null but empty?
``` where datalength(mytextfield)=0 ```
33,412
<p>After reading Jeff's blog post on <a href="http://www.codinghorror.com/blog/archives/001167.html" rel="noreferrer">Protecting Your Cookies: HttpOnly</a>. I'd like to implement HttpOnly cookies in my web application.</p> <p>How do you tell tomcat to use http only cookies for sessions?</p>
[ { "answer_id": 33456, "author": "Shabaz", "author_id": 1827, "author_profile": "https://Stackoverflow.com/users/1827", "pm_score": 3, "selected": false, "text": "<p>For session cookies it doesn't seem to be supported in Tomcat yet. See the bug report <a href=\"https://issues.apache.org/bugzilla/show_bug.cgi?id=44382\" rel=\"noreferrer\">Need to add support for HTTPOnly session cookie parameter</a>. A somewhat involved work-around for now can be found <a href=\"http://manicode.blogspot.com/2008/03/httponly-support-for-apache-tomcat.html\" rel=\"noreferrer\">here</a>, which basically boils down to manually patching Tomcat. Can't really find an easy way to do it at this moment at this point I'm affraid. </p>\n\n<p>To summarize the work-around, it involves downloading the 5.5 <a href=\"http://tomcat.apache.org/tomcat-5.5-doc/building.html\" rel=\"noreferrer\">source</a>, and then change the source in the following places:</p>\n\n<p><em>org.apache.catalina.connector.Request.java</em></p>\n\n<pre><code>//this is what needs to be changed\n//response.addCookieInternal(cookie);\n\n//this is whats new\nresponse.addCookieInternal(cookie, true);\n}\n</code></pre>\n\n<p><em>org.apache.catalina.connectorResponse.addCookieInternal</em></p>\n\n<pre><code>public void addCookieInternal(final Cookie cookie) {\naddCookieInternal(cookie, false);\n}\n\npublic void addCookieInternal(final Cookie cookie, boolean HTTPOnly) {\n\nif (isCommitted())\nreturn;\n\nfinal StringBuffer sb = new StringBuffer();\n//web application code can receive a IllegalArgumentException\n//from the appendCookieValue invokation\nif (SecurityUtil.isPackageProtectionEnabled()) {\nAccessController.doPrivileged(new PrivilegedAction() {\npublic Object run(){\nServerCookie.appendCookieValue\n(sb, cookie.getVersion(), cookie.getName(),\ncookie.getValue(), cookie.getPath(),\ncookie.getDomain(), cookie.getComment(),\ncookie.getMaxAge(), cookie.getSecure());\nreturn null;\n}\n});\n} else {\nServerCookie.appendCookieValue\n(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),\ncookie.getPath(), cookie.getDomain(), cookie.getComment(),\ncookie.getMaxAge(), cookie.getSecure());\n}\n//of course, we really need to modify ServerCookie\n//but this is the general idea\nif (HTTPOnly) {\nsb.append(\"; HttpOnly\");\n}\n\n//if we reached here, no exception, cookie is valid\n// the header name is Set-Cookie for both \"old\" and v.1 ( RFC2109 )\n// RFC2965 is not supported by browsers and the Servlet spec\n// asks for 2109.\naddHeader(\"Set-Cookie\", sb.toString());\n\ncookies.add(cookie);\n}\n</code></pre>\n" }, { "answer_id": 33461, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p><strong>Update: The JSESSIONID stuff here is\n only for older containers. Please use\n jt's currently accepted answer unless\n you are using &lt; Tomcat 6.0.19 or &lt; Tomcat\n 5.5.28 or another container that does not support HttpOnly JSESSIONID cookies as a config option.</strong></p>\n</blockquote>\n\n<p>When setting cookies in your app, use</p>\n\n<pre><code>response.setHeader( \"Set-Cookie\", \"name=value; HttpOnly\");\n</code></pre>\n\n<p>However, in many webapps, the most important cookie is the session identifier, which is automatically set by the container as the JSESSIONID cookie.</p>\n\n<p>If you only use this cookie, you can write a ServletFilter to re-set the cookies on the way out, forcing JSESSIONID to HttpOnly. The page at <strike><a href=\"http://keepitlocked.net/archive/2007/11/05/java-and-httponly.aspx\" rel=\"noreferrer\">http://keepitlocked.net/archive/2007/11/05/java-and-httponly.aspx</a></strike> <a href=\"http://alexsmolen.com/blog/?p=16\" rel=\"noreferrer\">http://alexsmolen.com/blog/?p=16</a> suggests adding the following in a filter.</p>\n\n<pre><code>if (response.containsHeader( \"SET-COOKIE\" )) {\n String sessionid = request.getSession().getId();\n response.setHeader( \"SET-COOKIE\", \"JSESSIONID=\" + sessionid \n + \";Path=/&lt;whatever&gt;; Secure; HttpOnly\" );\n} \n</code></pre>\n\n<p>but note that this will overwrite all cookies and only set what you state here in this filter. </p>\n\n<p>If you use additional cookies to the JSESSIONID cookie, then you'll need to extend this code to set all the cookies in the filter. This is not a great solution in the case of multiple-cookies, but is a perhaps an acceptable quick-fix for the JSESSIONID-only setup. </p>\n\n<p>Please note that as your code evolves over time, there's a nasty hidden bug waiting for you when you forget about this filter and try and set another cookie somewhere else in your code. Of course, it won't get set.</p>\n\n<p>This really is a hack though. If you do use Tomcat and can compile it, then take a look at Shabaz's excellent suggestion to patch HttpOnly support into Tomcat.</p>\n" }, { "answer_id": 1088009, "author": "jt.", "author_id": 4362, "author_profile": "https://Stackoverflow.com/users/4362", "pm_score": 7, "selected": true, "text": "<p>httpOnly is supported as of Tomcat 6.0.19 and Tomcat 5.5.28.</p>\n\n<p>See the <a href=\"http://tomcat.apache.org/tomcat-6.0-doc/changelog.html\" rel=\"noreferrer\">changelog</a> entry for bug 44382. </p>\n\n<p>The last comment for bug <a href=\"https://issues.apache.org/bugzilla/show_bug.cgi?id=44382\" rel=\"noreferrer\">44382</a> states, \"this has been applied to 5.5.x and will be included in 5.5.28 onwards.\" However, it does not appear that 5.5.28 has been released.</p>\n\n<p>The httpOnly functionality can be enabled for all webapps in <strong>conf/context.xml</strong>:</p>\n\n<pre><code>&lt;Context useHttpOnly=\"true\"&gt;\n...\n&lt;/Context&gt;\n</code></pre>\n\n<p>My interpretation is that it also works for an individual context by setting it on the desired <strong><em>Context</em></strong> entry in <strong>conf/server.xml</strong> (in the same manner as above).</p>\n" }, { "answer_id": 1465092, "author": "Hendrik Brummermann", "author_id": 177701, "author_profile": "https://Stackoverflow.com/users/177701", "pm_score": 4, "selected": false, "text": "<p>Please be careful not to overwrite the \";secure\" cookie flag in https-sessions. This flag prevents the browser from sending the cookie over an unencrypted http connection, basically rendering the use of https for legit requests pointless.</p>\n\n<pre><code>private void rewriteCookieToHeader(HttpServletRequest request, HttpServletResponse response) {\n if (response.containsHeader(\"SET-COOKIE\")) {\n String sessionid = request.getSession().getId();\n String contextPath = request.getContextPath();\n String secure = \"\";\n if (request.isSecure()) {\n secure = \"; Secure\"; \n }\n response.setHeader(\"SET-COOKIE\", \"JSESSIONID=\" + sessionid\n + \"; Path=\" + contextPath + \"; HttpOnly\" + secure);\n }\n}\n</code></pre>\n" }, { "answer_id": 3516432, "author": "Pete Brumm", "author_id": 335770, "author_profile": "https://Stackoverflow.com/users/335770", "pm_score": 2, "selected": false, "text": "<p>also it should be noted that turning on HttpOnly will break applets that require stateful access back to the jvm.</p>\n\n<p>the Applet http requests will not use the jsessionid cookie and may get assigned to a different tomcat.</p>\n" }, { "answer_id": 14610452, "author": "Jesse Vogt", "author_id": 9822, "author_profile": "https://Stackoverflow.com/users/9822", "pm_score": 2, "selected": false, "text": "<p>For cookies that I am explicitly setting, I switched to use <a href=\"http://shiro.apache.org/static/current/apidocs/org/apache/shiro/web/servlet/SimpleCookie.html\" rel=\"nofollow\">SimpleCookie</a> provided by <a href=\"http://shiro.apache.org/\" rel=\"nofollow\">Apache Shiro</a>. It does not inherit from javax.servlet.http.Cookie so it takes a bit more juggling to get everything to work correctly however it does provide a property set HttpOnly and it works with Servlet 2.5.</p>\n\n<p>For setting a cookie on a response, rather than doing <code>response.addCookie(cookie)</code> you need to do <code>cookie.saveTo(request, response)</code>.</p>\n" }, { "answer_id": 30995999, "author": "Alireza Fattahi", "author_id": 2648077, "author_profile": "https://Stackoverflow.com/users/2648077", "pm_score": 4, "selected": false, "text": "<p>If your web server supports Serlvet 3.0 spec, like tomcat 7.0+, you can use below in <code>web.xml</code> as:</p>\n\n<pre><code>&lt;session-config&gt;\n &lt;cookie-config&gt;\n &lt;http-only&gt;true&lt;/http-only&gt; \n &lt;secure&gt;true&lt;/secure&gt; \n &lt;/cookie-config&gt;\n&lt;/session-config&gt;\n</code></pre>\n\n<p>As mentioned in docs:</p>\n\n<blockquote>\n <p><strong>HttpOnly</strong>: Specifies whether any session tracking cookies created by\n this web application will be marked as HttpOnly </p>\n \n <p><strong>Secure</strong>: Specifies\n whether any session tracking cookies created by this web application\n will be marked as secure even if the request that initiated the\n corresponding session is using plain HTTP instead of HTTPS</p>\n</blockquote>\n\n<p>Please refer to <a href=\"https://stackoverflow.com/questions/15510354/how-to-set-httponly-and-session-cookie-for-java-web-appliaction\">how to set httponly and session cookie for java web application</a></p>\n" }, { "answer_id": 34147407, "author": "Systemsplanet", "author_id": 586841, "author_profile": "https://Stackoverflow.com/users/586841", "pm_score": 1, "selected": false, "text": "<p>In Tomcat6, You can conditionally enable from your HTTP Listener Class:</p>\n\n<pre><code>public void contextInitialized(ServletContextEvent event) { \n if (Boolean.getBoolean(\"HTTP_ONLY_SESSION\")) HttpOnlyConfig.enable(event);\n}\n</code></pre>\n\n<p>Using this class</p>\n\n<pre><code>import java.lang.reflect.Field;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletContextEvent;\nimport org.apache.catalina.core.StandardContext;\npublic class HttpOnlyConfig\n{\n public static void enable(ServletContextEvent event)\n {\n ServletContext servletContext = event.getServletContext();\n Field f;\n try\n { // WARNING TOMCAT6 SPECIFIC!!\n f = servletContext.getClass().getDeclaredField(\"context\");\n f.setAccessible(true);\n org.apache.catalina.core.ApplicationContext ac = (org.apache.catalina.core.ApplicationContext) f.get(servletContext);\n f = ac.getClass().getDeclaredField(\"context\");\n f.setAccessible(true);\n org.apache.catalina.core.StandardContext sc = (StandardContext) f.get(ac);\n sc.setUseHttpOnly(true);\n }\n catch (Exception e)\n {\n System.err.print(\"HttpOnlyConfig cant enable\");\n e.printStackTrace();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 53652036, "author": "Ravipati Praveen", "author_id": 3876619, "author_profile": "https://Stackoverflow.com/users/3876619", "pm_score": 2, "selected": false, "text": "<p>I Found in <a href=\"https://www.owasp.org/index.php/HttpOnly\" rel=\"nofollow noreferrer\">OWASP</a></p>\n\n<pre><code>&lt;session-config&gt;\n &lt;cookie-config&gt;\n &lt;http-only&gt;true&lt;/http-only&gt;\n &lt;/cookie-config&gt;\n&lt;/session-config&gt;\n</code></pre>\n\n<p>this is also fix for \"httponlycookies in config\" security issue</p>\n" }, { "answer_id": 67748208, "author": "Akash Chatterjee", "author_id": 5010765, "author_profile": "https://Stackoverflow.com/users/5010765", "pm_score": 0, "selected": false, "text": "<p>Implementation: in Tomcat 7.x/8.x/9.x</p>\n<p>Go to Tomcat &gt;&gt; conf folder\nOpen web.xml and add below in session-config section</p>\n<pre><code> &lt;cookie-config&gt;\n &lt;http-only&gt;true&lt;/http-only&gt;\n &lt;secure&gt;true&lt;/secure&gt;\n &lt;/cookie-config&gt;\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
After reading Jeff's blog post on [Protecting Your Cookies: HttpOnly](http://www.codinghorror.com/blog/archives/001167.html). I'd like to implement HttpOnly cookies in my web application. How do you tell tomcat to use http only cookies for sessions?
httpOnly is supported as of Tomcat 6.0.19 and Tomcat 5.5.28. See the [changelog](http://tomcat.apache.org/tomcat-6.0-doc/changelog.html) entry for bug 44382. The last comment for bug [44382](https://issues.apache.org/bugzilla/show_bug.cgi?id=44382) states, "this has been applied to 5.5.x and will be included in 5.5.28 onwards." However, it does not appear that 5.5.28 has been released. The httpOnly functionality can be enabled for all webapps in **conf/context.xml**: ``` <Context useHttpOnly="true"> ... </Context> ``` My interpretation is that it also works for an individual context by setting it on the desired ***Context*** entry in **conf/server.xml** (in the same manner as above).
33,449
<p>Is there a way to call out from a TSQL stored procedure or function to a webservice?</p>
[ { "answer_id": 33455, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 3, "selected": false, "text": "<p>Not in T-SQL code itself, but with SQL Server 2005 and above, they've enabled the ability to write CLR stored procedures, which are essentially functions in .NET code and then expose them as stored procedures for consumption. You have most of the .NET framework at your fingertips for this, so I can see consumption of a web service possible through this.</p>\n\n<p>It is a little lengthy to discuss in detail here, but here's a link to an <a href=\"http://msdn.microsoft.com/en-us/library/ms131094.aspx\" rel=\"noreferrer\">MSDN article</a> on the topic.</p>\n" }, { "answer_id": 33799, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "<p>In earlier versions of Sql, you could use either an extended stored proc or xp_cmdshell to shell out and call a webservice.</p>\n\n<p>Not that either of these sound like a decent architecture - but sometimes you have to do crazy stuff.</p>\n" }, { "answer_id": 33884, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 5, "selected": false, "text": "<p>Sure you <em>can</em>, but this is a terrible idea. </p>\n\n<p>As web-service calls may take arbitrary amounts of time, and randomly fail, depending on how many games of counterstrike are being played on your network at the time, you can't tell how long this is going to take. </p>\n\n<p>At the bare minimum you're looking at probably half a second by the time it builds the XML, sends the HTTP request to the remote server, which then has to parse the XML and send a response back.</p>\n\n<ol>\n<li><p>Whichever application did the <code>INSERT INTO BLAH</code> query which caused the web-service to fire is going to have to wait for it to finish. Unless this is something that only happens in the background like a daily scheduled task, your app's performance is going to bomb</p></li>\n<li><p>The web service-invoking code runs inside SQL server, and uses up it's resources. As it's going to take a long time to wait for the HTTP request, you'll end up using up a lot of resources, which will again hurt the performance of your server.</p></li>\n</ol>\n" }, { "answer_id": 1947732, "author": "Brian", "author_id": 237021, "author_profile": "https://Stackoverflow.com/users/237021", "pm_score": 2, "selected": false, "text": "<p>You can do it with the embedded VB objects.</p>\n\n<p>First you create one VB object of type 'MSXML2.XMLHttp', and you use this one object for all of your queries (if you recreate it each time expect a heavy performance penalty).</p>\n\n<p>Then you feed that object, some parameters, into a stored procedure that invokes sp_OAMethod on the object.</p>\n\n<p>Sorry for the inprecise example, but a quick google search should reveal how the vb-script method is done.</p>\n\n<p>--</p>\n\n<p>But the CLR version is much....MUCH easier.\nThe problem with invoking webservices is that they cannot keep pace with the DB engine. You'll get lots of errors where it just cannot keep up.</p>\n\n<p>And remember, web SERVICES require a new connection each time. Multiplicity comes into play. You don't want to open 5000 socket connections to service a function call on a table. Thats looney!</p>\n\n<p>In that case you'd have to create a custom aggregate function, and use THAT as an argument to pass to your webservice, which would return a result set...then you'd have to collate that. Its really an awkward way of getting data.</p>\n" }, { "answer_id": 1955255, "author": "bander", "author_id": 237897, "author_profile": "https://Stackoverflow.com/users/237897", "pm_score": 1, "selected": false, "text": "<p>If you're working with sql 2000 compatibility levels and cannot do clr integration, see <a href=\"http://www.vishalseth.com/post/2009/12/22/Call-a-webservice-from-TSQL-(Stored-Procedure)-using-MSXML.aspx\" rel=\"nofollow noreferrer\">http://www.vishalseth.com/post/2009/12/22/Call-a-webservice-from-TSQL-(Stored-Procedure)-using-MSXML.aspx</a></p>\n" }, { "answer_id": 30211736, "author": "Kiran.Bakwad", "author_id": 2940450, "author_profile": "https://Stackoverflow.com/users/2940450", "pm_score": 6, "selected": true, "text": "<p>Yes , you can create like this</p>\n\n<pre><code>CREATE PROCEDURE CALLWEBSERVICE(@Para1 ,@Para2)\nAS\nBEGIN\n Declare @Object as Int;\n Declare @ResponseText as Varchar(8000);\n\n Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;\n Exec sp_OAMethod @Object, 'open', NULL, 'get', 'http://www.webservicex.com/stockquote.asmx/GetQuote?symbol=MSFT','false'\n Exec sp_OAMethod @Object, 'send'\n Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT\n Select @ResponseText\n Exec sp_OADestroy @Object\nEND\n</code></pre>\n" }, { "answer_id": 43993270, "author": "Tom Stickel", "author_id": 756246, "author_profile": "https://Stackoverflow.com/users/756246", "pm_score": 3, "selected": false, "text": "<p>I would not do this for heavy traffic or mission critical stuff, HOWEVER, if you do NOT need to receive feedback from a service, then it is actually a great thing to do. </p>\n\n<p>Here is an example of what I have done.</p>\n\n<ol>\n<li>Triggers Insert and Update on a Table </li>\n<li>Trigger called Stored Proc that is passes the JSON data of the transaction to a Web Api Endpoint that then Inserts into a MongoDB in AWS. </li>\n</ol>\n\n<p>Don't do old XML </p>\n\n<p>JSON </p>\n\n<pre><code>EXEC sp_OACreate 'WinHttp.WinHttpRequest.5.1', @Object OUT;\nEXEC sp_OAMethod @Object, 'Open', NULL, 'POST', 'http://server/api/method', 'false'\nEXEC sp_OAMethod @Object, 'setRequestHeader', null, 'Content-Type', 'application/json'\nDECLARE @len INT = len(@requestBody) \n</code></pre>\n\n<p>Full example:</p>\n\n<pre><code>Alter Procedure yoursprocname\n\n @WavName varchar(50),\n @Dnis char(4) \n\n AS\nBEGIN\n\n SET NOCOUNT ON;\n\n\nDECLARE @Object INT;\nDECLARE @Status INT;\n\n\nDECLARE @requestBody NVARCHAR(MAX) = '{\n\"WavName\": \"{WavName}\",\n\"Dnis\": \"{Dnis}\"\n}'\n\n\nSET @requestBody = REPLACE(@requestBody, '{WavName}', @WavName)\nSET @requestBody = REPLACE(@requestBody, '{Dnis}', @Dnis)\n\n\nEXEC sp_OACreate 'WinHttp.WinHttpRequest.5.1', @Object OUT;\nEXEC sp_OAMethod @Object, 'Open', NULL, 'POST', 'http://server/api/method', 'false'\nEXEC sp_OAMethod @Object, 'setRequestHeader', null, 'Content-Type', 'application/json'\nDECLARE @len INT = len(@requestBody) \nEXEC sp_OAMethod @Object, 'setRequestHeader', null, 'Content-Length', @len\nEXEC sp_OAMethod @Object, 'send', null, @requestBody\nEXEC sp_OAGetProperty @Object, 'Status', @Status OUT\nEXEC sp_OADestroy @Object\n</code></pre>\n" }, { "answer_id": 54149765, "author": "Guillermo Jimenez", "author_id": 10349499, "author_profile": "https://Stackoverflow.com/users/10349499", "pm_score": 1, "selected": false, "text": "<p>I been working for big/global companies around the world, using Oracle databases. We are consuming web services all time thru DB with store procedures and no issues, even those ones with heavy traffic. All of them for internal use, I mean with no access to internet, only inside the plant. I would recommend to use it but being really careful about how you design it</p>\n" }, { "answer_id": 59046429, "author": "Jan", "author_id": 2386040, "author_profile": "https://Stackoverflow.com/users/2386040", "pm_score": 2, "selected": false, "text": "<p>Here'a an example to get some data from a webservice. In this case parse a user agent string to JSON.</p>\n\n<pre><code>--first configure MSSQL to enable calling out to a webservice (1=true, 0=false)\nsp_configure 'show advanced options', 1; \nGO \nRECONFIGURE; \nGO \nsp_configure 'Ole Automation Procedures', 1; \nGO \nRECONFIGURE; \nGO \n\nCREATE PROCEDURE CallWebAPI_ParseUserAgent @UserAgent VARCHAR(512)\nAS\nBEGIN\n SET NOCOUNT ON;\n\n DECLARE @Object INT;\n DECLARE @ResponseText AS VARCHAR(8000);\n DECLARE @url VARCHAR(512)\n\n SET @url = 'http://www.useragentstring.com/?getJSON=all&amp;uas=' + @UserAgent;\n\n EXEC sp_OACreate 'WinHttp.WinHttpRequest.5.1', @Object OUT;\n EXEC sp_OAMethod @Object, 'Open', NULL, 'GET', @url, 'false'\n EXEC sp_OAMethod @Object, 'setRequestHeader', NULL, 'Content-Type', 'application/json'\n EXEC sp_OAMethod @Object, 'send'\n EXEC sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT\n SELECT @ResponseText\n EXEC sp_OADestroy @Object\nEND\n\n--example how to call the API\nCallWebAPI_ParseUserAgent 'Mozilla/5.0 (Windows NT 6.2; rv:53.0) Gecko/20100101 Firefox/53.0'\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1874/" ]
Is there a way to call out from a TSQL stored procedure or function to a webservice?
Yes , you can create like this ``` CREATE PROCEDURE CALLWEBSERVICE(@Para1 ,@Para2) AS BEGIN Declare @Object as Int; Declare @ResponseText as Varchar(8000); Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT; Exec sp_OAMethod @Object, 'open', NULL, 'get', 'http://www.webservicex.com/stockquote.asmx/GetQuote?symbol=MSFT','false' Exec sp_OAMethod @Object, 'send' Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT Select @ResponseText Exec sp_OADestroy @Object END ```
33,459
<p>Is it possible to use a flash document embedded in HTML as a link?</p> <p>I tried just wrapping the <code>object</code> element with an <code>a</code> like this:</p> <pre><code>&lt;a href="http://whatever.com"&gt; &lt;object ...&gt; &lt;embed ... /&gt; &lt;/object&gt; &lt;/a&gt; </code></pre> <p>In Internet Explorer, that made it show the location in the status bar like a link, but it doesn't do anything.</p> <p>I just have the .swf file, so I can't add a click handler in ActionScript.</p>
[ { "answer_id": 33519, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 2, "selected": true, "text": "<p>Though the object really should respond to being wrapped in an a href tag, you could open the swf in vim and just throw in an <code>_root.onPress=function(){getURL(\"http://yes.no/\");};</code> or if it's AS3, something like <code>_root.addEventHandler(MouseEvent.PRESS, function (e:event) {getURL(\"http://yes.no/\");});</code> But if editing the swf is your route, you'd likely have more success with <a href=\"http://www.buraks.com/uae/1.html\" rel=\"nofollow noreferrer\">a tool for the purpose</a>.</p>\n" }, { "answer_id": 36141, "author": "Tim", "author_id": 1970, "author_profile": "https://Stackoverflow.com/users/1970", "pm_score": 0, "selected": false, "text": "<p>As an addition to dlamblin's answer it is often best to use the clickTAG technique to open URLS from a flash movie.</p>\n\n<p>More information can be found here:</p>\n\n<p><a href=\"http://www.adobe.com/resources/richmedia/tracking/designers_guide/\" rel=\"nofollow noreferrer\">http://www.adobe.com/resources/richmedia/tracking/designers_guide/</a></p>\n\n<p>The advantage of using the clickTAG technique is that you can set the URL to jump to in the HTML page.</p>\n\n<p>This means that you can set the flash movie to link to different places without modifying the flash file (beyond adding the initial clickTAG code). You can use link tracking on the URL as well.</p>\n" }, { "answer_id": 2945945, "author": "s0natagrl", "author_id": 354886, "author_profile": "https://Stackoverflow.com/users/354886", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>You could use Javascript to add a\n handler (added inline for brevity):</p>\n\n<pre><code>&lt;object onclick=\"window.location='URLHERE'; return false;\"&gt;\n</code></pre>\n \n <p>That should work, methinks.</p>\n</blockquote>\n\n<p>This worked for me but the litle hand for clicking stuff doesn´t appear. The link works though</p>\n" }, { "answer_id": 6732973, "author": "Lukas", "author_id": 709556, "author_profile": "https://Stackoverflow.com/users/709556", "pm_score": 2, "selected": false, "text": "<p>You can use transparent div with same height and width over that object.\nAnd let javascript open your url on click action on that div.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2214/" ]
Is it possible to use a flash document embedded in HTML as a link? I tried just wrapping the `object` element with an `a` like this: ``` <a href="http://whatever.com"> <object ...> <embed ... /> </object> </a> ``` In Internet Explorer, that made it show the location in the status bar like a link, but it doesn't do anything. I just have the .swf file, so I can't add a click handler in ActionScript.
Though the object really should respond to being wrapped in an a href tag, you could open the swf in vim and just throw in an `_root.onPress=function(){getURL("http://yes.no/");};` or if it's AS3, something like `_root.addEventHandler(MouseEvent.PRESS, function (e:event) {getURL("http://yes.no/");});` But if editing the swf is your route, you'd likely have more success with [a tool for the purpose](http://www.buraks.com/uae/1.html).
33,465
<p>Working on a little side project web app...</p> <p>I'd like to have it set up so that, when users send email to a certain account, I can kick off a PHP script that reads the email, pulls out some key info, and writes it to a database.</p> <p>What's the best way to do this? A cron job that checks for new email?</p> <p>The app is running on a "Dedicated-Virtual" Server at MediaTemple, so I guess I have a reasonable level of control, which should give me a range of options.</p> <p>I'm very slowly learning the ropes (PHP, MySQL, configuring/managing the server), so your advice and insight are much appreciated.</p> <p>Cheers, Matt Stuehler</p>
[ { "answer_id": 33472, "author": "crono", "author_id": 1462, "author_profile": "https://Stackoverflow.com/users/1462", "pm_score": 0, "selected": false, "text": "<p>The Cronjob is the common solution to such a task. <a href=\"http://php.net/manual/en/function.imap-getmailboxes.php\" rel=\"nofollow noreferrer\">Checking for new Mails with PHP</a> is no Problem. If you run a qmail-server (maybe other servers can do this too?) you can <a href=\"http://www.faqts.com/knowledge_base/view.phtml/aid/34099/fid/139\" rel=\"nofollow noreferrer\">fire a script</a> on every \"received mail\", which triggers your php script.</p>\n" }, { "answer_id": 33479, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>if you have control of a mail transfer agent that is configurable to allow .forwards or similar configurable delivery options (qmail, postfix, and sendmail all are), i'd just set the script up in your .forward, .procmailrc, or other similar programmable delivery mechanism. when doing this, you should do some serious input validation on the mail (make sure the sender is who you expect, the received lines match up, the data is sane) if you don't want others who stumble onto the address to be able to muck with your system.</p>\n\n<p>you'll also want to use whatever input sanitizer php uses to avoid things like sql injections from malicious data! we can all reflect upon the lesson of little bobby tables:</p>\n\n<p>xkcd.com/327/</p>\n" }, { "answer_id": 33488, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 0, "selected": false, "text": "<p>You can use a <a href=\"http://activecampaign.com/support/tt/index.php?action=kb&amp;article=145\" rel=\"nofollow noreferrer\">.forward</a> file.</p>\n\n<p>Just place the full path of your PHP script into the file, after a pipe sign:</p>\n\n<pre><code>|/full/path/to/script.php\n</code></pre>\n" }, { "answer_id": 33921, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 2, "selected": false, "text": "<p>Procmail is how I do it. Here's an example where I actually process the text inside the email to archive it back to a MySQL database. </p>\n\n<pre><code>:0: \n* ^(From).*[email protected]\n{ \n :0 c\n | php /var/www/app/process_email.php\n\n}\n</code></pre>\n" }, { "answer_id": 804920, "author": "Warren Krewenki", "author_id": 98028, "author_profile": "https://Stackoverflow.com/users/98028", "pm_score": 1, "selected": false, "text": "<p>I recently worked on a project that had this need. I had great success using a .forward file in the mail accounts home directory. For example, let's say you're trying to do this for the address [email protected], and the server you are working with is the mail server for bar.com. You would first need to create a .forward file for this account. On the server I worked on, this would be:</p>\n\n<p>/home/email/[email protected]/.forward</p>\n\n<p>The contents of that file were as follows:</p>\n\n<p>\"|/path/to/script.php\"</p>\n\n<p>Also, the .forward file's owner was [email protected], and it was chmod'd to 600 (read/write to owner only.)</p>\n\n<p>Next, you need to setup the script you're piping the mail to (/path/to/script.php above.)\nFirstly, that script needs to be executable (+x). The rest simply reads STDIN and handles it however you wish. Here's a sample script that reads the entire message and stores it in a variable $email.</p>\n\n<pre><code>#!/usr/local/bin/php\n&lt;?php\n$fd = fopen(\"php://stdin\",\"r\");\n$email = '';\nwhile($feof($fd)){\n $email .= fread($fd, 1024);\n}\nfclose($fd);\n?&gt;\n</code></pre>\n\n<p>Hopefully that was of some help to you.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Working on a little side project web app... I'd like to have it set up so that, when users send email to a certain account, I can kick off a PHP script that reads the email, pulls out some key info, and writes it to a database. What's the best way to do this? A cron job that checks for new email? The app is running on a "Dedicated-Virtual" Server at MediaTemple, so I guess I have a reasonable level of control, which should give me a range of options. I'm very slowly learning the ropes (PHP, MySQL, configuring/managing the server), so your advice and insight are much appreciated. Cheers, Matt Stuehler
Procmail is how I do it. Here's an example where I actually process the text inside the email to archive it back to a MySQL database. ``` :0: * ^(From).*[email protected] { :0 c | php /var/www/app/process_email.php } ```
33,469
<p>So I just fixed a bug in a framework I'm developing. The pseudo-pseudocode looks like this:</p> <pre><code>myoldObject = new MyObject { someValue = "old value" }; cache.Insert("myObjectKey", myoldObject); myNewObject = cache.Get("myObjectKey"); myNewObject.someValue = "new value"; if(myObject.someValue != cache.Get("myObjectKey").someValue) myObject.SaveToDatabase(); </code></pre> <p>So, essentially, I was getting an object from the cache, and then later on comparing the original object to the cached object to see if I need to save it to the database in case it's changed. The problem arose because the original object is a reference...so changing someValue also changed the referenced cached object, so it'd never save back to the database. I fixed it by cloning the object off of the cached version, severing the reference and allowing me to compare the new object against the cached one.</p> <p>My question is: <strong>is there a better way to do this, some pattern, that you could recommend?</strong> I can't be the only person that's done this before :)</p>
[ { "answer_id": 33507, "author": "Craig Walker", "author_id": 3488, "author_profile": "https://Stackoverflow.com/users/3488", "pm_score": 1, "selected": false, "text": "<p>I've done similar things, but I got around it by cloning too. The difference is that I had the cache do the cloning. When you put an object into the cache, the cache will clone the object first and store the cloned version (so you can mutate the original object without poisoning the cache). When you get an object from the cache, the cache returns a clone of the object instead of the stored object (again so that the caller can mutate the object without effecting the cached/canonical object).</p>\n\n<p>I think that this is perfectly acceptable as long as the data you're storing/duping is small. </p>\n" }, { "answer_id": 33795, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 6, "selected": true, "text": "<p>Dirty tracking is the normal way to handle this, I think. Something like:</p>\n\n<pre><code>class MyObject {\n public string SomeValue { \n get { return _someValue; }\n set { \n if (value != SomeValue) {\n IsDirty = true;\n _someValue = value;\n }\n }\n\n public bool IsDirty {\n get;\n private set;\n }\n\n void SaveToDatabase() {\n base.SaveToDatabase(); \n IsDirty = false;\n }\n}\n\nmyoldObject = new MyObject { someValue = \"old value\" };\ncache.Insert(\"myObjectKey\", myoldObject);\nmyNewObject = cache.Get(\"myObjectKey\");\nmyNewObject.someValue = \"new value\";\nif(myNewObject.IsDirty)\n myNewObject.SaveToDatabase();\n</code></pre>\n" }, { "answer_id": 9415335, "author": "Contra", "author_id": 112508, "author_profile": "https://Stackoverflow.com/users/112508", "pm_score": 1, "selected": false, "text": "<p>A little improvement on Marks anwser when using linq:</p>\n\n<p>When using Linq, fetching entities from DB will mark every object as IsDirty. \nI made a workaround for this, by not setting IsDirty when the value is not set; for this instance: when null. For ints, I sat the orig-value to -1, and then checked for that. This will not work, however, if the saved value is the same as the uninitialized value (null in my example). </p>\n\n<pre><code>private string _name;\n[Column]\npublic string Name\n{\n get { return _name; }\n set\n {\n if (value != _name)\n {\n if (_name != null)\n {\n IsDirty = true; \n }\n _name = value;\n }\n }\n}\n</code></pre>\n\n<p>Could probably be improved further by setting IsDirty after initialization somehow.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212/" ]
So I just fixed a bug in a framework I'm developing. The pseudo-pseudocode looks like this: ``` myoldObject = new MyObject { someValue = "old value" }; cache.Insert("myObjectKey", myoldObject); myNewObject = cache.Get("myObjectKey"); myNewObject.someValue = "new value"; if(myObject.someValue != cache.Get("myObjectKey").someValue) myObject.SaveToDatabase(); ``` So, essentially, I was getting an object from the cache, and then later on comparing the original object to the cached object to see if I need to save it to the database in case it's changed. The problem arose because the original object is a reference...so changing someValue also changed the referenced cached object, so it'd never save back to the database. I fixed it by cloning the object off of the cached version, severing the reference and allowing me to compare the new object against the cached one. My question is: **is there a better way to do this, some pattern, that you could recommend?** I can't be the only person that's done this before :)
Dirty tracking is the normal way to handle this, I think. Something like: ``` class MyObject { public string SomeValue { get { return _someValue; } set { if (value != SomeValue) { IsDirty = true; _someValue = value; } } public bool IsDirty { get; private set; } void SaveToDatabase() { base.SaveToDatabase(); IsDirty = false; } } myoldObject = new MyObject { someValue = "old value" }; cache.Insert("myObjectKey", myoldObject); myNewObject = cache.Get("myObjectKey"); myNewObject.someValue = "new value"; if(myNewObject.IsDirty) myNewObject.SaveToDatabase(); ```
33,471
<p>Is there a way to tell subversion "update/merge unless it would cause a conflict"?</p> <p>I know you can use <code>--dry-run</code> / <code>status -u</code> to check before running the update, but I often have others running updates and getting broken webpages because they don't notice the "C index.php" line.</p> <p>I've also noticed that svn doesn't seem too unhappy about conflicts - it still says "updated to revision blah" and exits zero, regardless of conflicts. So I have to parse the line-by-line output to discover them. Surely there's a better way?</p>
[ { "answer_id": 33483, "author": "jsight", "author_id": 1432, "author_profile": "https://Stackoverflow.com/users/1432", "pm_score": 1, "selected": false, "text": "<p>Perhaps a better way is to use a graphical tool? Or write a script to do the update that redirects the output to a file and does a \"cat svnupdate.log | grep \"^C \"\" at the end to show you any conflicts?</p>\n\n<p>With the graphical tools that I use (TortoiseSVN and Netbeans), they make a nasty noise at the end and present you with a merge selection dialog for dealing with them. I don't know of an equivalent with as much power for the command line tools.</p>\n" }, { "answer_id": 33504, "author": "Peter Stone", "author_id": 1806, "author_profile": "https://Stackoverflow.com/users/1806", "pm_score": 1, "selected": false, "text": "<p>@jsight: TortoiseSVN is great, but I primarily develop in a *NIX environment, without X. So I'm usually using (restricted to) the command line.</p>\n\n<p>In re your script suggestion, that's what I'm working on now - which is why I'm annoyed that I can't just check $?. Right now I'm skipping the \"output to a file\" and using a pipe, but otherwise exactly what you describe.</p>\n" }, { "answer_id": 33646, "author": "Damien B", "author_id": 3069, "author_profile": "https://Stackoverflow.com/users/3069", "pm_score": 1, "selected": false, "text": "<p>You could use the --diff3-cmd parameter to specify which merging tool to use (usually diff3 from diffutils).</p>\n" }, { "answer_id": 152539, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 0, "selected": false, "text": "<p>you could also use a pre-commit script to look for conflict markers in files and prevent commit when they are present.</p>\n" }, { "answer_id": 164940, "author": "Sander Rijken", "author_id": 5555, "author_profile": "https://Stackoverflow.com/users/5555", "pm_score": 3, "selected": true, "text": "<p>You can use the --accept parameter to indicate what should happen when a conflict occurs:</p>\n\n<pre><code>--accept ARG : specify automatic conflict resolution action\n ('postpone', 'base', 'mine-full', 'theirs-full',\n 'edit', 'launch')\n</code></pre>\n\n<p>See also the <a href=\"http://svnbook.red-bean.com/en/1.5/svn.tour.cycle.html#svn.tour.cycle.resolve.diff\" rel=\"nofollow noreferrer\">interactive conflict resolution</a> page in the svnbook</p>\n" }, { "answer_id": 165026, "author": "jackr", "author_id": 9205, "author_profile": "https://Stackoverflow.com/users/9205", "pm_score": 0, "selected": false, "text": "<p>Subversion 1.5 (recently released) adds some ability to specify what happens during an update conflict, with the \"--accept\" argument.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1806/" ]
Is there a way to tell subversion "update/merge unless it would cause a conflict"? I know you can use `--dry-run` / `status -u` to check before running the update, but I often have others running updates and getting broken webpages because they don't notice the "C index.php" line. I've also noticed that svn doesn't seem too unhappy about conflicts - it still says "updated to revision blah" and exits zero, regardless of conflicts. So I have to parse the line-by-line output to discover them. Surely there's a better way?
You can use the --accept parameter to indicate what should happen when a conflict occurs: ``` --accept ARG : specify automatic conflict resolution action ('postpone', 'base', 'mine-full', 'theirs-full', 'edit', 'launch') ``` See also the [interactive conflict resolution](http://svnbook.red-bean.com/en/1.5/svn.tour.cycle.html#svn.tour.cycle.resolve.diff) page in the svnbook
33,475
<p>I need to launch a server on the remote machine and retrieve the port number that the server process is lsitening on. When invoked, the server will listen on a random port and output the port number on stderr.</p> <p>I want to automate the process of logging on to the remote machine, launching the process, and retrieving the port number. I wrote a Python script called "<code>invokejob.py</code>" that lives on the remote machine to act as a wrapper that invokes the job and then returns the port number, it looks like this:</p> <pre><code>import re, subprocess executable = ... # Name of executable regex = ... # Regex to extract the port number from the output p = subprocess.Popen(executable, bufsize=1, # line buffered stderr=subprocess.PIPE ) s = p.stderr.readline() port = re.match(regex).groups()[0] print port </code></pre> <p>If I log in interactively, this script works:</p> <pre><code>$ ssh remotehost.example.com Last login: Thu Aug 28 17:31:18 2008 from localhost $ ./invokejob.py 63409 $ exit logout Connection to remotehost.example.com closed. </code></pre> <p>(Note: successful logout, it did not hang).</p> <p>However, if I try to invoke it from the command-line, it just hangs:</p> <pre><code>$ ssh remotehost.example.com invokejob.py </code></pre> <p>Does anybody know why it hangs in the second case, and what I can do to avoid this? </p> <p>Note that I need to retrieve the output of the program, so I can't just use the ssh "-f" flag or redirect standard output.</p>
[ { "answer_id": 33486, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 3, "selected": true, "text": "<blockquote>\n<pre><code>s = p.stderr.readline()\n</code></pre>\n</blockquote>\n\n<p>I suspect it's the above line. When you invoke a command directly through ssh, you don't get your full pty (assuming Linux), and thus no stderr to read from.</p>\n\n<p>When you log in interactively, stdin, stdout, and stderr are set up for you, and so your script works.</p>\n" }, { "answer_id": 33673, "author": "Misha M", "author_id": 3467, "author_profile": "https://Stackoverflow.com/users/3467", "pm_score": 0, "selected": false, "text": "<p>what if you do the following:</p>\n\n<h2><code>ssh &lt;remote host&gt; '&lt;your command&gt; ;&lt;your regexp using awk or something&gt;'</code></h2>\n\n<p>For example</p>\n\n<h2><code>ssh &lt;remote host&gt; '&lt;your program&gt;; ps aux | awk \\'/root/ {print $2}\\''</code></h2>\n\n<p>This will connect to , execute and then print each PSID for any user root or any process with root in its description.</p>\n\n<p>I have used this method for running all kinds of commands on remote machines. The catch is to wrap the command(s) you wish to execute in single quotation marks (') and to separate each command with a semi-colon (;).</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
I need to launch a server on the remote machine and retrieve the port number that the server process is lsitening on. When invoked, the server will listen on a random port and output the port number on stderr. I want to automate the process of logging on to the remote machine, launching the process, and retrieving the port number. I wrote a Python script called "`invokejob.py`" that lives on the remote machine to act as a wrapper that invokes the job and then returns the port number, it looks like this: ``` import re, subprocess executable = ... # Name of executable regex = ... # Regex to extract the port number from the output p = subprocess.Popen(executable, bufsize=1, # line buffered stderr=subprocess.PIPE ) s = p.stderr.readline() port = re.match(regex).groups()[0] print port ``` If I log in interactively, this script works: ``` $ ssh remotehost.example.com Last login: Thu Aug 28 17:31:18 2008 from localhost $ ./invokejob.py 63409 $ exit logout Connection to remotehost.example.com closed. ``` (Note: successful logout, it did not hang). However, if I try to invoke it from the command-line, it just hangs: ``` $ ssh remotehost.example.com invokejob.py ``` Does anybody know why it hangs in the second case, and what I can do to avoid this? Note that I need to retrieve the output of the program, so I can't just use the ssh "-f" flag or redirect standard output.
> > > ``` > s = p.stderr.readline() > > ``` > > I suspect it's the above line. When you invoke a command directly through ssh, you don't get your full pty (assuming Linux), and thus no stderr to read from. When you log in interactively, stdin, stdout, and stderr are set up for you, and so your script works.
33,529
<p>Inspired by this CodingHorror article, "<a href="http://www.codinghorror.com/blog/archives/001167.html" rel="noreferrer">Protecting Your Cookies: HttpOnly</a>"</p> <p>How do you set this property? Somewhere in the web config?</p>
[ { "answer_id": 33532, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 4, "selected": false, "text": "<p>With props to Rick (second comment down in the blog post mentioned), here's the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.httponlycookies.aspx\" rel=\"noreferrer\">MSDN article</a> on httpOnlyCookies.</p>\n\n<p>Bottom line is that you just add the following section in your system.web section in your web.config:</p>\n\n<pre><code>&lt;httpCookies domain=\"\" httpOnlyCookies=\"true|false\" requireSSL=\"true|false\" /&gt;\n</code></pre>\n" }, { "answer_id": 33541, "author": "Corey McKinnon", "author_id": 633, "author_profile": "https://Stackoverflow.com/users/633", "pm_score": 7, "selected": true, "text": "<p>If you're using ASP.NET 2.0 or greater, you can turn it on in the Web.config file. In the &lt;system.web&gt; section, add the following line:</p>\n\n<pre><code>&lt;httpCookies httpOnlyCookies=\"true\"/&gt;\n</code></pre>\n" }, { "answer_id": 33887, "author": "Portman", "author_id": 1690, "author_profile": "https://Stackoverflow.com/users/1690", "pm_score": 3, "selected": false, "text": "<p>If you want to do it in code, use the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httpcookie.httponly.aspx\" rel=\"noreferrer\">System.Web.HttpCookie.HttpOnly</a> property.</p>\n\n<p>This is directly from the MSDN docs:</p>\n\n<pre><code>// Create a new HttpCookie.\nHttpCookie myHttpCookie = new HttpCookie(\"LastVisit\", DateTime.Now.ToString());\n// By default, the HttpOnly property is set to false \n// unless specified otherwise in configuration.\nmyHttpCookie.Name = \"MyHttpCookie\";\nResponse.AppendCookie(myHttpCookie);\n// Show the name of the cookie.\nResponse.Write(myHttpCookie.Name);\n// Create an HttpOnly cookie.\nHttpCookie myHttpOnlyCookie = new HttpCookie(\"LastVisit\", DateTime.Now.ToString());\n// Setting the HttpOnly value to true, makes\n// this cookie accessible only to ASP.NET.\nmyHttpOnlyCookie.HttpOnly = true;\nmyHttpOnlyCookie.Name = \"MyHttpOnlyCookie\";\nResponse.AppendCookie(myHttpOnlyCookie);\n// Show the name of the HttpOnly cookie.\nResponse.Write(myHttpOnlyCookie.Name);\n</code></pre>\n\n<p>Doing it in code allows you to selectively choose which cookies are HttpOnly and which are not.</p>\n" }, { "answer_id": 770764, "author": "Matthew Lock", "author_id": 74585, "author_profile": "https://Stackoverflow.com/users/74585", "pm_score": 2, "selected": false, "text": "<p>Interestingly putting <code>&lt;httpCookies httpOnlyCookies=\"false\"/&gt;</code> doesn't seem to disable <code>httpOnlyCookies</code> in ASP.NET 2.0. Check this article about <a href=\"http://nerd.steveferson.com/2007/09/14/act-sessionid-and-login-problems-with-asp-net-20/\" rel=\"nofollow noreferrer\">SessionID and Login Problems With ASP .NET 2.0</a>.</p>\n\n<p>Looks like Microsoft took the decision to not allow you to disable it from the web.config. Check this <a href=\"http://forums.asp.net/p/976773/1240648.aspx\" rel=\"nofollow noreferrer\">post on forums.asp.net</a></p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1842/" ]
Inspired by this CodingHorror article, "[Protecting Your Cookies: HttpOnly](http://www.codinghorror.com/blog/archives/001167.html)" How do you set this property? Somewhere in the web config?
If you're using ASP.NET 2.0 or greater, you can turn it on in the Web.config file. In the <system.web> section, add the following line: ``` <httpCookies httpOnlyCookies="true"/> ```
33,534
<p>I'm trying to extend some "base" classes in Python:</p> <pre><code>class xlist (list): def len(self): return len(self) def add(self, *args): self.extend(args) return None class xint (int): def add(self, value): self += value return self x = xlist([1,2,3]) print x.len() ## &gt;&gt;&gt; 3 ok print x ## &gt;&gt;&gt; [1,2,3] ok x.add (4, 5, 6) print x ## &gt;&gt;&gt; [1,2,3,4,5,6] ok x = xint(10) print x ## &gt;&gt;&gt; 10 ok x.add (2) print x ## &gt;&gt;&gt; 10 # Not ok (#1) print type(x) ## &gt;&gt;&gt; &lt;class '__main__.xint'&gt; ok x += 5 print type(x) ## &gt;&gt;&gt; &lt;type 'int'&gt; # Not ok (#2) </code></pre> <p>It works fine in the <em>list</em> case because the <em>append</em> method modifies the object "in place", without returning it. But in the <em>int</em> case, the <em>add</em> method doesn't modify the value of the external <em>x</em> variable. I suppose that's fine in the sense that <em>self</em> is a local variable in the <em>add</em> method of the class, but this is preventing me from modifying the initial value assigned to the instance of the class.</p> <p>Is it possible to extend a class this way or should I define a class property with the base type and map all the needed methods to this property?</p>
[ { "answer_id": 33556, "author": "dwestbrook", "author_id": 3119, "author_profile": "https://Stackoverflow.com/users/3119", "pm_score": 0, "selected": false, "text": "<p>Ints are immutable and you can't modify them in place, so you should go with option #2 (because option #1 is impossible without some trickery).</p>\n" }, { "answer_id": 33563, "author": "John Douthat", "author_id": 2774, "author_profile": "https://Stackoverflow.com/users/2774", "pm_score": 4, "selected": true, "text": "<p><code>int</code> is a value type, so each time you do an assignment, (e.g. both instances of <code>+=</code> above), it doesn't modify the object you have on the heap, but replaces the reference with one of the result of the right hand side of the assignment (i.e. an <code>int</code>)</p>\n<p><code>list</code> isn't a value type, so it isn't bound by the same rules.</p>\n<p>this page has more details on the differences: <a href=\"https://docs.python.org/3/reference/datamodel.html\" rel=\"nofollow noreferrer\">The Python Language Reference - 3. Data model</a></p>\n<p>IMO, yes, you should define a new class that keeps an int as an instance variable</p>\n" }, { "answer_id": 33663, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 5, "selected": false, "text": "<p>Your two <code>xint</code> examples don't work for two different reasons.</p>\n\n<p>The first doesn't work because <code>self += value</code> is equivalent to <code>self = self + value</code> which just reassigns the local variable <code>self</code> to a different object (an integer) but doesn't change the original object. You can't really get this </p>\n\n<pre><code>&gt;&gt;&gt; x = xint(10)\n&gt;&gt;&gt; x.add(2)\n</code></pre>\n\n<p>to work with a subclass of <code>int</code> since integers are <a href=\"http://docs.python.org/ref/objects.html\" rel=\"noreferrer\">immutable</a>.</p>\n\n<p>To get the second one to work you can define an <a href=\"http://docs.python.org/ref/numeric-types.html\" rel=\"noreferrer\"><code>__add__</code> method</a>, like so:</p>\n\n<pre><code>class xint(int):\n def __add__(self, value):\n return xint(int.__add__(self, value))\n\n&gt;&gt;&gt; x = xint(10)\n&gt;&gt;&gt; type(x)\n&lt;class '__main__.xint'&gt;\n&gt;&gt;&gt; x += 3\n&gt;&gt;&gt; x\n13\n&gt;&gt;&gt; type(x)\n&lt;class '__main__.xint'&gt;\n</code></pre>\n" }, { "answer_id": 6809498, "author": "gtmanfred", "author_id": 786635, "author_profile": "https://Stackoverflow.com/users/786635", "pm_score": 2, "selected": false, "text": "<p>i expanded you xlist class just a bit, made it so you could find all index points of a number making it so you can extend with multiple lists at once making it initialize and making it so you can iterate through it</p>\n\n<pre><code>class xlist:\n def __init__(self,alist):\n if type(alist)==type(' '):\n self.alist = [int(i) for i in alist.split(' ')]\n else:\n self.alist = alist\n def __iter__(self):\n i = 0\n while i&lt;len(self.alist):\n yield self.alist[i]\n i+=1\n def len(self):\n return len(self.alist)\n def add(self, *args):\n if type(args[0])==type([1]):\n if len(args)&gt;1:\n tmp = []\n [tmp.extend(i) for i in args]\n args = tmp\n else:args = args[0]\n if type(args)==type(''):args = [int(i) for i in args.split(' ')] \n (self.alist).extend(args)\n return None\n def index(self,val):\n gen = (i for i,x in enumerate(self.alist) if x == val)\n return list(gen)\n</code></pre>\n" }, { "answer_id": 71140509, "author": "Raphael", "author_id": 5943840, "author_profile": "https://Stackoverflow.com/users/5943840", "pm_score": 0, "selected": false, "text": "<p>I wrote an example of a mutable integer class that implements some basic methods from <a href=\"https://docs.python.org/3/library/operator.html#mapping-operators-to-functions\" rel=\"nofollow noreferrer\">the list of operator methods</a>. It can print properly, add, subtract, multiply, divide, sort, and compare equality.</p>\n<p>If you want it to do everything an int can you'll have to implement more methods.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class MutablePartialInt:\n def __init__(self, value):\n self.value = value\n\n def _do_relational_method(self, other, method_to_run):\n func = getattr(self.value, method_to_run)\n if type(other) is MutablePartialInt:\n return func(other.value)\n else:\n return func(other)\n\n def __add__(self, other):\n return self._do_relational_method(other, &quot;__add__&quot;)\n \n def __sub__(self, other):\n return self._do_relational_method(other, &quot;__sub__&quot;)\n\n def __mul__(self, other):\n return self._do_relational_method(other, &quot;__mul__&quot;)\n \n def __truediv__(self, other):\n return self._do_relational_method(other, &quot;__truediv__&quot;)\n\n def __floordiv__(self, other):\n return self._do_relational_method(other, &quot;__floordiv__&quot;)\n\n def __eq__(self, other):\n return self._do_relational_method(other, &quot;__eq__&quot;)\n \n def __neq__(self, other):\n return self._do_relational_method(other, &quot;__neq__&quot;)\n\n def __lt__(self, other):\n return self._do_relational_method(other, &quot;__lt__&quot;)\n\n def __gt__(self, other):\n return self._do_relational_method(other, &quot;__gt__&quot;)\n\n def __str__(self):\n return str(self.value)\n\n def __repr__(self):\n return self.__str__()\n</code></pre>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/394/" ]
I'm trying to extend some "base" classes in Python: ``` class xlist (list): def len(self): return len(self) def add(self, *args): self.extend(args) return None class xint (int): def add(self, value): self += value return self x = xlist([1,2,3]) print x.len() ## >>> 3 ok print x ## >>> [1,2,3] ok x.add (4, 5, 6) print x ## >>> [1,2,3,4,5,6] ok x = xint(10) print x ## >>> 10 ok x.add (2) print x ## >>> 10 # Not ok (#1) print type(x) ## >>> <class '__main__.xint'> ok x += 5 print type(x) ## >>> <type 'int'> # Not ok (#2) ``` It works fine in the *list* case because the *append* method modifies the object "in place", without returning it. But in the *int* case, the *add* method doesn't modify the value of the external *x* variable. I suppose that's fine in the sense that *self* is a local variable in the *add* method of the class, but this is preventing me from modifying the initial value assigned to the instance of the class. Is it possible to extend a class this way or should I define a class property with the base type and map all the needed methods to this property?
`int` is a value type, so each time you do an assignment, (e.g. both instances of `+=` above), it doesn't modify the object you have on the heap, but replaces the reference with one of the result of the right hand side of the assignment (i.e. an `int`) `list` isn't a value type, so it isn't bound by the same rules. this page has more details on the differences: [The Python Language Reference - 3. Data model](https://docs.python.org/3/reference/datamodel.html) IMO, yes, you should define a new class that keeps an int as an instance variable
33,577
<p>I want to check out all files in all subdirectories of a specified folder.</p> <p>(And it is painful to do this using the GUI, because there is no recursive checkout option).</p>
[ { "answer_id": 33605, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "<pre><code>cleartool find somedir -exec \"cleartool checkout -nc \\\"%CLEARCASE_PN%\\\"\"\n</code></pre>\n\n<p>Also an article \"<a href=\"http://www.ibm.com/developerworks/rational/library/4687.html\" rel=\"noreferrer\">ClearCase: The ten best scripts</a>\" might be helpful</p>\n" }, { "answer_id": 119595, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 6, "selected": true, "text": "<p>Beware: ClearCase is File-centric, not repository centric (like SVN or CVS).</p>\n\n<p>That means it is rarely a good solution to checkout all files (and it can be fairly long with ClearCase ;) )</p>\n\n<p>That being said, the question is perfectly legitimate and I would like to point out another way:</p>\n\n<p>open a <code>cleartool</code> session in the 'specified folder':</p>\n\n<pre><code>c:\\MyFolder&gt; cleartool\ncleartool&gt; co -c \"Reason for massive checkout\" .../*\n</code></pre>\n\n<p>does the trick too. But as the aku's answer, it does checkout <em>everything</em>: files and directories... and you may most <em>not need</em> to checkout directories! </p>\n\n<pre><code>cleartool find somedir -type f -exec \"cleartool checkout -c \\\"Reason for massive checkout\\\" \\\"%CLEARCASE_PN%\\\"\"\n</code></pre>\n\n<p>would only checkout files...</p>\n\n<p>Now the problem is to checkin everything that has changed. It is problematic since often <em>not everything</em> has changed, and CleaCase will trigger an error message when trying to check in an identical file. Meaning you will need 2 commands:</p>\n\n<pre><code>ct lsco -r -cvi -fmt \"ci -nc \\\"%n\\\"\\n\" | ct\nct lsco -r -cvi -fmt \"unco -rm %n\\n\" | ct\n</code></pre>\n\n<p>(with '<code>ct</code> being '<code>cleartool</code>' : type '<code>doskey ct=cleartool $*</code>' on Windows to set that alias)</p>\n\n<p>Note that <code>ct ci -nc</code> will check-in with the comment used for the checkout stage.<br>\nSo it is <em>not</em> a checkin without a comment (like the <code>-nc</code> option -- or \"no comment\" -- could make believe).</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ]
I want to check out all files in all subdirectories of a specified folder. (And it is painful to do this using the GUI, because there is no recursive checkout option).
Beware: ClearCase is File-centric, not repository centric (like SVN or CVS). That means it is rarely a good solution to checkout all files (and it can be fairly long with ClearCase ;) ) That being said, the question is perfectly legitimate and I would like to point out another way: open a `cleartool` session in the 'specified folder': ``` c:\MyFolder> cleartool cleartool> co -c "Reason for massive checkout" .../* ``` does the trick too. But as the aku's answer, it does checkout *everything*: files and directories... and you may most *not need* to checkout directories! ``` cleartool find somedir -type f -exec "cleartool checkout -c \"Reason for massive checkout\" \"%CLEARCASE_PN%\"" ``` would only checkout files... Now the problem is to checkin everything that has changed. It is problematic since often *not everything* has changed, and CleaCase will trigger an error message when trying to check in an identical file. Meaning you will need 2 commands: ``` ct lsco -r -cvi -fmt "ci -nc \"%n\"\n" | ct ct lsco -r -cvi -fmt "unco -rm %n\n" | ct ``` (with '`ct` being '`cleartool`' : type '`doskey ct=cleartool $*`' on Windows to set that alias) Note that `ct ci -nc` will check-in with the comment used for the checkout stage. So it is *not* a checkin without a comment (like the `-nc` option -- or "no comment" -- could make believe).
33,590
<p>Has anyone looked at <a href="http://developer.yahoo.com/flash/" rel="nofollow noreferrer">Yahoo's ASTRA</a>? It's fairly nifty, but I had some issues creating a custom label for a pie chart. They have an example for a line chart, which overrides an axis's series's label renderer. My solution was to override the <code>myPieChart.dataTipFunction</code>. For data that looks like:</p> <pre><code>myPieChart.dataProvider = [ { category: &quot;Groceries&quot;, cost: 50 }, { category: &quot;Transportation&quot;, cost: 175} ] myPieChart.dataField = &quot;cost&quot;; myPieChart.categoryField = &quot;category&quot;; </code></pre> <p>I wrote a function like this:</p> <pre><code>import com.yahoo.astra.fl.charts.series.* myPieChart.dataTipFunction = function (obj:Object, index:int, series:ISeries):String { return obj.category + &quot;\n$&quot; + obj.cost; }; </code></pre> <p>There's ceil(2.718281828459045) problems with this:</p> <ol> <li><p>I'm directly calling the category and cost properties of the data provider. The names are actually configurable when setting up the chart, I'd like to maintain that flexibility.</p> </li> <li><p>The default data tip would show the category, the cost (without a dollar sign), and the percentage it makes up in the pie chart. So here, I've lost the percentage. I just have no idea which property of what would hold that. It might be part of the series.</p> </li> <li><p>I probably only need to override the <code>dataItemRenderer</code> for the cost part of the series, but I don't know how to access it. The documentation is a little ... lacking there.</p> </li> </ol> <p>Normally I would just look at the default implementation of the <code>dataTipFunction</code> but it's all inside a compiled shm that's part of the components distributed from yahoo.</p> <p>Can anyone help me complete this overridden function with percentage information and the flexibility mentioned in point 1?</p>
[ { "answer_id": 35019, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 3, "selected": true, "text": "<p>Okay... so no-one's tried Astra, or people just avoid Flash questions.</p>\n\n<p>After a lot of guess work it turns out I needed to cast the series to a PieSeries and then work with those member functions, as the ISeries was useless on it's own.</p>\n\n<pre><code>myPieChart.dataTipFunction = \n function (item:Object, index:int, series:ISeries):String {\n var oPieSeries:PieSeries = series as PieSeries;\n return oPieSeries.itemToCategory(item,index) + \"\\n$\" + \n oPieSeries.itemToData(item) + \"\\n\" + \n Number(oPieSeries.itemToPercentage(item)).toFixed(2) + \"%\";\n };\n</code></pre>\n" }, { "answer_id": 68699, "author": "Josh Tynjala", "author_id": 10768, "author_profile": "https://Stackoverflow.com/users/10768", "pm_score": 0, "selected": false, "text": "<p>The Astra components are distributed with the complete source code. Flash CS3 components use compiled shims because otherwise you'd need to manually add the raw source files to your classpath. As a bonus, they also improve compile times because they're already built for you. Look in the \"Source\" folder in the Astra zip file, and you'll find all the ActionScript classes for the Astra components.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459/" ]
Has anyone looked at [Yahoo's ASTRA](http://developer.yahoo.com/flash/)? It's fairly nifty, but I had some issues creating a custom label for a pie chart. They have an example for a line chart, which overrides an axis's series's label renderer. My solution was to override the `myPieChart.dataTipFunction`. For data that looks like: ``` myPieChart.dataProvider = [ { category: "Groceries", cost: 50 }, { category: "Transportation", cost: 175} ] myPieChart.dataField = "cost"; myPieChart.categoryField = "category"; ``` I wrote a function like this: ``` import com.yahoo.astra.fl.charts.series.* myPieChart.dataTipFunction = function (obj:Object, index:int, series:ISeries):String { return obj.category + "\n$" + obj.cost; }; ``` There's ceil(2.718281828459045) problems with this: 1. I'm directly calling the category and cost properties of the data provider. The names are actually configurable when setting up the chart, I'd like to maintain that flexibility. 2. The default data tip would show the category, the cost (without a dollar sign), and the percentage it makes up in the pie chart. So here, I've lost the percentage. I just have no idea which property of what would hold that. It might be part of the series. 3. I probably only need to override the `dataItemRenderer` for the cost part of the series, but I don't know how to access it. The documentation is a little ... lacking there. Normally I would just look at the default implementation of the `dataTipFunction` but it's all inside a compiled shm that's part of the components distributed from yahoo. Can anyone help me complete this overridden function with percentage information and the flexibility mentioned in point 1?
Okay... so no-one's tried Astra, or people just avoid Flash questions. After a lot of guess work it turns out I needed to cast the series to a PieSeries and then work with those member functions, as the ISeries was useless on it's own. ``` myPieChart.dataTipFunction = function (item:Object, index:int, series:ISeries):String { var oPieSeries:PieSeries = series as PieSeries; return oPieSeries.itemToCategory(item,index) + "\n$" + oPieSeries.itemToData(item) + "\n" + Number(oPieSeries.itemToPercentage(item)).toFixed(2) + "%"; }; ```
33,594
<p>I need to <code>ShellExecute</code> something as another user, currently I start a helper process with <code>CreateProcessAsUser</code> that calls <code>ShellExecute</code>, but that seems like too much of a hack (Wrong parent process etc.) Is there a better way to do this?</p> <p>@PabloG: ImpersonateLoggedOnUser does not work:</p> <pre> HANDLE hTok; VERIFY(LogonUser("otheruser",0,"password",LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT,&hTok)); VERIFY(ImpersonateLoggedOnUser(hTok)); ShellExecute(0,0,"calc.exe",0,0,SW_SHOW); RevertToSelf(); CloseHandle(hTok); </pre> <p>will just start calc as the logged in user, not "otheruser"</p> <p>@1800 INFORMATION: <code>CreateProcess</code>/<code>CreateProcessAsUser</code> is not the same as <code>ShellExecute</code>, with UAC on Vista, <code>CreateProcess</code> is useless when you don't have control over what program the user is executing (<code>CreateProcess</code> will return with a error if you give it a exe file with a manifest marked as requireAdmin)</p> <p>@Brian R. Bondy: I already know this info (And don't get me wrong, its good stuff), but it is off topic (IMHO) I am asking for a <code>ShellExecuteAsUser</code>, not about starting processes as another user, I already know how to do that.</p>
[ { "answer_id": 33661, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 0, "selected": false, "text": "<p>You can wrap the ShellExecute between ImpersonateLoggedOnUser / RevertToSelf</p>\n\n<p>links: \nImpersonateLoggedOnUser: <a href=\"http://msdn.microsoft.com/en-us/library/aa378612(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa378612(VS.85).aspx</a>\nRevertToSelf: <a href=\"http://msdn.microsoft.com/en-us/library/aa379317.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa379317.aspx</a></p>\n\n<p>sorry, cannot hyperlink URLs with \"()\"</p>\n" }, { "answer_id": 33824, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p>Why don't you just do CreateProcessAsUser specifying the process you want to run?</p>\n\n<p>You may also be able to use SHCreateProcessAsUserW.</p>\n" }, { "answer_id": 35688, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 3, "selected": false, "text": "<p>The solution really depends on what your needs are, and can be pretty complex (Thanks fully to Windows Vista). This is probably going to be beyond your need, but this will help others that find this page via search.</p>\n\n<ol>\n<li>If you do not need the process to run with a GUI and you do not require elevation</li>\n<li>If the user you want to run as is already logged into a session</li>\n<li>If you need to run the process with a GUI, and the user may, or may not be logged in</li>\n<li>If you need to run the process with elevation</li>\n</ol>\n\n<p><strong>Regarding 1:</strong>\nIn windows Vista there exists something called session 0 isolation. All services run as session 0 and you are not supposed to have a GUI in session 0. The first logged on user is logged into session 1. In previous versions of windows (pre Vista), the first logged on user was also ran fully in session 0. </p>\n\n<p>You can run several different processes with different usernames in the same session. You can find a good document about session 0 isolation <a href=\"http://www.microsoft.com/whdc/system/vista/services.mspx\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Since we're dealing with option 1), you don't need a GUI. Therefore you can start your process in session 0. </p>\n\n<p>You'll want a call sequence something like this:\nLogonUser, ExpandEnvironmentStringsForUser, GetLogonSID, LoadUserProfile, CreateEnvironmentBlock, CreateProcessAsUser. </p>\n\n<p>Example code for this can be found via any search engine, or via <a href=\"http://www.google.com/codesearch\" rel=\"noreferrer\">Google code search</a></p>\n\n<p><strong>Regarding 2:</strong> If the user you'd like to run the process as is already logged in, you can simply use: WTSEnumerateSessions, and WTSQuerySessionInformation to get the session ID, and then WTSQueryUserToken to get the user token. From there you can just use the user token in the CreateProcessAsUser Win32 API.</p>\n\n<p>This is a great method because you don't even need to login as the user nor know the user's username/password. I believe this is only possible via a service though running as local system account. </p>\n\n<p>You can get the current session via WTSGetActiveConsoleSessionId.</p>\n\n<p><strong>Regarding 3:</strong>\nYou would follow the same steps as #1, but in addition you would use the STARTUPINFO's lpDesktop field. Set this to winsta0\\Default. You will also need to try to use the OpenDesktop Win32 API and if this fails you can CreateDesktop. Before using the station and desktop handles you should use SetSecurityInfo on each of them with SE_WINDOW_OBJECT, and GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION.</p>\n\n<p>If the user in question later tries to login, he will actually see the running process. </p>\n\n<p><strong>Regarding 4:</strong>\nThis can be done as well, but it requires you to already be running an elevated process. A service running as local system account does run as elevated. I could also only get it to work by having an authenticode signed process that I wanted to start. The process you want to start also must have a manifest file associated with it with the requestedExecutionLevel level=\"requireAdministrator\"</p>\n\n<p>Other notes:</p>\n\n<ul>\n<li>You can set a token's session via SetTokenInformation and TokenSessionId</li>\n<li>You cannot change the session ID of an already running process. </li>\n<li>This whole process would be drastically more simple if Vista was not in the equation. </li>\n</ul>\n" }, { "answer_id": 1012800, "author": "devdimi", "author_id": 54983, "author_profile": "https://Stackoverflow.com/users/54983", "pm_score": 2, "selected": false, "text": "<p>If you need ShellExecute semantics you can feed following: </p>\n\n<p><code>C:\\windwos\\system32\\cmd.exe /k\" start &lt;your_target_to_be_ShellExecuted&gt;\"</code>\n to <code>CreateProcessAsUser</code> and you are done.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3501/" ]
I need to `ShellExecute` something as another user, currently I start a helper process with `CreateProcessAsUser` that calls `ShellExecute`, but that seems like too much of a hack (Wrong parent process etc.) Is there a better way to do this? @PabloG: ImpersonateLoggedOnUser does not work: ``` HANDLE hTok; VERIFY(LogonUser("otheruser",0,"password",LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT,&hTok)); VERIFY(ImpersonateLoggedOnUser(hTok)); ShellExecute(0,0,"calc.exe",0,0,SW_SHOW); RevertToSelf(); CloseHandle(hTok); ``` will just start calc as the logged in user, not "otheruser" @1800 INFORMATION: `CreateProcess`/`CreateProcessAsUser` is not the same as `ShellExecute`, with UAC on Vista, `CreateProcess` is useless when you don't have control over what program the user is executing (`CreateProcess` will return with a error if you give it a exe file with a manifest marked as requireAdmin) @Brian R. Bondy: I already know this info (And don't get me wrong, its good stuff), but it is off topic (IMHO) I am asking for a `ShellExecuteAsUser`, not about starting processes as another user, I already know how to do that.
The solution really depends on what your needs are, and can be pretty complex (Thanks fully to Windows Vista). This is probably going to be beyond your need, but this will help others that find this page via search. 1. If you do not need the process to run with a GUI and you do not require elevation 2. If the user you want to run as is already logged into a session 3. If you need to run the process with a GUI, and the user may, or may not be logged in 4. If you need to run the process with elevation **Regarding 1:** In windows Vista there exists something called session 0 isolation. All services run as session 0 and you are not supposed to have a GUI in session 0. The first logged on user is logged into session 1. In previous versions of windows (pre Vista), the first logged on user was also ran fully in session 0. You can run several different processes with different usernames in the same session. You can find a good document about session 0 isolation [here](http://www.microsoft.com/whdc/system/vista/services.mspx). Since we're dealing with option 1), you don't need a GUI. Therefore you can start your process in session 0. You'll want a call sequence something like this: LogonUser, ExpandEnvironmentStringsForUser, GetLogonSID, LoadUserProfile, CreateEnvironmentBlock, CreateProcessAsUser. Example code for this can be found via any search engine, or via [Google code search](http://www.google.com/codesearch) **Regarding 2:** If the user you'd like to run the process as is already logged in, you can simply use: WTSEnumerateSessions, and WTSQuerySessionInformation to get the session ID, and then WTSQueryUserToken to get the user token. From there you can just use the user token in the CreateProcessAsUser Win32 API. This is a great method because you don't even need to login as the user nor know the user's username/password. I believe this is only possible via a service though running as local system account. You can get the current session via WTSGetActiveConsoleSessionId. **Regarding 3:** You would follow the same steps as #1, but in addition you would use the STARTUPINFO's lpDesktop field. Set this to winsta0\Default. You will also need to try to use the OpenDesktop Win32 API and if this fails you can CreateDesktop. Before using the station and desktop handles you should use SetSecurityInfo on each of them with SE\_WINDOW\_OBJECT, and GROUP\_SECURITY\_INFORMATION | DACL\_SECURITY\_INFORMATION. If the user in question later tries to login, he will actually see the running process. **Regarding 4:** This can be done as well, but it requires you to already be running an elevated process. A service running as local system account does run as elevated. I could also only get it to work by having an authenticode signed process that I wanted to start. The process you want to start also must have a manifest file associated with it with the requestedExecutionLevel level="requireAdministrator" Other notes: * You can set a token's session via SetTokenInformation and TokenSessionId * You cannot change the session ID of an already running process. * This whole process would be drastically more simple if Vista was not in the equation.
33,685
<p>This is a sql 2000 database that I am working with.</p> <p>I have what I call a staging table that is a raw data dump of data, so everything is ntext or nvarchar(255). </p> <p>I need to cast/convert all of this data into the appropriate data types (ie int, decimal, nvarchar, etc.)</p> <p>The way I was going to do this was to iterate through all records using a while loop and attempt a CAST on each column on a single record during each iteration, after I visit a particular record I flag it as processed (bit field).</p> <p>But how can I log the error when/if it occurs but allow the while loop to continue.</p> <p>At first I implemented this using a TRY CATCH in a local SQL 2005 instance (to get the project going) and all was working well, but i learned today that the dev &amp; production database that the international DBA's have set up is a SQL 2000 instance so I have to conform.</p> <p><strong>EDIT</strong>: I am using a SSIS package to populate the staging table. I see that now I must revisit that package and implement a script component to handle the conversions. Thanks guys</p> <p><strong>EDIT</strong>: I <em>am</em> doing this on a record by record basis, not a batch insert, so the transaction idea seems like it would be feasible but I'm not sure how to trap @@ERROR and allow the stored procedure to continue.</p> <p><strong>EDIT</strong>: I really like <a href="https://stackoverflow.com/questions/33685/sql-2000-try-catch-like-error-handling#39161">Guy's approach</a>, I am going to implement it this way.</p>
[ { "answer_id": 33717, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 2, "selected": false, "text": "<p>What are you using to import the file? DTS has scripting abilities that can be used for data validation. If your not using DTS are you using a custom tool? If so do your validation there.</p>\n\n<p>But i think this is what your looking for.<br>\n<a href=\"http://www.sqlteam.com/article/using-dts-to-automate-a-data-import-process\" rel=\"nofollow noreferrer\">http://www.sqlteam.com/article/using-dts-to-automate-a-data-import-process</a></p>\n\n<pre><code>IF @@Error &lt;&gt; 0\n GOTO LABEL\n</code></pre>\n\n<p>@op<br>\nIn SSIS the \"red line\" from a data import task can redirect bad rows to a separate destination or transform. I haven't played with it in a while but hope it helps.</p>\n" }, { "answer_id": 33725, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 1, "selected": false, "text": "<p>It looks like you are doomed. See <a href=\"http://www.sommarskog.se/error-handling-I.html#whathappens\" rel=\"nofollow noreferrer\">this</a> document.</p>\n\n<p>TL/DR: A data conversion error always causes the whole batch to be aborted - your sql script will not continue to execute no matter what you do. Transactions won't help. You can't check @@ERROR because execution will already have aborted.</p>\n\n<p>I would first reexamine why you need a staging database full of varchar(255) columns - can whatever fills that database do the conversion?</p>\n\n<p>If not, I guess you'll need to write a program/script to select from the varchar columns, convert, and insert into the prod db.</p>\n" }, { "answer_id": 33740, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<p>Run each cast in a transaction, after each cast, check @@ERROR, if its clear, commit and move on.</p>\n" }, { "answer_id": 39136, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 1, "selected": false, "text": "<p>You could try checking for the data type before casting and actually avoid throwing errors.</p>\n\n<p>You could use functions like:<PRE>\nISNUM - to check if the data is of a numeric type\nISDATE - to check if it can be cast to DATETIME</PRE></p>\n" }, { "answer_id": 39161, "author": "Guy", "author_id": 993, "author_profile": "https://Stackoverflow.com/users/993", "pm_score": 3, "selected": true, "text": "<p>Generally I don't like \"loop through the record\" solutions as they tend to be slow and you end up writing a lot of custom code.</p>\n\n<p>So...</p>\n\n<p>Depending on how many records are in your staging table, you could post process the data with a series of SQL statements that test the columns for correctness and mark any records that fail the test.</p>\n\n<p>i.e.</p>\n\n<pre><code>UPDATE staging_table\nSET status_code = 'FAIL_TEST_1'\nWHERE status_code IS NULL\nAND ISDATE(ntext_column1) = 0;\n\nUPDATE staging_table\nSET status_code = 'FAIL_TEST_2'\nWHERE status_code IS NULL\nAND ISNUMERIC(ntext_column2) = 0;\n\netc...\n</code></pre>\n\n<p>Finally</p>\n\n<pre><code>INSERT INTO results_table ( mydate, myprice )\nSELECT ntext_column1 AS mydate, ntext_column2 AS myprice\nFROM staging_table\nWHERE status_code IS NULL;\n\nDELETE FROM staging_table\nWHERE status_code IS NULL;\n</code></pre>\n\n<p>And the staging table has all the errors, that you can export and report out.</p>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1950/" ]
This is a sql 2000 database that I am working with. I have what I call a staging table that is a raw data dump of data, so everything is ntext or nvarchar(255). I need to cast/convert all of this data into the appropriate data types (ie int, decimal, nvarchar, etc.) The way I was going to do this was to iterate through all records using a while loop and attempt a CAST on each column on a single record during each iteration, after I visit a particular record I flag it as processed (bit field). But how can I log the error when/if it occurs but allow the while loop to continue. At first I implemented this using a TRY CATCH in a local SQL 2005 instance (to get the project going) and all was working well, but i learned today that the dev & production database that the international DBA's have set up is a SQL 2000 instance so I have to conform. **EDIT**: I am using a SSIS package to populate the staging table. I see that now I must revisit that package and implement a script component to handle the conversions. Thanks guys **EDIT**: I *am* doing this on a record by record basis, not a batch insert, so the transaction idea seems like it would be feasible but I'm not sure how to trap @@ERROR and allow the stored procedure to continue. **EDIT**: I really like [Guy's approach](https://stackoverflow.com/questions/33685/sql-2000-try-catch-like-error-handling#39161), I am going to implement it this way.
Generally I don't like "loop through the record" solutions as they tend to be slow and you end up writing a lot of custom code. So... Depending on how many records are in your staging table, you could post process the data with a series of SQL statements that test the columns for correctness and mark any records that fail the test. i.e. ``` UPDATE staging_table SET status_code = 'FAIL_TEST_1' WHERE status_code IS NULL AND ISDATE(ntext_column1) = 0; UPDATE staging_table SET status_code = 'FAIL_TEST_2' WHERE status_code IS NULL AND ISNUMERIC(ntext_column2) = 0; etc... ``` Finally ``` INSERT INTO results_table ( mydate, myprice ) SELECT ntext_column1 AS mydate, ntext_column2 AS myprice FROM staging_table WHERE status_code IS NULL; DELETE FROM staging_table WHERE status_code IS NULL; ``` And the staging table has all the errors, that you can export and report out.
33,708
<p>So I've got a <code>JPanel</code> implementing <code>MouseListener</code> and <code>MouseMotionListener</code>:</p> <pre><code>import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DisplayArea extends JPanel implements MouseListener, MouseMotionListener { public DisplayArea(Rectangle bounds, Display display) { setLayout(null); setBounds(bounds); setOpaque(false); setPreferredSize(new Dimension(bounds.width, bounds.height)); this.display = display; } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; if (display.getControlPanel().Antialiasing()) { g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); } g2.setColor(Color.white); g2.fillRect(0, 0, getWidth(), getHeight()); } public void mousePressed(MouseEvent event) { System.out.println("mousePressed()"); mx1 = event.getX(); my1 = event.getY(); } public void mouseReleased(MouseEvent event) { System.out.println("mouseReleased()"); mx2 = event.getX(); my2 = event.getY(); int mode = display.getControlPanel().Mode(); switch (mode) { case ControlPanel.LINE: System.out.println("Line from " + mx1 + ", " + my1 + " to " + mx2 + ", " + my2 + "."); } } public void mouseEntered(MouseEvent event) { System.out.println("mouseEntered()"); } public void mouseExited(MouseEvent event) { System.out.println("mouseExited()"); } public void mouseClicked(MouseEvent event) { System.out.println("mouseClicked()"); } public void mouseMoved(MouseEvent event) { System.out.println("mouseMoved()"); } public void mouseDragged(MouseEvent event) { System.out.println("mouseDragged()"); } private Display display = null; private int mx1 = -1; private int my1 = -1; private int mx2 = -1; private int my2 = -1; } </code></pre> <p>The trouble is, none of these mouse functions are ever called. <code>DisplayArea</code> is created like this:</p> <pre><code>da = new DisplayArea(new Rectangle(CONTROL_WIDTH, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT), this); </code></pre> <p>I am not really a Java programmer (this is part of an assignment), but I can't see anything glaringly obvious. Can someone smarter than I see anything?</p>
[ { "answer_id": 33715, "author": "Shabaz", "author_id": 1827, "author_profile": "https://Stackoverflow.com/users/1827", "pm_score": 5, "selected": true, "text": "<p>The <em>implements mouselistener, mousemotionlistener</em> just allows the displayArea class to listen to some, to be defined, Swing component's mouse events. You have to explicitly define what it should be listening at. So I suppose you could add something like this to the constructor:</p>\n\n<pre><code>this.addMouseListener(this);\nthis.addMouseMotionListener(this);\n</code></pre>\n" }, { "answer_id": 33716, "author": "Neal", "author_id": 723, "author_profile": "https://Stackoverflow.com/users/723", "pm_score": 2, "selected": false, "text": "<p>I don't see anywhere in the code where you call addMouseListener(this) or addMouseMotionListener(this) for the DisplayArea in order for it to subscribe to those events. </p>\n" }, { "answer_id": 33718, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 2, "selected": false, "text": "<p>I don't see any code here to register to the mouse listeners. You have to call addMouseListener(this) and addMouseMotionListener(this) on the DisplayArea.</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ]
So I've got a `JPanel` implementing `MouseListener` and `MouseMotionListener`: ``` import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DisplayArea extends JPanel implements MouseListener, MouseMotionListener { public DisplayArea(Rectangle bounds, Display display) { setLayout(null); setBounds(bounds); setOpaque(false); setPreferredSize(new Dimension(bounds.width, bounds.height)); this.display = display; } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; if (display.getControlPanel().Antialiasing()) { g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); } g2.setColor(Color.white); g2.fillRect(0, 0, getWidth(), getHeight()); } public void mousePressed(MouseEvent event) { System.out.println("mousePressed()"); mx1 = event.getX(); my1 = event.getY(); } public void mouseReleased(MouseEvent event) { System.out.println("mouseReleased()"); mx2 = event.getX(); my2 = event.getY(); int mode = display.getControlPanel().Mode(); switch (mode) { case ControlPanel.LINE: System.out.println("Line from " + mx1 + ", " + my1 + " to " + mx2 + ", " + my2 + "."); } } public void mouseEntered(MouseEvent event) { System.out.println("mouseEntered()"); } public void mouseExited(MouseEvent event) { System.out.println("mouseExited()"); } public void mouseClicked(MouseEvent event) { System.out.println("mouseClicked()"); } public void mouseMoved(MouseEvent event) { System.out.println("mouseMoved()"); } public void mouseDragged(MouseEvent event) { System.out.println("mouseDragged()"); } private Display display = null; private int mx1 = -1; private int my1 = -1; private int mx2 = -1; private int my2 = -1; } ``` The trouble is, none of these mouse functions are ever called. `DisplayArea` is created like this: ``` da = new DisplayArea(new Rectangle(CONTROL_WIDTH, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT), this); ``` I am not really a Java programmer (this is part of an assignment), but I can't see anything glaringly obvious. Can someone smarter than I see anything?
The *implements mouselistener, mousemotionlistener* just allows the displayArea class to listen to some, to be defined, Swing component's mouse events. You have to explicitly define what it should be listening at. So I suppose you could add something like this to the constructor: ``` this.addMouseListener(this); this.addMouseMotionListener(this); ```
33,746
<p>At work we are being asked to create XML files to pass data to another offline application that will then create a second XML file to pass back in order to update some of our data. During the process we have been discussing with the team of the other application about the structure of the XML file. </p> <p>The sample I came up with is essentially something like:</p> <pre><code>&lt;INVENTORY&gt; &lt;ITEM serialNumber="something" location="something" barcode="something"&gt; &lt;TYPE modelNumber="something" vendor="something"/&gt; &lt;/ITEM&gt; &lt;/INVENTORY&gt; </code></pre> <p>The other team said that this was not industry standard and that attributes should only be used for meta data. They suggested:</p> <pre><code>&lt;INVENTORY&gt; &lt;ITEM&gt; &lt;SERIALNUMBER&gt;something&lt;/SERIALNUMBER&gt; &lt;LOCATION&gt;something&lt;/LOCATION&gt; &lt;BARCODE&gt;something&lt;/BARCODE&gt; &lt;TYPE&gt; &lt;MODELNUMBER&gt;something&lt;/MODELNUMBER&gt; &lt;VENDOR&gt;something&lt;/VENDOR&gt; &lt;/TYPE&gt; &lt;/ITEM&gt; &lt;/INVENTORY&gt; </code></pre> <p>The reason I suggested the first is that the size of the file created is much smaller. There will be roughly 80000 items that will be in the file during transfer. Their suggestion in reality turns out to be three times larger than the one I suggested. I searched for the mysterious "Industry Standard" that was mentioned, but the closest I could find was that XML attributes should only be used for meta data, but said the debate was about what was actually meta data.</p> <p>After the long winded explanation (sorry) how do you determine what is meta data, and when designing the structure of an XML document how should you decide when to use an attribute or an element?</p>
[ { "answer_id": 33749, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "<p>Both methods for storing object's properties are perfectly valid. You should depart from pragmatic considerations. Try answering following question:</p>\n<ol>\n<li><p>Which representation leads to faster data parsing\\generation?</p>\n</li>\n<li><p>Which representation leads to faster data transfer?</p>\n</li>\n<li><p>Does readability matter?</p>\n<p>...</p>\n</li>\n</ol>\n" }, { "answer_id": 33750, "author": "Adam", "author_id": 3142, "author_profile": "https://Stackoverflow.com/users/3142", "pm_score": 3, "selected": false, "text": "<p>the million dollar question!</p>\n\n<p>first off, don't worry too much about performance now. you will be amazed at how quickly an optimized xml parser will rip through your xml. more importantly, what is your design for the future: as the XML evolves, how will you maintain loose coupling and interoperability?</p>\n\n<p>more concretely, you can make the content model of an element more complex but it's harder to extend an attribute.</p>\n" }, { "answer_id": 33755, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 2, "selected": false, "text": "<p>It is arguable either way, but your colleagues are right in the sense that the XML should be used for \"markup\" or meta-data around the actual data. For your part, you are right in that it's sometimes hard to decide where the line between meta-data and data is when modeling your domain in XML. In practice, what I do is pretend that anything in the markup is hidden, and only the data outside the markup is readable. Does the document make some sense in that way?</p>\n\n<p>XML is notoriously bulky. For transport and storage, compression is highly recommended if you can afford the processing power. XML compresses well, sometimes phenomenally well, because of its repetitiveness. I've had large files compress to less than 5% of their original size.</p>\n\n<p>Another point to bolster your position is that while the other team is arguing about style (in that most XML tools will handle an all-attribute document just as easily as an all-#PCDATA document) you are arguing practicalities. While style can't be totally ignored, technical merits should carry more weight.</p>\n" }, { "answer_id": 33756, "author": "Luke", "author_id": 327, "author_profile": "https://Stackoverflow.com/users/327", "pm_score": 3, "selected": false, "text": "<p>When in doubt, <a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"noreferrer\">KISS</a> -- why mix attributes and elements when you don't have a clear reason to use attributes. If you later decide to define an XSD, that will end up being cleaner as well. Then if you even later decide to generate a class structure from your XSD, that will be simpler as well. </p>\n" }, { "answer_id": 33757, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "<p>I use this rule of thumb:</p>\n\n<ol>\n<li>An Attribute is something that is self-contained, i.e., a color, an ID, a name.</li>\n<li>An Element is something that does or could have attributes of its own or contain other elements.</li>\n</ol>\n\n<p>So yours is close. I would have done something like:</p>\n\n<p><strong>EDIT</strong>: Updated the original example based on feedback below.</p>\n\n<pre><code> &lt;ITEM serialNumber=\"something\"&gt;\n &lt;BARCODE encoding=\"Code39\"&gt;something&lt;/BARCODE&gt;\n &lt;LOCATION&gt;XYX&lt;/LOCATION&gt;\n &lt;TYPE modelNumber=\"something\"&gt;\n &lt;VENDOR&gt;YYZ&lt;/VENDOR&gt;\n &lt;/TYPE&gt;\n &lt;/ITEM&gt;\n</code></pre>\n" }, { "answer_id": 152363, "author": "Rory Becker", "author_id": 11356, "author_profile": "https://Stackoverflow.com/users/11356", "pm_score": 2, "selected": false, "text": "<p>It's largely a matter of preference. I use Elements for grouping and attributes for data where possible as I see this as more compact than the alternative.</p>\n\n<p>For example I prefer.....</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;data&gt;\n &lt;people&gt;\n &lt;person name=\"Rory\" surname=\"Becker\" age=\"30\" /&gt;\n &lt;person name=\"Travis\" surname=\"Illig\" age=\"32\" /&gt;\n &lt;person name=\"Scott\" surname=\"Hanselman\" age=\"34\" /&gt;\n &lt;/people&gt;\n&lt;/data&gt;\n</code></pre>\n\n<p>...Instead of....</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;data&gt;\n &lt;people&gt;\n &lt;person&gt;\n &lt;name&gt;Rory&lt;/name&gt;\n &lt;surname&gt;Becker&lt;/surname&gt;\n &lt;age&gt;30&lt;/age&gt;\n &lt;/person&gt;\n &lt;person&gt;\n &lt;name&gt;Travis&lt;/name&gt;\n &lt;surname&gt;Illig&lt;/surname&gt;\n &lt;age&gt;32&lt;/age&gt;\n &lt;/person&gt;\n &lt;person&gt;\n &lt;name&gt;Scott&lt;/name&gt;\n &lt;surname&gt;Hanselman&lt;/surname&gt;\n &lt;age&gt;34&lt;/age&gt;\n &lt;/person&gt;\n &lt;/people&gt;\n&lt;/data&gt;\n</code></pre>\n\n<p>However if I have data which does not represent easily inside of say 20-30 characters or contains many quotes or other characters that need escaping then I'd say it's time to break out the elements... possibly with CData blocks.</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;data&gt;\n &lt;people&gt;\n &lt;person name=\"Rory\" surname=\"Becker\" age=\"30\" &gt;\n &lt;comment&gt;A programmer whose interested in all sorts of misc stuff. His Blog can be found at http://rorybecker.blogspot.com and he's on twitter as @RoryBecker&lt;/comment&gt;\n &lt;/person&gt;\n &lt;person name=\"Travis\" surname=\"Illig\" age=\"32\" &gt;\n &lt;comment&gt;A cool guy for who has helped me out with all sorts of SVn information&lt;/comment&gt;\n &lt;/person&gt;\n &lt;person name=\"Scott\" surname=\"Hanselman\" age=\"34\" &gt;\n &lt;comment&gt;Scott works for MS and has a great podcast available at http://www.hanselminutes.com &lt;/comment&gt;\n &lt;/person&gt;\n &lt;/people&gt;\n&lt;/data&gt;\n</code></pre>\n" }, { "answer_id": 152509, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 5, "selected": false, "text": "<p>It may depend on your usage. XML that is used to represent stuctured data generated from a database may work well with ultimately field values being placed as attributes.</p>\n\n<p>However XML used as a message transport would often be better using more elements.</p>\n\n<p>For example lets say we had this XML as proposed in the answer:-</p>\n\n<pre><code>&lt;INVENTORY&gt;\n &lt;ITEM serialNumber=\"something\" barcode=\"something\"&gt;\n &lt;Location&gt;XYX&lt;/LOCATION&gt;\n &lt;TYPE modelNumber=\"something\"&gt;\n &lt;VENDOR&gt;YYZ&lt;/VENDOR&gt;\n &lt;/TYPE&gt;\n &lt;/ITEM&gt;\n&lt;/INVENTORY&gt;\n</code></pre>\n\n<p>Now we want to send the ITEM element to a device to print he barcode however there is a choice of encoding types. How do we represent the encoding type required? Suddenly we realise, somewhat belatedly, that the barcode wasn't a single automic value but rather it may be qualified with the encoding required when printed.</p>\n\n<pre><code> &lt;ITEM serialNumber=\"something\"&gt;\n &lt;barcode encoding=\"Code39\"&gt;something&lt;/barcode&gt;\n &lt;Location&gt;XYX&lt;/LOCATION&gt;\n &lt;TYPE modelNumber=\"something\"&gt;\n &lt;VENDOR&gt;YYZ&lt;/VENDOR&gt;\n &lt;/TYPE&gt;\n &lt;/ITEM&gt;\n</code></pre>\n\n<p>The point is unless you building some kind of XSD or DTD along with a namespace to fix the structure in stone, you may be best served leaving your options open.</p>\n\n<p>IMO XML is at its most useful when it can be flexed without breaking existing code using it.</p>\n" }, { "answer_id": 420197, "author": "user44350", "author_id": 44350, "author_profile": "https://Stackoverflow.com/users/44350", "pm_score": 6, "selected": false, "text": "<p>Some of the problems with attributes are:</p>\n\n<ul>\n<li>attributes cannot contain multiple values (child elements can)</li>\n<li>attributes are not easily expandable (for future changes)</li>\n<li>attributes cannot describe structures (child elements can)</li>\n<li>attributes are more difficult to manipulate by program code</li>\n<li>attribute values are not easy to test against a DTD</li>\n</ul>\n\n<p>If you use attributes as containers for data, you end up with documents that are difficult to read and maintain. Try to use elements to describe data. Use attributes only to provide information that is not relevant to the data.</p>\n\n<p>Don't end up like this (this is not how XML should be used):</p>\n\n<pre><code>&lt;note day=\"12\" month=\"11\" year=\"2002\" \n to=\"Tove\" to2=\"John\" from=\"Jani\" heading=\"Reminder\" \n body=\"Don't forget me this weekend!\"&gt; \n&lt;/note&gt;\n</code></pre>\n\n<p>Source: <a href=\"http://www.w3schools.com/xml/xml_dtd_el_vs_attr.asp\" rel=\"noreferrer\">http://www.w3schools.com/xml/xml_dtd_el_vs_attr.asp</a></p>\n" }, { "answer_id": 448093, "author": "Michael J", "author_id": 46462, "author_profile": "https://Stackoverflow.com/users/46462", "pm_score": 3, "selected": false, "text": "<p>Use elements for data and attributes for meta data (data about the element's data).</p>\n\n<p>If an element is showing up as a predicate in your select strings, you have a good sign that it should be an attribute. Likewise if an attribute never is used as a predicate, then maybe it is not useful meta data.</p>\n\n<p>Remember that XML is supposed to be machine readable not human readable and for large documents XML compresses very well.</p>\n" }, { "answer_id": 724334, "author": "ottodidakt", "author_id": 33434, "author_profile": "https://Stackoverflow.com/users/33434", "pm_score": -1, "selected": false, "text": "<p>I agree with feenster. Stay away from attributes if you can. Elements are evolution friendly and more interoperable between web service toolkits. You'd never find these toolkits serializing your request/response messages using attributes. This also makes sense since our messages are data (not metadata) for a web service toolkit.</p>\n" }, { "answer_id": 1083932, "author": "peter.murray.rust", "author_id": 130964, "author_profile": "https://Stackoverflow.com/users/130964", "pm_score": 3, "selected": false, "text": "<p>There is no universal answer to this question (I was heavily involved in the creation of the W3C spec). XML can be used for many purposes - text-like documents, data and declarative code are three of the most common. I also use it a lot as a data model. There are aspects of these applications where attributes are more common and others where child elements are more natural. There are also features of various tools that make it easier or harder to use them. </p>\n\n<p>XHTML is one area where attributes have a natural use (e.g. in class='foo'). Attributes have no order and this may make it easier for some people to develop tools. OTOH attributes are harder to type without a schema. I also find namespaced attributes (foo:bar=\"zork\") are often harder to manage in various toolsets. But have a look at some of the W3C languages to see the mixture that is common. SVG, XSLT, XSD, MathML are some examples of well-known languages and all have a rich supply of attributes and elements. Some languages even allow more-than-one-way to do it, e.g.</p>\n\n<pre><code>&lt;foo title=\"bar\"/&gt;;\n</code></pre>\n\n<p>or </p>\n\n<pre><code>&lt;foo&gt;\n &lt;title&gt;bar&lt;/title&gt;;\n&lt;/foo&gt;;\n</code></pre>\n\n<p>Note that these are NOT equivalent syntactically and require explicit support in processing tools)</p>\n\n<p>My advice would be to have a look at common practice in the area closest to your application and also consider what toolsets you may wish to apply.</p>\n\n<p>Finally make sure that you differentiate namespaces from attributes. Some XML systems (e.g. Linq) represent namespaces as attributes in the API. IMO this is ugly and potentially confusing.</p>\n" }, { "answer_id": 1174651, "author": "brianary", "author_id": 54323, "author_profile": "https://Stackoverflow.com/users/54323", "pm_score": 2, "selected": false, "text": "<p>Just a couple of corrections to some bad info:</p>\n\n<p>@John Ballinger: Attributies can contain any character data. &lt; > &amp; \" ' need to be escaped to &amp;lt; &amp;gt; &amp;amp; &amp;quot; and &amp;apos; , respectively. If you use an XML library, it will take care of that for you. </p>\n\n<p>Hell, an attribute can contain binary data such as an image, if you really want, just by base64-encoding it and making it a data: URL.</p>\n\n<p>@feenster: Attributes can contain space-separated multiple items in the case of IDS or NAMES, which would include numbers. Nitpicky, but this can end up saving space.</p>\n\n<p>Using attributes can keep XML competitive with JSON. See <em><a href=\"http://www.balisage.net/Proceedings/vol10/html/Lee01/BalisageVol10-Lee01.html\" rel=\"nofollow noreferrer\">Fat Markup: Trimming the Fat Markup Myth one calorie at a time</a></em>.</p>\n" }, { "answer_id": 1709380, "author": "Patrick", "author_id": 38892, "author_profile": "https://Stackoverflow.com/users/38892", "pm_score": 3, "selected": false, "text": "<p>Others have covered how to differentiate between attributes from elements but from a more general perspective putting everything in attributes because it makes the resulting XML smaller is wrong. </p>\n\n<p>XML is not designed to be compact but to be portable and human readable. If you want to decrease the size of the data in transit then use something else (such as <a href=\"http://code.google.com/apis/protocolbuffers/\" rel=\"noreferrer\">google's protocol buffers</a>).</p>\n" }, { "answer_id": 3107163, "author": "dan04", "author_id": 287586, "author_profile": "https://Stackoverflow.com/users/287586", "pm_score": 5, "selected": false, "text": "<p>\"XML\" stands for \"eXtensible <em>Markup</em> Language\". A markup language implies that the data is text, <em>marked up</em> with metadata about structure or formatting.</p>\n\n<p>XHTML is an example of XML used the way it was intended:</p>\n\n<pre><code>&lt;p&gt;&lt;span lang=\"es\"&gt;El Jefe&lt;/span&gt; insists that you\n &lt;em class=\"urgent\"&gt;MUST&lt;/em&gt; complete your project by Friday.&lt;/p&gt;\n</code></pre>\n\n<p>Here, the distinction between elements and attributes is clear. Text elements are displayed in the browser, and attributes are instructions about <em>how</em> to display them (although there are a few tags that don't work that way).</p>\n\n<p>Confusion arises when XML is used not as a markup language, but as a <em>data serialization</em> language, in which the distinction between \"data\" and \"metadata\" is more vague. So the choice between elements and attributes is more-or-less arbitrary except for things that <em>can't</em> be represented with attributes (see feenster's answer).</p>\n" }, { "answer_id": 4458404, "author": "Archimedes Trajano", "author_id": 242042, "author_profile": "https://Stackoverflow.com/users/242042", "pm_score": 4, "selected": false, "text": "<p>I use the following guidelines in my schema design with regards to attributes vs. elements:</p>\n\n<ul>\n<li>Use elements for long running text (usually those of string or\nnormalizedString types) </li>\n<li>Do not use an attribute if there is grouping of two values (e.g.\neventStartDate and eventEndDate) for an element. In the previous example,\nthere should be a new element for \"event\" which may contain the startDate and\nendDate attributes.</li>\n<li>Business Date, DateTime and numbers (e.g. counts, amount and rate) should be\nelements.</li>\n<li>Non-business time elements such as last updated, expires on should be\nattributes.</li>\n<li>Non-business numbers such as hash codes and indices should be attributes.* Use elements if the type will be complex.</li>\n<li>Use attributes if the value is a simple type and does not repeat.</li>\n<li>xml:id and xml:lang must be attributes referencing the XML schema</li>\n<li>Prefer attributes when technically possible.</li>\n</ul>\n\n<p>The preference for attributes is it provides the following:</p>\n\n<ul>\n<li>unique (the attribute cannot appear multiple times)</li>\n<li>order does not matter</li>\n<li>the above properties are inheritable (this is something that the \"all\" content model does not support in the current schema language)</li>\n<li>bonus is they are less verbose and use up less bandwidth, but that's not really a reason to prefer attributes over elements.</li>\n</ul>\n\n<p>I added <em>when technically possible</em> because there are times where the use of attributes are not possible. For example, attribute set choices. For example use (startDate and endDate) xor (startTS and endTS) is not possible with the current schema language</p>\n\n<p>If XML Schema starts allowing the \"all\" content model to be restricted or extended then I would probably drop it</p>\n" }, { "answer_id": 4945261, "author": "rpattabi", "author_id": 15139, "author_profile": "https://Stackoverflow.com/users/15139", "pm_score": 2, "selected": false, "text": "<p>How about taking advantage of our hard earned object orientation intuition? I usually find it is straight forward to think which is an object and which is an attribute of the object or which object it is referring to. </p>\n\n<p>Whichever intuitively make sense as objects shall fit in as elements. Its attributes (or properties) would be attributes for these elements in xml or child element with attribute.</p>\n\n<p>I think for simpler cases like in the example object orientation analogy works okay to figure out which is element and which is attribute of an element.</p>\n" }, { "answer_id": 5600135, "author": "oh pot", "author_id": 699275, "author_profile": "https://Stackoverflow.com/users/699275", "pm_score": -1, "selected": false, "text": "<p>Attributes can easily become difficult to manage over time trust me. i always stay away from them personally. Elements are far more explicit and readable/usable by both parsers and users.</p>\n\n<p>Only time i've ever used them was to define the file extension of an asset url:</p>\n\n<pre><code>&lt;image type=\"gif\"&gt;wank.jpg&lt;/image&gt; ...etc etc\n</code></pre>\n\n<p>i guess if you know 100% the attribute will not need to be expanded you could use them, but how many times do you know that.</p>\n\n<pre><code>&lt;image&gt;\n &lt;url&gt;wank.jpg&lt;/url&gt;\n &lt;fileType&gt;gif&lt;/fileType&gt;\n&lt;/image&gt;\n</code></pre>\n" }, { "answer_id": 7252024, "author": "Walter A. Jablonowski", "author_id": 509073, "author_profile": "https://Stackoverflow.com/users/509073", "pm_score": 1, "selected": false, "text": "<p>This is very clear in HTML where the differences of attributes and markup can be clearly seen:</p>\n\n<ol>\n<li>All data is between markup</li>\n<li>Attributes are used to characterize this data (e.g. formats)</li>\n</ol>\n\n<p>If you just have pure data as XML, there is a less clear difference. Data could stand between markup or as attributes.</p>\n\n<p>=> Most data should stand between markup.</p>\n\n<p>If you want to use attributes here: You could divide data into two categories: Data and \"meta data\", where meta data is not part of the record, you want to present, but things like \"format version\", \"created date\", etc.</p>\n\n<pre><code>&lt;customer format=\"\"&gt;\n &lt;name&gt;&lt;/name&gt;\n ...\n&lt;/customer&gt;\n</code></pre>\n\n<p>One could also say: \"Use attributes to characterize the tag, use tags to provide data itself.\"</p>\n" }, { "answer_id": 23133755, "author": "kjhughes", "author_id": 290085, "author_profile": "https://Stackoverflow.com/users/290085", "pm_score": 5, "selected": false, "text": "<h2>XML Element vs XML Attribute</h2>\n\n<p>XML is all about agreement. <strong><em>First defer to any existing XML schemas or established conventions within your community or industry.</em></strong></p>\n\n<p>If you are truly in a situation to define your schema from the ground up, here are some general considerations that should inform the <strong>element vs attribute decision</strong>:</p>\n\n<pre><code>&lt;versus&gt;\n &lt;element attribute=\"Meta content\"&gt;\n Content\n &lt;/element&gt;\n &lt;element attribute=\"Flat\"&gt;\n &lt;parent&gt;\n &lt;child&gt;Hierarchical&lt;/child&gt;\n &lt;/parent&gt;\n &lt;/element&gt;\n &lt;element attribute=\"Unordered\"&gt;\n &lt;ol&gt;\n &lt;li&gt;Has&lt;/li&gt;\n &lt;li&gt;order&lt;/li&gt;\n &lt;/ol&gt;\n &lt;/element&gt;\n &lt;element attribute=\"Must copy to reuse\"&gt;\n Can reference to re-use\n &lt;/element&gt;\n &lt;element attribute=\"For software\"&gt;\n For humans\n &lt;/element&gt;\n &lt;element attribute=\"Extreme use leads to micro-parsing\"&gt;\n Extreme use leads to document bloat\n &lt;/element&gt;\n &lt;element attribute=\"Unique names\"&gt;\n Unique or non-unique names\n &lt;/element&gt;\n &lt;element attribute=\"SAX parse: read first\"&gt;\n SAX parse: read later\n &lt;/element&gt;\n &lt;element attribute=\"DTD: default value\"&gt;\n DTD: no default value\n &lt;/element&gt;\n&lt;/versus&gt;\n</code></pre>\n" }, { "answer_id": 30265154, "author": "MGrier", "author_id": 3956776, "author_profile": "https://Stackoverflow.com/users/3956776", "pm_score": 1, "selected": false, "text": "<p>I am always surprised by the results of these kinds of discussions. To me there is a very simple rule for deciding whether data belongs in an attribute or as content and that is whether the data has navigable sub-structure.</p>\n\n<p>So for example, non-markup text always belongs in attributes. Always.</p>\n\n<p>Lists belong in sub-structure or content. Text which may over time include embedded structured sub-content belong in content. (In my experience there is relatively little of this - text with markup - when using XML for data storage or exchange.)</p>\n\n<p>XML schema written this way is concise.</p>\n\n<p>Whenever I see cases like <code>&lt;car&gt;&lt;make&gt;Ford&lt;/make&gt;&lt;color&gt;Red&lt;/color&gt;&lt;/car&gt;</code>, I think to myself \"gee did the author think that there were going to be sub-elements within the make element?\" <code>&lt;car make=\"Ford\" color=\"Red\" /&gt;</code> is significantly more readable, there's no question about how whitespace would be handled etc.</p>\n\n<p>Given just but the whitespace handling rules, I believe this was the clear intent of the XML designers.</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3340/" ]
At work we are being asked to create XML files to pass data to another offline application that will then create a second XML file to pass back in order to update some of our data. During the process we have been discussing with the team of the other application about the structure of the XML file. The sample I came up with is essentially something like: ``` <INVENTORY> <ITEM serialNumber="something" location="something" barcode="something"> <TYPE modelNumber="something" vendor="something"/> </ITEM> </INVENTORY> ``` The other team said that this was not industry standard and that attributes should only be used for meta data. They suggested: ``` <INVENTORY> <ITEM> <SERIALNUMBER>something</SERIALNUMBER> <LOCATION>something</LOCATION> <BARCODE>something</BARCODE> <TYPE> <MODELNUMBER>something</MODELNUMBER> <VENDOR>something</VENDOR> </TYPE> </ITEM> </INVENTORY> ``` The reason I suggested the first is that the size of the file created is much smaller. There will be roughly 80000 items that will be in the file during transfer. Their suggestion in reality turns out to be three times larger than the one I suggested. I searched for the mysterious "Industry Standard" that was mentioned, but the closest I could find was that XML attributes should only be used for meta data, but said the debate was about what was actually meta data. After the long winded explanation (sorry) how do you determine what is meta data, and when designing the structure of an XML document how should you decide when to use an attribute or an element?
I use this rule of thumb: 1. An Attribute is something that is self-contained, i.e., a color, an ID, a name. 2. An Element is something that does or could have attributes of its own or contain other elements. So yours is close. I would have done something like: **EDIT**: Updated the original example based on feedback below. ``` <ITEM serialNumber="something"> <BARCODE encoding="Code39">something</BARCODE> <LOCATION>XYX</LOCATION> <TYPE modelNumber="something"> <VENDOR>YYZ</VENDOR> </TYPE> </ITEM> ```
33,751
<p>I would like to add the following MIME type to a site run by <code>Apache</code>:</p> <pre><code>&lt;mime-mapping&gt; &lt;extension&gt;jnlp&lt;/extension&gt; &lt;mime-type&gt;application/x-java-jnlp-file&lt;/mime-type&gt; &lt;/mime-mapping&gt; </code></pre> <p><strong>That is the Tomcat format.</strong></p> <p>I'm on a shared host, so I can only create an <code>.htaccess</code> file. Would someone please specify the complete contents of such a file?</p>
[ { "answer_id": 33762, "author": "Ryan Guest", "author_id": 1811, "author_profile": "https://Stackoverflow.com/users/1811", "pm_score": 2, "selected": false, "text": "<p>You should be able to just add this line:</p>\n\n<pre><code>AddType application/x-java-jnlp-file .jnlp\n</code></pre>\n" }, { "answer_id": 33767, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 5, "selected": true, "text": "<pre><code>AddType application/x-java-jnlp-file .jnlp\n</code></pre>\n\n<p>Note that you might not actually be allowed to do that.</p>\n\n<p>See also the <a href=\"http://HTTPd.Apache.Org/docs/trunk/mod/mod_mime.html#addtype\" rel=\"noreferrer\" title=\"mod_mime - AddType\">documentation of the AddType directive</a> and the <a href=\"http://HTTPd.Apache.Org/docs/trunk/howto/htaccess.html\" rel=\"noreferrer\" title=\".htaccess howto\">.htaccess howto</a>.</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
I would like to add the following MIME type to a site run by `Apache`: ``` <mime-mapping> <extension>jnlp</extension> <mime-type>application/x-java-jnlp-file</mime-type> </mime-mapping> ``` **That is the Tomcat format.** I'm on a shared host, so I can only create an `.htaccess` file. Would someone please specify the complete contents of such a file?
``` AddType application/x-java-jnlp-file .jnlp ``` Note that you might not actually be allowed to do that. See also the [documentation of the AddType directive](http://HTTPd.Apache.Org/docs/trunk/mod/mod_mime.html#addtype "mod_mime - AddType") and the [.htaccess howto](http://HTTPd.Apache.Org/docs/trunk/howto/htaccess.html ".htaccess howto").
33,779
<p>Does anyone know of a powershell cmdlet out there for automating task scheduler in XP/2003? If you've ever tried to work w/ schtasks you know it's pretty painful.</p>
[ { "answer_id": 33805, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 1, "selected": false, "text": "<p>You don't need PowerShell to automate the Task Scheduler, you can use the SCHTASKS command in XP.</p>\n\n<p>According to <a href=\"http://en.wikipedia.org/wiki/Task_Scheduler\" rel=\"nofollow noreferrer\">Wikipedia</a>, the Task Scheduler 2.0 (Vista and Server 2008) is accesible via COM.</p>\n" }, { "answer_id": 33806, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 0, "selected": false, "text": "<p>Not \"native\" PowerShell, but if you're running powershell.exe as an administrator then you should have access to the \"at\" command, which you can use to schedule tasks.</p>\n" }, { "answer_id": 33817, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 2, "selected": false, "text": "<p>Ok, Pablo has sparked my interest in saying that the scheduler is accessible via COM.</p>\n\n<p>In PowerShell you can do this:</p>\n\n<pre><code>$svc = new-object -com Schedule.Service\n</code></pre>\n\n<p>... and that gives you a handle to the task scheduler. You can see what members it has using:</p>\n\n<pre><code>$svc | get-member\n</code></pre>\n\n<p>One of its methods is NewTask, so I'd start there.</p>\n\n<p>Edit: Some more info <a href=\"http://msdn.microsoft.com/en-us/library/aa446862.aspx\" rel=\"nofollow noreferrer\">here</a>. It's a VBScript example but it'll give you the gist.</p>\n" }, { "answer_id": 40695, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://myitforum.com/cs2/blogs/yli628/archive/2008/07/28/powershell-script-to-retrieve-scheduled-tasks-on-a-remote-machine-task-scheduler-api.aspx\" rel=\"nofollow noreferrer\">This</a> is a good article (be sure to read the other linked article in it) that discusses looking at th scheduled tasks on remote machines. It is not exactly what you were asking for but it should get you headed in the right direction.</p>\n" }, { "answer_id": 51716, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": -1, "selected": false, "text": "<p>@slipsec: I don't have access to a 2003 server to try, but googling \"2003 server\" SCHTASKS there are links related to questions about it. Perhaps you misspell the command?\nLike Matt says, you also can use AT, but in this case you don't have access to the scheduled tasks via the Control Panel, only via the AT command.</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1635/" ]
Does anyone know of a powershell cmdlet out there for automating task scheduler in XP/2003? If you've ever tried to work w/ schtasks you know it's pretty painful.
Ok, Pablo has sparked my interest in saying that the scheduler is accessible via COM. In PowerShell you can do this: ``` $svc = new-object -com Schedule.Service ``` ... and that gives you a handle to the task scheduler. You can see what members it has using: ``` $svc | get-member ``` One of its methods is NewTask, so I'd start there. Edit: Some more info [here](http://msdn.microsoft.com/en-us/library/aa446862.aspx). It's a VBScript example but it'll give you the gist.
33,790
<p>I am currently using the following command to upload my site content:</p> <pre><code>scp -r web/* [email protected]:site.com/ </code></pre> <p>This works great except that the .htaccess file is not sent. Presumably, this is because it's hidden.</p> <p>I have tried adding a second line to send the file explicitely:</p> <pre><code>scp -r web/.htaccess [email protected]:site.com/.htaccess </code></pre> <p>This works great except now I have to enter my password twice.</p> <p>Any thoughts on how to make this deploy with only 1 or 0 entries of my password?</p>
[ { "answer_id": 33791, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 4, "selected": true, "text": "<p>Just combine the two commands:</p>\n\n<pre><code>scp -r web/* web/.htaccess [email protected]:site.com/\n</code></pre>\n\n<p>If you want 0 entries of your password you can set up <a href=\"http://sial.org/howto/openssh/publickey-auth/\" rel=\"noreferrer\">public key authentication</a> for ssh/scp.</p>\n" }, { "answer_id": 33803, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 2, "selected": false, "text": "<p>A word of caution - don't attempt to match dotted files (like <code>.htaccess</code>) with <code>.*</code> - this inconveniently also matches <code>..</code>, and would result in copying all the files on the path to the root directory. I did this once (with <code>rm</code>, no less!) and I had to rebuild the server because I'd messed with <code>/var</code>.</p>\n\n<p>@jwmittag:</p>\n\n<p>I just did a test on Ubuntu and <code>.*</code> matches when I use <code>cp</code>. Here's an example:</p>\n\n<pre><code>root@krash:/# mkdir a\nroot@krash:/# mkdir b\nroot@krash:/# mkdir a/c\nroot@krash:/# touch a/d\nroot@krash:/# touch a/c/e\nroot@krash:/# cp -r a/c/.* b\ncp: will not create hard link `b/c' to directory `b/.'\nroot@krash:/# ls b\nd e\n</code></pre>\n\n<p>If <code>.*</code> did not match <code>..</code>, then <code>d</code> shouldn't be in <code>b</code>.</p>\n" }, { "answer_id": 33804, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 2, "selected": false, "text": "<p>Some background info: the <code>*</code> wildcard does not match so-called \"dot-files\" (i.e. files whose name begins with a dot).</p>\n\n<p>Some shells allow you to set an option, so that it <em>will</em> match dot-files, however, doing that is asking for a lot of pain: now <code>*</code> will also match <code>.</code> (the current directory) and <code>..</code> (the parent directory), which is usually not what is intended and can be quite surprising! (<code>rm -rf *</code> deleting the parent directory is probably not the best way to start a day ...)</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
I am currently using the following command to upload my site content: ``` scp -r web/* [email protected]:site.com/ ``` This works great except that the .htaccess file is not sent. Presumably, this is because it's hidden. I have tried adding a second line to send the file explicitely: ``` scp -r web/.htaccess [email protected]:site.com/.htaccess ``` This works great except now I have to enter my password twice. Any thoughts on how to make this deploy with only 1 or 0 entries of my password?
Just combine the two commands: ``` scp -r web/* web/.htaccess [email protected]:site.com/ ``` If you want 0 entries of your password you can set up [public key authentication](http://sial.org/howto/openssh/publickey-auth/) for ssh/scp.
33,813
<p>I noticed that many people here use <a href="http://macromates.com/" rel="nofollow noreferrer">TextMate</a> for coding on OS X. I've recently started using it, and although I like its minimalistic interface, it makes it harder to stumble upon cool features if you don't know what you're looking for.</p> <p>So, what feature have you found most helpful for coding (mainly in Python)? Are there any third-party bundles I should know about, besides what's included?</p>
[ { "answer_id": 33819, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": false, "text": "<p>The ease of snippet creation.</p>\n\n<p>It's trivial to create new snippets that can accomplish a lot using replacements, tabbing order, and regex substitutions. Quickly assigning these to the tab key for specific languages makes me more productive. And makes me worry about code bloat. :-)</p>\n" }, { "answer_id": 33821, "author": "Rob Bazinet", "author_id": 2305, "author_profile": "https://Stackoverflow.com/users/2305", "pm_score": 1, "selected": false, "text": "<p>It's nice and lightweight and has all of the macros built-in for Ruby and let's you run Ruby code, or any other code for that matter just with a keystroke.</p>\n" }, { "answer_id": 33910, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 4, "selected": false, "text": "<p>Holding down option while dragging allows you to highlight a block of text. If you type while the highlight is active, your keystrokes appear on multiple lines. </p>\n" }, { "answer_id": 33935, "author": "Jeremy", "author_id": 1114, "author_profile": "https://Stackoverflow.com/users/1114", "pm_score": 4, "selected": false, "text": "<p>Being able to write simple commands in any scripting language and bind them to a context-specific hotkey.</p>\n" }, { "answer_id": 36309, "author": "Teifion", "author_id": 1384652, "author_profile": "https://Stackoverflow.com/users/1384652", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://boagworld.com/podcast/123/\" rel=\"nofollow noreferrer\">I mention some in a review on Boagworld</a>, I find the snippets, project manager, columnar editing (hold down option while selecting stuff or push it after having selected stuff) and CSS scopes for syntax.</p>\n" }, { "answer_id": 36316, "author": "jlleblanc", "author_id": 586, "author_profile": "https://Stackoverflow.com/users/586", "pm_score": 6, "selected": true, "text": "<p>Don't neglect the 'mate' command line tool. You can use it to pipe output into TextMate, so if you do the following...</p>\n\n<pre><code>diff file1.py file2.py | mate\n</code></pre>\n\n<p>...it will not only open in TextMate, but it is smart enough to know that you're looking at a diff and highlight lines on screen.</p>\n\n<p>TextMate's SVN integration is great; it also seems to have bundles for some other version control systems as well.</p>\n\n<p>Add GetBundle to browse the bundle repository. I found the jQuery bundle through it and it's very handy.</p>\n\n<p>As others have mentioned, rolling your own bundle for frequently used snippets is very helpful. If you have some snippets that are specific to a project or framework, you might want to prefix all of them with a common letter to keep the namespace tidy.</p>\n" }, { "answer_id": 40045, "author": "Charles Roper", "author_id": 1944, "author_profile": "https://Stackoverflow.com/users/1944", "pm_score": 2, "selected": false, "text": "<p><strong>It is worth noting here that there is a Windows alternative to TextMate called <a href=\"http://www.e-texteditor.com/\" rel=\"nofollow noreferrer\">E Text Editor</a></strong>. It does pretty much everything TextMate does <strike>(apart from macros, but the author is working on this, I think)</strike>, and even - <em>shock, horror</em> - does some things better, such as the superb bundles editor, the bundles manager, and the branching undo history. <strong>Update: and now there's <a href=\"http://e-texteditor.com/blog/2008/snippet-pipes\" rel=\"nofollow noreferrer\">Snippet Pipes</a></strong>.</p>\n\n<p>So, not exactly a useful feature of TextMate as such, but <em>very</em> useful to know if you're a fan of TextMate and you have to use Windows for whatever reason.</p>\n" }, { "answer_id": 66060, "author": "pjbeardsley", "author_id": 6812, "author_profile": "https://Stackoverflow.com/users/6812", "pm_score": 3, "selected": false, "text": "<p>I like the integrated HTML/XML Tidy. Cmd-shift-H is your friend.</p>\n\n<p>Also, nice integration with a variety of scp/sftp clients.</p>\n" }, { "answer_id": 76244, "author": "Steve Losh", "author_id": 13498, "author_profile": "https://Stackoverflow.com/users/13498", "pm_score": 2, "selected": false, "text": "<p>Using snippets to expand into large, repetitive blocks of code and then using the tab key to move through and only edit the pieces I need to without having to use the mouse or arrow keys.</p>\n" }, { "answer_id": 86602, "author": "Matt", "author_id": 15368, "author_profile": "https://Stackoverflow.com/users/15368", "pm_score": 3, "selected": false, "text": "<p>My favourite two features are auto-completion (bound to ⎋ [esc]), and column editing (bound to ⌥ [alt]) both of these things save me quite a lot of time, and are definitely '<a href=\"http://www.pragprog.com/titles/textmate/textmate\" rel=\"nofollow noreferrer\" title=\"The Pragmatic Bookshelf | TextMate\">robot ninjas</a>'.</p>\n\n<p>The book linked above is also a really useful into to the power of TextMate, although it doesn't specifically mention python.</p>\n" }, { "answer_id": 96936, "author": "Martin", "author_id": 15840, "author_profile": "https://Stackoverflow.com/users/15840", "pm_score": 3, "selected": false, "text": "<p>Don't forget \"Drag commands\".\nThey give you the ability to drag, say, an image into a blog.html document and will then upload it to the proper folder and insert the markup for you.</p>\n\n<p><a href=\"http://ctrloptcmd.com/archives/336/textmate-quicksilver-drag-drop-actionscript-imports/\" rel=\"nofollow noreferrer\">Here</a> is another example of how you can expand further on drag commands if you pair TM up with <a href=\"http://blacktree.com\" rel=\"nofollow noreferrer\">QuickSilver</a>.</p>\n\n<p>(Disclaimer: I wrote the blog post I linked to there. I still think it's cool though.)</p>\n" }, { "answer_id": 248289, "author": "feoh", "author_id": 32514, "author_profile": "https://Stackoverflow.com/users/32514", "pm_score": 2, "selected": false, "text": "<p>For me the best features are:</p>\n\n<ul>\n<li>Projects - I know every IDE under\nthe sun has this but TextMate makes\nthis useful for all sorts of editing\nand text processing tasks, and\nmoreover makes navigating around\nthese projects easy without ever\nlifting your hands from the\nkeyboard. This is huge for Rails or\nGrails projects or large programming\nprojects with many modules.</li>\n<li>The excellent syntax highlighting\nand 'snippets' for myriad languages\nand tools</li>\n<li>The excellent scripting language\nsupport (Being able to evaluate\nchunks of Ruby and the like with a\nsingle key chord)</li>\n<li>The built in Blogging bundle is\nsuperb. I now use TextMate\nexclusively for all my blog posts.</li>\n<li>Columnar editing</li>\n<li>The ability to use just about any\nlanguage or tool to extend TextMate,\nRuby, Perl, shell, name your poison.</li>\n<li>An excellent mix of great Aqua GUI\nsupport and excellent command line\nsupport through the\n<code>mate</code> and\n commands, for\ninstance making it easy and pleasant\nto use TextMate as your default\neditor for your SCM.</li>\n</ul>\n" }, { "answer_id": 299208, "author": "Gabe Hollombe", "author_id": 30632, "author_profile": "https://Stackoverflow.com/users/30632", "pm_score": 4, "selected": false, "text": "<p>The Navigation menu commands <strong>Go to File</strong> (Command + T) and <strong>Go to Symbol</strong> (Command + Shift + T) are both extremely helpful. </p>\n\n<p><strong>Go to File</strong>, which works when you have a project open, lets you type any part of the file name to see only files that match what you've typed. </p>\n\n<p><strong>Go to Symbol</strong> has the same type-to-filter interface, but operates on what I'd call the basic block elements of your document. For example, if you're editing a class, Go to Symbol works on the method names, but in a CSS document, you'll be searching on your selectors. It's pretty awesome.</p>\n" }, { "answer_id": 618848, "author": "DEfusion", "author_id": 6432, "author_profile": "https://Stackoverflow.com/users/6432", "pm_score": 0, "selected": false, "text": "<p>The <code>mate</code> command line tool is great, you can open an individual file or my favourite use of it is to open a directory of files as a project (e.g. <code>mate .</code>)</p>\n" }, { "answer_id": 654768, "author": "pojo", "author_id": 70350, "author_profile": "https://Stackoverflow.com/users/70350", "pm_score": 1, "selected": false, "text": "<p>Check out <a href=\"http://ciaranwal.sh/2008/08/05/textmate-plug-in-projectplus\" rel=\"nofollow noreferrer\">ProjectPlus</a>, it gives some useful options for the sidebar, it has SCM status badges for svn and git (though I find the git thing a bit buggy).</p>\n\n<p>I like the fact that it can change the sidebar to an embedded panel on left or right (as opposed to the drawer that's default).</p>\n" }, { "answer_id": 1581719, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Checkout <a href=\"http://code.google.com/p/zen-coding/\" rel=\"nofollow noreferrer\">Zen Coding bundle</a> . It gives you an awesome productivity boost to developing both HTML and CSS.</p>\n" }, { "answer_id": 2911283, "author": "stephenr", "author_id": 348325, "author_profile": "https://Stackoverflow.com/users/348325", "pm_score": 1, "selected": false, "text": "<p>If, like me, you're borderline OCD when it comes to making code look neat, then Option+Cmd+] to line up all the assignments around the current line is awesome!</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3002/" ]
I noticed that many people here use [TextMate](http://macromates.com/) for coding on OS X. I've recently started using it, and although I like its minimalistic interface, it makes it harder to stumble upon cool features if you don't know what you're looking for. So, what feature have you found most helpful for coding (mainly in Python)? Are there any third-party bundles I should know about, besides what's included?
Don't neglect the 'mate' command line tool. You can use it to pipe output into TextMate, so if you do the following... ``` diff file1.py file2.py | mate ``` ...it will not only open in TextMate, but it is smart enough to know that you're looking at a diff and highlight lines on screen. TextMate's SVN integration is great; it also seems to have bundles for some other version control systems as well. Add GetBundle to browse the bundle repository. I found the jQuery bundle through it and it's very handy. As others have mentioned, rolling your own bundle for frequently used snippets is very helpful. If you have some snippets that are specific to a project or framework, you might want to prefix all of them with a common letter to keep the namespace tidy.
33,814
<p>I'm writing a PHP script that involves scraping web pages. Currently, the script analyzes the page line by line, but it breaks if there is a tag that spans multiple lines, like </p> <pre><code>&lt;img src="example.jpg" alt="example"&gt; </code></pre> <p>If worse comes to worst, I could possibly preprocess the page by removing all line breaks, then re-inserting them at the closest <code>&gt;</code>, but this seems like a kludge.</p> <p>Ideally, I'd be able to detect a tag that spans lines, conjoin only those to lines, and continue processing.<br> So what's the best method to detect this?</p>
[ { "answer_id": 33835, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "<p>Well, this doesn't answer the question and is more of an opinion, but...</p>\n\n<p>I think that the best scraping strategy (and consequently, to eliminate this problem) is not to analyze an HTML line by line, which is unnatural to HTML, but to analyze it by its natural delimiter: &lt;> pairs.</p>\n\n<p>There will be two types of course:</p>\n\n<ul>\n<li>Tag elements that are immediately closed, e.g., &lt; br /></li>\n<li>Tag elements that need a separate closing tag, e.g., &lt; p > text &lt; /p ></li>\n</ul>\n\n<p>You can immediately see the advantage of using this strategy in the case of paragraph(p) tags: It will be easier to parse mutiline paragraphs instead of having to track where the closing tag is. </p>\n" }, { "answer_id": 33839, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 3, "selected": false, "text": "<p>This is one of my pet peeves: <em>never</em> parse HTML by hand. <em>Never</em> parse HTML with regexps. <em>Never</em> parse HTML with string comparisons. <em>Always</em> use an HTML parser to parse HTML – that's what they're there for.</p>\n\n<p>It's been a long time since I've done any PHP, but a quick search turned up <a href=\"http://SimpleHTMLDom.SourceForge.Net/\" rel=\"noreferrer\" title=\"PHP Simple HTML DOM\">this PHP5 HTML parser</a>.</p>\n" }, { "answer_id": 33841, "author": "Josh", "author_id": 257, "author_profile": "https://Stackoverflow.com/users/257", "pm_score": 2, "selected": false, "text": "<p>Don't write a parser, use someone else's: <a href=\"http://www.php.net/manual/en/domdocument.loadhtml.php\" rel=\"nofollow noreferrer\">DOMDocument::loadHTML</a> - that's just one, I think there are a lot of others.</p>\n" }, { "answer_id": 33875, "author": "corymathews", "author_id": 1925, "author_profile": "https://Stackoverflow.com/users/1925", "pm_score": 0, "selected": false, "text": "<p>Why don't you read in a line, and set it to a string, then check the string for tag openings and closings, If a tag spans more then one line add the next line to the string and move the part before the opening brace to your processed string. Then just parse through the entire file doing this. Its not beautiful but it should work.</p>\n" }, { "answer_id": 34602, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 0, "selected": false, "text": "<p>If you've gotta stick to your current method of parsing, and it's a regex, you can use the <a href=\"http://us3.php.net/manual/en/reference.pcre.pattern.modifiers.php\" rel=\"nofollow noreferrer\">multi-line flag</a> \"m\" to span across multiple lines.</p>\n" }, { "answer_id": 34614, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": 2, "selected": true, "text": "<p>Perhaps for future projects I'll use a parsing library, but that's kind of aside from the question at hand. This is my current solution. <code>rstrpos</code> is strpos, but from the reverse direction. Example use:</p>\n\n<pre><code>for($i=0; $i&lt;count($lines); $i++)\n{\n $line = handle_mulitline_tags(&amp;$i, $line, $lines);\n}\n</code></pre>\n\n<p>And here's that implementation:</p>\n\n<pre><code>function rstrpos($string, $charToFind, $relativePos)\n{\n $searchPos = $relativePos;\n $searchChar = '';\n\n while (($searchChar != $charToFind)&amp;&amp;($searchPos&gt;-1))\n {\n $newPos = $searchPos-1;\n $searchChar = substr($string,$newPos,strlen($charToFind));\n $searchPos = $newPos;\n }\n\n if (!empty($searchChar))\n {\n return $searchPos;\n return TRUE;\n }\n else\n {\n return FALSE;\n }\n}\n\nfunction handle_multiline_tags(&amp;$i, $line, $lines)\n{\n //if a tag is opened but not closed before a line break,\n\n $open = rstrpos($line, '&lt;', strlen($line));\n $close = rstrpos($line, '&gt;', strlen($line));\n if(($open &gt; $close)&amp;&amp;($open &gt; -1)&amp;&amp;($close &gt; -1))\n {\n $i++;\n return trim($line).trim(handle_multiline_tags(&amp;$i, $lines[$i], $lines));\n }\n else\n {\n return trim($line);\n }\n}\n</code></pre>\n\n<p>This could probably be optimized in some way, but for my purposes, it's sufficient.</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1569/" ]
I'm writing a PHP script that involves scraping web pages. Currently, the script analyzes the page line by line, but it breaks if there is a tag that spans multiple lines, like ``` <img src="example.jpg" alt="example"> ``` If worse comes to worst, I could possibly preprocess the page by removing all line breaks, then re-inserting them at the closest `>`, but this seems like a kludge. Ideally, I'd be able to detect a tag that spans lines, conjoin only those to lines, and continue processing. So what's the best method to detect this?
Perhaps for future projects I'll use a parsing library, but that's kind of aside from the question at hand. This is my current solution. `rstrpos` is strpos, but from the reverse direction. Example use: ``` for($i=0; $i<count($lines); $i++) { $line = handle_mulitline_tags(&$i, $line, $lines); } ``` And here's that implementation: ``` function rstrpos($string, $charToFind, $relativePos) { $searchPos = $relativePos; $searchChar = ''; while (($searchChar != $charToFind)&&($searchPos>-1)) { $newPos = $searchPos-1; $searchChar = substr($string,$newPos,strlen($charToFind)); $searchPos = $newPos; } if (!empty($searchChar)) { return $searchPos; return TRUE; } else { return FALSE; } } function handle_multiline_tags(&$i, $line, $lines) { //if a tag is opened but not closed before a line break, $open = rstrpos($line, '<', strlen($line)); $close = rstrpos($line, '>', strlen($line)); if(($open > $close)&&($open > -1)&&($close > -1)) { $i++; return trim($line).trim(handle_multiline_tags(&$i, $lines[$i], $lines)); } else { return trim($line); } } ``` This could probably be optimized in some way, but for my purposes, it's sufficient.
33,822
<p>Every time I turn on my company-owned development machine, I have to kill 10+ processes using the Task Manager or any other process management app just to get decent performance out of my IDE. Yes, these are processes from programs that my company installs on my machine for security and compliance. What I'd like to do is have a .bat file or script of some kind with which I can kill the processes in question. </p> <p>Does anybody know how to do this?</p>
[ { "answer_id": 33826, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 2, "selected": false, "text": "<p>Download <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896683.aspx\" rel=\"nofollow noreferrer\">PSKill</a>. Write a batch file that calls it for each process you want dead, passing in the name of the process for each.</p>\n" }, { "answer_id": 33828, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 7, "selected": false, "text": "<pre><code>taskkill /f /im \"devenv.exe\"\n</code></pre>\n\n<p>this will forcibly kill the pid with the exe name \"devenv.exe\"</p>\n\n<p>equivalent to -9 on the nix'y kill command</p>\n" }, { "answer_id": 33831, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": 9, "selected": true, "text": "<p>You can do this with '<strong>taskkill</strong>'.\nWith the /IM parameter, you can specify image names. </p>\n\n<p>Example:</p>\n\n<pre><code>taskkill /im somecorporateprocess.exe\n</code></pre>\n\n<p>You can also do this to '<strong>force</strong>' kill:</p>\n\n<p>Example:</p>\n\n<pre><code>taskkill /f /im somecorporateprocess.exe\n</code></pre>\n\n<p>Just add one line per process you want to kill, save it as a .bat file, and add in your startup directory. Problem solved!</p>\n\n<p>If this is a legacy system, <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896683.aspx\" rel=\"noreferrer\">PsKill</a> will do the same.</p>\n" }, { "answer_id": 33859, "author": "slipsec", "author_id": 1635, "author_profile": "https://Stackoverflow.com/users/1635", "pm_score": 1, "selected": false, "text": "<p>Use Powershell! Built in cmdlets for managing processes. <a href=\"http://blogs.msdn.com/powershell/archive/2007/01/16/managing-processes-in-powershell.aspx\" rel=\"nofollow noreferrer\">Examples here</a> (hard way), <a href=\"http://www.computerperformance.co.uk/powershell/powershell_process.htm\" rel=\"nofollow noreferrer\">here</a>(built in) and <a href=\"http://www.computerperformance.co.uk/powershell/powershell_process_stop.htm\" rel=\"nofollow noreferrer\">here</a> (more).</p>\n" }, { "answer_id": 33912, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 3, "selected": false, "text": "<p>I'm assuming as a developer, you have some degree of administrative control over your machine. If so, from the command line, run msconfig.exe. You can remove many processes from even starting, thereby eliminating the need to kill them with the above mentioned solutions.</p>\n" }, { "answer_id": 33920, "author": "Brian Stewart", "author_id": 3114, "author_profile": "https://Stackoverflow.com/users/3114", "pm_score": 3, "selected": false, "text": "<p>Get <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb963902.aspx\" rel=\"noreferrer\">Autoruns</a> from Mark Russinovich, the Sysinternals guy that discovered the Sony Rootkit... Best software I've ever used for cleaning up things that get started automatically.</p>\n" }, { "answer_id": 28273570, "author": "npocmaka", "author_id": 388389, "author_profile": "https://Stackoverflow.com/users/388389", "pm_score": 3, "selected": false, "text": "<p>As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:</p>\n\n<pre><code>TSKILL processName\n</code></pre>\n\n<p>or</p>\n\n<pre><code>TSKILL PID\n</code></pre>\n\n<p>Have on mind that <code>processName</code> should not have the <code>.exe</code> suffix and is limited to 18 characters.</p>\n\n<p>Another option is <code>WMIC</code> :</p>\n\n<pre><code>wmic Path win32_process Where \"Caption Like 'MyProcess%.exe'\" Call Terminate\n</code></pre>\n\n<p>wmic offer even more flexibility than taskkill with its SQL-like matchers .With <code>wmic Path win32_process get</code> you can see the available fileds you can filter (and <code>%</code> can be used as a wildcard). </p>\n" }, { "answer_id": 40262412, "author": "Sarath Subramanian", "author_id": 3312636, "author_profile": "https://Stackoverflow.com/users/3312636", "pm_score": 1, "selected": false, "text": "<p>Please find the below logic where it works on the condition.</p>\n\n<p>If we simply call <code>taskkill /im applicationname.exe</code>, it will kill only if this process is running. If this process is not running, it will throw an error.</p>\n\n<p>So as to check before <code>takskill</code> is called, a check can be done to make sure execute <code>taskkill</code> will be executed only if the process is running, so that it won't throw error.</p>\n\n<pre><code>tasklist /fi \"imagename eq applicationname.exe\" |find \":\" &gt; nul\n\nif errorlevel 1 taskkill /f /im \"applicationname.exe\"\n</code></pre>\n" }, { "answer_id": 48756190, "author": "Eduard Florinescu", "author_id": 1577343, "author_profile": "https://Stackoverflow.com/users/1577343", "pm_score": 1, "selected": false, "text": "<p>Here I wrote an example command that you can paste in your <code>cmd</code> command line prompt and is written for <code>chrome.exe</code>. </p>\n\n<pre><code>FOR /F \"tokens=2 delims= \" %P IN ('tasklist /FO Table /M \"chrome*\" /NH') DO (TASKKILL /PID %P)\n</code></pre>\n\n<p>The for just takes all the <code>PID</code>s listed on the below <code>tasklist</code> command and executes <code>TASKKILL /PID</code> on every <code>PID</code> </p>\n\n<pre><code>tasklist /FO Table /M \"chrome*\" /NH\n</code></pre>\n\n<p>If you use the for in a batch file just use %%P instead of %P</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3030/" ]
Every time I turn on my company-owned development machine, I have to kill 10+ processes using the Task Manager or any other process management app just to get decent performance out of my IDE. Yes, these are processes from programs that my company installs on my machine for security and compliance. What I'd like to do is have a .bat file or script of some kind with which I can kill the processes in question. Does anybody know how to do this?
You can do this with '**taskkill**'. With the /IM parameter, you can specify image names. Example: ``` taskkill /im somecorporateprocess.exe ``` You can also do this to '**force**' kill: Example: ``` taskkill /f /im somecorporateprocess.exe ``` Just add one line per process you want to kill, save it as a .bat file, and add in your startup directory. Problem solved! If this is a legacy system, [PsKill](http://technet.microsoft.com/en-us/sysinternals/bb896683.aspx) will do the same.
33,836
<p>This is a follow on question to "<a href="https://stackoverflow.com/questions/33778/how-do-i-delete-1-file-from-a-revision-in-svn">How do I delete 1 file from a revision in SVN?</a>" but because it probably has a very different answer and I believe that others would benefit from knowing the answer. (I don't know the answer yet.)</p> <p>The previous question was answered and I discovered that it is not possible to remove a revision from SVN. The second best solution was to remove the file from SVN, commit and then add the file back and commit again.</p> <p>I now want to make sure that the original file's revision history has gone. So I am hoping that the answer to the question "<strong>How can I find the revision history of the file that was deleted and then resubmitted to SVN?</strong>" is that you can't.</p>
[ { "answer_id": 33846, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 1, "selected": false, "text": "<p>I would have said you can't - you have created a new file and thus revision tree in the eyes of SVN.</p>\n\n<p>It may be possible to recover the old tree independently (not sure if you managed an actual delete or just SVN Delete) but there is no link between the old revision tree and the new one.</p>\n" }, { "answer_id": 33862, "author": "Damien B", "author_id": 3069, "author_profile": "https://Stackoverflow.com/users/3069", "pm_score": 3, "selected": true, "text": "<p>With a simple </p>\n\n<pre><code>svn log -v [folder]\n</code></pre>\n\n<p>you can browse quickly the adding and deletion.</p>\n\n<pre><code>------------------------------------------------------------------------\nr14 | kame | 2008-08-29 04:23:43 +0200 (ven., 29 aoû2008) | 1 line\nChemins modifié :\n A /a.txt\n\nReadded a\n------------------------------------------------------------------------\nr13 | kame | 2008-08-29 04:23:24 +0200 (ven., 29 aoû2008) | 1 line\nChemins modifié :\n D /a.txt\n\nDelete a\n------------------------------------------------------------------------\nr12 | kame | 2008-08-29 04:23:06 +0200 (ven., 29 aoû2008) | 1 line\nChemins modifié :\n A /a.txt\n</code></pre>\n\n<p>svn log won't show the file, svn diff will pretend that the old revision does not exist, but a svn checkout targeting the old revision will happily give you the old file.</p>\n" }, { "answer_id": 33874, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 2, "selected": false, "text": "<p>What makes you think that it is not possible to remove a revision from Subversion? The solution given to your other question (<code>svndumpfilter</code>) does exactly that (see the parameters <code>--drop-empty-revs</code> and <code>--renumber-revs</code>)! And when the revision is gone, there's obviously no way to get at the revision history, because it was never there in the first place.</p>\n" }, { "answer_id": 33878, "author": "AndrewR", "author_id": 2994, "author_profile": "https://Stackoverflow.com/users/2994", "pm_score": 2, "selected": false, "text": "<p><strong>Short answer:</strong> you can</p>\n\n<p><strong>Long answer:</strong></p>\n\n<p>Unfortunately (for you but perhaps not for most folks) , the revision history for a deleted file is still there - it's just a little harder to get at.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>$ touch one\n$ svn add one\n$ svn ci -m \"Added file one\"\n$ date &gt;&gt; one \n$ svn ci -m \"Updated file one\"\n$ date &gt;&gt; one\n$ svn ci -m \"Updated file one again\"\n$ svn log file:///repos/one\n\n------------------------------------------------------------------------\nr3 | andrewr | 2008-08-29 12:27:10 +1000 (Fri, 29 Aug 2008) | 1 line\n\nUpdated file one again\n------------------------------------------------------------------------\nr2 | andrewr | 2008-08-29 12:26:50 +1000 (Fri, 29 Aug 2008) | 1 line\n\nUpdated file one\n------------------------------------------------------------------------\nr1 | andrewr | 2008-08-29 12:25:07 +1000 (Fri, 29 Aug 2008) | 1 line\n\nAdded file one\n------------------------------------------------------------------------\n\n$ svn delete one\n$ svn ci -m \"Deleted file one\"\n$ svn up\n$ touch one\n$ svn add one\n$ svn ci -m \"Adding file one back in\"\n$ svn log file:///repos/one\n\n------------------------------------------------------------------------\nr5 | andrewr | 2008-08-29 12:29:13 +1000 (Fri, 29 Aug 2008) | 1 line\n\nadd one back\n------------------------------------------------------------------------\n</code></pre>\n\n<p>It looks like it works (the old history is gone), but if you request the file at older revisions you get the history\nof the deleted file.</p>\n\n<pre><code>$ svn log -r 3:1 file:///repos/one\n\n------------------------------------------------------------------------\nr3 | andrewr | 2008-08-29 12:27:10 +1000 (Fri, 29 Aug 2008) | 1 line\n\nUpdated file one again\n------------------------------------------------------------------------\nr2 | andrewr | 2008-08-29 12:26:50 +1000 (Fri, 29 Aug 2008) | 1 line\n\nUpdated file one\n------------------------------------------------------------------------\nr1 | andrewr | 2008-08-29 12:25:07 +1000 (Fri, 29 Aug 2008) | 1 line\n\nAdded file one\n------------------------------------------------------------------------\n</code></pre>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
This is a follow on question to "[How do I delete 1 file from a revision in SVN?](https://stackoverflow.com/questions/33778/how-do-i-delete-1-file-from-a-revision-in-svn)" but because it probably has a very different answer and I believe that others would benefit from knowing the answer. (I don't know the answer yet.) The previous question was answered and I discovered that it is not possible to remove a revision from SVN. The second best solution was to remove the file from SVN, commit and then add the file back and commit again. I now want to make sure that the original file's revision history has gone. So I am hoping that the answer to the question "**How can I find the revision history of the file that was deleted and then resubmitted to SVN?**" is that you can't.
With a simple ``` svn log -v [folder] ``` you can browse quickly the adding and deletion. ``` ------------------------------------------------------------------------ r14 | kame | 2008-08-29 04:23:43 +0200 (ven., 29 aoû2008) | 1 line Chemins modifié : A /a.txt Readded a ------------------------------------------------------------------------ r13 | kame | 2008-08-29 04:23:24 +0200 (ven., 29 aoû2008) | 1 line Chemins modifié : D /a.txt Delete a ------------------------------------------------------------------------ r12 | kame | 2008-08-29 04:23:06 +0200 (ven., 29 aoû2008) | 1 line Chemins modifié : A /a.txt ``` svn log won't show the file, svn diff will pretend that the old revision does not exist, but a svn checkout targeting the old revision will happily give you the old file.
33,837
<p>I have a page where there is a column and a content div, somewhat like this:</p> <pre><code>&lt;div id="container"&gt; &lt;div id="content"&gt;blahblahblah&lt;/div&gt; &lt;div id="column"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>With some styling I have an image that is split between the column and the content but needs to maintain the same vertical positioning so that it lines up.</p> <p>Styling is similar to this:</p> <pre class="lang-css prettyprint-override"><code>#column { width:150px; height:450px; left:-150px; bottom:-140px; background:url(../images/image.png) no-repeat; position:absolute; z-index:1; } #container { background:transparent url(../images/container.png) no-repeat scroll left bottom; position:relative; width:100px; } </code></pre> <p>This works great when content in <code>#content</code> is dynamically loaded before rendering. This also works great in firefox always. However, in IE6 and IE7 if I use javascript to change the content (and thus height) of <code>#content</code>, the images no longer line up (<code>#column</code> doesn't move). If I use IE Developer Bar to just update the div (say add position:absolute manually) the image jumps down and lines up again.</p> <p>Is there something I am missing here?</p> <p>@Ricky - Hmm, that means in this case there is no solution I think. At its best there will be a jaggedy matchup afterwards but as my content expands and contracts etc. hiding/showing doesn't work out to be practical. Still thanks for answering with the best solution.</p>
[ { "answer_id": 33854, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 3, "selected": true, "text": "<p>Its a bug in the rendering engine. I run into it all the time. One potential way to solve it is to hide and show the div whenever you change the content (that in turn changes the height):</p>\n\n<pre><code>var divCol = document.getElementById('column');\ndivCol.style.display = 'none';\ndivCol.style.display = 'block';\n</code></pre>\n\n<p>Hopefully this happens fast enough that it isn't noticeable :)</p>\n" }, { "answer_id": 2073214, "author": "tedL", "author_id": 251706, "author_profile": "https://Stackoverflow.com/users/251706", "pm_score": 0, "selected": false, "text": "<p>If you are worried about getting a flicker from showing and hiding divCol you can ajust another css property and it will have the same effect \ne.g.</p>\n\n<pre><code>var divCol = document.getElementById('column');\ndivCol.style.zoom = '1';\ndivCol.style.zoom = '';\n</code></pre>\n" }, { "answer_id": 4237045, "author": "Yousef Salimpour", "author_id": 405316, "author_profile": "https://Stackoverflow.com/users/405316", "pm_score": 1, "selected": false, "text": "<p>Another workaround which worked for me and had no flickering effect was to add and remove a dummy CSS class name, like this using jQuery:</p>\n\n<pre><code>$(element).toggleClass('damn-you-ie')\n</code></pre>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
I have a page where there is a column and a content div, somewhat like this: ``` <div id="container"> <div id="content">blahblahblah</div> <div id="column"> </div> </div> ``` With some styling I have an image that is split between the column and the content but needs to maintain the same vertical positioning so that it lines up. Styling is similar to this: ```css #column { width:150px; height:450px; left:-150px; bottom:-140px; background:url(../images/image.png) no-repeat; position:absolute; z-index:1; } #container { background:transparent url(../images/container.png) no-repeat scroll left bottom; position:relative; width:100px; } ``` This works great when content in `#content` is dynamically loaded before rendering. This also works great in firefox always. However, in IE6 and IE7 if I use javascript to change the content (and thus height) of `#content`, the images no longer line up (`#column` doesn't move). If I use IE Developer Bar to just update the div (say add position:absolute manually) the image jumps down and lines up again. Is there something I am missing here? @Ricky - Hmm, that means in this case there is no solution I think. At its best there will be a jaggedy matchup afterwards but as my content expands and contracts etc. hiding/showing doesn't work out to be practical. Still thanks for answering with the best solution.
Its a bug in the rendering engine. I run into it all the time. One potential way to solve it is to hide and show the div whenever you change the content (that in turn changes the height): ``` var divCol = document.getElementById('column'); divCol.style.display = 'none'; divCol.style.display = 'block'; ``` Hopefully this happens fast enough that it isn't noticeable :)
33,852
<p>Most of time we represent concepts which can never be less than 0. For example to declare length, we write:</p> <pre><code>int length; </code></pre> <p>The name expresses its purpose well but you can assign negative values to it. It seems that for some situations, you can represent your intent more clearly by writing it this way instead:</p> <pre><code>uint length; </code></pre> <p>Some disadvantages that I can think of:</p> <ul> <li>unsigned types (uint, ulong, ushort) are not CLS compliant so you can't use it with other languages that don't support this</li> <li>.Net classes use signed types most of the time so you have to cast</li> </ul> <p>Thoughts?</p>
[ { "answer_id": 33857, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 3, "selected": false, "text": "<p>If you decrement a signed number with a value of 0, it becomes negative and you can easily test for this. If you decrement an unsigned number with a value of 0, it underflows and becomes the maximum value for the type - somewhat more difficult to check for. </p>\n" }, { "answer_id": 33858, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 3, "selected": false, "text": "<p>Your second point is the most important. Generally you should just use <code>int</code> since that's a pretty good \"catch-all\" for integer values. I would only use <code>uint</code> if you absolutely need the ability to count higher than <code>int</code>, but without using the extra memory <code>long</code> requires (it's not much more memory, so don't be cheap :-p).</p>\n" }, { "answer_id": 33865, "author": "Rob Bazinet", "author_id": 2305, "author_profile": "https://Stackoverflow.com/users/2305", "pm_score": 2, "selected": false, "text": "<p>I think the subtle use of uint vs. int will cause confusing with developers unless it was written into developer guidelines for the company.</p>\n\n<p>If the length, for example, can't be less than zero then it should be expressed clearly in the business logic so future developers can read the code and know the true intent.</p>\n\n<p>Just my 2 cents.</p>\n" }, { "answer_id": 34008, "author": "Eric Burnett", "author_id": 3524, "author_profile": "https://Stackoverflow.com/users/3524", "pm_score": 2, "selected": false, "text": "<p>I will point out that in C# you can turn on <a href=\"http://msdn.microsoft.com/en-us/library/h25wtyxf.aspx\" rel=\"nofollow noreferrer\"><code>/checked</code></a> to check for arithmetic overflow / underflow, which isn't a bad idea anyways. If performance matters in a critical section, you can still use <code>unchecked</code> to avoid this. </p>\n\n<p>For internal code (ie code that won't be referenced in any interop manor with other languages) I vote for using unsigned when the situation warrants it, such as <code>length</code> variables as mentioned earlier. This - along with checked arithmetic - provides one more net for developers, catching subtle bugs earlier.</p>\n\n<p>Another point in the signed vs unsigned debate is that some programmers use values such as -1 to indicate errors, when they wouldn't otherwise have meaning. I subscribe to the view that each variable should have only one purpose, but if you - or colleagues you code with - like to indicate errors in this way, leaving variables signed gives you the flexibility to add error states later.</p>\n" }, { "answer_id": 34049, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 0, "selected": false, "text": "<p>Your two points are good. The primary reason to avoid it is casting, though. Casting makes them incredibly annoying to use. I tried using unisigned variables once but I had to sprinkle casts absolutely everywhere because the framework methods all use signed integers. Therefore, whenever you call a framework method, you have to cast.</p>\n" }, { "answer_id": 34108, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "<p>“When in Rome, do as the Romans do.”</p>\n\n<p>While there is theoretically an advantage in using unsigned values where applicable because it makes the code more expressive, this is simply not done in C#. I'm not sure why the developers initially didn't design the interfaces to handle <code>uints</code> and make the type CLS compliant but now the train has left the station.</p>\n\n<p>Since consistency is generally important I'd advise taking the C# road and using <code>int</code>s.</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/718/" ]
Most of time we represent concepts which can never be less than 0. For example to declare length, we write: ``` int length; ``` The name expresses its purpose well but you can assign negative values to it. It seems that for some situations, you can represent your intent more clearly by writing it this way instead: ``` uint length; ``` Some disadvantages that I can think of: * unsigned types (uint, ulong, ushort) are not CLS compliant so you can't use it with other languages that don't support this * .Net classes use signed types most of the time so you have to cast Thoughts?
“When in Rome, do as the Romans do.” While there is theoretically an advantage in using unsigned values where applicable because it makes the code more expressive, this is simply not done in C#. I'm not sure why the developers initially didn't design the interfaces to handle `uints` and make the type CLS compliant but now the train has left the station. Since consistency is generally important I'd advise taking the C# road and using `int`s.
33,860
<p>In Ruby on Rails, I'm attempting to update the <code>innerHTML</code> of a div tag using the <code>form_remote_tag</code> helper. This update happens whenever an associated select tag receives an onchange event. The problem is, <code>&lt;select onchange="this.form.submit();"&gt;</code>; doesn't work. Nor does <code>document.forms[0].submit()</code>. The only way to get the onsubmit code generated in the form_remote_tag to execute is to create a hidden submit button, and invoke the click method on the button from the select tag. Here's a working ERb partial example.</p> <pre><code>&lt;% form_remote_tag :url =&gt; product_path, :update =&gt; 'content', :method =&gt; 'get' do -%&gt; &lt;% content_tag :div, :id =&gt; 'content' do -%&gt; &lt;%= select_tag :update, options_for_select([["foo", 1], ["bar", 2]]), :onchange =&gt; "this.form.commit.click" %&gt; &lt;%= submit_tag 'submit_button', :style =&gt; "display: none" %&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>What I want to do is something like this, but it doesn't work.</p> <pre><code>&lt;% form_remote_tag :url =&gt; product_path, :update =&gt; 'content', :method =&gt; 'get' do -%&gt; &lt;% content_tag :div, :id =&gt; 'content' do -%&gt; # the following line does not work &lt;%= select_tag :update, options_for_select([["foo", 1], ["bar", 2]]), :onchange =&gt; "this.form.onsubmit()" %&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>So, is there any way to remove the invisible submit button for this use case?</p> <p>There seems to be some confusion. So, let me explain. The basic problem is that <code>submit()</code> doesn't call the <code>onsubmit()</code> code rendered into the form.</p> <p>The actual HTML form that Rails renders from this ERb looks like this:</p> <pre><code>&lt;form action="/products/1" method="post" onsubmit="new Ajax.Updater('content', '/products/1', {asynchronous:true, evalScripts:true, method:'get', parameters:Form.serialize(this)}); return false;"&gt; &lt;div style="margin:0;padding:0"&gt; &lt;input name="authenticity_token" type="hidden" value="4eacf78eb87e9262a0b631a8a6e417e9a5957cab" /&gt; &lt;/div&gt; &lt;div id="content"&gt; &lt;select id="update" name="update" onchange="this.form.commit.click"&gt; &lt;option value="1"&gt;foo&lt;/option&gt; &lt;option value="2"&gt;bar&lt;/option&gt; &lt;/select&gt; &lt;input name="commit" style="display: none" type="submit" value="submit_button" /&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>I want to axe the invisible submit button, but using a straight form.submit appears to not work. So, I need some way to call the form's onsubmit event code.</p> <p>Update: Orion Edwards solution would work if there wasn't a <code>return(false);</code> generated by Rails. I'm not sure which is worse though, sending a phantom click to an invisible submit button or calling eval on the <code>getAttribute('onsubmit')</code> call after removing the return call with a javascript string replacement! </p>
[ { "answer_id": 33879, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>give your form an <code>id</code>.</p>\n\n<p>then</p>\n\n<pre><code>document.getElementById('formid').submit();\n</code></pre>\n\n<p>If you are loading Javascript into a <code>div</code> via <code>innerHTML</code>, it won't run...just FYI.</p>\n" }, { "answer_id": 33941, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": -1, "selected": true, "text": "<p>If you didn't actually want to submit the form, but just invoke whatever code happened to be in the onsubmit, you could possibly do this: (untested)</p>\n\n<pre><code>var code = document.getElementById('formId').getAttribute('onsubmit');\neval(code);\n</code></pre>\n" }, { "answer_id": 33999, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>If you have to use Rail's built-in Javascript generation, I would use Orion's solution, but with one small alteration to compensate for the return code.</p>\n\n<pre><code>eval ('(function(){' + code + '})()');\n</code></pre>\n\n<p>However, in my opinion you'd have an easier time in the long run by separating out the Javascript code into an external file or separate callable functions.</p>\n" }, { "answer_id": 34046, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": -1, "selected": false, "text": "<p>In theory, something like <code>eval ('function(){' + code + '}()');</code> could work (that syntax fails though). Even if that did work, it would still be sort of ghetto to be calling an eval through a select <code>onchange</code>. Another solution would be to somehow get Rails to inject the <code>onsubmit</code> code into the <code>onchange</code> field of the select tag, but I'm not sure if there's a way to do that. ActionView has link_to_remote, but there's no obvious helper to generate the same code in the <code>onchange</code> field.</p>\n" }, { "answer_id": 104032, "author": "fatgeekuk", "author_id": 17518, "author_profile": "https://Stackoverflow.com/users/17518", "pm_score": 1, "selected": false, "text": "<p>Don't.</p>\n\n<p>You have a solution.</p>\n\n<p>Stop, move on to the next function point.</p>\n\n<p>I know, it is not pretty, but there are bigger problems.</p>\n" }, { "answer_id": 481682, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Not sure if you have an answer yet or not, but in the <code>onclick</code> function of the select, call <code>onsubmit</code> instead of <code>submit</code>.</p>\n" }, { "answer_id": 2466332, "author": "ErikE", "author_id": 57611, "author_profile": "https://Stackoverflow.com/users/57611", "pm_score": 3, "selected": false, "text": "<p>I realize this question is kind of old, but what the heck are you doing eval for?</p>\n\n<pre><code>document.getElementById('formId').onsubmit();\ndocument.getElementById('formId').submit();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>document.formName.onsubmit();\ndocument.formName.submit();\n</code></pre>\n\n<p>When the DOM of a document is loaded, the events are not strings any more, they are functions.</p>\n\n<pre><code>alert(typeof document.formName.onsubmit); // function\n</code></pre>\n\n<p>So there's no reason to convert a function to a string just so you can eval it.</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3499/" ]
In Ruby on Rails, I'm attempting to update the `innerHTML` of a div tag using the `form_remote_tag` helper. This update happens whenever an associated select tag receives an onchange event. The problem is, `<select onchange="this.form.submit();">`; doesn't work. Nor does `document.forms[0].submit()`. The only way to get the onsubmit code generated in the form\_remote\_tag to execute is to create a hidden submit button, and invoke the click method on the button from the select tag. Here's a working ERb partial example. ``` <% form_remote_tag :url => product_path, :update => 'content', :method => 'get' do -%> <% content_tag :div, :id => 'content' do -%> <%= select_tag :update, options_for_select([["foo", 1], ["bar", 2]]), :onchange => "this.form.commit.click" %> <%= submit_tag 'submit_button', :style => "display: none" %> <% end %> <% end %> ``` What I want to do is something like this, but it doesn't work. ``` <% form_remote_tag :url => product_path, :update => 'content', :method => 'get' do -%> <% content_tag :div, :id => 'content' do -%> # the following line does not work <%= select_tag :update, options_for_select([["foo", 1], ["bar", 2]]), :onchange => "this.form.onsubmit()" %> <% end %> <% end %> ``` So, is there any way to remove the invisible submit button for this use case? There seems to be some confusion. So, let me explain. The basic problem is that `submit()` doesn't call the `onsubmit()` code rendered into the form. The actual HTML form that Rails renders from this ERb looks like this: ``` <form action="/products/1" method="post" onsubmit="new Ajax.Updater('content', '/products/1', {asynchronous:true, evalScripts:true, method:'get', parameters:Form.serialize(this)}); return false;"> <div style="margin:0;padding:0"> <input name="authenticity_token" type="hidden" value="4eacf78eb87e9262a0b631a8a6e417e9a5957cab" /> </div> <div id="content"> <select id="update" name="update" onchange="this.form.commit.click"> <option value="1">foo</option> <option value="2">bar</option> </select> <input name="commit" style="display: none" type="submit" value="submit_button" /> </div> </form> ``` I want to axe the invisible submit button, but using a straight form.submit appears to not work. So, I need some way to call the form's onsubmit event code. Update: Orion Edwards solution would work if there wasn't a `return(false);` generated by Rails. I'm not sure which is worse though, sending a phantom click to an invisible submit button or calling eval on the `getAttribute('onsubmit')` call after removing the return call with a javascript string replacement!
If you didn't actually want to submit the form, but just invoke whatever code happened to be in the onsubmit, you could possibly do this: (untested) ``` var code = document.getElementById('formId').getAttribute('onsubmit'); eval(code); ```
33,881
<p>I always run into the same problem when creating web pages. When I add a font that is larger then about 16-18px it looks terrible. Its jagged, and pixelated. I have tried using different fonts and weights, however I haven't had much luck there. </p> <p>Note: Its only in windows that it is like this. Mainly in Opera and FF also in IE7 but not quite as bad. In Linux the font looks good. I haven't looked at a Mac.</p> <p>What do you guys do to fix this? if anything. I noticed that the titles here on SO are also pretty jagged but they are just small enough not to look bad. </p>
[ { "answer_id": 33885, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 0, "selected": false, "text": "<p>Enabling anti-aliasing should solve the display problem. </p>\n" }, { "answer_id": 33886, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 0, "selected": false, "text": "<p>Aside from anti-aliasing, try enabling clear type.</p>\n" }, { "answer_id": 316806, "author": "Philip Morton", "author_id": 21709, "author_profile": "https://Stackoverflow.com/users/21709", "pm_score": 0, "selected": false, "text": "<p>On Windows, enabling <a href=\"http://en.wikipedia.org/wiki/ClearType\" rel=\"nofollow noreferrer\">ClearType</a> will solve this. However, you can't force users to use it. It's not a browser issue; it's the operating system's font smoothing method.</p>\n" }, { "answer_id": 316867, "author": "Jack Ryan", "author_id": 28882, "author_profile": "https://Stackoverflow.com/users/28882", "pm_score": 2, "selected": true, "text": "<p>There is nothing you can do to force the user to change the way that their operating system renders fonts. If it is that big a deal to you then you can replace the large headings with images, this allows you to control exactly how the font is rendered (and ensures that the heading looks exactly as you wish, even if the user doesnt have your suggested font installed). </p>\n\n<p>If you do this make sure that you provide an alternative text representation for those who do not see images. I tend to use CSS to show a background image, and hide the contents of the heading. Like this.</p>\n\n<pre><code>&lt;style&gt;\n h1\n {\n height: 32px;\n width: 100px;\n background: url(\"path/to/image\")\n }\n\n h1 span\n {\n display: none;\n }\n&lt;/style&gt;\n\n&lt;h1&gt;\n &lt;span&gt;\n Heading Text\n &lt;span&gt;\n&lt;/h1&gt;\n</code></pre>\n\n<p>To be honest this does seem like overkill if it is on all large text. And be aware that it will increase the amount of data that your clients need to download. However for a large heading this method can lead to something that looks nicer than OS rendered text.</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1925/" ]
I always run into the same problem when creating web pages. When I add a font that is larger then about 16-18px it looks terrible. Its jagged, and pixelated. I have tried using different fonts and weights, however I haven't had much luck there. Note: Its only in windows that it is like this. Mainly in Opera and FF also in IE7 but not quite as bad. In Linux the font looks good. I haven't looked at a Mac. What do you guys do to fix this? if anything. I noticed that the titles here on SO are also pretty jagged but they are just small enough not to look bad.
There is nothing you can do to force the user to change the way that their operating system renders fonts. If it is that big a deal to you then you can replace the large headings with images, this allows you to control exactly how the font is rendered (and ensures that the heading looks exactly as you wish, even if the user doesnt have your suggested font installed). If you do this make sure that you provide an alternative text representation for those who do not see images. I tend to use CSS to show a background image, and hide the contents of the heading. Like this. ``` <style> h1 { height: 32px; width: 100px; background: url("path/to/image") } h1 span { display: none; } </style> <h1> <span> Heading Text <span> </h1> ``` To be honest this does seem like overkill if it is on all large text. And be aware that it will increase the amount of data that your clients need to download. However for a large heading this method can lead to something that looks nicer than OS rendered text.
33,893
<p>In my (PHP) web app, I have a part of my site that keeps a history of recent searches. The most recent queries get shown in a side box. If the query text is too long, I truncate it and show ellipses. Eg: "My very long query is..."</p> <p>Currently, I truncate after a certain number of characters. Since the font is not monotype, a query of all I's is more narrow than a query of all W's. I'd like them to all be about the same width prior to the ellipses. Is there a way to get the approximate width of the resulting string so that the ellipses for any given string will occur in about the same number of pixels from the beginning? Does CSS have a way? Does PHP? Would this be better handled by JavaScript?</p>
[ { "answer_id": 33899, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Does CSS have a way?</p>\n</blockquote>\n\n<p>No</p>\n\n<blockquote>\n <p>Does PHP?</p>\n</blockquote>\n\n<p>No</p>\n\n<p>-</p>\n\n<p>To do that you'd have to get the font metrics for each character, and apply them to all your letters in your string. While you could do this by using a drawing/rendering library like ImageMagick on the server, it wouldn't really work because different browser on different OS's render fonts differently.</p>\n\n<p>Even if it did work, you wouldn't want to do it, because it would also take forever to render. Your server would be able to push 1 page per second (if that) instead of several thousand.</p>\n\n<p>If you can live without the trailing ..., then you can nicely fake it using <code>div</code> tags and css <code>overflow: hidden</code>, like this:</p>\n\n<pre><code>.line_of_text {\n height:1.3em;\n line-height:1.3em;\n overflow:hidden;\n}\n\n&lt;div class=\"line_of_text\"&gt; Some long text which will arbitrarily be cut off at whatever word fits best&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 33919, "author": "Robert Groves", "author_id": 3534, "author_profile": "https://Stackoverflow.com/users/3534", "pm_score": 4, "selected": true, "text": "<p>Here's another take on it and you don't have to live without the ellipsis!</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n\n&lt;style&gt;\ndiv.sidebox {\n width: 25%;\n}\n\ndiv.sidebox div.qrytxt {\n height: 1em;\n line-height: 1em;\n overflow: hidden;\n}\n\ndiv.sidebox div.qrytxt span.ellipsis {\n float: right;\n}\n&lt;/style&gt;\n\n\n&lt;/head&gt;\n\n&lt;body&gt;\n\n&lt;div class=\"sidebox\"&gt;\n &lt;div class=\"qrytxt\"&gt;\n &lt;span class=\"ellipsis\"&gt;&amp;hellip;&lt;/span&gt;\n Some long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end.\n &lt;/div&gt;\n &lt;div class=\"qrytxt\"&gt;\n &lt;span class=\"ellipsis\"&gt;&amp;hellip;&lt;/span&gt;\n Some more long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end.\n &lt;/div&gt;\n &lt;div class=\"qrytxt\"&gt;\n &lt;span class=\"ellipsis\"&gt;&amp;hellip;&lt;/span&gt;\n Short text. Fail!\n &lt;/div&gt;\n&lt;/body&gt;\n\n&lt;/html&gt;\n</code></pre>\n\n<p>There is one flaw with this, if the text is short enough to be fully displayed, the ellipses will still be displayed as well.</p>\n\n<p>[EDIT: 6/26/2009]</p>\n\n<p>At the suggestion of Power-Coder I have revised this a little. There are really only two changes, the addition of the <code>doctype</code> (see notes below) and the addition of the <code>display: inline-block</code> attribute on the <code>.qrytxt</code> DIV. Here is what it looks like now...</p>\n\n<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;style&gt;\n div.sidebox \n {\n width: 25%;\n }\n\n div.sidebox div.qrytxt\n {\n height: 1em;\n line-height: 1em;\n overflow: hidden;\n display: inline-block;\n }\n\n div.sidebox div.qrytxt span.ellipsis\n {\n float: right;\n }\n&lt;/style&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n &lt;div class=\"sidebox\"&gt;\n &lt;div class=\"qrytxt\"&gt;\n &lt;span class=\"ellipsis\"&gt;&amp;hellip;&lt;/span&gt;\n Some long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end.\n &lt;/div&gt;\n\n &lt;div class=\"qrytxt\"&gt;\n &lt;span class=\"ellipsis\"&gt;&amp;hellip;&lt;/span&gt;\n Some more long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end.\n &lt;/div&gt;\n\n &lt;div class=\"qrytxt\"&gt;\n &lt;span class=\"ellipsis\"&gt;&amp;hellip;&lt;/span&gt;\n Short text. FTW\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li><p>Viewed in IE 8.0, Opera 9, FF 3</p></li>\n<li><p>A <code>doctype</code> is required for IE to get the <code>display: inline-block</code> to work correctly.</p></li>\n<li><p>If the <code>.qrytxt</code> DIV's overflow occurs on a long word, there is going to be a wide gap between the ellipsis and the last visible word. You can see this by viewing the example and resizing your browser width in small increments. (this probably existed in the original example as well, I just may have not noticed it then)</p></li>\n</ul>\n\n<p>So again, an imperfect CSS-only solution. Javascript may be the only thing that can get the effect perfect.</p>\n\n<p>[EDIT: 6/27/2009]</p>\n\n<p>Here is another alternative which uses browser specific extensions.</p>\n\n<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"&gt;\n\n&lt;html&gt;\n&lt;head&gt;\n &lt;style&gt;\n div.sidebox \n {\n width: 26%;\n }\n\n div.sidebox div.qrytxt\n {\n height: 1em;\n line-height: 1em;\n overflow: hidden;\n text-overflow:ellipsis;\n -o-text-overflow:ellipsis;\n -ms-text-overflow:ellipsis;\n -moz-binding:url(ellipsis-xbl.xml#ellipsis);\n white-space:nowrap;\n }\n &lt;/style&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n &lt;div class=\"sidebox\"&gt;\n &lt;div class=\"qrytxt\"&gt;\n Some long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end.\n &lt;/div&gt;\n\n &lt;div class=\"qrytxt\"&gt;\n Some more long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end.\n &lt;/div&gt;\n\n &lt;div class=\"qrytxt\"&gt;\n Short text. FTW\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Note that in order for the above example to work, you must create the xml file referenced by the -moz-binding rule, <strong><em>ellipsis-xbl.xml</em></strong>. It's should contain the following xml:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n &lt;bindings xmlns=\"http://www.mozilla.org/xbl\" xmlns:xbl=\"http://www.mozilla.org/xbl\" xmlns:xul=\"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul\"&gt;\n &lt;binding id=\"ellipsis\"&gt;\n &lt;content&gt;\n &lt;xul:window&gt;\n &lt;xul:description crop=\"end\" xbl:inherits=\"value=xbl:text\"&gt;&lt;children/&gt;&lt;/xul:description&gt;\n &lt;/xul:window&gt;\n &lt;/content&gt;\n &lt;/binding&gt;\n &lt;/bindings&gt;\n</code></pre>\n" }, { "answer_id": 33942, "author": "Jiaaro", "author_id": 2908, "author_profile": "https://Stackoverflow.com/users/2908", "pm_score": 2, "selected": false, "text": "<p>@Robert</p>\n\n<p>what if you put the ellipses in a div with a low <code>z-index</code> so that when it moves to the left (for shorter lines) they get covered up by a background image or something?</p>\n\n<p>it's pretty hacky I know, but hey worth a try right?</p>\n\n<p><strong>edit</strong> Another idea: determine the position of the div containing the ellipses with javascript and if it's not pushed all the way right, hide it?</p>\n" }, { "answer_id": 43472, "author": "Evil Andy", "author_id": 4431, "author_profile": "https://Stackoverflow.com/users/4431", "pm_score": 2, "selected": false, "text": "<p>You could also quite easily use a bit of javascript:</p>\n\n<pre><code>document.getElementByID(\"qrytxt\").offsetWidth;\n</code></pre>\n\n<p>will give you the width of an element in pixels and even works in IE6. If you append a span containing ellipses to the end of each query a simple logical test in JavaScript with a bit of CSS manipulation could be used to hide/show them as needed.</p>\n" }, { "answer_id": 1047647, "author": "joebert", "author_id": 128357, "author_profile": "https://Stackoverflow.com/users/128357", "pm_score": 2, "selected": false, "text": "<p>PHP should be left out of consideration completely due to the fact that even though there is a function designed for measuring fonts, <a href=\"http://www.php.net/imageftbbox\" rel=\"nofollow noreferrer\">http://www.php.net/imageftbbox</a> , there is no way for PHP to know whether the visitor has a minimum font size setup that is larger than your anticipated font size.</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356/" ]
In my (PHP) web app, I have a part of my site that keeps a history of recent searches. The most recent queries get shown in a side box. If the query text is too long, I truncate it and show ellipses. Eg: "My very long query is..." Currently, I truncate after a certain number of characters. Since the font is not monotype, a query of all I's is more narrow than a query of all W's. I'd like them to all be about the same width prior to the ellipses. Is there a way to get the approximate width of the resulting string so that the ellipses for any given string will occur in about the same number of pixels from the beginning? Does CSS have a way? Does PHP? Would this be better handled by JavaScript?
Here's another take on it and you don't have to live without the ellipsis! ``` <html> <head> <style> div.sidebox { width: 25%; } div.sidebox div.qrytxt { height: 1em; line-height: 1em; overflow: hidden; } div.sidebox div.qrytxt span.ellipsis { float: right; } </style> </head> <body> <div class="sidebox"> <div class="qrytxt"> <span class="ellipsis">&hellip;</span> Some long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end. </div> <div class="qrytxt"> <span class="ellipsis">&hellip;</span> Some more long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end. </div> <div class="qrytxt"> <span class="ellipsis">&hellip;</span> Short text. Fail! </div> </body> </html> ``` There is one flaw with this, if the text is short enough to be fully displayed, the ellipses will still be displayed as well. [EDIT: 6/26/2009] At the suggestion of Power-Coder I have revised this a little. There are really only two changes, the addition of the `doctype` (see notes below) and the addition of the `display: inline-block` attribute on the `.qrytxt` DIV. Here is what it looks like now... ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <style> div.sidebox { width: 25%; } div.sidebox div.qrytxt { height: 1em; line-height: 1em; overflow: hidden; display: inline-block; } div.sidebox div.qrytxt span.ellipsis { float: right; } </style> </head> <body> <div class="sidebox"> <div class="qrytxt"> <span class="ellipsis">&hellip;</span> Some long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end. </div> <div class="qrytxt"> <span class="ellipsis">&hellip;</span> Some more long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end. </div> <div class="qrytxt"> <span class="ellipsis">&hellip;</span> Short text. FTW </div> </div> </body> </html> ``` Notes: * Viewed in IE 8.0, Opera 9, FF 3 * A `doctype` is required for IE to get the `display: inline-block` to work correctly. * If the `.qrytxt` DIV's overflow occurs on a long word, there is going to be a wide gap between the ellipsis and the last visible word. You can see this by viewing the example and resizing your browser width in small increments. (this probably existed in the original example as well, I just may have not noticed it then) So again, an imperfect CSS-only solution. Javascript may be the only thing that can get the effect perfect. [EDIT: 6/27/2009] Here is another alternative which uses browser specific extensions. ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <style> div.sidebox { width: 26%; } div.sidebox div.qrytxt { height: 1em; line-height: 1em; overflow: hidden; text-overflow:ellipsis; -o-text-overflow:ellipsis; -ms-text-overflow:ellipsis; -moz-binding:url(ellipsis-xbl.xml#ellipsis); white-space:nowrap; } </style> </head> <body> <div class="sidebox"> <div class="qrytxt"> Some long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end. </div> <div class="qrytxt"> Some more long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end. </div> <div class="qrytxt"> Short text. FTW </div> </div> </body> </html> ``` Note that in order for the above example to work, you must create the xml file referenced by the -moz-binding rule, ***ellipsis-xbl.xml***. It's should contain the following xml: ``` <?xml version="1.0" encoding="UTF-8"?> <bindings xmlns="http://www.mozilla.org/xbl" xmlns:xbl="http://www.mozilla.org/xbl" xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <binding id="ellipsis"> <content> <xul:window> <xul:description crop="end" xbl:inherits="value=xbl:text"><children/></xul:description> </xul:window> </content> </binding> </bindings> ```
33,923
<p>Whilst starting to learn lisp, I've come across the term <em>tail-recursive</em>. What does it mean exactly?</p>
[ { "answer_id": 33924, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 4, "selected": false, "text": "<p>I'm not a Lisp programmer, but I think <a href=\"http://en.wikipedia.org/wiki/Tail_recursion\" rel=\"noreferrer\">this</a> will help.</p>\n\n<p>Basically it's a style of programming such that the recursive call is the last thing you do.</p>\n" }, { "answer_id": 33928, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 6, "selected": false, "text": "<p>Using regular recursion, each recursive call pushes another entry onto the call stack. When the recursion is completed, the app then has to pop each entry off all the way back down.</p>\n\n<p>With tail recursion, depending on language the compiler may be able to collapse the stack down to one entry, so you save stack space...A large recursive query can actually cause a stack overflow.</p>\n\n<p>Basically Tail recursions are able to be optimized into iteration.</p>\n" }, { "answer_id": 33929, "author": "Peter Meyer", "author_id": 1875, "author_profile": "https://Stackoverflow.com/users/1875", "pm_score": 6, "selected": false, "text": "<p>Tail recursion refers to the recursive call being last in the last logic instruction in the recursive algorithm.</p>\n\n<p>Typically in recursion, you have a <em>base-case</em> which is what stops the recursive calls and begins popping the call stack. To use a classic example, though more C-ish than Lisp, the factorial function illustrates tail recursion. The recursive call occurs <em>after</em> checking the base-case condition.</p>\n\n<pre class=\"lang-c++ prettyprint-override\"><code>factorial(x, fac=1) {\n if (x == 1)\n return fac;\n else\n return factorial(x-1, x*fac);\n}\n</code></pre>\n\n<p>The initial call to factorial would be <code>factorial(n)</code> where <code>fac=1</code> (default value) and n is the number for which the factorial is to be calculated.</p>\n" }, { "answer_id": 33930, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 10, "selected": false, "text": "<p>In <strong>traditional recursion</strong>, the typical model is that you perform your recursive calls first, and then you take the return value of the recursive call and calculate the result. In this manner, you don't get the result of your calculation until you have returned from every recursive call.</p>\n\n<p>In <strong>tail recursion</strong>, you perform your calculations first, and then you execute the recursive call, passing the results of your current step to the next recursive step. This results in the last statement being in the form of <code>(return (recursive-function params))</code>. <strong>Basically, the return value of any given recursive step is the same as the return value of the next recursive call</strong>.</p>\n\n<p>The consequence of this is that once you are ready to perform your next recursive step, you don't need the current stack frame any more. This allows for some optimization. In fact, with an appropriately written compiler, you should never have a stack overflow <em>snicker</em> with a tail recursive call. Simply reuse the current stack frame for the next recursive step. I'm pretty sure Lisp does this.</p>\n" }, { "answer_id": 33931, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 6, "selected": false, "text": "<p>Instead of explaining it with words, here's an example. This is a Scheme version of the factorial function:\n</p>\n\n<pre class=\"lang-scm prettyprint-override\"><code>(define (factorial x)\n (if (= x 0) 1\n (* x (factorial (- x 1)))))\n</code></pre>\n\n<p>Here is a version of factorial that is tail-recursive:</p>\n\n<pre class=\"lang-scm prettyprint-override\"><code>(define factorial\n (letrec ((fact (lambda (x accum)\n (if (= x 0) accum\n (fact (- x 1) (* accum x))))))\n (lambda (x)\n (fact x 1))))\n</code></pre>\n\n<p>You will notice in the first version that the recursive call to fact is fed into the multiplication expression, and therefore the state has to be saved on the stack when making the recursive call. In the tail-recursive version there is no other S-expression waiting for the value of the recursive call, and since there is no further work to do, the state doesn't have to be saved on the stack. As a rule, Scheme tail-recursive functions use constant stack space.</p>\n" }, { "answer_id": 34105, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 6, "selected": false, "text": "<p>The jargon file has this to say about the definition of tail recursion:</p>\n\n<p><strong>tail recursion</strong> /n./</p>\n\n<p>If you aren't sick of it already, see tail recursion. </p>\n" }, { "answer_id": 34540, "author": "Hoffmann", "author_id": 3485, "author_profile": "https://Stackoverflow.com/users/3485", "pm_score": 7, "selected": false, "text": "<p>This excerpt from the book <em>Programming in Lua</em> shows <a href=\"http://www.lua.org/pil/6.3.html\" rel=\"noreferrer\">how to make a proper tail recursion</a> (in Lua, but should apply to Lisp too) and why it's better.</p>\n\n<blockquote>\n <p>A <em>tail call</em> [tail recursion] is a kind of goto dressed\n as a call. A tail call happens when a\n function calls another as its last\n action, so it has nothing else to do.\n For instance, in the following code,\n the call to <code>g</code> is a tail call:</p>\n \n <pre class=\"lang-lua prettyprint-override\"><code>function f (x)\n return g(x)\nend\n</code></pre>\n \n <p>After <code>f</code> calls <code>g</code>, it has nothing else\n to do. In such situations, the program\n does not need to return to the calling\n function when the called function\n ends. Therefore, after the tail call,\n the program does not need to keep any\n information about the calling function\n in the stack. ...</p>\n \n <p>Because a proper tail call uses no\n stack space, there is no limit on the\n number of \"nested\" tail calls that a\n program can make. For instance, we can\n call the following function with any\n number as argument; it will never\n overflow the stack:</p>\n \n <pre class=\"lang-lua prettyprint-override\"><code>function foo (n)\n if n &gt; 0 then return foo(n - 1) end\nend\n</code></pre>\n \n <p>... As I said earlier, a tail call is a\n kind of goto. As such, a quite useful\n application of proper tail calls in\n Lua is for programming state machines.\n Such applications can represent each\n state by a function; to change state\n is to go to (or to call) a specific\n function. As an example, let us\n consider a simple maze game. The maze\n has several rooms, each with up to\n four doors: north, south, east, and\n west. At each step, the user enters a\n movement direction. If there is a door\n in that direction, the user goes to\n the corresponding room; otherwise, the\n program prints a warning. The goal is\n to go from an initial room to a final\n room.</p>\n \n <p>This game is a typical state machine,\n where the current room is the state.\n We can implement such maze with one\n function for each room. We use tail\n calls to move from one room to\n another. A small maze with four rooms\n could look like this:</p>\n \n <pre class=\"lang-lua prettyprint-override\"><code>function room1 ()\n local move = io.read()\n if move == \"south\" then return room3()\n elseif move == \"east\" then return room2()\n else print(\"invalid move\")\n return room1() -- stay in the same room\n end\nend\n\nfunction room2 ()\n local move = io.read()\n if move == \"south\" then return room4()\n elseif move == \"west\" then return room1()\n else print(\"invalid move\")\n return room2()\n end\nend\n\nfunction room3 ()\n local move = io.read()\n if move == \"north\" then return room1()\n elseif move == \"east\" then return room4()\n else print(\"invalid move\")\n return room3()\n end\nend\n\nfunction room4 ()\n print(\"congratulations!\")\nend\n</code></pre>\n</blockquote>\n\n<p>So you see, when you make a recursive call like:</p>\n\n<pre class=\"lang-lua prettyprint-override\"><code>function x(n)\n if n==0 then return 0\n n= n-2\n return x(n) + 1\nend\n</code></pre>\n\n<p>This is not tail recursive because you still have things to do (add 1) in that function after the recursive call is made. If you input a very high number it will probably cause a stack overflow.</p>\n" }, { "answer_id": 36985, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 8, "selected": false, "text": "<p>An important point is that tail recursion is essentially equivalent to looping. It's not just a matter of compiler optimization, but a fundamental fact about expressiveness. This goes both ways: you can take any loop of the form</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>while(E) { S }; return Q\n</code></pre>\n\n<p>where <code>E</code> and <code>Q</code> are expressions and <code>S</code> is a sequence of statements, and turn it into a tail recursive function</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>f() = if E then { S; return f() } else { return Q }\n</code></pre>\n\n<p>Of course, <code>E</code>, <code>S</code>, and <code>Q</code> have to be defined to compute some interesting value over some variables. For example, the looping function</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>sum(n) {\n int i = 1, k = 0;\n while( i &lt;= n ) {\n k += i;\n ++i;\n }\n return k;\n}\n</code></pre>\n\n<p>is equivalent to the tail-recursive function(s)</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>sum_aux(n,i,k) {\n if( i &lt;= n ) {\n return sum_aux(n,i+1,k+i);\n } else {\n return k;\n }\n}\n\nsum(n) {\n return sum_aux(n,1,0);\n}\n</code></pre>\n\n<p>(This \"wrapping\" of the tail-recursive function with a function with fewer parameters is a common functional idiom.)</p>\n" }, { "answer_id": 37010, "author": "Lorin Hochstein", "author_id": 742, "author_profile": "https://Stackoverflow.com/users/742", "pm_score": 12, "selected": true, "text": "<p>Consider a simple function that adds the first N natural numbers. (e.g. <code>sum(5) = 0 + 1 + 2 + 3 + 4 + 5 = 15</code>).</p>\n<p>Here is a simple JavaScript implementation that uses recursion:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function recsum(x) {\n if (x === 0) {\n return 0;\n } else {\n return x + recsum(x - 1);\n }\n}\n</code></pre>\n<p>If you called <code>recsum(5)</code>, this is what the JavaScript interpreter would evaluate:</p>\n<pre class=\"lang-js prettyprint-override\"><code>recsum(5)\n5 + recsum(4)\n5 + (4 + recsum(3))\n5 + (4 + (3 + recsum(2)))\n5 + (4 + (3 + (2 + recsum(1))))\n5 + (4 + (3 + (2 + (1 + recsum(0)))))\n5 + (4 + (3 + (2 + (1 + 0))))\n5 + (4 + (3 + (2 + 1)))\n5 + (4 + (3 + 3))\n5 + (4 + 6)\n5 + 10\n15\n</code></pre>\n<p>Note how every recursive call has to complete before the JavaScript interpreter begins to actually do the work of calculating the sum.</p>\n<p>Here's a tail-recursive version of the same function:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function tailrecsum(x, running_total = 0) {\n if (x === 0) {\n return running_total;\n } else {\n return tailrecsum(x - 1, running_total + x);\n }\n}\n</code></pre>\n<p>Here's the sequence of events that would occur if you called <code>tailrecsum(5)</code>, (which would effectively be <code>tailrecsum(5, 0)</code>, because of the default second argument).</p>\n<pre class=\"lang-js prettyprint-override\"><code>tailrecsum(5, 0)\ntailrecsum(4, 5)\ntailrecsum(3, 9)\ntailrecsum(2, 12)\ntailrecsum(1, 14)\ntailrecsum(0, 15)\n15\n</code></pre>\n<p>In the tail-recursive case, with each evaluation of the recursive call, the <code>running_total</code> is updated.</p>\n<p><em>Note: The original answer used examples from Python. These have been changed to JavaScript, since Python interpreters don't support <a href=\"https://stackoverflow.com/questions/310974/what-is-tail-call-optimization\">tail call optimization</a>. However, while tail call optimization is <a href=\"https://www.ecma-international.org/ecma-262/6.0/#sec-tail-position-calls\" rel=\"noreferrer\">part of the ECMAScript 2015 spec</a>, most JavaScript interpreters <a href=\"https://kangax.github.io/compat-table/es6/#test-proper_tail_calls_(tail_call_optimisation)\" rel=\"noreferrer\">don't support it</a>.</em></p>\n" }, { "answer_id": 37273, "author": "Chris Smith", "author_id": 322, "author_profile": "https://Stackoverflow.com/users/322", "pm_score": 5, "selected": false, "text": "<p>It means that rather than needing to push the instruction pointer on the stack, you can simply jump to the top of a recursive function and continue execution. This allows for functions to recurse indefinitely without overflowing the stack. </p>\n\n<p>I wrote a <a href=\"http://blogs.msdn.com/chrsmith/archive/2008/08/07/understanding-tail-recursion.aspx\" rel=\"noreferrer\">blog</a> post on the subject, which has graphical examples of what the stack frames look like.</p>\n" }, { "answer_id": 39604, "author": "magice", "author_id": 227049, "author_profile": "https://Stackoverflow.com/users/227049", "pm_score": 3, "selected": false, "text": "<p>Recursion means a function calling itself. For example:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(define (un-ended name)\n (un-ended 'me)\n (print \"How can I get here?\"))\n</code></pre>\n\n<p>Tail-Recursion means the recursion that conclude the function:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(define (un-ended name)\n (print \"hello\")\n (un-ended 'me))\n</code></pre>\n\n<p>See, the last thing un-ended function (procedure, in Scheme jargon) does is to call itself. Another (more useful) example is:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(define (map lst op)\n (define (helper done left)\n (if (nil? left)\n done\n (helper (cons (op (car left))\n done)\n (cdr left))))\n (reverse (helper '() lst)))\n</code></pre>\n\n<p>In the helper procedure, the LAST thing it does if the left is not nil is to call itself (AFTER cons something and cdr something). This is basically how you map a list.</p>\n\n<p>The tail-recursion has a great advantage that the interpreter (or compiler, dependent on the language and vendor) can optimize it, and transform it into something equivalent to a while loop. As matter of fact, in Scheme tradition, most \"for\" and \"while\" loop is done in a tail-recursion manner (there is no for and while, as far as I know).</p>\n" }, { "answer_id": 159975, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 3, "selected": false, "text": "<p>here is a Perl 5 version of the <code>tailrecsum</code> function mentioned earlier.</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>sub tail_rec_sum($;$){\n my( $x,$running_total ) = (@_,0);\n\n return $running_total unless $x;\n\n @_ = ($x-1,$running_total+$x);\n goto &amp;tail_rec_sum; # throw away current stack frame\n}\n</code></pre>\n" }, { "answer_id": 202904, "author": "jorgetown", "author_id": 7465, "author_profile": "https://Stackoverflow.com/users/7465", "pm_score": 4, "selected": false, "text": "<p>In Java, here's a possible tail recursive implementation of the Fibonacci function:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public int tailRecursive(final int n) {\n if (n &lt;= 2)\n return 1;\n return tailRecursiveAux(n, 1, 1);\n}\n\nprivate int tailRecursiveAux(int n, int iter, int acc) {\n if (iter == n)\n return acc;\n return tailRecursiveAux(n, ++iter, acc + iter);\n}\n</code></pre>\n\n<p>Contrast this with the standard recursive implementation:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public int recursive(final int n) {\n if (n &lt;= 2)\n return 1;\n return recursive(n - 1) + recursive(n - 2);\n}\n</code></pre>\n" }, { "answer_id": 4483714, "author": "AbuZubair", "author_id": 547780, "author_profile": "https://Stackoverflow.com/users/547780", "pm_score": 5, "selected": false, "text": "<p>Here is a quick code snippet comparing two functions. The first is traditional recursion for finding the factorial of a given number. The second uses tail recursion. </p>\n\n<p>Very simple and intuitive to understand.</p>\n\n<p>An easy way to tell if a recursive function is a tail recursive is if it returns a concrete value in the base case. Meaning that it doesn't return 1 or true or anything like that. It will more than likely return some variant of one of the method parameters.</p>\n\n<p>Another way is to tell is if the recursive call is free of any addition, arithmetic, modification, etc... Meaning its nothing but a pure recursive call. </p>\n\n<pre class=\"lang-c prettyprint-override\"><code>public static int factorial(int mynumber) {\n if (mynumber == 1) {\n return 1;\n } else { \n return mynumber * factorial(--mynumber);\n }\n}\n\npublic static int tail_factorial(int mynumber, int sofar) {\n if (mynumber == 1) {\n return sofar;\n } else {\n return tail_factorial(--mynumber, sofar * mynumber);\n }\n}\n</code></pre>\n" }, { "answer_id": 9652860, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Here is a Common Lisp example that does factorials using tail-recursion. Due to the stack-less nature, one could perform insanely large factorial computations ... </p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(defun ! (n &amp;optional (product 1))\n (if (zerop n) product\n (! (1- n) (* product n))))\n</code></pre>\n\n<p>And then for fun you could try <code>(format nil \"~R\" (! 25))</code></p>\n" }, { "answer_id": 23349362, "author": "devinbost", "author_id": 1887281, "author_profile": "https://Stackoverflow.com/users/1887281", "pm_score": 3, "selected": false, "text": "<p>To understand some of the core differences between tail-call recursion and non-tail-call recursion we can explore the .NET implementations of these techniques. </p>\n\n<p>Here is an article with some examples in C#, F#, and C++\\CLI: <a href=\"http://blogs.msdn.com/b/jomo_fisher/archive/2007/09/19/adventures-in-f-tail-recursion-in-three-languages.aspx\" rel=\"nofollow noreferrer\">Adventures in Tail Recursion in C#, F#, and C++\\CLI</a>.</p>\n\n<p>C# does not optimize for tail-call recursion whereas F# does.</p>\n\n<p>The differences of principle involve loops vs. Lambda calculus. C# is designed with loops in mind whereas F# is built from the principles of Lambda calculus. For a very good (and free) book on the principles of Lambda calculus, see <a href=\"http://mitpress.mit.edu/sicp/\" rel=\"nofollow noreferrer\">Structure and Interpretation of Computer Programs, by Abelson, Sussman, and Sussman</a>. </p>\n\n<p>Regarding tail calls in F#, for a very good introductory article, see <a href=\"http://blogs.msdn.com/b/fsharpteam/archive/2011/07/08/tail-calls-in-fsharp.aspx\" rel=\"nofollow noreferrer\">Detailed Introduction to Tail Calls in F#</a>. Finally, here is an article that covers the difference between non-tail recursion and tail-call recursion (in F#): <a href=\"https://stackoverflow.com/questions/3248091/f-tail-recursive-function-example\">Tail-recursion vs. non-tail recursion in F sharp</a>.</p>\n\n<p>If you want to read about some of the design differences of tail-call recursion between C# and F#, see <a href=\"https://stackoverflow.com/questions/15864670/generate-tail-call-opcode\">Generating Tail-Call Opcode in C# and F#</a>.</p>\n\n<p>If you care enough to want to know what conditions prevent the C# compiler from performing tail-call optimizations, see this article: <a href=\"http://blogs.msdn.com/b/davbr/archive/2007/06/20/tail-call-jit-conditions.aspx\" rel=\"nofollow noreferrer\">JIT CLR tail-call conditions</a>.</p>\n" }, { "answer_id": 34394967, "author": "Abhiroop Sarkar", "author_id": 1942289, "author_profile": "https://Stackoverflow.com/users/1942289", "pm_score": 5, "selected": false, "text": "<p>The best way for me to understand <code>tail call recursion</code> is a special case of recursion where the <strong>last call</strong>(or the tail call) is the function itself.</p>\n\n<p>Comparing the examples provided in Python:</p>\n\n<pre><code>def recsum(x):\n if x == 1:\n return x\n else:\n return x + recsum(x - 1)\n</code></pre>\n\n<p>^RECURSION</p>\n\n<pre><code>def tailrecsum(x, running_total=0):\n if x == 0:\n return running_total\n else:\n return tailrecsum(x - 1, running_total + x)\n</code></pre>\n\n<p>^TAIL RECURSION</p>\n\n<p>As you can see in the general recursive version, the final call in the code block is <code>x + recsum(x - 1)</code>. So after calling the <code>recsum</code> method, there is another operation which is <code>x + ..</code>.</p>\n\n<p>However, in the tail recursive version, the final call(or the tail call) in the code block is <code>tailrecsum(x - 1, running_total + x)</code> which means the last call is made to the method itself and no operation after that.</p>\n\n<p>This point is important because tail recursion as seen here is not making the memory grow because when the underlying VM sees a function calling itself in a tail position (the last expression to be evaluated in a function), it eliminates the current stack frame, which is known as Tail Call Optimization(TCO).</p>\n\n<h2>EDIT</h2>\n\n<p><em>NB. Do bear in mind that the example above is written in Python whose runtime does not support TCO. This is just an example to explain the point. TCO is supported in languages like Scheme, Haskell etc</em></p>\n" }, { "answer_id": 38050598, "author": "ayushgp", "author_id": 3719089, "author_profile": "https://Stackoverflow.com/users/3719089", "pm_score": 3, "selected": false, "text": "<p>This is an excerpt from <a href=\"https://xuanji.appspot.com/isicp/1-2-procedures.html\" rel=\"noreferrer\">Structure and Interpretation of Computer Programs</a> about tail recursion.</p>\n\n<blockquote>\n <p>In contrasting iteration and recursion, we must be careful not to\n confuse the notion of a recursive process with the notion of a\n recursive procedure. When we describe a procedure as recursive, we are\n referring to the syntactic fact that the procedure definition refers\n (either directly or indirectly) to the procedure itself. But when we\n describe a process as following a pattern that is, say, linearly\n recursive, we are speaking about how the process evolves, not about\n the syntax of how a procedure is written. It may seem disturbing that\n we refer to a recursive procedure such as fact-iter as generating an\n iterative process. However, the process really is iterative: Its state\n is captured completely by its three state variables, and an\n interpreter need keep track of only three variables in order to\n execute the process.</p>\n \n <p>One reason that the distinction between process and procedure may be\n confusing is that most implementations of common languages (including Ada, Pascal, and\n C) are designed in such a way that the interpretation of any recursive\n procedure consumes an amount of memory that grows with the number of\n procedure calls, even when the process described is, in principle,\n iterative. As a consequence, these languages can describe iterative\n processes only by resorting to special-purpose “looping constructs”\n such as do, repeat, until, for, and while. <strong>The implementation of\n Scheme does not share this defect. It\n will execute an iterative process in constant space, even if the\n iterative process is described by a recursive procedure. An\n implementation with this property is called tail-recursive.</strong> With a\n tail-recursive implementation, iteration can be expressed using the\n ordinary procedure call mechanism, so that special iteration\n constructs are useful only as syntactic sugar.</p>\n</blockquote>\n" }, { "answer_id": 40498100, "author": "justyy", "author_id": 1479619, "author_profile": "https://Stackoverflow.com/users/1479619", "pm_score": 3, "selected": false, "text": "<p>In short, a tail recursion has the recursive call as the <strong>last</strong> statement in the function so that it doesn't have to wait for the recursive call.</p>\n\n<p>So this is a tail recursion i.e. N(x - 1, p * x) is the last statement in the function where the compiler is clever to figure out that it can be optimised to a for-loop (factorial). The second parameter p carries the intermediate product value. </p>\n\n<pre><code>function N(x, p) {\n return x == 1 ? p : N(x - 1, p * x);\n}\n</code></pre>\n\n<p>This is the non-tail-recursive way of writing the above factorial function (although some C++ compilers may be able to optimise it anyway).</p>\n\n<pre><code>function N(x) {\n return x == 1 ? 1 : x * N(x - 1);\n}\n</code></pre>\n\n<p>but this is not:</p>\n\n<pre><code>function F(x) {\n if (x == 1) return 0;\n if (x == 2) return 1;\n return F(x - 1) + F(x - 2);\n}\n</code></pre>\n\n<p>I did write a long post titled \"<a href=\"https://helloacm.com/understanding-tail-recursion-visual-studio-c-assembly-view/\" rel=\"noreferrer\">Understanding Tail Recursion – Visual Studio C++ – Assembly View</a>\"</p>\n\n<p><a href=\"https://i.stack.imgur.com/52QrO.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/52QrO.jpg\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 41305954, "author": "Mulan", "author_id": 633183, "author_profile": "https://Stackoverflow.com/users/633183", "pm_score": 3, "selected": false, "text": "<p>Tail recursion is the life you are living right now. You constantly recycle the same stack frame, over and over, because there's no reason or means to return to a \"previous\" frame. The past is over and done with so it can be discarded. You get one frame, forever moving into the future, until your process inevitably dies.</p>\n\n<p><sub>The analogy breaks down when you consider some processes might utilize additional frames but are still considered tail-recursive if the stack does not grow infinitely.</sub></p>\n" }, { "answer_id": 44924202, "author": "pnkfelix", "author_id": 36585, "author_profile": "https://Stackoverflow.com/users/36585", "pm_score": 2, "selected": false, "text": "<p>This question has a lot of great answers... but I cannot help but chime in with an alternative take on how to define \"tail recursion\", or at least \"proper tail recursion.\" Namely: should one look at it as a property of a particular expression in a program? Or should one look at it as a property of an <em>implementation of a programming language</em>?</p>\n\n<p>For more on the latter view, there is a classic <a href=\"http://www.cesura17.net/~will/professional/research/papers/tail.pdf\" rel=\"nofollow noreferrer\" title=\"Proper Tail Recursion and Space Efficiency (PLDI 1998)\">paper</a> by Will Clinger, \"Proper Tail Recursion and Space Efficiency\" (PLDI 1998), that defined \"proper tail recursion\" as a property of a programming language implementation. The definition is constructed to allow one to ignore implementation details (such as whether the call stack is actually represented via the runtime stack or via a heap-allocated linked list of frames).</p>\n\n<p>To accomplish this, it uses asymptotic analysis: not of program execution time as one usually sees, but rather of program <em>space usage</em>. This way, the space usage of a heap-allocated linked list vs a runtime call stack ends up being asymptotically equivalent; so one gets to ignore that programming language implementation detail (a detail which certainly matters quite a bit in practice, but can muddy the waters quite a bit when one attempts to determine whether a given implementation is satisfying the requirement to be \"property tail recursive\")</p>\n\n<p>The paper is worth careful study for a number of reasons:</p>\n\n<ul>\n<li><p>It gives an inductive definition of the <em>tail expressions</em> and <em>tail calls</em> of a program. (Such a definition, and why such calls are important, seems to be the subject of most of the other answers given here.)</p>\n\n<p>Here are those definitions, just to provide a flavor of the text:</p>\n\n<blockquote>\n <p><strong>Definition 1</strong> The <em>tail expressions</em> of a program written in Core Scheme are defined inductively as follows.</p>\n \n <ol>\n <li>The body of a lambda expression is a tail expression</li>\n <li>If <code>(if E0 E1 E2)</code> is a tail expression, then both <code>E1</code> and <code>E2</code> are tail expressions.</li>\n <li>Nothing else is a tail expression.</li>\n </ol>\n \n <p><strong>Definition 2</strong> A <em>tail call</em> is a tail expression that is a procedure call.</p>\n</blockquote></li>\n</ul>\n\n<p>(a tail recursive call, or as the paper says, \"self-tail call\" is a special case of a tail call where the procedure is invoked itself.)</p>\n\n<ul>\n<li><p>It provides formal definitions for six different \"machines\" for evaluating Core Scheme, where each machine has the same observable behavior <em>except</em> for the <em>asymptotic</em> space complexity class that each is in.</p>\n\n<p>For example, after giving definitions for machines with respectively, 1. stack-based memory management, 2. garbage collection but no tail calls, 3. garbage collection and tail calls, the paper continues onward with even more advanced storage management strategies, such as 4. \"evlis tail recursion\", where the environment does not need to be preserved across the evaluation of the last sub-expression argument in a tail call, 5. reducing the environment of a closure to <em>just</em> the free variables of that closure, and 6. so-called \"safe-for-space\" semantics as defined by <a href=\"http://www.cs.princeton.edu/~appel/papers/stack2.pdf\" rel=\"nofollow noreferrer\" title=\"Empirical and Analytic Study of Stack versus Heap Cost for Languages with Closures. (JFP 1996)\">Appel and Shao</a>.</p></li>\n<li><p>In order to prove that the machines actually belong to six distinct space complexity classes, the paper, for each pair of machines under comparison, provides concrete examples of programs that will expose asymptotic space blowup on one machine but not the other.</p></li>\n</ul>\n\n<hr>\n\n<p>(Reading over my answer now, I'm not sure if I'm managed to actually capture the crucial points of the <a href=\"http://www.cesura17.net/~will/professional/research/papers/tail.pdf\" rel=\"nofollow noreferrer\" title=\"Proper Tail Recursion and Space Efficiency (PLDI 1998)\">Clinger paper</a>. But, alas, I cannot devote more time to developing this answer right now.)</p>\n" }, { "answer_id": 47952480, "author": "coding_ninza", "author_id": 8295641, "author_profile": "https://Stackoverflow.com/users/8295641", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>A tail recursion is a recursive function where the function calls\n itself at the end (\"tail\") of the function in which no computation is\n done after the return of recursive call. Many compilers optimize to\n change a recursive call to a tail recursive or an iterative call.</p>\n</blockquote>\n\n<p>Consider the problem of computing factorial of a number.</p>\n\n<p>A straightforward approach would be:</p>\n\n<pre><code> factorial(n):\n\n if n==0 then 1\n\n else n*factorial(n-1)\n</code></pre>\n\n<p>Suppose you call factorial(4). The recursion tree would be:</p>\n\n<pre><code> factorial(4)\n / \\\n 4 factorial(3)\n / \\\n 3 factorial(2)\n / \\\n 2 factorial(1)\n / \\\n1 factorial(0)\n \\\n 1 \n</code></pre>\n\n<p>The maximum recursion depth in the above case is O(n).</p>\n\n<p>However, consider the following example:</p>\n\n<pre><code>factAux(m,n):\nif n==0 then m;\nelse factAux(m*n,n-1);\n\nfactTail(n):\n return factAux(1,n);\n</code></pre>\n\n<p>Recursion tree for factTail(4) would be:</p>\n\n<pre><code>factTail(4)\n |\nfactAux(1,4)\n |\nfactAux(4,3)\n |\nfactAux(12,2)\n |\nfactAux(24,1)\n |\nfactAux(24,0)\n |\n 24\n</code></pre>\n\n<p>Here also, maximum recursion depth is O(n) but none of the calls adds any extra variable to the stack. Hence the compiler can do away with a stack.</p>\n" }, { "answer_id": 50231106, "author": "Abdullah Khan", "author_id": 3094731, "author_profile": "https://Stackoverflow.com/users/3094731", "pm_score": 2, "selected": false, "text": "<p>There are two basic kinds of recursions: <strong>head recursion</strong> and <strong>tail recursion.</strong> </p>\n\n<blockquote>\n <p>In <strong>head recursion</strong>, a function makes its recursive call and then\n performs some more calculations, maybe using the result of the\n recursive call, for example.</p>\n \n <p>In a <strong>tail recursive</strong> function, all calculations happen first and\n the recursive call is the last thing that happens.</p>\n</blockquote>\n\n<p>Taken from <a href=\"https://oldfashionedsoftware.com/2008/09/27/tail-recursion-basics-in-scala/\" rel=\"nofollow noreferrer\">this</a> super awesome post. \nPlease consider reading it.</p>\n" }, { "answer_id": 54036034, "author": "V. S.", "author_id": 10014202, "author_profile": "https://Stackoverflow.com/users/10014202", "pm_score": 2, "selected": false, "text": "<p>Many people have already explained recursion here. I would like to cite a couple of thoughts about some advantages that recursion gives from the book “Concurrency in .NET, Modern patterns of concurrent and parallel programming” by Riccardo Terrell: </p>\n\n<blockquote>\n <p>“Functional recursion is the natural way to iterate in FP because it\n avoids mutation of state. During each iteration, a new value is passed\n into the loop constructor instead to be updated (mutated). In\n addition, a recursive function can be composed, making your program\n more modular, as well as introducing opportunities to exploit\n parallelization.\"</p>\n</blockquote>\n\n<p>Here also are some interesting notes from the same book about tail recursion:</p>\n\n<blockquote>\n <p>Tail-call recursion is a technique that converts a regular recursive\n function into an optimized version that can handle large inputs\n without any risks and side effects. </p>\n \n <p>NOTE The primary reason for a tail call as an optimization is to\n improve data locality, memory usage, and cache usage. By doing a tail\n call, the callee uses the same stack space as the caller. This reduces\n memory pressure. It marginally improves the cache because the same\n memory is reused for subsequent callers and can stay in the cache,\n rather than evicting an older cache line to make room for a new cache\n line.</p>\n</blockquote>\n" }, { "answer_id": 54573509, "author": "Nursnaaz", "author_id": 6949469, "author_profile": "https://Stackoverflow.com/users/6949469", "pm_score": 4, "selected": false, "text": "<p>The recursive function is a function which <strong>calls by itself</strong></p>\n\n<p>It allows programmers to write efficient programs using a <strong>minimal amount of code</strong>.</p>\n\n<p>The downside is that they can <strong>cause infinite loops</strong> and other unexpected results if <strong>not written properly</strong>.</p>\n\n<p>I will explain both <strong>Simple Recursive function and Tail Recursive function</strong></p>\n\n<p>In order to write a <strong>Simple recursive function</strong> </p>\n\n<ol>\n<li><strong>The first point to consider is when should you decide on coming out \nof the loop which is the if loop</strong></li>\n<li><strong>The second is what process to do if we are our own function</strong></li>\n</ol>\n\n<p>From the given example:</p>\n\n<pre><code>public static int fact(int n){\n if(n &lt;=1)\n return 1;\n else \n return n * fact(n-1);\n}\n</code></pre>\n\n<p>From the above example</p>\n\n<pre><code>if(n &lt;=1)\n return 1;\n</code></pre>\n\n<p>Is the deciding factor when to exit the loop</p>\n\n<pre><code>else \n return n * fact(n-1);\n</code></pre>\n\n<p>Is the actual processing to be done </p>\n\n<p>Let me the break the task one by one for easy understanding.</p>\n\n<p>Let us see what happens internally if I run <code>fact(4)</code></p>\n\n<ol>\n<li><strong>Substituting n=4</strong></li>\n</ol>\n\n<pre><code>public static int fact(4){\n if(4 &lt;=1)\n return 1;\n else \n return 4 * fact(4-1);\n}\n</code></pre>\n\n<p><code>If</code> loop fails so it goes to <code>else</code> loop\nso it returns <code>4 * fact(3)</code></p>\n\n<ol start=\"2\">\n<li><p>In stack memory, we have <code>4 * fact(3)</code></p>\n\n<p><strong>Substituting n=3</strong></p></li>\n</ol>\n\n<pre><code>public static int fact(3){\n if(3 &lt;=1)\n return 1;\n else \n return 3 * fact(3-1);\n}\n</code></pre>\n\n<p><code>If</code> loop fails so it goes to <code>else</code> loop</p>\n\n<p>so it returns <code>3 * fact(2)</code></p>\n\n<p>Remember we called ```4 * fact(3)``</p>\n\n<p>The output for <code>fact(3) = 3 * fact(2)</code></p>\n\n<p>So far the stack has <code>4 * fact(3) = 4 * 3 * fact(2)</code></p>\n\n<ol start=\"3\">\n<li><p>In stack memory, we have <code>4 * 3 * fact(2)</code></p>\n\n<p><strong>Substituting n=2</strong></p></li>\n</ol>\n\n<pre><code>public static int fact(2){\n if(2 &lt;=1)\n return 1;\n else \n return 2 * fact(2-1);\n}\n</code></pre>\n\n<p><code>If</code> loop fails so it goes to <code>else</code> loop</p>\n\n<p>so it returns <code>2 * fact(1)</code></p>\n\n<p>Remember we called <code>4 * 3 * fact(2)</code></p>\n\n<p>The output for <code>fact(2) = 2 * fact(1)</code></p>\n\n<p>So far the stack has <code>4 * 3 * fact(2) = 4 * 3 * 2 * fact(1)</code></p>\n\n<ol start=\"3\">\n<li><p>In stack memory, we have <code>4 * 3 * 2 * fact(1)</code></p>\n\n<p><strong>Substituting n=1</strong></p></li>\n</ol>\n\n<pre><code>public static int fact(1){\n if(1 &lt;=1)\n return 1;\n else \n return 1 * fact(1-1);\n}\n</code></pre>\n\n<p><code>If</code> loop is true</p>\n\n<p>so it returns <code>1</code></p>\n\n<p>Remember we called <code>4 * 3 * 2 * fact(1)</code></p>\n\n<p>The output for <code>fact(1) = 1</code></p>\n\n<p>So far the stack has <code>4 * 3 * 2 * fact(1) = 4 * 3 * 2 * 1</code></p>\n\n<p>Finally, the result of <strong>fact(4) = 4 * 3 * 2 * 1 = 24</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/ELSwN.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ELSwN.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>The <strong>Tail Recursion</strong> would be</p>\n\n<pre><code>public static int fact(x, running_total=1) {\n if (x==1) {\n return running_total;\n } else {\n return fact(x-1, running_total*x);\n }\n}\n\n</code></pre>\n\n<ol>\n<li><strong>Substituting n=4</strong> </li>\n</ol>\n\n<pre><code>public static int fact(4, running_total=1) {\n if (x==1) {\n return running_total;\n } else {\n return fact(4-1, running_total*4);\n }\n}\n</code></pre>\n\n<p><code>If</code> loop fails so it goes to <code>else</code> loop\nso it returns <code>fact(3, 4)</code></p>\n\n<ol start=\"2\">\n<li><p>In stack memory, we have <code>fact(3, 4)</code></p>\n\n<p><strong>Substituting n=3</strong></p></li>\n</ol>\n\n<pre><code>public static int fact(3, running_total=4) {\n if (x==1) {\n return running_total;\n } else {\n return fact(3-1, 4*3);\n }\n}\n</code></pre>\n\n<p><code>If</code> loop fails so it goes to <code>else</code> loop</p>\n\n<p>so it returns <code>fact(2, 12)</code></p>\n\n<ol start=\"2\">\n<li><p>In stack memory, we have <code>fact(2, 12)</code></p>\n\n<p><strong>Substituting n=2</strong></p></li>\n</ol>\n\n<pre><code>public static int fact(2, running_total=12) {\n if (x==1) {\n return running_total;\n } else {\n return fact(2-1, 12*2);\n }\n}\n</code></pre>\n\n<p><code>If</code> loop fails so it goes to <code>else</code> loop</p>\n\n<p>so it returns <code>fact(1, 24)</code></p>\n\n<ol start=\"3\">\n<li><p>In stack memory, we have <code>fact(1, 24)</code></p>\n\n<p><strong>Substituting n=1</strong></p></li>\n</ol>\n\n<pre><code>public static int fact(1, running_total=24) {\n if (x==1) {\n return running_total;\n } else {\n return fact(1-1, 24*1);\n }\n}\n</code></pre>\n\n<p><code>If</code> loop is true</p>\n\n<p>so it returns <code>running_total</code></p>\n\n<p>The output for <code>running_total = 24</code></p>\n\n<p>Finally, the result of <strong>fact(4,1) = 24</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/FkcU1.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/FkcU1.jpg\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 54601924, "author": "Al Sweigart", "author_id": 1893164, "author_profile": "https://Stackoverflow.com/users/1893164", "pm_score": 3, "selected": false, "text": "<p>A <em>tail recursive</em> function is a recursive function where the last operation it does before returning is make the recursive function call. That is, the return value of the recursive function call is immediately returned. For example, your code would look like this:</p>\n\n<pre><code>def recursiveFunction(some_params):\n # some code here\n return recursiveFunction(some_args)\n # no code after the return statement\n</code></pre>\n\n<p>Compilers and interpreters that implement <em>tail call optimization</em> or <em>tail call elimination</em> can optimize recursive code to prevent stack overflows. If your compiler or interpreter doesn't implement tail call optimization (such as the CPython interpreter) there is no additional benefit to writing your code this way.</p>\n\n<p>For example, this is a standard recursive factorial function in Python:</p>\n\n<pre><code>def factorial(number):\n if number == 1:\n # BASE CASE\n return 1\n else:\n # RECURSIVE CASE\n # Note that `number *` happens *after* the recursive call.\n # This means that this is *not* tail call recursion.\n return number * factorial(number - 1)\n</code></pre>\n\n<p>And this is a tail call recursive version of the factorial function:</p>\n\n<pre><code>def factorial(number, accumulator=1):\n if number == 0:\n # BASE CASE\n return accumulator\n else:\n # RECURSIVE CASE\n # There's no code after the recursive call.\n # This is tail call recursion:\n return factorial(number - 1, number * accumulator)\nprint(factorial(5))\n</code></pre>\n\n<p>(Note that even though this is Python code, the CPython interpreter doesn't do tail call optimization, so arranging your code like this confers no runtime benefit.)</p>\n\n<p>You may have to make your code a bit more unreadable to make use of tail call optimization, as shown in the factorial example. (For example, the base case is now a bit unintuitive, and the <code>accumulator</code> parameter is effectively used as a sort of global variable.)</p>\n\n<p>But the benefit of tail call optimization is that it prevents stack overflow errors. (I'll note that you can get this same benefit by using an iterative algorithm instead of a recursive one.)</p>\n\n<p>Stack overflows are caused when the call stack has had too many frame objects pushed onto. A frame object is pushed onto the call stack when a function is called, and popped off the call stack when the function returns. Frame objects contain info such as local variables and what line of code to return to when the function returns.</p>\n\n<p>If your recursive function makes too many recursive calls without returning, the call stack can exceed its frame object limit. (The number varies by platform; in Python it is 1000 frame objects by default.) This causes a <em>stack overflow</em> error. (Hey, that's where the name of this website comes from!)</p>\n\n<p>However, if the last thing your recursive function does is make the recursive call and return its return value, then there's no reason it needs to keep the current frame object needs to stay on the call stack. After all, if there's no code after the recursive function call, there's no reason to hang on to the current frame object's local variables. So we can get rid of the current frame object immediately rather than keep it on the call stack. The end result of this is that your call stack doesn't grow in size, and thus cannot stack overflow.</p>\n\n<p>A compiler or interpreter must have tail call optimization as a feature for it to be able to recognize when tail call optimization can be applied. Even then, you may have rearrange the code in your recursive function to make use of tail call optimization, and it's up to you if this potential decrease in readability is worth the optimization.</p>\n" }, { "answer_id": 56460840, "author": "Rohit Garg", "author_id": 6234459, "author_profile": "https://Stackoverflow.com/users/6234459", "pm_score": 3, "selected": false, "text": "<p>Tail Recursion is pretty fast as compared to normal recursion.\nIt is fast because the output of the ancestors call will not be written in stack to keep the track.\nBut in normal recursion all the ancestor calls output written in stack to keep the track.</p>\n" }, { "answer_id": 64956968, "author": "Hari", "author_id": 216562, "author_profile": "https://Stackoverflow.com/users/216562", "pm_score": 2, "selected": false, "text": "<p>A function is tail recursive if each recursive case consists <em>only</em> of a call to the function itself, possibly with different arguments. Or, tail recursion is <em>recursion with no pending work</em>. Note that this is a programming-language independent concept.</p>\n<p>Consider the function defined as:</p>\n<pre><code>g(a, b, n) = a * b^n\n</code></pre>\n<p>A possible tail-recursive formulation is:</p>\n<pre><code>g(a, b, n) | n is zero = a\n | n is odd = g(a*b, b, n-1)\n | otherwise = g(a, b*b, n/2)\n</code></pre>\n<p>If you examine each RHS of <code>g(...)</code> that involves a recursive case, you'll find that the whole body of the RHS is a call to <code>g(...)</code>, and <em>only</em> that. This definition is <em>tail recursive</em>.</p>\n<p>For comparison, a non-tail-recursive formulation might be:</p>\n<pre><code>g'(a, b, n) = a * f(b, n)\nf(b, n) | n is zero = 1\n | n is odd = f(b, n-1) * b\n | otherwise = f(b, n/2) ^ 2\n</code></pre>\n<p>Each recursive case in <code>f(...)</code> has some <em>pending work</em> that needs to happen after the recursive call.</p>\n<p>Note that when we went from <code>g'</code> to <code>g</code>, we made essential use of associativity\n(and commutativity) of multiplication. This is not an accident, and most cases where you will need to transform recursion to tail-recursion will make use of such properties: if we want to eagerly do some work rather than leave it pending, we have to use something like associativity to prove that the answer will be the same.</p>\n<p>Tail recursive calls can be implemented with a backwards jump, as opposed to using a stack for normal recursive calls. Note that detecting a tail call, or emitting a backwards jump is usually straightforward. However, it is often hard to rearrange the arguments such that the backwards jump is possible. Since this optimization is not free, language implementations can choose not to implement this optimization, or require opt-in by marking recursive calls with a 'tailcall' instruction and/or choosing a higher optimization setting.</p>\n<p>Some languages (e.g. Scheme) do, however, require <em>all</em> implementations to optimize tail-recursive functions, maybe even all calls in tail position.</p>\n<p>Backwards jumps are usually abstracted as a (while) loop in most imperative languages, and tail-recursion, when optimized to a backwards jump, is isomorphic to looping.</p>\n" }, { "answer_id": 71566598, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 3, "selected": false, "text": "<ul>\n<li>Tail Recursive Function is a recursive function in which recursive call is the last executed thing in the function.</li>\n</ul>\n<p>Regular recursive function, we have stack and everytime we invoke a recursive function within that recursive function, adds another layer to our call stack. In normal recursion\nspace: <code>O(n)</code> tail recursion makes space complexity from</p>\n<pre><code>O(N)=&gt;O(1)\n</code></pre>\n<ul>\n<li><p>Tail call optimization means that it is possible to call a function from another function without growing the call stack.</p>\n</li>\n<li><p>We should write tail recursion in recursive solutions. but certain languages do not actually support the tail recursion in their engine that compiles the language down. since ecma6, there has been tail recursion that was in the specification. BUt none of the engines that compile js have implemented tail recursion into it. you wont achieve O(1) in js, because the compiler itself does not know how to implement this tail recursion. As of January 1, 2020 Safari is the only browser that supports tail call optimization.</p>\n</li>\n<li><p>Haskell and Java have tail recursion optimization</p>\n</li>\n</ul>\n<h2>Regular Recursive Factorial</h2>\n<pre><code>function Factorial(x) {\n //Base case x&lt;=1\n if (x &lt;= 1) {\n return 1;\n } else {\n // x is waiting for the return value of Factorial(x-1)\n // the last thing we do is NOT applying the recursive call\n // after recursive call we still have to multiply.\n return x * Factorial(x - 1);\n }\n}\n</code></pre>\n<p>we have 4 calls in our call stack.</p>\n<pre><code>Factorial(4); // waiting in the memory for Factorial(3)\n4 * Factorial(3); // waiting in the memory for Factorial(2)\n4 * (3 * Factorial(2)); // waiting in the memory for Factorial(1)\n4 * (3 * (2 * Factorial(1)));\n4 * (3 * (2 * 1));\n</code></pre>\n<ul>\n<li>We are making 4 Factorial() calls, space is O(n)</li>\n<li>this mmight cause Stackoverflow</li>\n</ul>\n<h2>Tail Recursive Factorial</h2>\n<pre><code>function tailFactorial(x, totalSoFar = 1) {\n //Base Case: x===0. In recursion there must be base case. Otherwise they will never stop\n if (x === 0) {\n return totalSoFar;\n } else {\n // there is nothing waiting for tailFactorial to complete. we are returning another instance of tailFactorial()\n // we are not doing any additional computaion with what we get back from this recursive call\n return tailFactorial(x - 1, totalSoFar * x);\n }\n}\n</code></pre>\n<ul>\n<li>We dont need to remember anything after we make our recursive call</li>\n</ul>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045/" ]
Whilst starting to learn lisp, I've come across the term *tail-recursive*. What does it mean exactly?
Consider a simple function that adds the first N natural numbers. (e.g. `sum(5) = 0 + 1 + 2 + 3 + 4 + 5 = 15`). Here is a simple JavaScript implementation that uses recursion: ```js function recsum(x) { if (x === 0) { return 0; } else { return x + recsum(x - 1); } } ``` If you called `recsum(5)`, this is what the JavaScript interpreter would evaluate: ```js recsum(5) 5 + recsum(4) 5 + (4 + recsum(3)) 5 + (4 + (3 + recsum(2))) 5 + (4 + (3 + (2 + recsum(1)))) 5 + (4 + (3 + (2 + (1 + recsum(0))))) 5 + (4 + (3 + (2 + (1 + 0)))) 5 + (4 + (3 + (2 + 1))) 5 + (4 + (3 + 3)) 5 + (4 + 6) 5 + 10 15 ``` Note how every recursive call has to complete before the JavaScript interpreter begins to actually do the work of calculating the sum. Here's a tail-recursive version of the same function: ```js function tailrecsum(x, running_total = 0) { if (x === 0) { return running_total; } else { return tailrecsum(x - 1, running_total + x); } } ``` Here's the sequence of events that would occur if you called `tailrecsum(5)`, (which would effectively be `tailrecsum(5, 0)`, because of the default second argument). ```js tailrecsum(5, 0) tailrecsum(4, 5) tailrecsum(3, 9) tailrecsum(2, 12) tailrecsum(1, 14) tailrecsum(0, 15) 15 ``` In the tail-recursive case, with each evaluation of the recursive call, the `running_total` is updated. *Note: The original answer used examples from Python. These have been changed to JavaScript, since Python interpreters don't support [tail call optimization](https://stackoverflow.com/questions/310974/what-is-tail-call-optimization). However, while tail call optimization is [part of the ECMAScript 2015 spec](https://www.ecma-international.org/ecma-262/6.0/#sec-tail-position-calls), most JavaScript interpreters [don't support it](https://kangax.github.io/compat-table/es6/#test-proper_tail_calls_(tail_call_optimisation)).*
33,933
<p>I have the following <code>textarea</code> in a <code>table</code>:</p> <pre><code>&lt;table width="300"&gt;&lt;tr&gt;&lt;td&gt; &lt;textarea style="width:100%"&gt; longstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstring &lt;/textarea&gt; &lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; </code></pre> <p>With a long string in the textarea, the textarea stretches out to accommodate it in one line in IE7, but retains its 300px width in other browsers.</p> <p>Any ideas as to how to fix this in IE?</p>
[ { "answer_id": 33936, "author": "Jiaaro", "author_id": 2908, "author_profile": "https://Stackoverflow.com/users/2908", "pm_score": 0, "selected": false, "text": "<p>did you try...</p>\n\n<p><code>overflow: hidden;</code></p>\n\n<p>??</p>\n\n<p>I'm not sure if it should be in the table of the textarea... experiment a bit</p>\n" }, { "answer_id": 33938, "author": "Peter Meyer", "author_id": 1875, "author_profile": "https://Stackoverflow.com/users/1875", "pm_score": 0, "selected": false, "text": "<p>or, how about:</p>\n\n<pre><code>overflow: scroll;\n</code></pre>\n\n<p>Edit:</p>\n\n<p>I actually tested this. I think the behavior is such because the width is on the table, which I believe (I have nothing to back this up) I read long ago that the table width is a <em>suggested</em> width, but can be expanded to accommodate its content. Not sure. I know if you use a <code>&lt;DIV&gt;</code> rather than a table, it works. Additionally, if you apply the 300 pixel width to the containing <code>&lt;TD&gt;</code> element as opposed to the <code>&lt;TABLE&gt;</code> element, it works as well. Also, the <code>overflow: scroll</code> does nothing! :P</p>\n\n<p>Nice, funky IE behavior, for sure!</p>\n" }, { "answer_id": 33947, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 0, "selected": false, "text": "<p>IE also supports the <a href=\"http://msdn.microsoft.com/en-us/library/ms531184.aspx\" rel=\"nofollow noreferrer\"><code>word-break</code></a> CSS 3 property.</p>\n" }, { "answer_id": 33948, "author": "dansays", "author_id": 1923, "author_profile": "https://Stackoverflow.com/users/1923", "pm_score": 3, "selected": false, "text": "<p>Apply the width to the <code>td</code>, not the <code>table</code>.</p>\n\n<p>EDIT: @Emmett - the width could just as easily be applied via CSS.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>td {\n width: 300px;\n}\n</code></pre>\n\n<p>produces the desired result. Or, if you're using jQuery, you could add the width through script:</p>\n\n<pre><code>$('textarea[width=100%]').parent('td').css('width', '300px');\n</code></pre>\n\n<p>Point being, there's more than one way to apply a width to a table cell, if development constraints prevent you from applying it directly.</p>\n" }, { "answer_id": 33950, "author": "Emmett", "author_id": 2749, "author_profile": "https://Stackoverflow.com/users/2749", "pm_score": 2, "selected": false, "text": "<p>@<a href=\"https://stackoverflow.com/questions/33933/textarea-with-100-width-ignores-parent-elements-width-in-ie7#33938\">Peter Meyer</a>, <a href=\"https://stackoverflow.com/questions/33933/textarea-with-100-width-ignores-parent-elements-width-in-ie7#33936\">Jim Robert</a></p>\n\n<p>I tried different overflow values, to no avail.</p>\n\n<p>Experimenting with different values for the wrap attribute and the word-wrap style also wasn't fruitful.</p>\n\n<p>EDIT:</p>\n\n<p>@<a href=\"https://stackoverflow.com/questions/33933/textarea-with-100-width-ignores-parent-elements-width-in-ie7#33936\">dansays</a>, <a href=\"https://stackoverflow.com/questions/33933/textarea-with-100-width-ignores-parent-elements-width-in-ie7#33951\">seanb</a></p>\n\n<p>Due to some awkward application-specific constraints, the width can only be applied to the table.</p>\n\n<p>@<a href=\"https://stackoverflow.com/questions/33933/textarea-with-100-width-ignores-parent-elements-width-in-ie7#33947\">travis</a></p>\n\n<p>Setting style=\"word-break:break-all;\" sort of worked! It still wraps differently in IE7 and FF. I'll accept this answer if nothing better comes up.</p>\n" }, { "answer_id": 33951, "author": "seanb", "author_id": 3354, "author_profile": "https://Stackoverflow.com/users/3354", "pm_score": 0, "selected": false, "text": "<p>Best thing I could find to make it work, a little hacky:<br>\nwrap textarea with <code>&lt;div style=\"width:300px; overflow:auto;\"&gt;</code> \nmight want to play around with the overflow value </p>\n" }, { "answer_id": 34195, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 0, "selected": false, "text": "<p>The overflow property is the way to go. In particular, if you want the extra text to be ignored, you can use \"overflow:hidden\" as a css property on the text.</p>\n\n<p>In general, when a browser has an unbreakable object, such as a long string without spaces, it can have a conflict between various size constraints - those of the string (long) vs its container (short). If you see different behavior in different browsers, they are just resolving this conflict differently.</p>\n\n<p>By the way, there is a nice trick available for long strings - the &lt;wbr&gt; tag. If your browser sees longstringlongstring, then it will <em>try</em> to fit it in the container as a single, unbroken string -- but if it can't fit, it will break that string in half at the wbr. It's basically a break point with a implicit request to not break there, if possible (sort of like a hyphen in printed texts). By the way, it's a little buggy in some versions of Safari and Opera - check out <a href=\"http://www.quirksmode.org/oddsandends/wbr.html\" rel=\"nofollow noreferrer\">this quirksmode page</a> for more.</p>\n" }, { "answer_id": 35568, "author": "seanb", "author_id": 3354, "author_profile": "https://Stackoverflow.com/users/3354", "pm_score": 1, "selected": false, "text": "<p>Another very hacky option, if you are stuck with a lot of constraints, but know what the surrounding dom will look like: </p>\n\n<pre><code>style=\"width:100%;width:expression(this.parentNode.parentNode.parentNode.parentNode.width +'px')\" \n</code></pre>\n\n<p>not pretty, but does work in IE7.<br>\nUsing jquery or similar would be a much neater solution, but it depends on the other constraints you have.</p>\n" }, { "answer_id": 450690, "author": "John Dunagan", "author_id": 28939, "author_profile": "https://Stackoverflow.com/users/28939", "pm_score": 0, "selected": false, "text": "<p>I've run into this problem before. It's related to how HTML parses table and cell widths.</p>\n\n<p>You're fine setting 300 as a width as long as the contents of the element can never exceed that (setting a div with a definite width inside and an overflow rule is my favorite way). </p>\n\n<p>But absent a solution like the above, the minute ANY element pushes you past that width, all bets are off. The element becomes as wide as it has to to accommodate the contents.</p>\n\n<p>Additional tip - encase your width values in whatever set of quotes will nest the value properly (<code>&lt;table width='300'</code>). If someone comes along and changes it to a %, it will ignore the %, otherwise.</p>\n\n<p>Unfortunately, you're always going to have trouble breaking strings that do not have 'natural' breaks in IE, unless you can do something to break them up via code.</p>\n" }, { "answer_id": 594697, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Another hacky option, but the only option that works for me - none of the other suggestions on this page do - is to wrap the textarea in a single cell table with a fixed table layout.</p>\n\n<pre><code>&lt;table style=\"width:100%;table-layout:fixed\"&gt;&lt;tr&gt;&lt;td&gt;\n&lt;textarea style=\"width:100%\"&gt;longstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstring&lt;/textarea&gt;\n&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;\n</code></pre>\n" }, { "answer_id": 13009054, "author": "Saeed", "author_id": 1726377, "author_profile": "https://Stackoverflow.com/users/1726377", "pm_score": 0, "selected": false, "text": "<p>For solve this issue you use space in your text,and you too use this code</p>\n\n<pre><code>overflow:hidden\n</code></pre>\n" }, { "answer_id": 13603097, "author": "Mukesh", "author_id": 1616003, "author_profile": "https://Stackoverflow.com/users/1616003", "pm_score": 0, "selected": false, "text": "<p>Give the width in pixels.this should work properly</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2749/" ]
I have the following `textarea` in a `table`: ``` <table width="300"><tr><td> <textarea style="width:100%"> longstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstring </textarea> </td></tr></table> ``` With a long string in the textarea, the textarea stretches out to accommodate it in one line in IE7, but retains its 300px width in other browsers. Any ideas as to how to fix this in IE?
Apply the width to the `td`, not the `table`. EDIT: @Emmett - the width could just as easily be applied via CSS. ```css td { width: 300px; } ``` produces the desired result. Or, if you're using jQuery, you could add the width through script: ``` $('textarea[width=100%]').parent('td').css('width', '300px'); ``` Point being, there's more than one way to apply a width to a table cell, if development constraints prevent you from applying it directly.
33,956
<p>Assume that I have a field called <em>price</em> for the documents in Solr and I have that field faceted. I want to get the facets as ranges of values (eg: 0-100, 100-500, 500-1000, etc). How to do it?</p> <p>I can specify the ranges beforehand, but I also want to know whether it is possible to calculate the ranges (say for 5 values) automatically based on the values in the documents?</p>
[ { "answer_id": 34027, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 2, "selected": false, "text": "<p>There may well be a better Solr-specific answer, but I work with straight Lucene, and since you're not getting much traction I'll take a stab. There, I'd create a populate a <code>Filter</code> with a <code>FilteredQuery</code> wrapping the original <code>Query</code>. Then I'd get a <code>FieldCache</code> for the field of interest. Enumerate the hits in the filter's bitset, and for each hit, you get the value of the field from the field cache, and add it to a SortedSet. When you've got all of the hits, divide the size of the set into the number of ranges you want (five to seven is a good number according the user interface guys), and rather than a single-valued constraint, your facets will be a range query with the lower and upper bounds of each of those subsets.</p>\n\n<p>I'd recommend using some special-case logic for a small number of values; obviously, if you only have four distinct values, it doesn't make sense to try and make 5 range refinements out of them. Below a certain threshold (say 3*your ideal number of ranges), you just show the facets normally rather than ranges.</p>\n" }, { "answer_id": 170477, "author": "Mauricio Scheffer", "author_id": 21239, "author_profile": "https://Stackoverflow.com/users/21239", "pm_score": 4, "selected": false, "text": "<p>To answer your first question, you can get facet ranges by using the the generic facet query support. <a href=\"http://wiki.apache.org/solr/SimpleFacetParameters#head-1da3ab3995bc4abcdce8e0f04be7355ba19e9b2c\" rel=\"nofollow noreferrer\">Here</a>'s an example:</p>\n\n<pre><code>http://localhost:8983/solr/select?q=video&amp;rows=0&amp;facet=true&amp;facet.query=price:[*+TO+500]&amp;facet.query=price:[500+TO+*]\n</code></pre>\n\n<p>As for your second question (automatically suggesting facet ranges), that's not yet implemented. Some argue that this kind of querying would be best implemented on your application rather that letting Solr \"guess\" the best facet ranges.</p>\n\n<p>Here are some discussions on the topic:</p>\n\n<ul>\n<li>(Archived) <a href=\"https://web.archive.org/web/20100416235126/http://old.nabble.com/Re:-faceted-browsing-p3753053.html\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20100416235126/http://old.nabble.com/Re:-faceted-browsing-p3753053.html</a></li>\n<li>(Archived) <a href=\"https://web.archive.org/web/20090430160232/http://www.nabble.com/Re:-Sorting-p6803791.html\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20090430160232/http://www.nabble.com/Re:-Sorting-p6803791.html</a></li>\n<li>(Archived) <a href=\"https://web.archive.org/web/20090504020754/http://www.nabble.com/Dynamically-calculated-range-facet-td11314725.html\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20090504020754/http://www.nabble.com/Dynamically-calculated-range-facet-td11314725.html</a></li>\n</ul>\n" }, { "answer_id": 10599043, "author": "Garytxo", "author_id": 174816, "author_profile": "https://Stackoverflow.com/users/174816", "pm_score": 2, "selected": false, "text": "<p>You can use solr facet ranges</p>\n\n<p><a href=\"http://wiki.apache.org/solr/SimpleFacetParameters#Facet_by_Range\" rel=\"nofollow\">http://wiki.apache.org/solr/SimpleFacetParameters#Facet_by_Range</a></p>\n" }, { "answer_id": 11329853, "author": "Graham", "author_id": 130988, "author_profile": "https://Stackoverflow.com/users/130988", "pm_score": 3, "selected": false, "text": "<p>I have worked out how to calculate sensible dynamic facets for product price ranges. The solution involves some pre-processing of documents and some post-processing of the query results, but it requires only one query to Solr, and should even work on old version of Solr like 1.4.</p>\n\n<h1>Round up prices before submission</h1>\n\n<p>First, before submitting the document, <strong>round up</strong> the the price to the nearest \"nice round facet boundary\" and store it in a \"rounded_price\" field. Users like their facets to look like \"250-500\" not \"247-483\", and rounding also means you get back hundreds of price facets not millions of them. With some effort the following code can be generalised to round nicely at any price scale:</p>\n\n<pre><code> public static decimal RoundPrice(decimal price)\n {\n if (price &lt; 25)\n return Math.Ceiling(price);\n else if (price &lt; 100)\n return Math.Ceiling(price / 5) * 5;\n else if (price &lt; 250)\n return Math.Ceiling(price / 10) * 10;\n else if (price &lt; 1000)\n return Math.Ceiling(price / 25) * 25;\n else if (price &lt; 2500)\n return Math.Ceiling(price / 100) * 100;\n else if (price &lt; 10000)\n return Math.Ceiling(price / 250) * 250;\n else if (price &lt; 25000)\n return Math.Ceiling(price / 1000) * 1000;\n else if (price &lt; 100000)\n return Math.Ceiling(price / 2500) * 2500;\n else\n return Math.Ceiling(price / 5000) * 5000;\n }\n</code></pre>\n\n<p>Permissible prices go 1,2,3,...,24,25,30,35,...,95,100,110,...,240,250,275,300,325,...,975,1000 and so forth. </p>\n\n<h1>Get all facets on rounded prices</h1>\n\n<p>Second, when submitting the query, request all facets on rounded prices sorted by price: <code>facet.field=rounded_price</code>. Thanks to the rounding, you'll get at most a few hundred facets back.</p>\n\n<h1>Combine adjacent facets into larger facets</h1>\n\n<p>Third, after you have the results, the user wants see only 3 to 7 facets, not hundreds of facets. So, combine adjacent facets into a few large facets (called \"segments\") trying to get a roughly equal number of documents in each segment. The following rather more complicated code does this, returning tuples of (start, end, count) suitable for performing range queries. The counts returned will be correct provided prices were been rounded <em>up</em> to the nearest boundary:</p>\n\n<pre><code> public static List&lt;Tuple&lt;string, string, int&gt;&gt; CombinePriceFacets(int nSegments, ICollection&lt;KeyValuePair&lt;string, int&gt;&gt; prices)\n {\n var ranges = new List&lt;Tuple&lt;string, string, int&gt;&gt;();\n int productCount = prices.Sum(p =&gt; p.Value);\n int productsRemaining = productCount;\n if (nSegments &lt; 2)\n return ranges;\n int segmentSize = productCount / nSegments;\n string start = \"*\";\n string end = \"0\";\n int count = 0;\n int totalCount = 0;\n int segmentIdx = 1;\n foreach (KeyValuePair&lt;string, int&gt; price in prices)\n {\n end = price.Key;\n count += price.Value;\n totalCount += price.Value;\n productsRemaining -= price.Value;\n if (totalCount &gt;= segmentSize * segmentIdx)\n {\n ranges.Add(new Tuple&lt;string, string, int&gt;(start, end, count));\n start = end;\n count = 0;\n segmentIdx += 1;\n }\n if (segmentIdx == nSegments)\n {\n ranges.Add(new Tuple&lt;string, string, int&gt;(start, \"*\", count + productsRemaining));\n break;\n }\n }\n return ranges;\n }\n</code></pre>\n\n<h1>Filter results by selected facet</h1> \n\n<p>Fourth, suppose (\"250\",\"500\",38) was one of the resulting segments. If the user selects \"$250 to $500\" as a filter, simply do a filter query <code>fq=price:[250 TO 500]</code></p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
Assume that I have a field called *price* for the documents in Solr and I have that field faceted. I want to get the facets as ranges of values (eg: 0-100, 100-500, 500-1000, etc). How to do it? I can specify the ranges beforehand, but I also want to know whether it is possible to calculate the ranges (say for 5 values) automatically based on the values in the documents?
To answer your first question, you can get facet ranges by using the the generic facet query support. [Here](http://wiki.apache.org/solr/SimpleFacetParameters#head-1da3ab3995bc4abcdce8e0f04be7355ba19e9b2c)'s an example: ``` http://localhost:8983/solr/select?q=video&rows=0&facet=true&facet.query=price:[*+TO+500]&facet.query=price:[500+TO+*] ``` As for your second question (automatically suggesting facet ranges), that's not yet implemented. Some argue that this kind of querying would be best implemented on your application rather that letting Solr "guess" the best facet ranges. Here are some discussions on the topic: * (Archived) <https://web.archive.org/web/20100416235126/http://old.nabble.com/Re:-faceted-browsing-p3753053.html> * (Archived) <https://web.archive.org/web/20090430160232/http://www.nabble.com/Re:-Sorting-p6803791.html> * (Archived) <https://web.archive.org/web/20090504020754/http://www.nabble.com/Dynamically-calculated-range-facet-td11314725.html>
33,969
<p>We're experimenting with various ways to throttle user actions in a <strong>given time period</strong>:</p> <ul> <li>Limit question/answer posts</li> <li>Limit edits</li> <li>Limit feed retrievals</li> </ul> <p>For the time being, we're using the Cache to simply insert a record of user activity - if that record exists if/when the user does the same activity, we throttle.</p> <p>Using the Cache automatically gives us stale data cleaning and sliding activity windows of users, but how it will scale could be a problem.</p> <p>What are some other ways of ensuring that requests/user actions can be effectively throttled (emphasis on stability)?</p>
[ { "answer_id": 291390, "author": "Rob Kraft", "author_id": 37749, "author_profile": "https://Stackoverflow.com/users/37749", "pm_score": 4, "selected": false, "text": "<p>We use the technique borrowed from this URL <a href=\"http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx</a>, not for throttling, but for a poor man's Denial Of Service (D.O.S). This is also cache-based, and may be similar to what you are doing. Are you throttling to prevent D.O.S. attacks? Routers can certainly be used to reduce D.O.S; do you think a router could handle the throttling you need?</p>\n" }, { "answer_id": 584689, "author": "notandy", "author_id": 4221, "author_profile": "https://Stackoverflow.com/users/4221", "pm_score": 6, "selected": false, "text": "<p>Microsoft has a new extension for IIS 7 called Dynamic IP Restrictions Extension for IIS 7.0 - Beta. </p>\n\n<blockquote>\n <p>\"The Dynamic IP Restrictions for IIS 7.0 is a module that provides protection against denial of service and brute force attacks on web server and web sites. Such protection is provided by temporarily blocking IP addresses of the HTTP clients who make unusually high number of concurrent requests or who make large number of requests over small period of time.\"\n <a href=\"http://learn.iis.net/page.aspx/548/using-dynamic-ip-restrictions/\" rel=\"noreferrer\">http://learn.iis.net/page.aspx/548/using-dynamic-ip-restrictions/</a></p>\n</blockquote>\n\n<p>Example:</p>\n\n<p>If you set the criteria to block after <code>X requests in Y milliseconds</code> or <code>X concurrent connections in Y milliseconds</code> the IP address will be blocked for <code>Y milliseconds</code> then requests will be permitted again.</p>\n" }, { "answer_id": 1318059, "author": "Jarrod Dixon", "author_id": 3, "author_profile": "https://Stackoverflow.com/users/3", "pm_score": 9, "selected": true, "text": "<p>Here's a generic version of what we've been using on Stack Overflow for the past year:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Decorates any MVC route that needs to have client requests limited by time.\n/// &lt;/summary&gt;\n/// &lt;remarks&gt;\n/// Uses the current System.Web.Caching.Cache to store each client request to the decorated route.\n/// &lt;/remarks&gt;\n[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]\npublic class ThrottleAttribute : ActionFilterAttribute\n{\n /// &lt;summary&gt;\n /// A unique name for this Throttle.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// We'll be inserting a Cache record based on this name and client IP, e.g. \"Name-192.168.0.1\"\n /// &lt;/remarks&gt;\n public string Name { get; set; }\n\n /// &lt;summary&gt;\n /// The number of seconds clients must wait before executing this decorated route again.\n /// &lt;/summary&gt;\n public int Seconds { get; set; }\n\n /// &lt;summary&gt;\n /// A text message that will be sent to the client upon throttling. You can include the token {n} to\n /// show this.Seconds in the message, e.g. \"Wait {n} seconds before trying again\".\n /// &lt;/summary&gt;\n public string Message { get; set; }\n\n public override void OnActionExecuting(ActionExecutingContext c)\n {\n var key = string.Concat(Name, \"-\", c.HttpContext.Request.UserHostAddress);\n var allowExecute = false;\n\n if (HttpRuntime.Cache[key] == null)\n {\n HttpRuntime.Cache.Add(key,\n true, // is this the smallest data we can have?\n null, // no dependencies\n DateTime.Now.AddSeconds(Seconds), // absolute expiration\n Cache.NoSlidingExpiration,\n CacheItemPriority.Low,\n null); // no callback\n\n allowExecute = true;\n }\n\n if (!allowExecute)\n {\n if (String.IsNullOrEmpty(Message))\n Message = \"You may only perform this action every {n} seconds.\";\n\n c.Result = new ContentResult { Content = Message.Replace(\"{n}\", Seconds.ToString()) };\n // see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html\n c.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;\n }\n }\n}\n</code></pre>\n\n<p>Sample usage:</p>\n\n<pre><code>[Throttle(Name=\"TestThrottle\", Message = \"You must wait {n} seconds before accessing this url again.\", Seconds = 5)]\npublic ActionResult TestThrottle()\n{\n return Content(\"TestThrottle executed\");\n}\n</code></pre>\n\n<p>The ASP.NET Cache works like a champ here - by using it, you get automatic clean-up of your throttle entries. And with our growing traffic, we're not seeing that this is an issue on the server.</p>\n\n<p>Feel free to give feedback on this method; when we make Stack Overflow better, you get your <a href=\"https://stackoverflow.blog/2009/05/31/the-stack-overflow-trilogy/\">Ewok fix</a> even faster :)</p>\n" }, { "answer_id": 71646995, "author": "JsAndDotNet", "author_id": 852806, "author_profile": "https://Stackoverflow.com/users/852806", "pm_score": 2, "selected": false, "text": "<p>It took me some time to work out an equivalent for .NET 5+ (formerly .NET Core), so here's a starting point.</p>\n<p>The old way of caching has gone and been replaced by <code>Microsoft.Extensions.Caching.Memory</code> with <a href=\"https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-6.0\" rel=\"nofollow noreferrer\">IMemoryCache</a>.</p>\n<p>I separated it out a bit more, so here's what you need...</p>\n<p><strong>The Cache Management Class</strong></p>\n<p>I've added the whole thing here, so you can see the using statements.</p>\n<pre><code>using Microsoft.Extensions.Caching.Memory;\nusing Microsoft.Extensions.Primitives;\nusing System;\nusing System.Threading;\n\nnamespace MyWebApplication\n{\n public interface IThrottleCache\n {\n bool AddToCache(string key, int expriryTimeInSeconds);\n\n bool AddToCache&lt;T&gt;(string key, T value, int expriryTimeInSeconds);\n\n T GetFromCache&lt;T&gt;(string key);\n\n bool IsInCache(string key);\n }\n\n /// &lt;summary&gt;\n /// A caching class, based on the docs\n /// https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-6.0\n /// Uses the recommended library &quot;Microsoft.Extensions.Caching.Memory&quot;\n /// &lt;/summary&gt;\n public class ThrottleCache : IThrottleCache\n {\n private IMemoryCache _memoryCache;\n\n public ThrottleCache(IMemoryCache memoryCache)\n {\n _memoryCache = memoryCache;\n }\n\n\n public bool AddToCache(string key, int expriryTimeInSeconds)\n {\n bool isSuccess = false; // Only a success if a new value gets added.\n\n if (!IsInCache(key))\n {\n var cancellationTokenSource = new CancellationTokenSource(\n TimeSpan.FromSeconds(expriryTimeInSeconds));\n\n var cacheEntryOptions = new MemoryCacheEntryOptions()\n .SetSize(1)\n .AddExpirationToken(\n new CancellationChangeToken(cancellationTokenSource.Token));\n\n _memoryCache.Set(key, DateTime.Now, cacheEntryOptions);\n\n isSuccess = true;\n }\n\n return isSuccess;\n }\n\n\n public bool AddToCache&lt;T&gt;(string key, T value, int expriryTimeInSeconds)\n {\n bool isSuccess = false;\n\n if (!IsInCache(key))\n {\n var cancellationTokenSource = new CancellationTokenSource(\n TimeSpan.FromSeconds(expriryTimeInSeconds));\n\n var cacheEntryOptions = new MemoryCacheEntryOptions()\n .SetAbsoluteExpiration(DateTimeOffset.Now.AddSeconds(expriryTimeInSeconds))\n .SetSize(1)\n .AddExpirationToken(\n new CancellationChangeToken(cancellationTokenSource.Token));\n\n _memoryCache.Set&lt;T&gt;(key, value, cacheEntryOptions);\n\n isSuccess = true;\n }\n\n return isSuccess;\n }\n\n\n public T GetFromCache&lt;T&gt;(string key)\n {\n return _memoryCache.Get&lt;T&gt;(key);\n }\n\n\n public bool IsInCache(string key)\n {\n var item = _memoryCache.Get(key);\n\n return item != null;\n }\n\n\n }\n}\n</code></pre>\n<p><strong>The attribute itself</strong></p>\n<pre><code>using Microsoft.AspNetCore.Mvc;\nusing Microsoft.AspNetCore.Mvc.Filters;\nusing System;\nusing System.Net;\n\nnamespace MyWebApplication\n{\n /// &lt;summary&gt;\n /// Decorates any MVC route that needs to have client requests limited by time.\n /// Based on how they throttle at stack overflow (updated for .NET5+)\n /// https://stackoverflow.com/questions/33969/best-way-to-implement-request-throttling-in-asp-net-mvc/1318059#1318059\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// Uses the current System.Web.Caching.Cache to store each client request to the decorated route.\n /// &lt;/remarks&gt;\n [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]\n public class ThrottleByIPAddressAttribute : ActionFilterAttribute\n {\n /// &lt;summary&gt;\n /// The caching class (which will be instantiated as a singleton)\n /// &lt;/summary&gt;\n private IThrottleCache _throttleCache;\n\n\n /// &lt;summary&gt;\n /// A unique name for this Throttle.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// We'll be inserting a Cache record based on this name and client IP, e.g. &quot;Name-192.168.0.1&quot;\n /// &lt;/remarks&gt;\n public string Name { get; set; }\n\n /// &lt;summary&gt;\n /// The number of seconds clients must wait before executing this decorated route again.\n /// &lt;/summary&gt;\n public int Seconds { get; set; }\n\n /// &lt;summary&gt;\n /// A text message that will be sent to the client upon throttling. You can include the token {n} to\n /// show this.Seconds in the message, e.g. &quot;Wait {n} seconds before trying again&quot;.\n /// &lt;/summary&gt;\n public string Message { get; set; } = &quot;You may only perform this action every {n} seconds.&quot;;\n\n public override void OnActionExecuting(ActionExecutingContext c)\n {\n if(_throttleCache == null)\n {\n var cache = c.HttpContext.RequestServices.GetService(typeof(IThrottleCache));\n _throttleCache = (IThrottleCache)cache;\n }\n \n var key = string.Concat(Name, &quot;-&quot;, c.HttpContext.Request.HttpContext.Connection.RemoteIpAddress);\n\n var allowExecute = _throttleCache.AddToCache(key, Seconds);\n\n\n if (!allowExecute)\n {\n if (String.IsNullOrEmpty(Message))\n Message = &quot;You may only perform this action every {n} seconds.&quot;;\n\n c.Result = new ContentResult { Content = Message.Replace(&quot;{n}&quot;, Seconds.ToString()) };\n // see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html\n c.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;\n }\n }\n }\n}\n</code></pre>\n<p><strong>Startup.cs or Program.cs - Register the services with DI</strong></p>\n<p>This example uses Startup.cs/ConfigureServices - Put the code somewhere after <code>AddControllersWithViews</code>).</p>\n<p>For a project created in .NET6+ I think you'd add the equivalent between <code>builder.Services.AddRazorPages();</code> and <code>var app = builder.Build();</code> in program.cs. <code>services</code> would be <code>builder.Services</code>.</p>\n<p>If you don't get the placement of this code right, the cache will be empty every time you check it.</p>\n<pre><code>// The cache for throttling must be a singleton and requires IMemoryCache to be set up.\n// Place it after AddControllersWithViews or AddRazorPages as they build a cache themselves\n\n// Need this for IThrottleCache to work.\nservices.AddMemoryCache(_ =&gt; new MemoryCacheOptions\n{\n SizeLimit = 1024, /* TODO: CHECK THIS IS THIS THE RIGHT SIZE FOR YOU! */\n CompactionPercentage = .3,\n ExpirationScanFrequency = TimeSpan.FromSeconds(30),\n});\nservices.AddSingleton&lt;IThrottleCache, ThrottleCache&gt;();\n</code></pre>\n<p><strong>Example Usage</strong></p>\n<pre><code>[HttpGet, Route(&quot;GetTest&quot;)]\n[ThrottleByIPAddress(Name = &quot;MyControllerGetTest&quot;, Seconds = 5)]\npublic async Task&lt;ActionResult&lt;string&gt;&gt; GetTest()\n{\n return &quot;Hello world&quot;;\n}\n</code></pre>\n<p>To help understand caching in .NET 5+, I've also made a <a href=\"https://gist.github.com/JsAndDotNet/594019f4053a498aef3e0fcd59f5c68d\" rel=\"nofollow noreferrer\">caching console demo</a>.</p>\n" }, { "answer_id": 72008712, "author": "prem", "author_id": 3085520, "author_profile": "https://Stackoverflow.com/users/3085520", "pm_score": 1, "selected": false, "text": "<p>Since the highly voted answers to this question are too old, I am sharing the latest solution which worked for me.</p>\n<p>I tried using the Dynamic IP restrictions as given in an <a href=\"https://stackoverflow.com/a/584689/3085520\">answer</a> on this page but when I tried to use that extension, I found that this extension has been discontinued by Microsoft and on the <a href=\"https://www.iis.net/downloads/microsoft/dynamic-ip-restrictions\" rel=\"nofollow noreferrer\">download page</a> they have clearly written the below message.</p>\n<pre><code>Microsoft has discontinued the Dynamic IP Restrictions extension and this download is no longer available.\n</code></pre>\n<p>So I researched further and found that the Dynamic IP Restrictions is now by default included in IIS 8.0 and above. The below information is fetched from the Microsoft Dynamic IP Restrictions page.</p>\n<p>In IIS 8.0, Microsoft has expanded the built-in functionality to include several new features:</p>\n<ul>\n<li>Dynamic IP address filtering, which allows administrators to\nconfigure their server to block access for IP addresses that exceed\nthe specified number of requests.</li>\n<li>The IP address filtering features now allow administrators to specify\nthe behavior when IIS blocks an IP address, so requests from\nmalicious clients can be aborted by the server instead of returning\nHTTP 403.6 responses to the client.</li>\n<li>IP filtering now feature a proxy mode, which allows IP addresses to\nbe blocked not only by the client IP that is seen by IIS but also by\nthe values that are received in the x-forwarded-for HTTP header</li>\n</ul>\n<p>For step by step instructions to implement Dynamic IP Restrictions, please visit the below link:</p>\n<p><a href=\"https://learn.microsoft.com/en-us/iis/get-started/whats-new-in-iis-8/iis-80-dynamic-ip-address-restrictions\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/iis/get-started/whats-new-in-iis-8/iis-80-dynamic-ip-address-restrictions</a></p>\n<p>I hope it helps someone stuck in a similar problem.</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/33969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3/" ]
We're experimenting with various ways to throttle user actions in a **given time period**: * Limit question/answer posts * Limit edits * Limit feed retrievals For the time being, we're using the Cache to simply insert a record of user activity - if that record exists if/when the user does the same activity, we throttle. Using the Cache automatically gives us stale data cleaning and sliding activity windows of users, but how it will scale could be a problem. What are some other ways of ensuring that requests/user actions can be effectively throttled (emphasis on stability)?
Here's a generic version of what we've been using on Stack Overflow for the past year: ``` /// <summary> /// Decorates any MVC route that needs to have client requests limited by time. /// </summary> /// <remarks> /// Uses the current System.Web.Caching.Cache to store each client request to the decorated route. /// </remarks> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class ThrottleAttribute : ActionFilterAttribute { /// <summary> /// A unique name for this Throttle. /// </summary> /// <remarks> /// We'll be inserting a Cache record based on this name and client IP, e.g. "Name-192.168.0.1" /// </remarks> public string Name { get; set; } /// <summary> /// The number of seconds clients must wait before executing this decorated route again. /// </summary> public int Seconds { get; set; } /// <summary> /// A text message that will be sent to the client upon throttling. You can include the token {n} to /// show this.Seconds in the message, e.g. "Wait {n} seconds before trying again". /// </summary> public string Message { get; set; } public override void OnActionExecuting(ActionExecutingContext c) { var key = string.Concat(Name, "-", c.HttpContext.Request.UserHostAddress); var allowExecute = false; if (HttpRuntime.Cache[key] == null) { HttpRuntime.Cache.Add(key, true, // is this the smallest data we can have? null, // no dependencies DateTime.Now.AddSeconds(Seconds), // absolute expiration Cache.NoSlidingExpiration, CacheItemPriority.Low, null); // no callback allowExecute = true; } if (!allowExecute) { if (String.IsNullOrEmpty(Message)) Message = "You may only perform this action every {n} seconds."; c.Result = new ContentResult { Content = Message.Replace("{n}", Seconds.ToString()) }; // see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html c.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict; } } } ``` Sample usage: ``` [Throttle(Name="TestThrottle", Message = "You must wait {n} seconds before accessing this url again.", Seconds = 5)] public ActionResult TestThrottle() { return Content("TestThrottle executed"); } ``` The ASP.NET Cache works like a champ here - by using it, you get automatic clean-up of your throttle entries. And with our growing traffic, we're not seeing that this is an issue on the server. Feel free to give feedback on this method; when we make Stack Overflow better, you get your [Ewok fix](https://stackoverflow.blog/2009/05/31/the-stack-overflow-trilogy/) even faster :)
34,065
<p>Given the key for some registry value (e.g. HKEY_LOCAL_MACHINE\blah\blah\blah\foo) how can I:</p> <ol> <li>Safely determine that such a key exists.</li> <li>Programmatically (i.e. with code) get its value.</li> </ol> <p>I have absolutely no intention of writing anything back to the registry (for the duration of my career if I can help it). So we can skip the lecture about every molecule in my body exploding at the speed of light if I write to the registry incorrectly. </p> <p>Prefer answers in C++, but mostly just need to know what the special Windows API incantation to get at the value is.</p>
[ { "answer_id": 34067, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms724911%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">RegQueryValueEx</a></p>\n\n<p>This gives the value if it exists, and returns an error code ERROR_FILE_NOT_FOUND if the key doesn't exist.</p>\n\n<p>(I can't tell if my link is working or not, but if you just google for \"RegQueryValueEx\" the first hit is the msdn documentation.)</p>\n" }, { "answer_id": 34071, "author": "Serge", "author_id": 1007, "author_profile": "https://Stackoverflow.com/users/1007", "pm_score": 3, "selected": false, "text": "<p>The pair <a href=\"http://msdn.microsoft.com/en-us/library/ms724895%28VS.85%29.aspx\" rel=\"noreferrer\">RegOpenKey</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms724911%28VS.85%29.aspx\" rel=\"noreferrer\">RegQueryKeyEx</a> will do the trick.</p>\n\n<p>If you use MFC <a href=\"http://msdn.microsoft.com/en-us/library/xka57xy4%28VS.80%29.aspx\" rel=\"noreferrer\">CRegKey</a> class is even more easier solution.</p>\n" }, { "answer_id": 34082, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 3, "selected": false, "text": "<pre><code>const CString REG_SW_GROUP_I_WANT = _T(\"SOFTWARE\\\\My Corporation\\\\My Package\\\\Group I want\");\nconst CString REG_KEY_I_WANT= _T(\"Key Name\");\n\nCRegKey regKey;\nDWORD dwValue = 0;\n\nif(ERROR_SUCCESS != regKey.Open(HKEY_LOCAL_MACHINE, REG_SW_GROUP_I_WANT))\n{\n m_pobLogger-&gt;LogError(_T(\"CRegKey::Open failed in Method\"));\n regKey.Close();\n goto Function_Exit;\n}\nif( ERROR_SUCCESS != regKey.QueryValue( dwValue, REG_KEY_I_WANT))\n{\n m_pobLogger-&gt;LogError(_T(\"CRegKey::QueryValue Failed in Method\"));\n regKey.Close();\n goto Function_Exit;\n}\n\n// dwValue has the stuff now - use for further processing\n</code></pre>\n" }, { "answer_id": 35717, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 7, "selected": true, "text": "<p><strong>Here is some pseudo-code to retrieve the following:</strong></p>\n\n<ol>\n<li>If a registry key exists</li>\n<li>What the default value is for that registry key</li>\n<li>What a string value is</li>\n<li>What a DWORD value is</li>\n</ol>\n\n<p><strong>Example code:</strong></p>\n\n<p>Include the library dependency: Advapi32.lib</p>\n\n<pre><code>HKEY hKey;\nLONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L\"SOFTWARE\\\\Perl\", 0, KEY_READ, &amp;hKey);\nbool bExistsAndSuccess (lRes == ERROR_SUCCESS);\nbool bDoesNotExistsSpecifically (lRes == ERROR_FILE_NOT_FOUND);\nstd::wstring strValueOfBinDir;\nstd::wstring strKeyDefaultValue;\nGetStringRegKey(hKey, L\"BinDir\", strValueOfBinDir, L\"bad\");\nGetStringRegKey(hKey, L\"\", strKeyDefaultValue, L\"bad\");\n\nLONG GetDWORDRegKey(HKEY hKey, const std::wstring &amp;strValueName, DWORD &amp;nValue, DWORD nDefaultValue)\n{\n nValue = nDefaultValue;\n DWORD dwBufferSize(sizeof(DWORD));\n DWORD nResult(0);\n LONG nError = ::RegQueryValueExW(hKey,\n strValueName.c_str(),\n 0,\n NULL,\n reinterpret_cast&lt;LPBYTE&gt;(&amp;nResult),\n &amp;dwBufferSize);\n if (ERROR_SUCCESS == nError)\n {\n nValue = nResult;\n }\n return nError;\n}\n\n\nLONG GetBoolRegKey(HKEY hKey, const std::wstring &amp;strValueName, bool &amp;bValue, bool bDefaultValue)\n{\n DWORD nDefValue((bDefaultValue) ? 1 : 0);\n DWORD nResult(nDefValue);\n LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue);\n if (ERROR_SUCCESS == nError)\n {\n bValue = (nResult != 0) ? true : false;\n }\n return nError;\n}\n\n\nLONG GetStringRegKey(HKEY hKey, const std::wstring &amp;strValueName, std::wstring &amp;strValue, const std::wstring &amp;strDefaultValue)\n{\n strValue = strDefaultValue;\n WCHAR szBuffer[512];\n DWORD dwBufferSize = sizeof(szBuffer);\n ULONG nError;\n nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &amp;dwBufferSize);\n if (ERROR_SUCCESS == nError)\n {\n strValue = szBuffer;\n }\n return nError;\n}\n</code></pre>\n" }, { "answer_id": 7199329, "author": "Jim Michaels", "author_id": 591668, "author_profile": "https://Stackoverflow.com/users/591668", "pm_score": 0, "selected": false, "text": "<pre><code>#include &lt;windows.h&gt;\n#include &lt;map&gt;\n#include &lt;string&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;tr1/stdint.h&gt;\n\nusing namespace std;\n\nvoid printerr(DWORD dwerror) {\n LPVOID lpMsgBuf;\n FormatMessage(\n FORMAT_MESSAGE_ALLOCATE_BUFFER |\n FORMAT_MESSAGE_FROM_SYSTEM |\n FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL,\n dwerror,\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language\n (LPTSTR) &amp;lpMsgBuf,\n 0,\n NULL\n );\n // Process any inserts in lpMsgBuf.\n // ...\n // Display the string.\n if (isOut) {\n fprintf(fout, \"%s\\n\", lpMsgBuf);\n } else {\n printf(\"%s\\n\", lpMsgBuf);\n }\n // Free the buffer.\n LocalFree(lpMsgBuf);\n}\n\n\n\nbool regreadSZ(string&amp; hkey, string&amp; subkey, string&amp; value, string&amp; returnvalue, string&amp; regValueType) {\n char s[128000];\n map&lt;string,HKEY&gt; keys;\n keys[\"HKEY_CLASSES_ROOT\"]=HKEY_CLASSES_ROOT;\n keys[\"HKEY_CURRENT_CONFIG\"]=HKEY_CURRENT_CONFIG; //DID NOT SURVIVE?\n keys[\"HKEY_CURRENT_USER\"]=HKEY_CURRENT_USER;\n keys[\"HKEY_LOCAL_MACHINE\"]=HKEY_LOCAL_MACHINE;\n keys[\"HKEY_USERS\"]=HKEY_USERS;\n HKEY mykey;\n\n map&lt;string,DWORD&gt; valuetypes;\n valuetypes[\"REG_SZ\"]=REG_SZ;\n valuetypes[\"REG_EXPAND_SZ\"]=REG_EXPAND_SZ;\n valuetypes[\"REG_MULTI_SZ\"]=REG_MULTI_SZ; //probably can't use this.\n\n LONG retval=RegOpenKeyEx(\n keys[hkey], // handle to open key\n subkey.c_str(), // subkey name\n 0, // reserved\n KEY_READ, // security access mask\n &amp;mykey // handle to open key\n );\n if (ERROR_SUCCESS != retval) {printerr(retval); return false;}\n DWORD slen=128000;\n DWORD valuetype = valuetypes[regValueType];\n retval=RegQueryValueEx(\n mykey, // handle to key\n value.c_str(), // value name\n NULL, // reserved\n (LPDWORD) &amp;valuetype, // type buffer\n (LPBYTE)s, // data buffer\n (LPDWORD) &amp;slen // size of data buffer\n );\n switch(retval) {\n case ERROR_SUCCESS:\n //if (isOut) {\n // fprintf(fout,\"RegQueryValueEx():ERROR_SUCCESS:succeeded.\\n\");\n //} else {\n // printf(\"RegQueryValueEx():ERROR_SUCCESS:succeeded.\\n\");\n //}\n break;\n case ERROR_MORE_DATA:\n //what do I do now? data buffer is too small.\n if (isOut) {\n fprintf(fout,\"RegQueryValueEx():ERROR_MORE_DATA: need bigger buffer.\\n\");\n } else {\n printf(\"RegQueryValueEx():ERROR_MORE_DATA: need bigger buffer.\\n\");\n }\n return false;\n case ERROR_FILE_NOT_FOUND:\n if (isOut) {\n fprintf(fout,\"RegQueryValueEx():ERROR_FILE_NOT_FOUND: registry value does not exist.\\n\");\n } else {\n printf(\"RegQueryValueEx():ERROR_FILE_NOT_FOUND: registry value does not exist.\\n\");\n }\n return false;\n default:\n if (isOut) {\n fprintf(fout,\"RegQueryValueEx():unknown error type 0x%lx.\\n\", retval);\n } else {\n printf(\"RegQueryValueEx():unknown error type 0x%lx.\\n\", retval);\n }\n return false;\n\n }\n retval=RegCloseKey(mykey);\n if (ERROR_SUCCESS != retval) {printerr(retval); return false;}\n\n returnvalue = s;\n return true;\n}\n</code></pre>\n" }, { "answer_id": 50821858, "author": "Roi Danton", "author_id": 4566599, "author_profile": "https://Stackoverflow.com/users/4566599", "pm_score": 3, "selected": false, "text": "<p>Since Windows >=Vista/Server 2008, <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms724868(v=vs.85).aspx\" rel=\"noreferrer\">RegGetValue</a> is available, which <a href=\"https://msdn.microsoft.com/en-us/magazine/mt808504.aspx\" rel=\"noreferrer\">is a safer function</a> than <a href=\"https://msdn.microsoft.com/en-us/library/ms724911%28VS.85%29.aspx\" rel=\"noreferrer\">RegQueryValueEx</a>. No need for <code>RegOpenKeyEx</code>, <code>RegCloseKey</code> or <code>NUL</code> termination checks of string values (<a href=\"https://msdn.microsoft.com/en-us/library/ms724884(v=vs.85).aspx\" rel=\"noreferrer\"><code>REG_SZ</code>, <code>REG_MULTI_SZ</code>, <code>REG_EXPAND_SZ</code></a>).</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;exception&gt;\n#include &lt;windows.h&gt;\n\n/*! \\brief Returns a value from HKLM as string.\n \\exception std::runtime_error Replace with your error handling.\n*/\nstd::wstring GetStringValueFromHKLM(const std::wstring&amp; regSubKey, const std::wstring&amp; regValue)\n{\n size_t bufferSize = 0xFFF; // If too small, will be resized down below.\n std::wstring valueBuf; // Contiguous buffer since C++11.\n valueBuf.resize(bufferSize);\n auto cbData = static_cast&lt;DWORD&gt;(bufferSize * sizeof(wchar_t));\n auto rc = RegGetValueW(\n HKEY_LOCAL_MACHINE,\n regSubKey.c_str(),\n regValue.c_str(),\n RRF_RT_REG_SZ,\n nullptr,\n static_cast&lt;void*&gt;(valueBuf.data()),\n &amp;cbData\n );\n while (rc == ERROR_MORE_DATA)\n {\n // Get a buffer that is big enough.\n cbData /= sizeof(wchar_t);\n if (cbData &gt; static_cast&lt;DWORD&gt;(bufferSize))\n {\n bufferSize = static_cast&lt;size_t&gt;(cbData);\n }\n else\n {\n bufferSize *= 2;\n cbData = static_cast&lt;DWORD&gt;(bufferSize * sizeof(wchar_t));\n }\n valueBuf.resize(bufferSize);\n rc = RegGetValueW(\n HKEY_LOCAL_MACHINE,\n regSubKey.c_str(),\n regValue.c_str(),\n RRF_RT_REG_SZ,\n nullptr,\n static_cast&lt;void*&gt;(valueBuf.data()),\n &amp;cbData\n );\n }\n if (rc == ERROR_SUCCESS)\n {\n cbData /= sizeof(wchar_t);\n valueBuf.resize(static_cast&lt;size_t&gt;(cbData - 1)); // remove end null character\n return valueBuf;\n }\n else\n {\n throw std::runtime_error(\"Windows system error code: \" + std::to_string(rc));\n }\n}\n\nint main()\n{\n std::wstring regSubKey;\n#ifdef _WIN64 // Manually switching between 32bit/64bit for the example. Use dwFlags instead.\n regSubKey = L\"SOFTWARE\\\\WOW6432Node\\\\Company Name\\\\Application Name\\\\\";\n#else\n regSubKey = L\"SOFTWARE\\\\Company Name\\\\Application Name\\\\\";\n#endif\n std::wstring regValue(L\"MyValue\");\n std::wstring valueFromRegistry;\n try\n {\n valueFromRegistry = GetStringValueFromHKLM(regSubKey, regValue);\n }\n catch (std::exception&amp; e)\n {\n std::cerr &lt;&lt; e.what();\n }\n std::wcout &lt;&lt; valueFromRegistry;\n}\n</code></pre>\n\n<p>Its parameter <code>dwFlags</code> supports flags for type restriction, filling the value buffer with zeros on failure (<code>RRF_ZEROONFAILURE</code>) and 32/64bit registry access (<code>RRF_SUBKEY_WOW6464KEY</code>, <code>RRF_SUBKEY_WOW6432KEY</code>) for 64bit programs.</p>\n" }, { "answer_id": 53074007, "author": "kayleeFrye_onDeck", "author_id": 3543437, "author_profile": "https://Stackoverflow.com/users/3543437", "pm_score": 1, "selected": false, "text": "<p>This console app will list all the values and their data from a registry key for most of the potential registry values. There's some weird ones not often used. If you need to support all of them, expand from this example while referencing this <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/bb773476(v=vs.85).aspx\" rel=\"nofollow noreferrer\">Registry Value Type</a> documentation.</p>\n\n<p>Let this be the registry key content you can import from a <code>.reg</code> file format:</p>\n\n<pre><code>Windows Registry Editor Version 5.00\n\n[HKEY_CURRENT_USER\\added\\subkey]\n\"String_Value\"=\"hello, world!\"\n\"Binary_Value\"=hex:01,01,01,01\n\"Dword value\"=dword:00001224\n\"QWord val\"=hex(b):24,22,12,00,00,00,00,00\n\"multi-line val\"=hex(7):4c,00,69,00,6e,00,65,00,20,00,30,00,00,00,4c,00,69,00,\\\n 6e,00,65,00,20,00,31,00,00,00,4c,00,69,00,6e,00,65,00,20,00,32,00,00,00,00,\\\n 00\n\"expanded_val\"=hex(2):25,00,55,00,53,00,45,00,52,00,50,00,52,00,4f,00,46,00,49,\\\n 00,4c,00,45,00,25,00,5c,00,6e,00,65,00,77,00,5f,00,73,00,74,00,75,00,66,00,\\\n 66,00,00,00\n</code></pre>\n\n<p>The console app itself:</p>\n\n<pre><code>#include &lt;Windows.h&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;locale&gt;\n#include &lt;vector&gt;\n#include &lt;iomanip&gt;\n\nint wmain()\n{\n const auto hKey = HKEY_CURRENT_USER;\n constexpr auto lpSubKey = TEXT(\"added\\\\subkey\");\n auto openedKey = HKEY();\n auto status = RegOpenKeyEx(hKey, lpSubKey, 0, KEY_READ, &amp;openedKey);\n\n if (status == ERROR_SUCCESS) {\n auto valueCount = static_cast&lt;DWORD&gt;(0);\n auto maxNameLength = static_cast&lt;DWORD&gt;(0);\n auto maxValueLength = static_cast&lt;DWORD&gt;(0);\n status = RegQueryInfoKey(openedKey, NULL, NULL, NULL, NULL, NULL, NULL,\n &amp;valueCount, &amp;maxNameLength, &amp;maxValueLength, NULL, NULL);\n\n if (status == ERROR_SUCCESS) {\n DWORD type = 0;\n DWORD index = 0;\n std::vector&lt;wchar_t&gt; valueName = std::vector&lt;wchar_t&gt;(maxNameLength + 1);\n std::vector&lt;BYTE&gt; dataBuffer = std::vector&lt;BYTE&gt;(maxValueLength);\n\n for (DWORD index = 0; index &lt; valueCount; index++) {\n DWORD charCountValueName = static_cast&lt;DWORD&gt;(valueName.size());\n DWORD charBytesData = static_cast&lt;DWORD&gt;(dataBuffer.size());\n status = RegEnumValue(openedKey, index, valueName.data(), &amp;charCountValueName,\n NULL, &amp;type, dataBuffer.data(), &amp;charBytesData);\n\n if (type == REG_SZ) {\n const auto reg_string = reinterpret_cast&lt;wchar_t*&gt;(dataBuffer.data());\n std::wcout &lt;&lt; L\"Type: REG_SZ\" &lt;&lt; std::endl;\n std::wcout &lt;&lt; L\"\\tName: \" &lt;&lt; valueName.data() &lt;&lt; std::endl;\n std::wcout &lt;&lt; L\"\\tData : \" &lt;&lt; reg_string &lt;&lt; std::endl;\n }\n else if (type == REG_EXPAND_SZ) {\n const auto casted = reinterpret_cast&lt;wchar_t*&gt;(dataBuffer.data());\n TCHAR buffer[32000];\n ExpandEnvironmentStrings(casted, buffer, 32000);\n std::wcout &lt;&lt; L\"Type: REG_EXPAND_SZ\" &lt;&lt; std::endl;\n std::wcout &lt;&lt; L\"\\tName: \" &lt;&lt; valueName.data() &lt;&lt; std::endl;\n std::wcout &lt;&lt; L\"\\tData: \" &lt;&lt; buffer &lt;&lt; std::endl;\n }\n else if (type == REG_MULTI_SZ) {\n std::vector&lt;std::wstring&gt; lines;\n const auto str = reinterpret_cast&lt;wchar_t*&gt;(dataBuffer.data());\n auto line = str;\n lines.emplace_back(line);\n for (auto i = 0; i &lt; charBytesData / sizeof(wchar_t) - 1; i++) {\n const auto c = str[i];\n if (c == 0) {\n line = str + i + 1;\n const auto new_line = reinterpret_cast&lt;wchar_t*&gt;(line);\n if (wcsnlen_s(new_line, 1024) &gt; 0)\n lines.emplace_back(new_line);\n }\n }\n std::wcout &lt;&lt; L\"Type: REG_MULTI_SZ\" &lt;&lt; std::endl;\n std::wcout &lt;&lt; L\"\\tName: \" &lt;&lt; valueName.data() &lt;&lt; std::endl;\n std::wcout &lt;&lt; L\"\\tData: \" &lt;&lt; std::endl;\n for (size_t i = 0; i &lt; lines.size(); i++) {\n std::wcout &lt;&lt; L\"\\t\\tLine[\" &lt;&lt; i + 1 &lt;&lt; L\"]: \" &lt;&lt; lines[i] &lt;&lt; std::endl;\n }\n }\n if (type == REG_DWORD) {\n const auto dword_value = reinterpret_cast&lt;unsigned long*&gt;(dataBuffer.data());\n std::wcout &lt;&lt; L\"Type: REG_DWORD\" &lt;&lt; std::endl;\n std::wcout &lt;&lt; L\"\\tName: \" &lt;&lt; valueName.data() &lt;&lt; std::endl;\n std::wcout &lt;&lt; L\"\\tData : \" &lt;&lt; std::to_wstring(*dword_value) &lt;&lt; std::endl;\n }\n else if (type == REG_QWORD) {\n const auto qword_value = reinterpret_cast&lt;unsigned long long*&gt;(dataBuffer.data());\n std::wcout &lt;&lt; L\"Type: REG_DWORD\" &lt;&lt; std::endl;\n std::wcout &lt;&lt; L\"\\tName: \" &lt;&lt; valueName.data() &lt;&lt; std::endl;\n std::wcout &lt;&lt; L\"\\tData : \" &lt;&lt; std::to_wstring(*qword_value) &lt;&lt; std::endl;\n }\n else if (type == REG_BINARY) {\n std::vector&lt;uint16_t&gt; bins;\n for (auto i = 0; i &lt; charBytesData; i++) {\n bins.push_back(static_cast&lt;uint16_t&gt;(dataBuffer[i]));\n }\n std::wcout &lt;&lt; L\"Type: REG_BINARY\" &lt;&lt; std::endl;\n std::wcout &lt;&lt; L\"\\tName: \" &lt;&lt; valueName.data() &lt;&lt; std::endl;\n std::wcout &lt;&lt; L\"\\tData:\";\n for (size_t i = 0; i &lt; bins.size(); i++) {\n std::wcout &lt;&lt; L\" \" &lt;&lt; std::uppercase &lt;&lt; std::hex &lt;&lt; \\\n std::setw(2) &lt;&lt; std::setfill(L'0') &lt;&lt; std::to_wstring(bins[i]);\n }\n std::wcout &lt;&lt; std::endl;\n }\n }\n }\n }\n\n RegCloseKey(openedKey);\n return 0;\n}\n</code></pre>\n\n<p>Expected console output: </p>\n\n<pre><code>Type: REG_SZ\n Name: String_Value\n Data : hello, world!\nType: REG_BINARY\n Name: Binary_Value\n Data: 01 01 01 01\nType: REG_DWORD\n Name: Dword value\n Data : 4644\nType: REG_DWORD\n Name: QWord val\n Data : 1188388\nType: REG_MULTI_SZ\n Name: multi-line val\n Data:\n Line[1]: Line 0\n Line[2]: Line 1\n Line[3]: Line 2\nType: REG_EXPAND_SZ\n Name: expanded_val\n Data: C:\\Users\\user name\\new_stuff\n</code></pre>\n" }, { "answer_id": 57627988, "author": "Jarek C", "author_id": 3736444, "author_profile": "https://Stackoverflow.com/users/3736444", "pm_score": 2, "selected": false, "text": "<p>Typically the register key and value are constants in the program. If so, here is an example how to read a DWORD registry value <code>Computer\\HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\FileSystem\\LongPathsEnabled</code>:</p>\n\n<pre><code>#include &lt;windows.h&gt;\n\nDWORD val;\nDWORD dataSize = sizeof(val);\nif (ERROR_SUCCESS == RegGetValueA(HKEY_LOCAL_MACHINE, \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\FileSystem\", \"LongPathsEnabled\", RRF_RT_DWORD, nullptr /*type not required*/, &amp;val, &amp;dataSize)) {\n printf(\"Value is %i\\n\", val);\n // no CloseKey needed because it is a predefined registry key\n}\nelse {\n printf(\"Error reading.\\n\");\n}\n</code></pre>\n\n<p>To adapt for other value types, see <a href=\"https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-reggetvaluea\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-reggetvaluea</a> for complete spec.</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/34065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3551/" ]
Given the key for some registry value (e.g. HKEY\_LOCAL\_MACHINE\blah\blah\blah\foo) how can I: 1. Safely determine that such a key exists. 2. Programmatically (i.e. with code) get its value. I have absolutely no intention of writing anything back to the registry (for the duration of my career if I can help it). So we can skip the lecture about every molecule in my body exploding at the speed of light if I write to the registry incorrectly. Prefer answers in C++, but mostly just need to know what the special Windows API incantation to get at the value is.
**Here is some pseudo-code to retrieve the following:** 1. If a registry key exists 2. What the default value is for that registry key 3. What a string value is 4. What a DWORD value is **Example code:** Include the library dependency: Advapi32.lib ``` HKEY hKey; LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &hKey); bool bExistsAndSuccess (lRes == ERROR_SUCCESS); bool bDoesNotExistsSpecifically (lRes == ERROR_FILE_NOT_FOUND); std::wstring strValueOfBinDir; std::wstring strKeyDefaultValue; GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad"); GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad"); LONG GetDWORDRegKey(HKEY hKey, const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue) { nValue = nDefaultValue; DWORD dwBufferSize(sizeof(DWORD)); DWORD nResult(0); LONG nError = ::RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, reinterpret_cast<LPBYTE>(&nResult), &dwBufferSize); if (ERROR_SUCCESS == nError) { nValue = nResult; } return nError; } LONG GetBoolRegKey(HKEY hKey, const std::wstring &strValueName, bool &bValue, bool bDefaultValue) { DWORD nDefValue((bDefaultValue) ? 1 : 0); DWORD nResult(nDefValue); LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue); if (ERROR_SUCCESS == nError) { bValue = (nResult != 0) ? true : false; } return nError; } LONG GetStringRegKey(HKEY hKey, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue) { strValue = strDefaultValue; WCHAR szBuffer[512]; DWORD dwBufferSize = sizeof(szBuffer); ULONG nError; nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize); if (ERROR_SUCCESS == nError) { strValue = szBuffer; } return nError; } ```
34,079
<p>What's the best way to specify a proxy with username and password for an http connection in python?</p>
[ { "answer_id": 34116, "author": "bernhardrusch", "author_id": 3056, "author_profile": "https://Stackoverflow.com/users/3056", "pm_score": 6, "selected": false, "text": "<p>This works for me: </p>\n\n<pre><code>import urllib2\n\nproxy = urllib2.ProxyHandler({'http': 'http://\nusername:password@proxyurl:proxyport'})\nauth = urllib2.HTTPBasicAuthHandler()\nopener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)\nurllib2.install_opener(opener)\n\nconn = urllib2.urlopen('http://python.org')\nreturn_str = conn.read()\n</code></pre>\n" }, { "answer_id": 35443, "author": "gz.", "author_id": 3665, "author_profile": "https://Stackoverflow.com/users/3665", "pm_score": 3, "selected": false, "text": "<p>The best way of going through a proxy that requires authentication is using <a href=\"http://docs.python.org/lib/module-urllib2.html\" rel=\"noreferrer\">urllib2</a> to build a custom url opener, then using that to make all the requests you want to go through the proxy. Note in particular, you probably don't want to embed the proxy password in the url or the python source code (unless it's just a quick hack).</p>\n\n<pre><code>import urllib2\n\ndef get_proxy_opener(proxyurl, proxyuser, proxypass, proxyscheme=\"http\"):\n password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()\n password_mgr.add_password(None, proxyurl, proxyuser, proxypass)\n\n proxy_handler = urllib2.ProxyHandler({proxyscheme: proxyurl})\n proxy_auth_handler = urllib2.ProxyBasicAuthHandler(password_mgr)\n\n return urllib2.build_opener(proxy_handler, proxy_auth_handler)\n\nif __name__ == \"__main__\":\n import sys\n if len(sys.argv) &gt; 4:\n url_opener = get_proxy_opener(*sys.argv[1:4])\n for url in sys.argv[4:]:\n print url_opener.open(url).headers\n else:\n print \"Usage:\", sys.argv[0], \"proxy user pass fetchurls...\"\n</code></pre>\n\n<p>In a more complex program, you can seperate these components out as appropriate (for instance, only using one password manager for the lifetime of the application). The python documentation has <a href=\"http://docs.python.org/lib/urllib2-examples.html\" rel=\"noreferrer\">more examples on how to do complex things with urllib2</a> that you might also find useful.</p>\n" }, { "answer_id": 142324, "author": "Tony Meyer", "author_id": 4966, "author_profile": "https://Stackoverflow.com/users/4966", "pm_score": 2, "selected": false, "text": "<p>Or if you want to install it, so that it is always used with urllib2.urlopen (so you don't need to keep a reference to the opener around):</p>\n\n<pre><code>import urllib2\nurl = 'www.proxyurl.com'\nusername = 'user'\npassword = 'pass'\npassword_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()\n# None, with the \"WithDefaultRealm\" password manager means\n# that the user/pass will be used for any realm (where\n# there isn't a more specific match).\npassword_mgr.add_password(None, url, username, password)\nauth_handler = urllib2.HTTPBasicAuthHandler(password_mgr)\nopener = urllib2.build_opener(auth_handler)\nurllib2.install_opener(opener)\nprint urllib2.urlopen(\"http://www.example.com/folder/page.html\").read()\n</code></pre>\n" }, { "answer_id": 3942980, "author": "ducu", "author_id": 45712, "author_profile": "https://Stackoverflow.com/users/45712", "pm_score": 4, "selected": false, "text": "<p>Setting an environment var named <strong>http_proxy</strong> like this: <strong>http://username:password@proxy_url:port</strong></p>\n" }, { "answer_id": 36216636, "author": "daz", "author_id": 799873, "author_profile": "https://Stackoverflow.com/users/799873", "pm_score": 2, "selected": false, "text": "<p>Here is the method use urllib </p>\n\n<pre><code>import urllib.request\n\n# set up authentication info\nauthinfo = urllib.request.HTTPBasicAuthHandler()\nproxy_support = urllib.request.ProxyHandler({\"http\" : \"http://ahad-haam:3128\"})\n\n# build a new opener that adds authentication and caching FTP handlers\nopener = urllib.request.build_opener(proxy_support, authinfo,\n urllib.request.CacheFTPHandler)\n\n# install it\nurllib.request.install_opener(opener)\n\nf = urllib.request.urlopen('http://www.python.org/')\n\"\"\"\n</code></pre>\n" }, { "answer_id": 41920303, "author": "Aminah Nuraini", "author_id": 1564659, "author_profile": "https://Stackoverflow.com/users/1564659", "pm_score": 6, "selected": true, "text": "<p>Use this:</p>\n\n<pre><code>import requests\n\nproxies = {\"http\":\"http://username:password@proxy_ip:proxy_port\"}\n\nr = requests.get(\"http://www.example.com/\", proxies=proxies)\n\nprint(r.content)\n</code></pre>\n\n<p>I think it's much simpler than using <code>urllib</code>. I don't understand why people love using <code>urllib</code> so much.</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/34079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3573/" ]
What's the best way to specify a proxy with username and password for an http connection in python?
Use this: ``` import requests proxies = {"http":"http://username:password@proxy_ip:proxy_port"} r = requests.get("http://www.example.com/", proxies=proxies) print(r.content) ``` I think it's much simpler than using `urllib`. I don't understand why people love using `urllib` so much.
34,087
<pre><code>&lt;xsl:for-each select="./node [position() &amp;lt;= (count(*) div 2)]"&gt; &lt;li&gt;foo&lt;/li&gt; &lt;/xsl:for-each&gt; &lt;xsl:for-each select="./node [count(*) div 2 &amp;lt; position()]"&gt; &lt;li&gt;bar&lt;/li&gt; &lt;/xsl:for-each&gt; </code></pre> <p>My list has 12 nodes, but the second list is always 8 and the first is always 4. What's wrong with my selects?</p>
[ { "answer_id": 34111, "author": "A. Rex", "author_id": 3508, "author_profile": "https://Stackoverflow.com/users/3508", "pm_score": 0, "selected": false, "text": "<p>I'm not at all sure, but it seems to me that <code>count(*)</code> is not doing what you think it is. That counts the number of children of the current node, not the size of the current node list. Could you print it out to check that it's 8 or 9 instead of 12?</p>\n\n<p>Use <code>last()</code> to get the context size.</p>\n" }, { "answer_id": 34114, "author": "jelovirt", "author_id": 2679, "author_profile": "https://Stackoverflow.com/users/2679", "pm_score": 4, "selected": true, "text": "<p>When you do <code>count(*)</code>, the current node is the <code>node</code> element being processed. You want either <code>count(current()/node)</code> or <code>last()</code> (preferable), or just calculate the midpoint to a variable for better performance and clearer code:</p>\n\n<pre><code>&lt;xsl:variable name=\"nodes\" select=\"node\"/&gt;\n&lt;xsl:variable name=\"mid\" select=\"count($nodes) div 2\"/&gt;\n&lt;xsl:for-each select=\"$nodes[position() &amp;lt;= $mid]\"&gt;\n &lt;li&gt;foo&lt;/li&gt;\n&lt;/xsl:for-each&gt;\n&lt;xsl:for-each select=\"$nodes[$mid &amp;lt; position()]\"&gt;\n &lt;li&gt;bar&lt;/li&gt;\n&lt;/xsl:for-each&gt;\n</code></pre>\n" }, { "answer_id": 34133, "author": "codeape", "author_id": 3571, "author_profile": "https://Stackoverflow.com/users/3571", "pm_score": 0, "selected": false, "text": "<p>Try count(../node). The following will gives the correct result on my test XML file (a simple nodes root with node elements), using the xsltproc XSLT processor.</p>\n\n<pre><code>&lt;xsl:for-each select=\"node[position() &amp;lt;= (count(../node) div 2)]\"&gt;\n ...\n&lt;/xsl:for-each&gt;\n&lt;xsl:for-each select=\"node[(count(../node) div 2) &amp;lt; position()]\"&gt;\n ...\n&lt;/xsl:for-each&gt;\n</code></pre>\n" }, { "answer_id": 34159, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 2, "selected": false, "text": "<p>You could try using the <code>last()</code> function which will give you the size of the current context:</p>\n\n<pre><code>&lt;xsl:for-each select=\"./node [position() &amp;lt;= last() div 2]\"&gt;\n &lt;li&gt;foo&lt;/li&gt;\n&lt;/xsl:for-each&gt;\n&lt;xsl:for-each select=\"./node [last() div 2 &amp;lt; position()]\"&gt;\n &lt;li&gt;bar&lt;/li&gt;\n&lt;/xsl:for-each&gt;\n</code></pre>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/34087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786/" ]
``` <xsl:for-each select="./node [position() &lt;= (count(*) div 2)]"> <li>foo</li> </xsl:for-each> <xsl:for-each select="./node [count(*) div 2 &lt; position()]"> <li>bar</li> </xsl:for-each> ``` My list has 12 nodes, but the second list is always 8 and the first is always 4. What's wrong with my selects?
When you do `count(*)`, the current node is the `node` element being processed. You want either `count(current()/node)` or `last()` (preferable), or just calculate the midpoint to a variable for better performance and clearer code: ``` <xsl:variable name="nodes" select="node"/> <xsl:variable name="mid" select="count($nodes) div 2"/> <xsl:for-each select="$nodes[position() &lt;= $mid]"> <li>foo</li> </xsl:for-each> <xsl:for-each select="$nodes[$mid &lt; position()]"> <li>bar</li> </xsl:for-each> ```
34,093
<p>I want to apply an XSLT Stylesheet to an XML Document using C# and write the output to a File.</p>
[ { "answer_id": 34095, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 9, "selected": true, "text": "<p>I found a possible answer here: <a href=\"http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63\" rel=\"noreferrer\">http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63</a></p>\n\n<p>From the article:</p>\n\n<pre><code>XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;\nXslTransform myXslTrans = new XslTransform() ;\nmyXslTrans.Load(myStyleSheet);\nXmlTextWriter myWriter = new XmlTextWriter(\"result.html\",null) ;\nmyXslTrans.Transform(myXPathDoc,null,myWriter) ;\n</code></pre>\n\n<p><strong>Edit:</strong></p>\n\n<p>But my trusty compiler says, <code>XslTransform</code> is obsolete: Use <code>XslCompiledTransform</code> instead:</p>\n\n<pre><code>XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;\nXslCompiledTransform myXslTrans = new XslCompiledTransform();\nmyXslTrans.Load(myStyleSheet);\nXmlTextWriter myWriter = new XmlTextWriter(\"result.html\",null);\nmyXslTrans.Transform(myXPathDoc,null,myWriter);\n</code></pre>\n" }, { "answer_id": 4022970, "author": "ManBugra", "author_id": 162192, "author_profile": "https://Stackoverflow.com/users/162192", "pm_score": 4, "selected": false, "text": "<p>Here is a tutorial about how to do XSL Transformations in C# on MSDN:</p>\n\n<p><a href=\"http://support.microsoft.com/kb/307322/en-us/\" rel=\"noreferrer\">http://support.microsoft.com/kb/307322/en-us/</a></p>\n\n<p>and here how to write files:</p>\n\n<p><a href=\"http://support.microsoft.com/kb/816149/en-us\" rel=\"noreferrer\">http://support.microsoft.com/kb/816149/en-us</a></p>\n\n<p>just as a side note: if you want to do validation too here is another tutorial (for DTD, XDR, and XSD (=Schema)):</p>\n\n<p><a href=\"http://support.microsoft.com/kb/307379/en-us/\" rel=\"noreferrer\">http://support.microsoft.com/kb/307379/en-us/</a> </p>\n\n<p>i added this just to provide some more information.</p>\n" }, { "answer_id": 10596241, "author": "Heinzi", "author_id": 87698, "author_profile": "https://Stackoverflow.com/users/87698", "pm_score": 7, "selected": false, "text": "<p>Based on Daren's excellent answer, note that this code can be shortened significantly by using the appropriate <a href=\"http://msdn.microsoft.com/en-us/library/ms163431.aspx\">XslCompiledTransform.Transform overload</a>:</p>\n\n<pre><code>var myXslTrans = new XslCompiledTransform(); \nmyXslTrans.Load(\"stylesheet.xsl\"); \nmyXslTrans.Transform(\"source.xml\", \"result.html\"); \n</code></pre>\n\n<p><em>(Sorry for posing this as an answer, but the <code>code block</code> support in comments is rather limited.)</em></p>\n\n<p>In VB.NET, you don't even need a variable:</p>\n\n<pre><code>With New XslCompiledTransform()\n .Load(\"stylesheet.xsl\")\n .Transform(\"source.xml\", \"result.html\")\nEnd With\n</code></pre>\n" }, { "answer_id": 58930747, "author": "Vinod Srivastav", "author_id": 3057246, "author_profile": "https://Stackoverflow.com/users/3057246", "pm_score": 2, "selected": false, "text": "<p>This might help you</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static string TransformDocument(string doc, string stylesheetPath)\n{\n Func&lt;string,XmlDocument&gt; GetXmlDocument = (xmlContent) =&gt;\n {\n XmlDocument xmlDocument = new XmlDocument();\n xmlDocument.LoadXml(xmlContent);\n return xmlDocument;\n };\n\n try\n {\n var document = GetXmlDocument(doc);\n var style = GetXmlDocument(File.ReadAllText(stylesheetPath));\n\n System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();\n transform.Load(style); // compiled stylesheet\n System.IO.StringWriter writer = new System.IO.StringWriter();\n XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));\n transform.Transform(xmlReadB, null, writer);\n return writer.ToString();\n }\n catch (Exception ex)\n {\n throw ex;\n }\n\n} \n</code></pre>\n" }, { "answer_id": 72905605, "author": "Mubashar", "author_id": 806076, "author_profile": "https://Stackoverflow.com/users/806076", "pm_score": 0, "selected": false, "text": "<p>I would like to share this small piece of code which reads from Database and transforms using XSLT. On the top I also have used <code>xslt-extensions</code> which makes it little different than others.</p>\n<p>Note: <em>This is just a draft code and may need cleanup before using in production.</em></p>\n<pre><code>var schema = XDocument.Load(XsltPath);\nusing (var connection = new SqlConnection(ConnectionString))\n{\n connection.Open();\n using (var command = new SqlCommand(Sql, connection))\n {\n var reader = command.ExecuteReader();\n var dt = new DataTable(SourceNode);\n dt.Load(reader);\n \n string xml = &quot;&lt;?xml version=\\&quot;1.0\\&quot; encoding=\\&quot;UTF-8\\&quot;?&gt;&quot; + Environment.NewLine;\n using (var stringWriter = new StringWriter())\n {\n dt.WriteXml(stringWriter, true);\n xml += stringWriter.GetStringBuilder().ToString();\n }\n\n XDocument transformedXml = new XDocument();\n var xsltArgumentList = new XsltArgumentList();\n xsltArgumentList.AddExtensionObject(&quot;urn:xslt-extensions&quot;, new XsltExtensions());\n\n using (XmlWriter writer = transformedXml.CreateWriter())\n {\n XslCompiledTransform xslt = new XslCompiledTransform();\n xslt.Load(schema.CreateReader());\n xslt.Transform(XmlReader.Create(new StringReader(xml)), xsltArgumentList, writer);\n }\n var result = transformedXml.ToString();\n }\n}\n</code></pre>\n<p><code>XsltPath</code> is path to your xslt file.<br />\n<code>ConnectionString</code> constant is pointing to your database.<br />\n<code>Sql</code> is your query.<br />\n<code>SourceNode</code> is node of each record in source xml.</p>\n<p>Now the interesting part, please note the use of <code>urn:xslt-extensions</code> and <code>new XsltExtensions()</code> in above code. You can use this if need some complex computation which may not be possible in xslt. Following is a simple method to format date.</p>\n<pre><code>public class XsltExtensions\n{\n public string FormatDate(string dateString, string format)\n {\n DateTime date;\n\n if (DateTime.TryParse(dateString, out date))\n return date.ToString(format);\n\n return dateString;\n }\n}\n</code></pre>\n<p>In XSLT file you can use it as below;</p>\n<pre><code>&lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot; xmlns:ext=&quot;urn:xslt-extensions&quot;&gt;\n...\n&lt;myTag&gt;&lt;xsl:value-of select=&quot;ext:FormatDate(record_date, 'yyyy-MM-dd')&quot;/&gt;&lt;/myTag&gt;\n...\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/34093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ]
I want to apply an XSLT Stylesheet to an XML Document using C# and write the output to a File.
I found a possible answer here: <http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63> From the article: ``` XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ; XslTransform myXslTrans = new XslTransform() ; myXslTrans.Load(myStyleSheet); XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ; myXslTrans.Transform(myXPathDoc,null,myWriter) ; ``` **Edit:** But my trusty compiler says, `XslTransform` is obsolete: Use `XslCompiledTransform` instead: ``` XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ; XslCompiledTransform myXslTrans = new XslCompiledTransform(); myXslTrans.Load(myStyleSheet); XmlTextWriter myWriter = new XmlTextWriter("result.html",null); myXslTrans.Transform(myXPathDoc,null,myWriter); ```
34,125
<p>It seems to me that it would work perfectly well to do tail-recursion optimization in both C and C++, yet while debugging I never seem to see a frame stack that indicates this optimization. That is kind of good, because the stack tells me how deep the recursion is. However, the optimization would be kind of nice as well.</p> <p>Do any C++ compilers do this optimization? Why? Why not?</p> <p>How do I go about telling the compiler to do it?</p> <ul> <li>For MSVC: <code>/O2</code> or <code>/Ox</code></li> <li>For GCC: <code>-O2</code> or <code>-O3</code></li> </ul> <p>How about checking if the compiler has done this in a certain case?</p> <ul> <li>For MSVC, enable PDB output to be able to trace the code, then inspect the code</li> <li>For GCC..?</li> </ul> <p>I'd still take suggestions for how to determine if a certain function is optimized like this by the compiler (even though I find it reassuring that Konrad tells me to assume it)</p> <p>It is always possible to check if the compiler does this at all by making an infinite recursion and checking if it results in an infinite loop or a stack overflow (I did this with GCC and found out that <code>-O2</code> is sufficient), but I want to be able to check a certain function that I know will terminate anyway. I'd love to have an easy way of checking this :)</p> <hr> <p>After some testing, I discovered that destructors ruin the possibility of making this optimization. It can sometimes be worth it to change the scoping of certain variables and temporaries to make sure they go out of scope before the return-statement starts.</p> <p>If any destructor needs to be run after the tail-call, the tail-call optimization can not be done.</p>
[ { "answer_id": 34129, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 8, "selected": true, "text": "<p><strong>All current mainstream compilers perform tail call optimisation</strong> fairly well (and have done for more than a decade), <a href=\"https://godbolt.org/g/TjqTHV\" rel=\"noreferrer\">even for mutually recursive calls</a> such as:</p>\n\n<pre><code>int bar(int, int);\n\nint foo(int n, int acc) {\n return (n == 0) ? acc : bar(n - 1, acc + 2);\n}\n\nint bar(int n, int acc) {\n return (n == 0) ? acc : foo(n - 1, acc + 1);\n}\n</code></pre>\n\n<p>Letting the compiler do the optimisation is straightforward: Just switch on optimisation for speed:</p>\n\n<ul>\n<li>For MSVC, use <code>/O2</code> or <code>/Ox</code>.</li>\n<li>For GCC, Clang and ICC, use <code>-O3</code></li>\n</ul>\n\n<p>An easy way to check if the compiler did the optimisation is to perform a call that would otherwise result in a stack overflow — or looking at the assembly output.</p>\n\n<p>As an interesting historical note, tail call optimisation for C was added to the GCC in the course of a <a href=\"http://www.complang.tuwien.ac.at/schani/diplarb.ps\" rel=\"noreferrer\">diploma thesis</a> by Mark Probst. The thesis describes some interesting caveats in the implementation. It's worth reading.</p>\n" }, { "answer_id": 34139, "author": "Greg Whitfield", "author_id": 2102, "author_profile": "https://Stackoverflow.com/users/2102", "pm_score": 4, "selected": false, "text": "<p>Most compilers don't do any kind of optimisation in a debug build.</p>\n\n<p>If using VC, try a release build with PDB info turned on - this will let you trace through the optimised app and you should hopefully see what you want then. Note, however, that debugging and tracing an optimised build will jump you around all over the place, and often you cannot inspect variables directly as they only ever end up in registers or get optimised away entirely. It's an \"interesting\" experience...</p>\n" }, { "answer_id": 71115, "author": "0124816", "author_id": 11521, "author_profile": "https://Stackoverflow.com/users/11521", "pm_score": 3, "selected": false, "text": "<p>As Greg mentions, compilers won't do it in debug mode. It's ok for debug builds to be slower than a prod build, but they shouldn't crash more often: and if you depend on a tail call optimization, they may do exactly that. Because of this it is often best to rewrite the tail call as an normal loop. :-(</p>\n" }, { "answer_id": 220660, "author": "Tom Barta", "author_id": 29839, "author_profile": "https://Stackoverflow.com/users/29839", "pm_score": 5, "selected": false, "text": "<p>gcc 4.3.2 completely inlines this function (crappy/trivial <code>atoi()</code> implementation) into <code>main()</code>. Optimization level is <code>-O1</code>. I notice if I play around with it (even changing it from <code>static</code> to <code>extern</code>, the tail recursion goes away pretty fast, so I wouldn't depend on it for program correctness.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\nstatic int atoi(const char *str, int n)\n{\n if (str == 0 || *str == 0)\n return n;\n return atoi(str+1, n*10 + *str-'0');\n}\nint main(int argc, char **argv)\n{\n for (int i = 1; i != argc; ++i)\n printf(\"%s -&gt; %d\\n\", argv[i], atoi(argv[i], 0));\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 35649259, "author": "Martin Bonner supports Monica", "author_id": 771073, "author_profile": "https://Stackoverflow.com/users/771073", "pm_score": 5, "selected": false, "text": "<p>As well as the obvious (compilers don't do this sort of optimization unless you ask for it), there is a complexity about tail-call optimization in C++: destructors.</p>\n\n<p>Given something like:</p>\n\n<pre><code> int fn(int j, int i)\n {\n if (i &lt;= 0) return j;\n Funky cls(j,i);\n return fn(j, i-1);\n }\n</code></pre>\n\n<p>The compiler can't (in general) tail-call optimize this because it needs\nto call the destructor of <code>cls</code> <em>after</em> the recursive call returns.</p>\n\n<p>Sometimes the compiler can see that the destructor has no externally visible side effects (so it can be done early), but often it can't.</p>\n\n<p>A particularly common form of this is where <code>Funky</code> is actually a <code>std::vector</code> or similar.</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/34125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2971/" ]
It seems to me that it would work perfectly well to do tail-recursion optimization in both C and C++, yet while debugging I never seem to see a frame stack that indicates this optimization. That is kind of good, because the stack tells me how deep the recursion is. However, the optimization would be kind of nice as well. Do any C++ compilers do this optimization? Why? Why not? How do I go about telling the compiler to do it? * For MSVC: `/O2` or `/Ox` * For GCC: `-O2` or `-O3` How about checking if the compiler has done this in a certain case? * For MSVC, enable PDB output to be able to trace the code, then inspect the code * For GCC..? I'd still take suggestions for how to determine if a certain function is optimized like this by the compiler (even though I find it reassuring that Konrad tells me to assume it) It is always possible to check if the compiler does this at all by making an infinite recursion and checking if it results in an infinite loop or a stack overflow (I did this with GCC and found out that `-O2` is sufficient), but I want to be able to check a certain function that I know will terminate anyway. I'd love to have an easy way of checking this :) --- After some testing, I discovered that destructors ruin the possibility of making this optimization. It can sometimes be worth it to change the scoping of certain variables and temporaries to make sure they go out of scope before the return-statement starts. If any destructor needs to be run after the tail-call, the tail-call optimization can not be done.
**All current mainstream compilers perform tail call optimisation** fairly well (and have done for more than a decade), [even for mutually recursive calls](https://godbolt.org/g/TjqTHV) such as: ``` int bar(int, int); int foo(int n, int acc) { return (n == 0) ? acc : bar(n - 1, acc + 2); } int bar(int n, int acc) { return (n == 0) ? acc : foo(n - 1, acc + 1); } ``` Letting the compiler do the optimisation is straightforward: Just switch on optimisation for speed: * For MSVC, use `/O2` or `/Ox`. * For GCC, Clang and ICC, use `-O3` An easy way to check if the compiler did the optimisation is to perform a call that would otherwise result in a stack overflow — or looking at the assembly output. As an interesting historical note, tail call optimisation for C was added to the GCC in the course of a [diploma thesis](http://www.complang.tuwien.ac.at/schani/diplarb.ps) by Mark Probst. The thesis describes some interesting caveats in the implementation. It's worth reading.
34,126
<p>I see 2 main ways to set events in JavaScript:</p> <ol> <li><p>Add an event directly inside the tag like this:</p> <p><code>&lt;a href="" onclick="doFoo()"&gt;do foo&lt;/a&gt;</code></p></li> <li><p>Set them by JavaScript like this:</p> <p><code>&lt;a id="bar" href=""&gt;do bar&lt;/a&gt;</code></p></li> </ol> <p>and add an event in a <code>&lt;script&gt;</code> section inside the <code>&lt;head&gt;</code> section or in an external JavaScript file, like that if you're using <strong>prototypeJS</strong>:</p> <pre><code>Event.observe(window, 'load', function() { $('bar').observe('click', doBar); } </code></pre> <p>I think the first method is easier to read and maintain (because the JavaScript action is directly bound to the link) but it's not so clean (because users can click on the link even if the page is not fully loaded, which may cause JavaScript errors in some cases).</p> <p>The second method is cleaner (actions are added when the page is fully loaded) but it's more difficult to know that an action is linked to the tag.</p> <p>Which method is the best?</p> <p>A killer answer will be fully appreciated!</p>
[ { "answer_id": 34130, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 0, "selected": false, "text": "<p>Libraries like YUI and jQuery provide methods to add events only once the DOM is ready, which can be before window.onload. They also ensure that you can add multiple event handlers so that you can use scripts from different sources without the different event handlers overwriting each other.</p>\n\n<p>So your practical choices are;</p>\n\n<p>One. If your script is simple and the only one that will ever run on the page, create an init function like so:</p>\n\n<pre><code>window.onload = function () {\n init();\n}\nfunction init() {\n // actual function calls go here\n doFoo();\n}\n</code></pre>\n\n<p>Two. If you have many scripts or plan to mashup scripts from different sources, use a library and its <code>onDOMReady</code> method to safely add your event handlers</p>\n" }, { "answer_id": 34141, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>I think the first method is easier to read and maintain</p>\n</blockquote>\n\n<p>I've found the opposite to be true. Bear in mind that sometimes more than one event handler will be bound to a given control.</p>\n\n<p>Declaring all events in one central place helps to organize the actions taking place on the site. If you need to change something you don't have to search for all places making a call to a function, you simply have to change it in one place. When adding more elements that should have the same functionality you don't have to remember to add the handlers to them; instead, it's often enough to let them declare a class, or even not change them at all because they logically belong to a container element of which all child elements get wired to an action. From an actual code:</p>\n\n<pre><code>$$('#itemlist table th &gt; a').invoke('observe', 'click', performSort);\n</code></pre>\n\n<p>This wired an event handler to all column headers in a table to make the table sortable. Imagine the effort to make all column headers sortable separately.</p>\n" }, { "answer_id": 34163, "author": "Thomas Lötzer", "author_id": 3587, "author_profile": "https://Stackoverflow.com/users/3587", "pm_score": 3, "selected": true, "text": "<p>In my experience, there are two major points to this:</p>\n\n<p>1) The most important thing is to be consistent. I don't think either of the two methods is necessarily easier to read, as long as you stick to it. I only get confused when both methods are used in a project (or even worse on the same page) because then I have to start searching for the calls and don't immediately know where to look.</p>\n\n<p>2) The second kind, i.e. <code>Event.observe()</code> has advantages when the same or a very similar action is taken on multiple events because this becomes obvious when all those calls are in the same place. Also, as Konrad pointed out, in some cases this can be handled with a single call.</p>\n" }, { "answer_id": 34179, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 1, "selected": false, "text": "<p>You can also use addEventListener (not in IE) / attachEvent (in IE).</p>\n\n<p>Check out: <a href=\"http://www.quirksmode.org/js/events_advanced.html\" rel=\"nofollow noreferrer\">http://www.quirksmode.org/js/events_advanced.html</a></p>\n\n<p>These allow you to attach a function (or multiple functions) to an event on an existing DOM object. They also have the advantage of allowing un-attachment later.</p>\n\n<p>In general, if you're using a serious amount of javascript, it can be useful to make your <em>javascript</em> readable, as opposed to your html. So you could say that <code>onclick=X</code> in the html is very clear, but this is both a lack of separation of the code -- another syntactic dependency between pieces -- and a case in which you have to read both the html and the javascript to understand the dynamic behavior of the page.</p>\n" }, { "answer_id": 34212, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": 2, "selected": false, "text": "<p>I believe the second method is generally preferred because it keeps information about action (i.e. the JavaScript) separate from the markup in the same way CSS separates presentation from markup.</p>\n\n<p>I agree that this makes it a little more difficult to see what's happening in your page, but good tools like firebug will help you with this a lot. You'll also find much better IDE support available if you keep the mixing of HTML and Javascript to a minimum.</p>\n\n<p>This approach really comes into its own as your project grows, and you find you want to attach the same javascript event to a bunch of different element types on many different pages. In that case, it becomes much easier to have a single pace which attaches events, rather than having to search many different HTML files to find where a particular function is called.</p>\n" }, { "answer_id": 34293, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>My personal preference is to use jQuery in external js files so the js is completely separate from the html. Javascript should be unobtrusive so inline (ie, the first example) is not really the best choice in my opinion. When looking at the html, the only sign that you are using js should be the script includes in the head.</p>\n\n<p>An example of attaching (and handling) events might be something like this</p>\n\n<pre><code>var myObject = {\n\n allLinkElements: null, \n\n init: function()\n {\n // Set all the elements we need\n myObject.setElements();\n\n // Set event handlers for elements\n myObject.setEventHandlers();\n },\n\n clickedLink: function()\n {\n // Handle the click event\n alert('you clicked a link');\n },\n\n setElements: function()\n {\n // Find all &lt;a&gt; tags on the page\n myObject.allLinkElements = $('a');\n\n // Find other elements...\n },\n\n setEventHandlers: function()\n {\n // Loop through each link\n myObject.allLinkElements.each(function(id)\n { \n // Assign the handler for the click event\n $(this).click(myObject.clickedLink);\n });\n\n // Assign handlers for other elements...\n }\n}\n\n// Wait for the DOM to be ready before initialising\n$(document).ready(myObject.init);\n</code></pre>\n\n<p>I think this approach is useful if you want to keep all of your js organised, as you can use specific objects for tasks and everything is nicely contained. </p>\n\n<p>Of course, the huge benefit of letting jQuery (or another well known library) do the hard work is that cross-browser support is (largely) taken care of which makes life much easier</p>\n" } ]
2008/08/29
[ "https://Stackoverflow.com/questions/34126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3122/" ]
I see 2 main ways to set events in JavaScript: 1. Add an event directly inside the tag like this: `<a href="" onclick="doFoo()">do foo</a>` 2. Set them by JavaScript like this: `<a id="bar" href="">do bar</a>` and add an event in a `<script>` section inside the `<head>` section or in an external JavaScript file, like that if you're using **prototypeJS**: ``` Event.observe(window, 'load', function() { $('bar').observe('click', doBar); } ``` I think the first method is easier to read and maintain (because the JavaScript action is directly bound to the link) but it's not so clean (because users can click on the link even if the page is not fully loaded, which may cause JavaScript errors in some cases). The second method is cleaner (actions are added when the page is fully loaded) but it's more difficult to know that an action is linked to the tag. Which method is the best? A killer answer will be fully appreciated!
In my experience, there are two major points to this: 1) The most important thing is to be consistent. I don't think either of the two methods is necessarily easier to read, as long as you stick to it. I only get confused when both methods are used in a project (or even worse on the same page) because then I have to start searching for the calls and don't immediately know where to look. 2) The second kind, i.e. `Event.observe()` has advantages when the same or a very similar action is taken on multiple events because this becomes obvious when all those calls are in the same place. Also, as Konrad pointed out, in some cases this can be handled with a single call.