qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
120,033
<p>In C++, it's not possible to initialize array members in the initialization list, thus member objects should have default constructors and they should be properly initialized in the constructor. Is there any (reasonable) workaround for this apart from not using arrays?</p> <p>[Anything that can be initialized using only the initialization list is in our application far preferable to using the constructor, as that data can be allocated and initialized by the compiler and linker, and every CPU clock cycle counts, even before <code>main</code>. However, it is not always possible to have a default constructor for every class, and besides, reinitializing the data again in the constructor rather defeats the purpose anyway.]</p> <p>E.g. I'd like to have something like this (but this one doesn't work):</p> <pre><code>class OtherClass { private: int data; public: OtherClass(int i) : data(i) {}; // No default constructor! }; class Foo { private: OtherClass inst[3]; // Array size fixed and known ahead of time. public: Foo(...) : inst[0](0), inst[1](1), inst[2](2) {}; }; </code></pre> <p>The only workaround I'm aware of is the non-array one:</p> <pre><code>class Foo { private: OtherClass inst0; OtherClass inst1; OtherClass inst2; OtherClass *inst[3]; public: Foo(...) : inst0(0), inst1(1), inst2(2) { inst[0]=&amp;inst0; inst[1]=&amp;inst1; inst[2]=&amp;inst2; }; }; </code></pre> <p><b>Edit</b>: It should be stressed that <code>OtherClass</code> has no default constructor, and that it is very desirable to have the linker be able to allocate any memory needed (one or more static instances of <code>Foo</code> will be created), using the heap is essentially <i>verboten</i>. I've updated the examples above to highlight the first point.</p>
[ { "answer_id": 120084, "author": "Suma", "author_id": 16673, "author_profile": "https://Stackoverflow.com/users/16673", "pm_score": 3, "selected": true, "text": "<p>One possible workaround is to avoid the compiler calling the OtherClass constructor at all, and to call it on your own using placement new to initialize it whichever way you need. Example:</p>\n\n<pre><code> class Foo\n {\n private:\n char inst[3*sizeof(OtherClass)]; // Array size fixed. OtherClass has no default ctor.\n\n // use Inst to access, not inst\n OtherClass &amp;Inst(int i) {return (OtherClass *)inst+i;}\n const OtherClass &amp;Inst(int i) const {return (const OtherClass *)inst+i;}\n public:\n Foo(...)\n {\n new (Inst(0)) OtherClass(...);\n new (Inst(1)) OtherClass(...);\n new (Inst(2)) OtherClass(...);\n }\n ~Foo()\n {\n Inst(0)-&gt;~OtherClass();\n Inst(1)-&gt;~OtherClass();\n Inst(2)-&gt;~OtherClass();\n }\n };\n</code></pre>\n\n<p>To cater for possible alignment requirements of the OtherClass, you may need to use __declspec(align(x)) if working in VisualC++, or to use a type other than char like:</p>\n\n<pre><code>Type inst[3*(sizeof(OtherClass)+sizeof(Type)-1)/sizeof(Type)];\n</code></pre>\n\n<p>... where Type is int, double, long long, or whatever describes the alignment requirements.</p>\n" }, { "answer_id": 120089, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 2, "selected": false, "text": "<p>What data members are in OtherClass? Will value-initialization be enough for that class?</p>\n\n<p>If value-initialization is enough, then you can value-initialize an array in the member initialization list:</p>\n\n<pre><code>class A {\npublic:\n A ()\n : m_a() // All elements are value-initialized (which for int means zero'd)\n {\n }\n\nprivate:\n int m_a[3];\n};\n</code></pre>\n\n<p>If your array element types are class types, then the default constructor will be called.</p>\n\n<p><strong>EDIT:</strong> Just to clarify the comment from Drealmer.</p>\n\n<p>Where the element type is non-POD, then it should have an \"accessible default constructor\" (as was stated above). If the compiler cannot call the default constructor, then this solution will not work.</p>\n\n<p>The following example, would not work with this approach:</p>\n\n<pre><code>class Elem {\npublic:\n Elem (int); // User declared ctor stops generation of implicit default ctor\n};\n\nclass A {\npublic:\n A ()\n : m_a () // Compile error: No default constructor\n {}\n\nprivate:\n Elem m_a[10];\n};\n</code></pre>\n" }, { "answer_id": 120129, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 0, "selected": false, "text": "<p>Array members are not initialized by default. So you could use a static helper function that does the initialization, and store the result of the helper function in a member.</p>\n\n<pre><code>#include \"stdafx.h\"\n#include &lt;algorithm&gt;\n#include &lt;cassert&gt;\n\nclass C {\npublic: // for the sake of demonstration...\n typedef int t_is[4] ;\n t_is is;\n bool initialized;\n\n C() : initialized( false )\n {\n }\n\n C( int deflt )\n : initialized( sf_bInit( is, deflt ) )\n {}\n\n static bool sf_bInit( t_is&amp; av_is, const int i ){\n std::fill( av_is, av_is + sizeof( av_is )/sizeof( av_is[0] ), i );\n return true;\n }\n};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\n C c(1), d;\n\n assert( c.is[0] == 1 );\n\n return 0;\n}\n</code></pre>\n\n<p>Worth noting is that in the next standard, they're going to support array initializers.</p>\n" }, { "answer_id": 686574, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Use inheritance for creating proxy object</p>\n\n<pre><code>class ProxyOtherClass : public OtherClass {\npublic: \n ProxyOtherClass() : OtherClass(0) {}\n};\n\nclass Foo {\nprivate:\n ProxyOtherClass inst[3]; // Array size fixed and known ahead of time.\npublic:\n Foo(...) {}\n};\n</code></pre>\n" }, { "answer_id": 1547362, "author": "foxthrot", "author_id": 187579, "author_profile": "https://Stackoverflow.com/users/187579", "pm_score": 0, "selected": false, "text": "<p>And what about using array of pointers instead of array of objects?\nFor example:</p>\n\n<pre><code>class Foo {\nprivate:\n OtherClass *inst[3];\npublic:\n Foo(...) {\n inst[0]=new OtherClass(1);\n inst[1]=new OtherClass(2);\n inst[2]=new OtherClass(3);\n };\n\n ~Foo() {\n delete [] inst; \n }\n\n};\n</code></pre>\n" }, { "answer_id": 2642768, "author": "Matthew", "author_id": 317152, "author_profile": "https://Stackoverflow.com/users/317152", "pm_score": 0, "selected": false, "text": "<p>You say \"Anything that can be initialized using only the initialization list is in our application far preferable to using the constructor, as that data can be allocated and initialized by the compiler and linker, and every CPU clock cycle counts\".</p>\n\n<p>So, don't use constructors. That is, don't use conventional \"instances\". Declare everything statically. When you need a new \"instance\", create a new static declaration, potentially outside of any classes. Use structs with public members if you have to. Use C if you have to.</p>\n\n<p>You answered your own question. Constructors and destructors are only useful in environments with a lot of allocation and deallocation. What good is destruction if the goal is for as much data as possible to be allocated statically, and so what good is construction without destruction? To hell with both of them.</p>\n" }, { "answer_id": 3587596, "author": "Jeff G", "author_id": 433298, "author_profile": "https://Stackoverflow.com/users/433298", "pm_score": 1, "selected": false, "text": "<p>One method I typically use to make a class member \"appear\" to be on the stack (although actually stored on the heap):\n<pre>class Foo {\nprivate:\n int const (&amp;array)[3];\n int const (&amp;InitArray() const)[3] {\n int (*const rval)[3] = new int[1][3];\n (*rval)[0] = 2;\n (*rval)[1] = 3;\n (*rval)[2] = 5;\n return *rval;\n }\npublic:\n explicit Foo() : array(InitArray()) { }\n virtual ~Foo() { delete[] &amp;array[0]; }\n};</pre>To clients of your class, array appears to be of type \"int const [3]\". Combine this code with placement new and you can also truly initialize the values at your discretion using any constructor you desire. Hope this helps.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20957/" ]
In C++, it's not possible to initialize array members in the initialization list, thus member objects should have default constructors and they should be properly initialized in the constructor. Is there any (reasonable) workaround for this apart from not using arrays? [Anything that can be initialized using only the initialization list is in our application far preferable to using the constructor, as that data can be allocated and initialized by the compiler and linker, and every CPU clock cycle counts, even before `main`. However, it is not always possible to have a default constructor for every class, and besides, reinitializing the data again in the constructor rather defeats the purpose anyway.] E.g. I'd like to have something like this (but this one doesn't work): ``` class OtherClass { private: int data; public: OtherClass(int i) : data(i) {}; // No default constructor! }; class Foo { private: OtherClass inst[3]; // Array size fixed and known ahead of time. public: Foo(...) : inst[0](0), inst[1](1), inst[2](2) {}; }; ``` The only workaround I'm aware of is the non-array one: ``` class Foo { private: OtherClass inst0; OtherClass inst1; OtherClass inst2; OtherClass *inst[3]; public: Foo(...) : inst0(0), inst1(1), inst2(2) { inst[0]=&inst0; inst[1]=&inst1; inst[2]=&inst2; }; }; ``` **Edit**: It should be stressed that `OtherClass` has no default constructor, and that it is very desirable to have the linker be able to allocate any memory needed (one or more static instances of `Foo` will be created), using the heap is essentially *verboten*. I've updated the examples above to highlight the first point.
One possible workaround is to avoid the compiler calling the OtherClass constructor at all, and to call it on your own using placement new to initialize it whichever way you need. Example: ``` class Foo { private: char inst[3*sizeof(OtherClass)]; // Array size fixed. OtherClass has no default ctor. // use Inst to access, not inst OtherClass &Inst(int i) {return (OtherClass *)inst+i;} const OtherClass &Inst(int i) const {return (const OtherClass *)inst+i;} public: Foo(...) { new (Inst(0)) OtherClass(...); new (Inst(1)) OtherClass(...); new (Inst(2)) OtherClass(...); } ~Foo() { Inst(0)->~OtherClass(); Inst(1)->~OtherClass(); Inst(2)->~OtherClass(); } }; ``` To cater for possible alignment requirements of the OtherClass, you may need to use \_\_declspec(align(x)) if working in VisualC++, or to use a type other than char like: ``` Type inst[3*(sizeof(OtherClass)+sizeof(Type)-1)/sizeof(Type)]; ``` ... where Type is int, double, long long, or whatever describes the alignment requirements.
120,061
<p>I try to fetch a Wikipedia article with Python's urllib:</p> <pre><code>f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes") s = f.read() f.close() </code></pre> <p>However instead of the html page I get the following response: Error - Wikimedia Foundation:</p> <pre><code>Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT </code></pre> <p>Wikipedia seems to block request which are not from a standard browser.</p> <p>Anybody know how to work around this?</p>
[ { "answer_id": 120073, "author": "Vasil", "author_id": 7883, "author_profile": "https://Stackoverflow.com/users/7883", "pm_score": 1, "selected": false, "text": "<p>Try changing the user agent header you are sending in your request to something like:\nUser-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008072820 Ubuntu/8.04 (hardy) Firefox/3.0.1 (Linux Mint)</p>\n" }, { "answer_id": 120104, "author": "Gurch", "author_id": 21006, "author_profile": "https://Stackoverflow.com/users/21006", "pm_score": 1, "selected": false, "text": "<p>You don't need to impersonate a browser user-agent; any user-agent at all will work, just not a blank one.</p>\n" }, { "answer_id": 120113, "author": "Hannes Ovrén", "author_id": 13565, "author_profile": "https://Stackoverflow.com/users/13565", "pm_score": 5, "selected": false, "text": "<p>It is not a solution to the specific problem. But it might be intersting for you to use the mwclient library (<a href=\"http://botwiki.sno.cc/wiki/Python:Mwclient\" rel=\"noreferrer\">http://botwiki.sno.cc/wiki/Python:Mwclient</a>) instead. That would be so much easier. Especially since you will directly get the article contents which removes the need for you to parse the html.</p>\n\n<p>I have used it myself for two projects, and it works very well.</p>\n" }, { "answer_id": 120118, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 7, "selected": true, "text": "<p>You need to use the <a href=\"http://docs.python.org/lib/module-urllib2.html\" rel=\"nofollow noreferrer\">urllib2</a> that superseedes <a href=\"http://docs.python.org/lib/module-urllib.html\" rel=\"nofollow noreferrer\">urllib</a> in the <a href=\"http://docs.python.org/lib/\" rel=\"nofollow noreferrer\">python std library</a> in order to change the user agent.</p>\n\n<p>Straight from the <a href=\"http://web.archive.org/web/20070202031348/http://docs.python.org/lib/urllib2-examples.html\" rel=\"nofollow noreferrer\">examples</a></p>\n\n<pre><code>import urllib2\nopener = urllib2.build_opener()\nopener.addheaders = [('User-agent', 'Mozilla/5.0')]\ninfile = opener.open('http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes')\npage = infile.read()\n</code></pre>\n" }, { "answer_id": 120121, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 2, "selected": false, "text": "<p>The general solution I use for any site is to access the page using Firefox and, using an extension such as Firebug, record all details of the HTTP request including any cookies.</p>\n\n<p>In your program (in this case in Python) you should try to send a HTTP request as similar as necessary to the one that worked from Firefox. This often includes setting the User-Agent, Referer and Cookie fields, but there may be others.</p>\n" }, { "answer_id": 980529, "author": "sligocki", "author_id": 68736, "author_profile": "https://Stackoverflow.com/users/68736", "pm_score": 4, "selected": false, "text": "<p>Rather than trying to trick Wikipedia, you should consider using their <a href=\"http://www.mediawiki.org/wiki/API\" rel=\"noreferrer\">High-Level API</a>.</p>\n" }, { "answer_id": 4168237, "author": "mathias", "author_id": 506175, "author_profile": "https://Stackoverflow.com/users/506175", "pm_score": 2, "selected": false, "text": "<p>In case you are trying to access Wikipedia content (and don't need any specific information about the page itself), instead of using the api you should just call index.php with 'action=raw' in order to get the wikitext, like in:</p>\n\n<p>'http://en.wikipedia.org/w/index.php?<strong>action=raw</strong>&amp;title=Main_Page'</p>\n\n<p>Or, if you want the HTML code, use 'action=render' like in:</p>\n\n<p>'http://en.wikipedia.org/w/index.php?<strong>action=render</strong>&amp;title=Main_Page'</p>\n\n<p>You can also define a section to get just part of the content with something like 'section=3'.</p>\n\n<p>You could then access it using the urllib2 module (as sugested in the chosen answer).\nHowever, if you need information about the page itself (such as revisions), you'll be better using the mwclient as sugested above.</p>\n\n<p>Refer to <a href=\"http://www.mediawiki.org/wiki/API%3aFAQ#get_the_content_of_a_page_.28wikitext.29.3F\" rel=\"nofollow\">MediaWiki's FAQ</a> if you need more information.</p>\n" }, { "answer_id": 4795011, "author": "Finn Årup Nielsen", "author_id": 589165, "author_profile": "https://Stackoverflow.com/users/589165", "pm_score": 0, "selected": false, "text": "<pre><code>import urllib\ns = urllib.urlopen('http://en.wikipedia.org/w/index.php?action=raw&amp;title=Albert_Einstein').read()\n</code></pre>\n\n<p>This seems to work for me without changing the user agent. Without the \"action=raw\" it does not work for me.</p>\n" }, { "answer_id": 25927059, "author": "Aziz Alto", "author_id": 2839786, "author_profile": "https://Stackoverflow.com/users/2839786", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://docs.python-requests.org/en/latest/\" rel=\"nofollow\"><code>requests</code></a> is awesome!</p>\n\n<p>Here is how you can get the html content with <code>requests</code>:</p>\n\n<pre><code>import requests\nhtml = requests.get('http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes').text\n</code></pre>\n\n<p>Done!</p>\n" }, { "answer_id": 33645006, "author": "skierpage", "author_id": 1162195, "author_profile": "https://Stackoverflow.com/users/1162195", "pm_score": 1, "selected": false, "text": "<p>Requesting the page with <a href=\"https://en.wikipedia.org/wiki/Albert_Einstein?printable=yes\" rel=\"nofollow\"><code>?printable=yes</code></a> gives you an entire relatively clean HTML document. <a href=\"https://en.wikipedia.org/wiki/Albert_Einstein?action=render\" rel=\"nofollow\"><code>?action=render</code></a> gives you just the body HTML. Requesting to parse the page through the MediaWiki action API with <a href=\"https://en.wikipedia.org/w/api.php?action=parse&amp;page=Albert%20Einstein&amp;formatversion=2\" rel=\"nofollow\"><code>action=parse</code></a> likewise gives you just the body HTML but would be good if you want finer control, <a href=\"https://en.wikipedia.org/w/api.php?action=help&amp;modules=parse\" rel=\"nofollow\">see parse API help</a>.</p>\n\n<p>If you just want the page HTML so you can render it, it's faster and better is to use the new <a href=\"https://en.wikipedia.org/api/rest_v1/?doc\" rel=\"nofollow\">RESTBase</a> API, which returns a cached HTML representation of the page. In this case, <a href=\"https://en.wikipedia.org/api/rest_v1/page/html/Albert_Einstein\" rel=\"nofollow\">https://en.wikipedia.org/api/rest_v1/page/html/Albert_Einstein</a>.</p>\n\n<p>As of November 2015, you don't have to set your user-agent, but <a href=\"https://www.mediawiki.org/wiki/API:Etiquette#User-Agent_header\" rel=\"nofollow\">it's strongly encouraged</a>. Also, nearly all Wikimedia wikis <a href=\"http://blog.wikimedia.org/2015/06/12/securing-wikimedia-sites-with-https/\" rel=\"nofollow\">require HTTPS</a>, so avoid a 301 redirect and make http<strong>s</strong> requests.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20999/" ]
I try to fetch a Wikipedia article with Python's urllib: ``` f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes") s = f.read() f.close() ``` However instead of the html page I get the following response: Error - Wikimedia Foundation: ``` Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT ``` Wikipedia seems to block request which are not from a standard browser. Anybody know how to work around this?
You need to use the [urllib2](http://docs.python.org/lib/module-urllib2.html) that superseedes [urllib](http://docs.python.org/lib/module-urllib.html) in the [python std library](http://docs.python.org/lib/) in order to change the user agent. Straight from the [examples](http://web.archive.org/web/20070202031348/http://docs.python.org/lib/urllib2-examples.html) ``` import urllib2 opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] infile = opener.open('http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes') page = infile.read() ```
120,071
<p>I have a string of arbitrary length, and starting at position p0, I need to find the first occurrence of one of three 3-letter patterns.</p> <p>Assume the string contain only letters. I need to find the count of triplets starting at position p0 and jumping forward in triplets until the first occurrence of either 'aaa' or 'bbb' or 'ccc'.</p> <p>Is this even possible using just a regex?</p>
[ { "answer_id": 120094, "author": "Mike G.", "author_id": 18901, "author_profile": "https://Stackoverflow.com/users/18901", "pm_score": 4, "selected": false, "text": "<pre><code>$string=~/^ # from the start of the string\n (?:.{$p0}) # skip (don't capture) \"$p0\" occurrences of any character\n (?:...)*? # skip 3 characters at a time,\n # as few times as possible (non-greedy)\n (aaa|bbb|ccc) # capture aaa or bbb or ccc as $1\n /x;\n</code></pre>\n\n<p>(Assuming p0 is 0-based).</p>\n\n<p>Of course, it's probably more efficient to use substr on the string to skip forward:</p>\n\n<pre><code>substr($string, $p0)=~/^(?:...)*?(aaa|bbb|ccc)/;\n</code></pre>\n" }, { "answer_id": 120141, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 3, "selected": false, "text": "<p>You can't really count with regexes, but you can do something like this:</p>\n\n<pre><code>pos $string = $start_from;\n$string =~ m/\\G # anchor to previous pos()\n ((?:...)*?) # capture everything up to the match\n (aaa|bbb|ccc)\n /xs or die \"No match\"\nmy $result = length($1) / 3;\n</code></pre>\n\n<p>But I think it's a bit faster to use substr() and unpack() to split into triple and walk the triples in a for-loop.</p>\n\n<p>(edit: it's length(), not lenght() ;-)</p>\n" }, { "answer_id": 120207, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 5, "selected": true, "text": "<p>Moritz says this might be faster than a regex. Even if it's a little slower, it's easier to understand at 5 am. :)</p>\n\n<pre>\n #0123456789.123456789.123456789. \nmy $string = \"alsdhfaaasccclaaaagalkfgblkgbklfs\"; \nmy $pos = 9; \nmy $length = 3; \nmy $regex = qr/^(aaa|bbb|ccc)/;\n\nwhile( $pos &lt; length $string ) \n { \n print \"Checking $pos\\n\"; \n\n if( substr( $string, $pos, $length ) =~ /$regex/ )\n {\n print \"Found $1 at $pos\\n\";\n last;\n }\n\n $pos += $length;\n }\n</pre>\n" }, { "answer_id": 122794, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 0, "selected": false, "text": "<p>The main part of this is split /(...)/. But at the end of this, you'll have your positions and occurrence data. </p>\n\n<pre><code>my @expected_triplets = qw&lt;aaa bbb ccc&gt;;\nmy $data_string \n = 'fjeidoaaaivtrxxcccfznaaauitbbbfzjasdjfncccftjtjqznnjgjaaajeitjgbbblafjan'\n ;\nmy $place = 0;\nmy @triplets = grep { length } split /(...)/, $data_string;\nmy %occurrence_for = map { $_, [] } @expected_triplets;\nforeach my $i ( 0..@triplets ) {\n my $triplet = $triplets[$i];\n push( @{$occurrence_for{$triplet}}, $i ) if exists $occurrence_for{$triplet};\n}\n</code></pre>\n\n<p>Or for simple counting by regex (it uses Experimental (??{}))</p>\n\n<pre><code>my ( $count, %count );\nmy $data_string \n = 'fjeidoaaaivtrxxcccfznaaauitbbbfzjasdjfncccftjtjqznnjgjaaajeitjgbbblafjan'\n ;\n$data_string =~ m/(aaa|bbb|ccc)(??{ $count++; $count{$^N}++ })/g;\n</code></pre>\n" }, { "answer_id": 273659, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 0, "selected": false, "text": "<p>If speed is a serious concern, you can, depending on what the 3 strings are, get really fancy by creating a tree (e.g. Aho-Corasick algorithm or similar).</p>\n\n<p>A map for every possible state is possible, e.g. state[0]['a'] = 0 if no strings begin with 'a'.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15161/" ]
I have a string of arbitrary length, and starting at position p0, I need to find the first occurrence of one of three 3-letter patterns. Assume the string contain only letters. I need to find the count of triplets starting at position p0 and jumping forward in triplets until the first occurrence of either 'aaa' or 'bbb' or 'ccc'. Is this even possible using just a regex?
Moritz says this might be faster than a regex. Even if it's a little slower, it's easier to understand at 5 am. :) ``` #0123456789.123456789.123456789. my $string = "alsdhfaaasccclaaaagalkfgblkgbklfs"; my $pos = 9; my $length = 3; my $regex = qr/^(aaa|bbb|ccc)/; while( $pos < length $string ) { print "Checking $pos\n"; if( substr( $string, $pos, $length ) =~ /$regex/ ) { print "Found $1 at $pos\n"; last; } $pos += $length; } ```
120,082
<p>I have a problem with the design of a <code>VetoableChangeListener</code>. I implement the <code>VetoableChangeListener</code> interface to listen changes of a property in a model class, so when the model fires </p> <pre><code>vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException </code></pre> <p>…I try to save the change in a DB, which could fail (by an <code>SQLException</code>, for example). If it fails I throw a <code>PropertyVetoException</code> to revert changes in the model.</p> <p>The model is delegating in a <code>VetoableChangeSupport</code> (JDK class), which when it receives a <code>PropertyVetoException</code> catches it and notifies the revert to ALL the <code>VetoableChangeListener</code>, with the <code>oldValue</code>/<code>newValue</code> interchanged (later it rethrows the exception), so that the event comes to my class again and I try to save in DB again, etc...</p> <p>I have a workaround which is that the model does NOT change until nobody throws a <code>PropertyVetoException</code>, so that in the <code>VetoableChangeListener</code> I FIRST check if the data I'm going to save in the database is NOT equal to the data in the model, if it's equal I simply ignore the change.</p> <p>Is there another, better workaround?</p>
[ { "answer_id": 120712, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 0, "selected": false, "text": "<p>You should check the Vetoable change before you change the model, not after...</p>\n\n<p>ie: if there is a problem, the model is not changed, not revert the model if the change was wrong</p>\n" }, { "answer_id": 122682, "author": "Telcontar", "author_id": 518, "author_profile": "https://Stackoverflow.com/users/518", "pm_score": 0, "selected": false, "text": "<p>To:timyates</p>\n\n<p>Thats exactly what i do, i recive the event, try to update the DB, and it fails, i throw the exception vetoing the change, so that the model is not updated, but the problem is that the VetoableChangeSupport notifies me my own veto, entering in a bucle if i not do the workaround that i explain in the question</p>\n" }, { "answer_id": 238093, "author": "Joshua DeWald", "author_id": 22752, "author_profile": "https://Stackoverflow.com/users/22752", "pm_score": 1, "selected": false, "text": "<p>Your \"workaround\" is not really a workaround but in fact sounds like the proper solution to me: confirming that there is in fact a change for the current state of the object prior to attempting to \"change\" the persisted version. This will also be much more efficient (database access is expensive). </p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/518/" ]
I have a problem with the design of a `VetoableChangeListener`. I implement the `VetoableChangeListener` interface to listen changes of a property in a model class, so when the model fires ``` vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException ``` …I try to save the change in a DB, which could fail (by an `SQLException`, for example). If it fails I throw a `PropertyVetoException` to revert changes in the model. The model is delegating in a `VetoableChangeSupport` (JDK class), which when it receives a `PropertyVetoException` catches it and notifies the revert to ALL the `VetoableChangeListener`, with the `oldValue`/`newValue` interchanged (later it rethrows the exception), so that the event comes to my class again and I try to save in DB again, etc... I have a workaround which is that the model does NOT change until nobody throws a `PropertyVetoException`, so that in the `VetoableChangeListener` I FIRST check if the data I'm going to save in the database is NOT equal to the data in the model, if it's equal I simply ignore the change. Is there another, better workaround?
Your "workaround" is not really a workaround but in fact sounds like the proper solution to me: confirming that there is in fact a change for the current state of the object prior to attempting to "change" the persisted version. This will also be much more efficient (database access is expensive).
120,083
<p>Is there a way to alter the precision of an existing decimal column in Microsoft SQL Server?</p>
[ { "answer_id": 120821, "author": "VanSkalen", "author_id": 7367, "author_profile": "https://Stackoverflow.com/users/7367", "pm_score": 9, "selected": true, "text": "<pre><code>ALTER TABLE Testing ALTER COLUMN TestDec decimal(16,1)\n</code></pre>\n\n<p>Just put <code>decimal(precision, scale)</code>, replacing the precision and scale with your desired values.</p>\n\n<p>I haven't done any testing with this with data in the table, but if you alter the precision, you would be subject to losing data if the new precision is lower.</p>\n" }, { "answer_id": 22895155, "author": "bnieland", "author_id": 279393, "author_profile": "https://Stackoverflow.com/users/279393", "pm_score": 4, "selected": false, "text": "<p>There may be a better way, but you can always copy the column into a new column, drop it and rename the new column back to the name of the first column.</p>\n\n<p>to wit:</p>\n\n<pre><code>ALTER TABLE MyTable ADD NewColumnName DECIMAL(16, 2);\nGO\n\nUPDATE MyTable\nSET NewColumnName = OldColumnName;\nGO\n\nALTER TABLE CONTRACTS DROP COLUMN OldColumnName;\nGO\n\n\nEXEC sp_rename\n @objname = 'MyTable.NewColumnName',\n @newname = 'OldColumnName',\n @objtype = 'COLUMN'\nGO\n</code></pre>\n\n<p>This was tested on SQL Server 2008 R2, but should work on SQL Server 2000+.</p>\n" }, { "answer_id": 41933919, "author": "H Shah", "author_id": 7489262, "author_profile": "https://Stackoverflow.com/users/7489262", "pm_score": 1, "selected": false, "text": "<pre><code>ALTER TABLE (Your_Table_Name) MODIFY (Your_Column_Name) DATA_TYPE();\n</code></pre>\n\n<p>For you problem: </p>\n\n<pre><code>ALTER TABLE (Your_Table_Name) MODIFY (Your_Column_Name) DECIMAL(Precision, Scale); \n</code></pre>\n" }, { "answer_id": 68805771, "author": "Nilucshan Siva", "author_id": 6459557, "author_profile": "https://Stackoverflow.com/users/6459557", "pm_score": 0, "selected": false, "text": "<p>In Oracle 10G and later following statement will work.</p>\n<p><code>ALTER TABLE &lt;TABLE_NAME&gt; MODIFY &lt;COLUMN_NAME&gt; &lt;DATA_TYPE&gt;</code></p>\n<p>If the current data type is NUMBER(5,2) and you want to change it to NUMBER(10,2), following is the statement</p>\n<p><code>ALTER TABLE &lt;TABLE_NAME&gt; MODIFY &lt;COLUMN_NAME&gt; NUMBER(10,2)</code></p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12767/" ]
Is there a way to alter the precision of an existing decimal column in Microsoft SQL Server?
``` ALTER TABLE Testing ALTER COLUMN TestDec decimal(16,1) ``` Just put `decimal(precision, scale)`, replacing the precision and scale with your desired values. I haven't done any testing with this with data in the table, but if you alter the precision, you would be subject to losing data if the new precision is lower.
120,102
<p>My stored procedure is called as below from an SQL instegartion package within SQL Server 2005</p> <p>EXEC ? = Validation.PopulateFaultsFileDetails ? , 0</p> <p>Though i'm not sure what the ? means</p>
[ { "answer_id": 120115, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 1, "selected": false, "text": "<p>The ? stands fora variable, to be precise, a parameter. The first ? is the return value of the stored prcoedure and the second one is the first parameter of the stored procedure</p>\n" }, { "answer_id": 120231, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 2, "selected": true, "text": "<p>When this SQL statment is called, both question marks (?) will be replaced. The first will be replaced by a variable which will receive the return value of the stored procedure. The second will be replaced by a value which will be passed into the stored procedure. The code to use this statement will look something like this (pseudocode): </p>\n\n<pre><code>dim result\nSQL = \"EXEC ? = Validation.PopulateFaultsFileDetails ? , 0\"\nSQL.execute(result, 99) // pass in 99 to the stored proc\ndebug.print result\n</code></pre>\n\n<p>This gives you 3 advantages: </p>\n\n<ol>\n<li>you can re-use the same bit of SQL with different values </li>\n<li>you can pick up the return value and test for success/error </li>\n<li>if the value you are passing in is a string, it should be correctly escaped for you, reducing the risk of SQL injection vulnerabilities in your app. </li>\n</ol>\n" }, { "answer_id": 120245, "author": "test", "author_id": 21004, "author_profile": "https://Stackoverflow.com/users/21004", "pm_score": 0, "selected": false, "text": "<p>Thanks I appreciate the answer.</p>\n\n<p>I was able to successfully execute the stored procedure using \nDECLARE @FaultsFileName varchar\nDECLARE @FaultsFileID int\nEXEC @FaultsFileID = Validation.PopulateFaultsFileDetails 'SameMonth Test.txt' , @FaultsFileID\nSELECT @FaultsFileID</p>\n\n<p>But when I pass the input parameter as 'SameMonth Test.txt' in the Integration Package I get an error which says: </p>\n\n<p>Parameter names cannot be a mixture of ordinal and named types.\". Possible failure reasons: Problems with the query, \"ResultSet\" property not set correctly, parameters not set correctly, or connection not established correctly.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21004/" ]
My stored procedure is called as below from an SQL instegartion package within SQL Server 2005 EXEC ? = Validation.PopulateFaultsFileDetails ? , 0 Though i'm not sure what the ? means
When this SQL statment is called, both question marks (?) will be replaced. The first will be replaced by a variable which will receive the return value of the stored procedure. The second will be replaced by a value which will be passed into the stored procedure. The code to use this statement will look something like this (pseudocode): ``` dim result SQL = "EXEC ? = Validation.PopulateFaultsFileDetails ? , 0" SQL.execute(result, 99) // pass in 99 to the stored proc debug.print result ``` This gives you 3 advantages: 1. you can re-use the same bit of SQL with different values 2. you can pick up the return value and test for success/error 3. if the value you are passing in is a string, it should be correctly escaped for you, reducing the risk of SQL injection vulnerabilities in your app.
120,114
<p>I am using following PHP code to connect to MS Access database:</p> <pre><code>$odb_conn = new COM("ADODB.Connection"); $connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". $db_path.";"; $odb_conn-&gt;open($connstr); </code></pre> <p>How can I retrieve database catalog/metadata from the mdb file?</p> <p><strong>FOUND THE SOLUTION</strong></p> <pre><code>$rs_meta = $odb_conn-&gt;OpenSchema(20, array(Null, Null, Null, "TABLE")); </code></pre>
[ { "answer_id": 120195, "author": "Abbas", "author_id": 4714, "author_profile": "https://Stackoverflow.com/users/4714", "pm_score": 0, "selected": false, "text": "<p>The <code>MSysObjects</code> table can be used to query metadata in Access:</p>\n\n<pre><code>SELECT NAME\nFROM MSysObjects\nWHERE Type In (1,4,6) AND Left([Name],4)&lt;&gt;\"MSYS\"\n</code></pre>\n" }, { "answer_id": 120500, "author": "Michel", "author_id": 17316, "author_profile": "https://Stackoverflow.com/users/17316", "pm_score": 3, "selected": true, "text": "<p>You will find information on ADO here : </p>\n\n<ul>\n<li><p><a href=\"http://msdn.microsoft.com/en-us/library/ms675532(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms675532(VS.85).aspx</a></p></li>\n<li><p><a href=\"http://www.w3schools.com/ado/default.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/ado/default.asp</a></p></li>\n</ul>\n\n<p>The connection object has an OpenSchema method to get database schema information.</p>\n\n<p>I don't know how to use MS Acces DB with PHP and how your new COM() object works, but I think it's better to use an OleDB connection instead an ADO object : <a href=\"http://msdn.microsoft.com/en-us/library/ms722784(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms722784(VS.85).aspx</a></p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6561/" ]
I am using following PHP code to connect to MS Access database: ``` $odb_conn = new COM("ADODB.Connection"); $connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". $db_path.";"; $odb_conn->open($connstr); ``` How can I retrieve database catalog/metadata from the mdb file? **FOUND THE SOLUTION** ``` $rs_meta = $odb_conn->OpenSchema(20, array(Null, Null, Null, "TABLE")); ```
You will find information on ADO here : * <http://msdn.microsoft.com/en-us/library/ms675532(VS.85).aspx> * <http://www.w3schools.com/ado/default.asp> The connection object has an OpenSchema method to get database schema information. I don't know how to use MS Acces DB with PHP and how your new COM() object works, but I think it's better to use an OleDB connection instead an ADO object : <http://msdn.microsoft.com/en-us/library/ms722784(VS.85).aspx>
120,170
<p>I'm doing some testing on Firefox toolbars for the sake of learning and I can't find out any information on how to store the contents of a "search" drop-down inside the user's profile.</p> <p>Is there any tutorial on how to sort this out?</p>
[ { "answer_id": 121358, "author": "Gustavo Carreno", "author_id": 8167, "author_profile": "https://Stackoverflow.com/users/8167", "pm_score": 2, "selected": true, "text": "<p>Since it's taking quite a bit to get an answer I went and investigate it myself.\nHere is what I've got now. Not all is clear to me but it works.</p>\n\n<p>Let's assume you have a &lt;textbox&gt; like this, on your .xul:</p>\n\n<pre><code>&lt;textbox id=\"search_with_history\" /&gt;\n</code></pre>\n\n<p>You now have to add some other attributes to enable history.</p>\n\n<pre><code>&lt;textbox id=\"search_with_history\" type=\"autocomplete\"\n autocompletesearch=\"form-history\"\n autocompletesearchparam=\"Search-History-Name\"\n ontextentered=\"Search_Change(param);\"\n enablehistory=\"true\"\n /&gt;\n</code></pre>\n\n<p>This gives you the minimum to enable a history on that textbox.<br/>\nFor some reason, and here is where my ignorance shows, the onTextEntered event function has to have the param to it called \"param\". I tried \"event\" and it didn't work.<br/>\nBut that alone will not do work by itself. One has to add some Javascript to help with the job.</p>\n\n<pre><code>// This is the interface to store the history\nconst HistoryObject = Components.classes[\"@mozilla.org/satchel/form-history;1\"]\n .getService(\n Components.interfaces.nsIFormHistory2 || Components.interfaces.nsIFormHistory\n );\n// The above line was broken into 4 for clearness.\n// If you encounter problems please use only one line.\n\n// This function is the one called upon the event of pressing &lt;enter&gt;\n// on the text box\nfunction Search_Change(event) {\n var terms = document.getElementById('search_with_history').value;\n HistoryObject.addEntry('Search-History-Name', terms);\n}\n</code></pre>\n\n<p>This is the absolute minimum to get a history going on.</p>\n" }, { "answer_id": 247995, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Gustavo,\nI wanted to do the same thing - I found an answer <a href=\"http://support.mozilla.com/tiki-view_forum_thread.php?locale=sk&amp;comments_parentId=193208&amp;forumId=1\" rel=\"nofollow noreferrer\">here</a> on the Mozilla support forums. (Edit: I wanted to save my search history out of interest, not because I wanted to learn how the Firefox toolbars work, as you said.)</p>\n\n<p>Basically, that data is stored in a sqlite database file called formhistory.sqlite (in your Firefox profile directory). You can use the Firefox extension SQLite Manager to retrieve and export the data: <a href=\"https://addons.mozilla.org/firefox/addon/5817\" rel=\"nofollow noreferrer\">https://addons.mozilla.org/firefox/addon/5817</a></p>\n\n<p>You can export it as a CSV (comma- separated values) file and open it with Excel or other software.</p>\n\n<p>This has the added benefit of also saving the history of data you've entered into other forms/fields on sites, such as the Search field on Google, etc, if this data is of interest to you.</p>\n" }, { "answer_id": 429613, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Gustavo's solution is good, but <em>document.getElemenById('search_with_history').value;</em> is missing a 't' in getElementById</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8167/" ]
I'm doing some testing on Firefox toolbars for the sake of learning and I can't find out any information on how to store the contents of a "search" drop-down inside the user's profile. Is there any tutorial on how to sort this out?
Since it's taking quite a bit to get an answer I went and investigate it myself. Here is what I've got now. Not all is clear to me but it works. Let's assume you have a <textbox> like this, on your .xul: ``` <textbox id="search_with_history" /> ``` You now have to add some other attributes to enable history. ``` <textbox id="search_with_history" type="autocomplete" autocompletesearch="form-history" autocompletesearchparam="Search-History-Name" ontextentered="Search_Change(param);" enablehistory="true" /> ``` This gives you the minimum to enable a history on that textbox. For some reason, and here is where my ignorance shows, the onTextEntered event function has to have the param to it called "param". I tried "event" and it didn't work. But that alone will not do work by itself. One has to add some Javascript to help with the job. ``` // This is the interface to store the history const HistoryObject = Components.classes["@mozilla.org/satchel/form-history;1"] .getService( Components.interfaces.nsIFormHistory2 || Components.interfaces.nsIFormHistory ); // The above line was broken into 4 for clearness. // If you encounter problems please use only one line. // This function is the one called upon the event of pressing <enter> // on the text box function Search_Change(event) { var terms = document.getElementById('search_with_history').value; HistoryObject.addEntry('Search-History-Name', terms); } ``` This is the absolute minimum to get a history going on.
120,180
<p>I'm looking for a way to do query auto-completion/suggestions in Lucene. I've Googled around a bit and played around a bit, but all of the examples I've seen seem to be setting up filters in Solr. We don't use Solr and aren't planning to move to using Solr in the near future, and Solr is obviously just wrapping around Lucene anyway, so I imagine there must be a way to do it!</p> <p>I've looked into using EdgeNGramFilter, and I realise that I'd have to run the filter on the index fields and get the tokens out and then compare them against the inputted Query... I'm just struggling to make the connection between the two into a bit of code, so help is much appreciated!</p> <p>To be clear on what I'm looking for (I realised I wasn't being overly clear, sorry) - I'm looking for a solution where when searching for a term, it'd return a list of suggested queries. When typing 'inter' into the search field, it'll come back with a list of suggested queries, such as 'internet', 'international', etc.</p>
[ { "answer_id": 120430, "author": "Alexandre Victoor", "author_id": 11897, "author_profile": "https://Stackoverflow.com/users/11897", "pm_score": 2, "selected": false, "text": "<p>You can use the class <strong>PrefixQuery</strong> on a \"dictionary\" index. The class <strong>LuceneDictionary</strong> could be helpful too.</p>\n\n<p>Take a look at this article linked below. It explains how to implement the feature \"Did you mean ?\" available in modern search engine such as Google. You may not need something as complex as described in the article. However the article explains how to use the Lucene spell package.</p>\n\n<p>One way to build a \"dictionary\" index would be to iterate on a LuceneDictionary.</p>\n\n<p>Hope it helps</p>\n\n<p><a href=\"https://web.archive.org/web/20050811022737/http://today.java.net/pub/a/today/2005/08/09/didyoumean.html\" rel=\"nofollow noreferrer\">Did You Mean: Lucene? (page 1)</a></p>\n\n<p><a href=\"https://web.archive.org/web/20061103220620/http://today.java.net/pub/a/today/2005/08/09/didyoumean.html%3Fpage%3D2\" rel=\"nofollow noreferrer\">Did You Mean: Lucene? (page 2)</a></p>\n\n<p><a href=\"https://web.archive.org/web/20061103220620/http://today.java.net/pub/a/today/2005/08/09/didyoumean.html%3Fpage%3D3\" rel=\"nofollow noreferrer\">Did You Mean: Lucene? (page 3)</a></p>\n" }, { "answer_id": 121456, "author": "Mat Mannion", "author_id": 6282, "author_profile": "https://Stackoverflow.com/users/6282", "pm_score": 6, "selected": true, "text": "<p>Based on @Alexandre Victoor's answer, I wrote a little class based on the Lucene Spellchecker in the contrib package (and using the LuceneDictionary included in it) that does exactly what I want.</p>\n\n<p>This allows re-indexing from a single source index with a single field, and provides suggestions for terms. Results are sorted by the number of matching documents with that term in the original index, so more popular terms appear first. Seems to work pretty well :)</p>\n\n<pre><code>import java.io.IOException;\nimport java.io.Reader;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.lucene.analysis.Analyzer;\nimport org.apache.lucene.analysis.ISOLatin1AccentFilter;\nimport org.apache.lucene.analysis.LowerCaseFilter;\nimport org.apache.lucene.analysis.StopFilter;\nimport org.apache.lucene.analysis.TokenStream;\nimport org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter;\nimport org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter.Side;\nimport org.apache.lucene.analysis.standard.StandardFilter;\nimport org.apache.lucene.analysis.standard.StandardTokenizer;\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.document.Field;\nimport org.apache.lucene.index.CorruptIndexException;\nimport org.apache.lucene.index.IndexReader;\nimport org.apache.lucene.index.IndexWriter;\nimport org.apache.lucene.index.Term;\nimport org.apache.lucene.search.IndexSearcher;\nimport org.apache.lucene.search.Query;\nimport org.apache.lucene.search.ScoreDoc;\nimport org.apache.lucene.search.Sort;\nimport org.apache.lucene.search.TermQuery;\nimport org.apache.lucene.search.TopDocs;\nimport org.apache.lucene.search.spell.LuceneDictionary;\nimport org.apache.lucene.store.Directory;\nimport org.apache.lucene.store.FSDirectory;\n\n/**\n * Search term auto-completer, works for single terms (so use on the last term\n * of the query).\n * &lt;p&gt;\n * Returns more popular terms first.\n * \n * @author Mat Mannion, [email protected]\n */\npublic final class Autocompleter {\n\n private static final String GRAMMED_WORDS_FIELD = \"words\";\n\n private static final String SOURCE_WORD_FIELD = \"sourceWord\";\n\n private static final String COUNT_FIELD = \"count\";\n\n private static final String[] ENGLISH_STOP_WORDS = {\n \"a\", \"an\", \"and\", \"are\", \"as\", \"at\", \"be\", \"but\", \"by\",\n \"for\", \"i\", \"if\", \"in\", \"into\", \"is\",\n \"no\", \"not\", \"of\", \"on\", \"or\", \"s\", \"such\",\n \"t\", \"that\", \"the\", \"their\", \"then\", \"there\", \"these\",\n \"they\", \"this\", \"to\", \"was\", \"will\", \"with\"\n };\n\n private final Directory autoCompleteDirectory;\n\n private IndexReader autoCompleteReader;\n\n private IndexSearcher autoCompleteSearcher;\n\n public Autocompleter(String autoCompleteDir) throws IOException {\n this.autoCompleteDirectory = FSDirectory.getDirectory(autoCompleteDir,\n null);\n\n reOpenReader();\n }\n\n public List&lt;String&gt; suggestTermsFor(String term) throws IOException {\n // get the top 5 terms for query\n Query query = new TermQuery(new Term(GRAMMED_WORDS_FIELD, term));\n Sort sort = new Sort(COUNT_FIELD, true);\n\n TopDocs docs = autoCompleteSearcher.search(query, null, 5, sort);\n List&lt;String&gt; suggestions = new ArrayList&lt;String&gt;();\n for (ScoreDoc doc : docs.scoreDocs) {\n suggestions.add(autoCompleteReader.document(doc.doc).get(\n SOURCE_WORD_FIELD));\n }\n\n return suggestions;\n }\n\n @SuppressWarnings(\"unchecked\")\n public void reIndex(Directory sourceDirectory, String fieldToAutocomplete)\n throws CorruptIndexException, IOException {\n // build a dictionary (from the spell package)\n IndexReader sourceReader = IndexReader.open(sourceDirectory);\n\n LuceneDictionary dict = new LuceneDictionary(sourceReader,\n fieldToAutocomplete);\n\n // code from\n // org.apache.lucene.search.spell.SpellChecker.indexDictionary(\n // Dictionary)\n IndexReader.unlock(autoCompleteDirectory);\n\n // use a custom analyzer so we can do EdgeNGramFiltering\n IndexWriter writer = new IndexWriter(autoCompleteDirectory,\n new Analyzer() {\n public TokenStream tokenStream(String fieldName,\n Reader reader) {\n TokenStream result = new StandardTokenizer(reader);\n\n result = new StandardFilter(result);\n result = new LowerCaseFilter(result);\n result = new ISOLatin1AccentFilter(result);\n result = new StopFilter(result,\n ENGLISH_STOP_WORDS);\n result = new EdgeNGramTokenFilter(\n result, Side.FRONT,1, 20);\n\n return result;\n }\n }, true);\n\n writer.setMergeFactor(300);\n writer.setMaxBufferedDocs(150);\n\n // go through every word, storing the original word (incl. n-grams) \n // and the number of times it occurs\n Map&lt;String, Integer&gt; wordsMap = new HashMap&lt;String, Integer&gt;();\n\n Iterator&lt;String&gt; iter = (Iterator&lt;String&gt;) dict.getWordsIterator();\n while (iter.hasNext()) {\n String word = iter.next();\n\n int len = word.length();\n if (len &lt; 3) {\n continue; // too short we bail but \"too long\" is fine...\n }\n\n if (wordsMap.containsKey(word)) {\n throw new IllegalStateException(\n \"This should never happen in Lucene 2.3.2\");\n // wordsMap.put(word, wordsMap.get(word) + 1);\n } else {\n // use the number of documents this word appears in\n wordsMap.put(word, sourceReader.docFreq(new Term(\n fieldToAutocomplete, word)));\n }\n }\n\n for (String word : wordsMap.keySet()) {\n // ok index the word\n Document doc = new Document();\n doc.add(new Field(SOURCE_WORD_FIELD, word, Field.Store.YES,\n Field.Index.UN_TOKENIZED)); // orig term\n doc.add(new Field(GRAMMED_WORDS_FIELD, word, Field.Store.YES,\n Field.Index.TOKENIZED)); // grammed\n doc.add(new Field(COUNT_FIELD,\n Integer.toString(wordsMap.get(word)), Field.Store.NO,\n Field.Index.UN_TOKENIZED)); // count\n\n writer.addDocument(doc);\n }\n\n sourceReader.close();\n\n // close writer\n writer.optimize();\n writer.close();\n\n // re-open our reader\n reOpenReader();\n }\n\n private void reOpenReader() throws CorruptIndexException, IOException {\n if (autoCompleteReader == null) {\n autoCompleteReader = IndexReader.open(autoCompleteDirectory);\n } else {\n autoCompleteReader.reopen();\n }\n\n autoCompleteSearcher = new IndexSearcher(autoCompleteReader);\n }\n\n public static void main(String[] args) throws Exception {\n Autocompleter autocomplete = new Autocompleter(\"/index/autocomplete\");\n\n // run this to re-index from the current index, shouldn't need to do\n // this very often\n // autocomplete.reIndex(FSDirectory.getDirectory(\"/index/live\", null),\n // \"content\");\n\n String term = \"steve\";\n\n System.out.println(autocomplete.suggestTermsFor(term));\n // prints [steve, steven, stevens, stevenson, stevenage]\n }\n\n}\n</code></pre>\n" }, { "answer_id": 9183416, "author": "ThisIsTheDave", "author_id": 70578, "author_profile": "https://Stackoverflow.com/users/70578", "pm_score": 5, "selected": false, "text": "<p>Here's a transliteration of Mat's implementation into C# for Lucene.NET, along with a snippet for wiring a text box using jQuery's autocomplete feature.</p>\n\n<pre><code>&lt;input id=\"search-input\" name=\"query\" placeholder=\"Search database.\" type=\"text\" /&gt;\n</code></pre>\n\n<p>... JQuery Autocomplete:</p>\n\n<pre><code>// don't navigate away from the field when pressing tab on a selected item\n$( \"#search-input\" ).keydown(function (event) {\n if (event.keyCode === $.ui.keyCode.TAB &amp;&amp; $(this).data(\"autocomplete\").menu.active) {\n event.preventDefault();\n }\n});\n\n$( \"#search-input\" ).autocomplete({\n source: '@Url.Action(\"SuggestTerms\")', // &lt;-- ASP.NET MVC Razor syntax\n minLength: 2,\n delay: 500,\n focus: function () {\n // prevent value inserted on focus\n return false;\n },\n select: function (event, ui) {\n var terms = this.value.split(/\\s+/);\n terms.pop(); // remove dropdown item\n terms.push(ui.item.value.trim()); // add completed item\n this.value = terms.join(\" \"); \n return false;\n },\n });\n</code></pre>\n\n<p>... here's the ASP.NET MVC Controller code:</p>\n\n<pre><code> //\n // GET: /MyApp/SuggestTerms?term=something\n public JsonResult SuggestTerms(string term)\n {\n if (string.IsNullOrWhiteSpace(term))\n return Json(new string[] {});\n\n term = term.Split().Last();\n\n // Fetch suggestions\n string[] suggestions = SearchSvc.SuggestTermsFor(term).ToArray();\n\n return Json(suggestions, JsonRequestBehavior.AllowGet);\n }\n</code></pre>\n\n<p>... and here's Mat's code in C#:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Lucene.Net.Store;\nusing Lucene.Net.Index;\nusing Lucene.Net.Search;\nusing SpellChecker.Net.Search.Spell;\nusing Lucene.Net.Analysis;\nusing Lucene.Net.Analysis.Standard;\nusing Lucene.Net.Analysis.NGram;\nusing Lucene.Net.Documents;\n\nnamespace Cipher.Services\n{\n /// &lt;summary&gt;\n /// Search term auto-completer, works for single terms (so use on the last term of the query).\n /// Returns more popular terms first.\n /// &lt;br/&gt;\n /// Author: Mat Mannion, [email protected]\n /// &lt;seealso cref=\"http://stackoverflow.com/questions/120180/how-to-do-query-auto-completion-suggestions-in-lucene\"/&gt;\n /// &lt;/summary&gt;\n /// \n public class SearchAutoComplete {\n\n public int MaxResults { get; set; }\n\n private class AutoCompleteAnalyzer : Analyzer\n {\n public override TokenStream TokenStream(string fieldName, System.IO.TextReader reader)\n {\n TokenStream result = new StandardTokenizer(kLuceneVersion, reader);\n\n result = new StandardFilter(result);\n result = new LowerCaseFilter(result);\n result = new ASCIIFoldingFilter(result);\n result = new StopFilter(false, result, StopFilter.MakeStopSet(kEnglishStopWords));\n result = new EdgeNGramTokenFilter(\n result, Lucene.Net.Analysis.NGram.EdgeNGramTokenFilter.DEFAULT_SIDE,1, 20);\n\n return result;\n }\n }\n\n private static readonly Lucene.Net.Util.Version kLuceneVersion = Lucene.Net.Util.Version.LUCENE_29;\n\n private static readonly String kGrammedWordsField = \"words\";\n\n private static readonly String kSourceWordField = \"sourceWord\";\n\n private static readonly String kCountField = \"count\";\n\n private static readonly String[] kEnglishStopWords = {\n \"a\", \"an\", \"and\", \"are\", \"as\", \"at\", \"be\", \"but\", \"by\",\n \"for\", \"i\", \"if\", \"in\", \"into\", \"is\",\n \"no\", \"not\", \"of\", \"on\", \"or\", \"s\", \"such\",\n \"t\", \"that\", \"the\", \"their\", \"then\", \"there\", \"these\",\n \"they\", \"this\", \"to\", \"was\", \"will\", \"with\"\n };\n\n private readonly Directory m_directory;\n\n private IndexReader m_reader;\n\n private IndexSearcher m_searcher;\n\n public SearchAutoComplete(string autoCompleteDir) : \n this(FSDirectory.Open(new System.IO.DirectoryInfo(autoCompleteDir)))\n {\n }\n\n public SearchAutoComplete(Directory autoCompleteDir, int maxResults = 8) \n {\n this.m_directory = autoCompleteDir;\n MaxResults = maxResults;\n\n ReplaceSearcher();\n }\n\n /// &lt;summary&gt;\n /// Find terms matching the given partial word that appear in the highest number of documents.&lt;/summary&gt;\n /// &lt;param name=\"term\"&gt;A word or part of a word&lt;/param&gt;\n /// &lt;returns&gt;A list of suggested completions&lt;/returns&gt;\n public IEnumerable&lt;String&gt; SuggestTermsFor(string term) \n {\n if (m_searcher == null)\n return new string[] { };\n\n // get the top terms for query\n Query query = new TermQuery(new Term(kGrammedWordsField, term.ToLower()));\n Sort sort = new Sort(new SortField(kCountField, SortField.INT));\n\n TopDocs docs = m_searcher.Search(query, null, MaxResults, sort);\n string[] suggestions = docs.ScoreDocs.Select(doc =&gt; \n m_reader.Document(doc.Doc).Get(kSourceWordField)).ToArray();\n\n return suggestions;\n }\n\n\n /// &lt;summary&gt;\n /// Open the index in the given directory and create a new index of word frequency for the \n /// given index.&lt;/summary&gt;\n /// &lt;param name=\"sourceDirectory\"&gt;Directory containing the index to count words in.&lt;/param&gt;\n /// &lt;param name=\"fieldToAutocomplete\"&gt;The field in the index that should be analyzed.&lt;/param&gt;\n public void BuildAutoCompleteIndex(Directory sourceDirectory, String fieldToAutocomplete)\n {\n // build a dictionary (from the spell package)\n using (IndexReader sourceReader = IndexReader.Open(sourceDirectory, true))\n {\n LuceneDictionary dict = new LuceneDictionary(sourceReader, fieldToAutocomplete);\n\n // code from\n // org.apache.lucene.search.spell.SpellChecker.indexDictionary(\n // Dictionary)\n //IndexWriter.Unlock(m_directory);\n\n // use a custom analyzer so we can do EdgeNGramFiltering\n var analyzer = new AutoCompleteAnalyzer();\n using (var writer = new IndexWriter(m_directory, analyzer, true, IndexWriter.MaxFieldLength.LIMITED))\n {\n writer.MergeFactor = 300;\n writer.SetMaxBufferedDocs(150);\n\n // go through every word, storing the original word (incl. n-grams) \n // and the number of times it occurs\n foreach (string word in dict)\n {\n if (word.Length &lt; 3)\n continue; // too short we bail but \"too long\" is fine...\n\n // ok index the word\n // use the number of documents this word appears in\n int freq = sourceReader.DocFreq(new Term(fieldToAutocomplete, word));\n var doc = MakeDocument(fieldToAutocomplete, word, freq);\n\n writer.AddDocument(doc);\n }\n\n writer.Optimize();\n }\n\n }\n\n // re-open our reader\n ReplaceSearcher();\n }\n\n private static Document MakeDocument(String fieldToAutocomplete, string word, int frequency)\n {\n var doc = new Document();\n doc.Add(new Field(kSourceWordField, word, Field.Store.YES,\n Field.Index.NOT_ANALYZED)); // orig term\n doc.Add(new Field(kGrammedWordsField, word, Field.Store.YES,\n Field.Index.ANALYZED)); // grammed\n doc.Add(new Field(kCountField,\n frequency.ToString(), Field.Store.NO,\n Field.Index.NOT_ANALYZED)); // count\n return doc;\n }\n\n private void ReplaceSearcher() \n {\n if (IndexReader.IndexExists(m_directory))\n {\n if (m_reader == null)\n m_reader = IndexReader.Open(m_directory, true);\n else\n m_reader.Reopen();\n\n m_searcher = new IndexSearcher(m_reader);\n }\n else\n {\n m_searcher = null;\n }\n }\n\n\n }\n}\n</code></pre>\n" }, { "answer_id": 11435645, "author": "megawatts", "author_id": 1037199, "author_profile": "https://Stackoverflow.com/users/1037199", "pm_score": 2, "selected": false, "text": "<p>In addition to the above (much appreciated) post re: c# conversion, should you be using .NET 3.5 you'll need to include the code for the EdgeNGramTokenFilter - or at least I did - using Lucene 2.9.2 - this filter is missing from the .NET version as far as I could tell. I had to go and find the .NET 4 version online in 2.9.3 and port back - hope this makes the procedure less painful for someone...</p>\n\n<p>Edit : Please also note that the array returned by the SuggestTermsFor() function is sorted by count ascending, you'll probably want to reverse it to get the most popular terms first in your list</p>\n\n<pre><code>using System.IO;\nusing System.Collections;\nusing Lucene.Net.Analysis;\nusing Lucene.Net.Analysis.Tokenattributes;\nusing Lucene.Net.Util;\n\nnamespace Lucene.Net.Analysis.NGram\n{\n\n/**\n * Tokenizes the given token into n-grams of given size(s).\n * &lt;p&gt;\n * This {@link TokenFilter} create n-grams from the beginning edge or ending edge of a input token.\n * &lt;/p&gt;\n */\npublic class EdgeNGramTokenFilter : TokenFilter\n{\n public static Side DEFAULT_SIDE = Side.FRONT;\n public static int DEFAULT_MAX_GRAM_SIZE = 1;\n public static int DEFAULT_MIN_GRAM_SIZE = 1;\n\n // Replace this with an enum when the Java 1.5 upgrade is made, the impl will be simplified\n /** Specifies which side of the input the n-gram should be generated from */\n public class Side\n {\n private string label;\n\n /** Get the n-gram from the front of the input */\n public static Side FRONT = new Side(\"front\");\n\n /** Get the n-gram from the end of the input */\n public static Side BACK = new Side(\"back\");\n\n // Private ctor\n private Side(string label) { this.label = label; }\n\n public string getLabel() { return label; }\n\n // Get the appropriate Side from a string\n public static Side getSide(string sideName)\n {\n if (FRONT.getLabel().Equals(sideName))\n {\n return FRONT;\n }\n else if (BACK.getLabel().Equals(sideName))\n {\n return BACK;\n }\n return null;\n }\n }\n\n private int minGram;\n private int maxGram;\n private Side side;\n private char[] curTermBuffer;\n private int curTermLength;\n private int curGramSize;\n private int tokStart;\n\n private TermAttribute termAtt;\n private OffsetAttribute offsetAtt;\n\n protected EdgeNGramTokenFilter(TokenStream input) : base(input)\n {\n this.termAtt = (TermAttribute)AddAttribute(typeof(TermAttribute));\n this.offsetAtt = (OffsetAttribute)AddAttribute(typeof(OffsetAttribute));\n }\n\n /**\n * Creates EdgeNGramTokenFilter that can generate n-grams in the sizes of the given range\n *\n * @param input {@link TokenStream} holding the input to be tokenized\n * @param side the {@link Side} from which to chop off an n-gram\n * @param minGram the smallest n-gram to generate\n * @param maxGram the largest n-gram to generate\n */\n public EdgeNGramTokenFilter(TokenStream input, Side side, int minGram, int maxGram)\n : base(input)\n {\n\n if (side == null)\n {\n throw new System.ArgumentException(\"sideLabel must be either front or back\");\n }\n\n if (minGram &lt; 1)\n {\n throw new System.ArgumentException(\"minGram must be greater than zero\");\n }\n\n if (minGram &gt; maxGram)\n {\n throw new System.ArgumentException(\"minGram must not be greater than maxGram\");\n }\n\n this.minGram = minGram;\n this.maxGram = maxGram;\n this.side = side;\n this.termAtt = (TermAttribute)AddAttribute(typeof(TermAttribute));\n this.offsetAtt = (OffsetAttribute)AddAttribute(typeof(OffsetAttribute));\n }\n\n /**\n * Creates EdgeNGramTokenFilter that can generate n-grams in the sizes of the given range\n *\n * @param input {@link TokenStream} holding the input to be tokenized\n * @param sideLabel the name of the {@link Side} from which to chop off an n-gram\n * @param minGram the smallest n-gram to generate\n * @param maxGram the largest n-gram to generate\n */\n public EdgeNGramTokenFilter(TokenStream input, string sideLabel, int minGram, int maxGram)\n : this(input, Side.getSide(sideLabel), minGram, maxGram)\n {\n\n }\n\n public override bool IncrementToken()\n {\n while (true)\n {\n if (curTermBuffer == null)\n {\n if (!input.IncrementToken())\n {\n return false;\n }\n else\n {\n curTermBuffer = (char[])termAtt.TermBuffer().Clone();\n curTermLength = termAtt.TermLength();\n curGramSize = minGram;\n tokStart = offsetAtt.StartOffset();\n }\n }\n if (curGramSize &lt;= maxGram)\n {\n if (!(curGramSize &gt; curTermLength // if the remaining input is too short, we can't generate any n-grams\n || curGramSize &gt; maxGram))\n { // if we have hit the end of our n-gram size range, quit\n // grab gramSize chars from front or back\n int start = side == Side.FRONT ? 0 : curTermLength - curGramSize;\n int end = start + curGramSize;\n ClearAttributes();\n offsetAtt.SetOffset(tokStart + start, tokStart + end);\n termAtt.SetTermBuffer(curTermBuffer, start, curGramSize);\n curGramSize++;\n return true;\n }\n }\n curTermBuffer = null;\n }\n }\n\n public override Token Next(Token reusableToken)\n {\n return base.Next(reusableToken);\n }\n public override Token Next()\n {\n return base.Next();\n }\n public override void Reset()\n {\n base.Reset();\n curTermBuffer = null;\n }\n}\n}\n</code></pre>\n" }, { "answer_id": 20209880, "author": "user2098849", "author_id": 2098849, "author_profile": "https://Stackoverflow.com/users/2098849", "pm_score": 3, "selected": false, "text": "<p>my code based on lucene 4.2,may help you</p>\n\n<pre><code>import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;\nimport org.apache.lucene.index.DirectoryReader;\nimport org.apache.lucene.index.IndexWriterConfig;\nimport org.apache.lucene.index.IndexWriterConfig.OpenMode;\nimport org.apache.lucene.search.spell.Dictionary;\nimport org.apache.lucene.search.spell.LuceneDictionary;\nimport org.apache.lucene.search.spell.PlainTextDictionary;\nimport org.apache.lucene.search.spell.SpellChecker;\nimport org.apache.lucene.store.Directory;\nimport org.apache.lucene.store.FSDirectory;\nimport org.apache.lucene.store.IOContext;\nimport org.apache.lucene.store.RAMDirectory;\nimport org.apache.lucene.util.Version;\nimport org.wltea4pinyin.analyzer.lucene.IKAnalyzer4PinYin;\n\n\n/**\n * \n * \n * @author &lt;a href=\"mailto:[email protected]\"&gt;&lt;/a&gt;\n * @version 2013-11-25上午11:13:59\n */\npublic class LuceneSpellCheckerDemoService {\n\nprivate static final String INDEX_FILE = \"/Users/r/Documents/jar/luke/youtui/index\";\nprivate static final String INDEX_FILE_SPELL = \"/Users/r/Documents/jar/luke/spell\";\n\nprivate static final String INDEX_FIELD = \"app_name_quanpin\";\n\npublic static void main(String args[]) {\n\n try {\n //\n PerFieldAnalyzerWrapper wrapper = new PerFieldAnalyzerWrapper(new IKAnalyzer4PinYin(\n true));\n\n // read index conf\n IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_42, wrapper);\n conf.setOpenMode(OpenMode.CREATE_OR_APPEND);\n\n // read dictionary\n Directory directory = FSDirectory.open(new File(INDEX_FILE));\n RAMDirectory ramDir = new RAMDirectory(directory, IOContext.READ);\n DirectoryReader indexReader = DirectoryReader.open(ramDir);\n\n Dictionary dic = new LuceneDictionary(indexReader, INDEX_FIELD);\n\n\n SpellChecker sc = new SpellChecker(FSDirectory.open(new File(INDEX_FILE_SPELL)));\n //sc.indexDictionary(new PlainTextDictionary(new File(\"myfile.txt\")), conf, false);\n sc.indexDictionary(dic, conf, true);\n String[] strs = sc.suggestSimilar(\"zhsiwusdazhanjiangshi\", 10);\n for (int i = 0; i &lt; strs.length; i++) {\n System.out.println(strs[i]);\n }\n sc.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n}\n\n\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6282/" ]
I'm looking for a way to do query auto-completion/suggestions in Lucene. I've Googled around a bit and played around a bit, but all of the examples I've seen seem to be setting up filters in Solr. We don't use Solr and aren't planning to move to using Solr in the near future, and Solr is obviously just wrapping around Lucene anyway, so I imagine there must be a way to do it! I've looked into using EdgeNGramFilter, and I realise that I'd have to run the filter on the index fields and get the tokens out and then compare them against the inputted Query... I'm just struggling to make the connection between the two into a bit of code, so help is much appreciated! To be clear on what I'm looking for (I realised I wasn't being overly clear, sorry) - I'm looking for a solution where when searching for a term, it'd return a list of suggested queries. When typing 'inter' into the search field, it'll come back with a list of suggested queries, such as 'internet', 'international', etc.
Based on @Alexandre Victoor's answer, I wrote a little class based on the Lucene Spellchecker in the contrib package (and using the LuceneDictionary included in it) that does exactly what I want. This allows re-indexing from a single source index with a single field, and provides suggestions for terms. Results are sorted by the number of matching documents with that term in the original index, so more popular terms appear first. Seems to work pretty well :) ``` import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.ISOLatin1AccentFilter; import org.apache.lucene.analysis.LowerCaseFilter; import org.apache.lucene.analysis.StopFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter; import org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter.Side; import org.apache.lucene.analysis.standard.StandardFilter; import org.apache.lucene.analysis.standard.StandardTokenizer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.spell.LuceneDictionary; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; /** * Search term auto-completer, works for single terms (so use on the last term * of the query). * <p> * Returns more popular terms first. * * @author Mat Mannion, [email protected] */ public final class Autocompleter { private static final String GRAMMED_WORDS_FIELD = "words"; private static final String SOURCE_WORD_FIELD = "sourceWord"; private static final String COUNT_FIELD = "count"; private static final String[] ENGLISH_STOP_WORDS = { "a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "i", "if", "in", "into", "is", "no", "not", "of", "on", "or", "s", "such", "t", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with" }; private final Directory autoCompleteDirectory; private IndexReader autoCompleteReader; private IndexSearcher autoCompleteSearcher; public Autocompleter(String autoCompleteDir) throws IOException { this.autoCompleteDirectory = FSDirectory.getDirectory(autoCompleteDir, null); reOpenReader(); } public List<String> suggestTermsFor(String term) throws IOException { // get the top 5 terms for query Query query = new TermQuery(new Term(GRAMMED_WORDS_FIELD, term)); Sort sort = new Sort(COUNT_FIELD, true); TopDocs docs = autoCompleteSearcher.search(query, null, 5, sort); List<String> suggestions = new ArrayList<String>(); for (ScoreDoc doc : docs.scoreDocs) { suggestions.add(autoCompleteReader.document(doc.doc).get( SOURCE_WORD_FIELD)); } return suggestions; } @SuppressWarnings("unchecked") public void reIndex(Directory sourceDirectory, String fieldToAutocomplete) throws CorruptIndexException, IOException { // build a dictionary (from the spell package) IndexReader sourceReader = IndexReader.open(sourceDirectory); LuceneDictionary dict = new LuceneDictionary(sourceReader, fieldToAutocomplete); // code from // org.apache.lucene.search.spell.SpellChecker.indexDictionary( // Dictionary) IndexReader.unlock(autoCompleteDirectory); // use a custom analyzer so we can do EdgeNGramFiltering IndexWriter writer = new IndexWriter(autoCompleteDirectory, new Analyzer() { public TokenStream tokenStream(String fieldName, Reader reader) { TokenStream result = new StandardTokenizer(reader); result = new StandardFilter(result); result = new LowerCaseFilter(result); result = new ISOLatin1AccentFilter(result); result = new StopFilter(result, ENGLISH_STOP_WORDS); result = new EdgeNGramTokenFilter( result, Side.FRONT,1, 20); return result; } }, true); writer.setMergeFactor(300); writer.setMaxBufferedDocs(150); // go through every word, storing the original word (incl. n-grams) // and the number of times it occurs Map<String, Integer> wordsMap = new HashMap<String, Integer>(); Iterator<String> iter = (Iterator<String>) dict.getWordsIterator(); while (iter.hasNext()) { String word = iter.next(); int len = word.length(); if (len < 3) { continue; // too short we bail but "too long" is fine... } if (wordsMap.containsKey(word)) { throw new IllegalStateException( "This should never happen in Lucene 2.3.2"); // wordsMap.put(word, wordsMap.get(word) + 1); } else { // use the number of documents this word appears in wordsMap.put(word, sourceReader.docFreq(new Term( fieldToAutocomplete, word))); } } for (String word : wordsMap.keySet()) { // ok index the word Document doc = new Document(); doc.add(new Field(SOURCE_WORD_FIELD, word, Field.Store.YES, Field.Index.UN_TOKENIZED)); // orig term doc.add(new Field(GRAMMED_WORDS_FIELD, word, Field.Store.YES, Field.Index.TOKENIZED)); // grammed doc.add(new Field(COUNT_FIELD, Integer.toString(wordsMap.get(word)), Field.Store.NO, Field.Index.UN_TOKENIZED)); // count writer.addDocument(doc); } sourceReader.close(); // close writer writer.optimize(); writer.close(); // re-open our reader reOpenReader(); } private void reOpenReader() throws CorruptIndexException, IOException { if (autoCompleteReader == null) { autoCompleteReader = IndexReader.open(autoCompleteDirectory); } else { autoCompleteReader.reopen(); } autoCompleteSearcher = new IndexSearcher(autoCompleteReader); } public static void main(String[] args) throws Exception { Autocompleter autocomplete = new Autocompleter("/index/autocomplete"); // run this to re-index from the current index, shouldn't need to do // this very often // autocomplete.reIndex(FSDirectory.getDirectory("/index/live", null), // "content"); String term = "steve"; System.out.println(autocomplete.suggestTermsFor(term)); // prints [steve, steven, stevens, stevenson, stevenage] } } ```
120,191
<p>So you've created a ruby library.</p> <p>How do you create and publish your rubygem? And what common pitfalls and gotchas are there pertaining to creating and publishing rubygems?</p>
[ { "answer_id": 120390, "author": "user6325", "author_id": 6325, "author_profile": "https://Stackoverflow.com/users/6325", "pm_score": 2, "selected": false, "text": "<p>I recommend <a href=\"http://gems.github.com\" rel=\"nofollow noreferrer\">github</a> as a place to start, especially for open source projects.</p>\n" }, { "answer_id": 120408, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 2, "selected": false, "text": "<p>And try a google search as well... Very first search result for me...</p>\n\n<ul>\n<li><a href=\"http://www.5dollarwhitebox.org/drupal/creating_a_rubygem_package\" rel=\"nofollow noreferrer\">http://www.5dollarwhitebox.org/drupal/creating_a_rubygem_package</a></li>\n</ul>\n" }, { "answer_id": 120426, "author": "h3rald", "author_id": 21048, "author_profile": "https://Stackoverflow.com/users/21048", "pm_score": 2, "selected": false, "text": "<p>You may also want to checkout the Hoe gem, which can automate the gem creation process.</p>\n\n<p>See: <a href=\"http://nubyonrails.com/articles/tutorial-publishing-rubygems-with-hoe\" rel=\"nofollow noreferrer\">http://nubyonrails.com/articles/tutorial-publishing-rubygems-with-hoe</a></p>\n" }, { "answer_id": 122913, "author": "Clinton Dreisbach", "author_id": 6262, "author_profile": "https://Stackoverflow.com/users/6262", "pm_score": 4, "selected": true, "text": "<p>There are several tools to help you build your own gems. <a href=\"http://seattlerb.rubyforge.org/hoe/\" rel=\"noreferrer\">hoe</a> and <a href=\"http://newgem.rubyforge.org/\" rel=\"noreferrer\">newgem</a> are the best-known, and have a lot of good qualities. However, hoe adds itself as a dependency to your gem, and newgem has become a very large tool, one that I find unwieldy when I want to create and deploy a gem quickly.</p>\n\n<p>My favorite tool is <a href=\"http://codeforpeople.rubyforge.org/bones/\" rel=\"noreferrer\">Mr Bones</a> by Tim Pease. It’s lightweight, featureful, and does not add dependencies to your project. To create a project with it, you just run <code>bones &lt;my_project_name&gt;</code> on the command line, and a skeleton is built for you, complete with a <code>lib</code> directory for your code, a <code>bin</code> directory for your tools, and a test directory. The configuration is in a <code>Rakefile</code>, and it’s clear and concise. Here's the configuration for a project I did a few months ago:</p>\n\n<pre><code>load 'tasks/setup.rb'\n\nensure_in_path 'lib'\nrequire 'friend-feed'\n\ntask :default =&gt; 'test'\n\nPROJ.name = 'friend-feed'\nPROJ.authors = 'Clinton R. Nixon'\nPROJ.email = '[email protected]'\nPROJ.url = 'friend-feed.rubyforge.org'\nPROJ.rubyforge_name = 'friend-feed'\nPROJ.dependencies = ['json']\nPROJ.version = FriendFeed::VERSION\nPROJ.exclude = %w(.git pkg)\n</code></pre>\n\n<p>Mr Bones has the standard set of features you’d expect: you can use it to package up gems and tarfiles of your library, as well as release it on RubyForge and deploy your documentation there. Its killer feature, though, is its ability to freeze its skeleton in your home directory. When you run <code>bones --freeze</code>, a directory named <code>.mrbones</code> is copied into your home directory. You can edit the files in there to make a skeleton for your gems that works the way you work, and from then on, when you run bones to create a new gem, it will use your personal gem skeleton. You can unfreeze Mr Bones by running <code>bones --unfreeze</code> and your skeleton will be backed up, and the default skeleton will be used again.</p>\n\n<p>(Editorial note: I wrote a blog post about this several months ago, and most of this is copied from it.)</p>\n" }, { "answer_id": 144408, "author": "Atiaxi", "author_id": 2555346, "author_profile": "https://Stackoverflow.com/users/2555346", "pm_score": 1, "selected": false, "text": "<p>I actually wrote a tutorial on exactly this, and I wrote it as I was learning. It's more focused on the game I'd written than a library. Also, it assumes you want to build the gem via rake rather than on your own:</p>\n\n<ul>\n<li><a href=\"http://kuidev.blogspot.com/2008/04/day-89-gemification.html\" rel=\"nofollow noreferrer\">Part 1</a> on how to create the gem.</li>\n<li><a href=\"http://kuidev.blogspot.com/2008/04/day-90-gemification-2-revenge.html\" rel=\"nofollow noreferrer\">Part 2</a> on how to run binaries installed by your gem, and get to resources.</li>\n</ul>\n" }, { "answer_id": 399533, "author": "Dr Nic", "author_id": 36170, "author_profile": "https://Stackoverflow.com/users/36170", "pm_score": 1, "selected": false, "text": "<p>hoe no longer adds itself as a dependency as off rubygems 1.2. Its rake tasks are focused on deployment of the rubygem to rubyforge. If you just want to serve the gem from github I think there some new hoe-esque rake task tools to help. </p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683/" ]
So you've created a ruby library. How do you create and publish your rubygem? And what common pitfalls and gotchas are there pertaining to creating and publishing rubygems?
There are several tools to help you build your own gems. [hoe](http://seattlerb.rubyforge.org/hoe/) and [newgem](http://newgem.rubyforge.org/) are the best-known, and have a lot of good qualities. However, hoe adds itself as a dependency to your gem, and newgem has become a very large tool, one that I find unwieldy when I want to create and deploy a gem quickly. My favorite tool is [Mr Bones](http://codeforpeople.rubyforge.org/bones/) by Tim Pease. It’s lightweight, featureful, and does not add dependencies to your project. To create a project with it, you just run `bones <my_project_name>` on the command line, and a skeleton is built for you, complete with a `lib` directory for your code, a `bin` directory for your tools, and a test directory. The configuration is in a `Rakefile`, and it’s clear and concise. Here's the configuration for a project I did a few months ago: ``` load 'tasks/setup.rb' ensure_in_path 'lib' require 'friend-feed' task :default => 'test' PROJ.name = 'friend-feed' PROJ.authors = 'Clinton R. Nixon' PROJ.email = '[email protected]' PROJ.url = 'friend-feed.rubyforge.org' PROJ.rubyforge_name = 'friend-feed' PROJ.dependencies = ['json'] PROJ.version = FriendFeed::VERSION PROJ.exclude = %w(.git pkg) ``` Mr Bones has the standard set of features you’d expect: you can use it to package up gems and tarfiles of your library, as well as release it on RubyForge and deploy your documentation there. Its killer feature, though, is its ability to freeze its skeleton in your home directory. When you run `bones --freeze`, a directory named `.mrbones` is copied into your home directory. You can edit the files in there to make a skeleton for your gems that works the way you work, and from then on, when you run bones to create a new gem, it will use your personal gem skeleton. You can unfreeze Mr Bones by running `bones --unfreeze` and your skeleton will be backed up, and the default skeleton will be used again. (Editorial note: I wrote a blog post about this several months ago, and most of this is copied from it.)
120,201
<p>I want to upload and then process a file in a Ruby on Rails app. The file upload is usually quite short, but the server-side processing can take some time (more than 20 seconds) so I want to give the user some indicator - something better than a meaningless 'processing...' screen.</p> <p>I'm trying to use the following code in the view</p> <pre><code>&lt;%= periodically_call_remote(:url =&gt; {:action =&gt; 'progress_monitor', :controller =&gt; 'files'}, :frequency =&gt; '5', :update =&gt; "setProgress('progressBar','5')" ) %&gt; </code></pre> <p>The content of the :update parameter is the javascript I want to run every 5 seconds</p> <p>and the following code is in the files controller</p> <pre><code>def progress_monitor render :text =&gt; 'whatever' end </code></pre> <p>Eventually the progress_monitor method will return the current progress as an integer (% complete) and that will be passed into the 'setProgress' JavaScript code (that will update an on screen element)</p> <p>However, I'm struggling to get a correct response from from the server that can then be passed into JavaScript.</p> <p>Can anyone help, or am I approaching this the wrong way?</p> <p>There is a follow up question to this, I originally updated this question but the update was sufficiently different to warrant a new question, <a href="https://stackoverflow.com/questions/126011/monitoring-a-server-side-process-on-rails-application-using-ajax-xmlhttprequest">here</a>.</p>
[ { "answer_id": 120317, "author": "liangzan", "author_id": 11927, "author_profile": "https://Stackoverflow.com/users/11927", "pm_score": 3, "selected": true, "text": "<p><code>periodically_call_remote()</code> updates a <code>div</code>. It won't call your JavaScript function. I'm no JavaScript guru, but to solve your problem, you should do your own <code>xmlhttp</code> call. If I were you, I'd use prototype's AJAX request</p>\n\n<p><a href=\"http://www.prototypejs.org/api/ajax/request\" rel=\"nofollow noreferrer\">http://www.prototypejs.org/api/ajax/request</a></p>\n\n<p>and use JavaScript's settimeout or setinterval to do the periodic polling</p>\n\n<p><a href=\"http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/\" rel=\"nofollow noreferrer\">http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/</a></p>\n\n<p>hope this helps cos actually I've encountered the same prb too =)</p>\n" }, { "answer_id": 121201, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 0, "selected": false, "text": "<p>The <code>:update</code> option should only list the div you want to update, NOT have Javascript that you want to evaluate.</p>\n\n<p>The Rails helpers are still very good for this situation, there's no need to write much custom JS. If you wish to execute JS on return, an easy way would be to render an RJS template. If you wish to do it with pure HTML, simply render a view (or partial, or return directly from the <code>render</code> method with the HTML of the progress bar) and put the div of the progress bar in the <code>:update</code> option of the <code>periodically_call_remote</code> method.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6106/" ]
I want to upload and then process a file in a Ruby on Rails app. The file upload is usually quite short, but the server-side processing can take some time (more than 20 seconds) so I want to give the user some indicator - something better than a meaningless 'processing...' screen. I'm trying to use the following code in the view ``` <%= periodically_call_remote(:url => {:action => 'progress_monitor', :controller => 'files'}, :frequency => '5', :update => "setProgress('progressBar','5')" ) %> ``` The content of the :update parameter is the javascript I want to run every 5 seconds and the following code is in the files controller ``` def progress_monitor render :text => 'whatever' end ``` Eventually the progress\_monitor method will return the current progress as an integer (% complete) and that will be passed into the 'setProgress' JavaScript code (that will update an on screen element) However, I'm struggling to get a correct response from from the server that can then be passed into JavaScript. Can anyone help, or am I approaching this the wrong way? There is a follow up question to this, I originally updated this question but the update was sufficiently different to warrant a new question, [here](https://stackoverflow.com/questions/126011/monitoring-a-server-side-process-on-rails-application-using-ajax-xmlhttprequest).
`periodically_call_remote()` updates a `div`. It won't call your JavaScript function. I'm no JavaScript guru, but to solve your problem, you should do your own `xmlhttp` call. If I were you, I'd use prototype's AJAX request <http://www.prototypejs.org/api/ajax/request> and use JavaScript's settimeout or setinterval to do the periodic polling <http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/> hope this helps cos actually I've encountered the same prb too =)
120,206
<p>The problem is not about randomness itself (we have rand), but in cryptographically secure PRNG. What can be used on Linux, or ideally POSIX? Does NSS have something useful?</p> <p><strong>Clarification</strong>: I know about /dev/random, but it may run out of entropy pool. And I'm not sure whether /dev/urandom is guaranteed to be cryptographically secure.</p>
[ { "answer_id": 120209, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>The <code>/dev/random</code> device is intended to be a source of cryptographically secure bits.</p>\n" }, { "answer_id": 120223, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 4, "selected": true, "text": "<p>Use <code>/dev/random</code> (requires user input, eg mouse movements) or <code>/dev/urandom</code>. The latter has an entropy pool and doesn't require any user input unless the pool is empty.</p>\n\n<p>You can read from the pool like this:</p>\n\n<pre><code>char buf[100];\nFILE *fp;\nif (fp = fopen(\"/dev/urandom\", \"r\")) {\n fread(&amp;buf, sizeof(char), 100, fp);\n fclose(fp);\n}\n</code></pre>\n\n<p>Or something like that.</p>\n" }, { "answer_id": 120267, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": false, "text": "<p>From <a href=\"http://en.wikipedia.org/wiki/Urandom\" rel=\"nofollow noreferrer\">Wikipedia</a> (my italics):</p>\n\n<p>A counterpart to /dev/random is /dev/urandom (\"unlocked\" random source) which reuses the internal pool to produce more pseudo-random bits. This means that the call will not block, but the output may contain less entropy than the corresponding read from /dev/random. The <em>intent</em> is to serve as a <em>cryptographically secure pseudorandom number generator</em>. This may be used for less secure applications.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
The problem is not about randomness itself (we have rand), but in cryptographically secure PRNG. What can be used on Linux, or ideally POSIX? Does NSS have something useful? **Clarification**: I know about /dev/random, but it may run out of entropy pool. And I'm not sure whether /dev/urandom is guaranteed to be cryptographically secure.
Use `/dev/random` (requires user input, eg mouse movements) or `/dev/urandom`. The latter has an entropy pool and doesn't require any user input unless the pool is empty. You can read from the pool like this: ``` char buf[100]; FILE *fp; if (fp = fopen("/dev/urandom", "r")) { fread(&buf, sizeof(char), 100, fp); fclose(fp); } ``` Or something like that.
120,212
<p>I am using VMware Server 1.0.7 on Windows XP SP3 at the moment to test software in virtual machines.</p> <p>I have also tried Microsoft Virtual PC (do not remeber the version, could be 2004 or 2007) and VMware was way faster at the time.</p> <p>I have heard of Parallels and VirtualBox but I did not have the time to try them out. Anybody has some benchmarks how fast is each of them (or some other)?</p> <p>I searched for benchmarks on the web, but found nothing useful.</p> <p>I am looking primarily for free software, but if it is really better than free ones I would pay for it.</p> <p>Also, if you are using (or know of) a good virtualization software but have no benchmarks for it, please let me know.</p>
[ { "answer_id": 120209, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>The <code>/dev/random</code> device is intended to be a source of cryptographically secure bits.</p>\n" }, { "answer_id": 120223, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 4, "selected": true, "text": "<p>Use <code>/dev/random</code> (requires user input, eg mouse movements) or <code>/dev/urandom</code>. The latter has an entropy pool and doesn't require any user input unless the pool is empty.</p>\n\n<p>You can read from the pool like this:</p>\n\n<pre><code>char buf[100];\nFILE *fp;\nif (fp = fopen(\"/dev/urandom\", \"r\")) {\n fread(&amp;buf, sizeof(char), 100, fp);\n fclose(fp);\n}\n</code></pre>\n\n<p>Or something like that.</p>\n" }, { "answer_id": 120267, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": false, "text": "<p>From <a href=\"http://en.wikipedia.org/wiki/Urandom\" rel=\"nofollow noreferrer\">Wikipedia</a> (my italics):</p>\n\n<p>A counterpart to /dev/random is /dev/urandom (\"unlocked\" random source) which reuses the internal pool to produce more pseudo-random bits. This means that the call will not block, but the output may contain less entropy than the corresponding read from /dev/random. The <em>intent</em> is to serve as a <em>cryptographically secure pseudorandom number generator</em>. This may be used for less secure applications.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17469/" ]
I am using VMware Server 1.0.7 on Windows XP SP3 at the moment to test software in virtual machines. I have also tried Microsoft Virtual PC (do not remeber the version, could be 2004 or 2007) and VMware was way faster at the time. I have heard of Parallels and VirtualBox but I did not have the time to try them out. Anybody has some benchmarks how fast is each of them (or some other)? I searched for benchmarks on the web, but found nothing useful. I am looking primarily for free software, but if it is really better than free ones I would pay for it. Also, if you are using (or know of) a good virtualization software but have no benchmarks for it, please let me know.
Use `/dev/random` (requires user input, eg mouse movements) or `/dev/urandom`. The latter has an entropy pool and doesn't require any user input unless the pool is empty. You can read from the pool like this: ``` char buf[100]; FILE *fp; if (fp = fopen("/dev/urandom", "r")) { fread(&buf, sizeof(char), 100, fp); fclose(fp); } ``` Or something like that.
120,228
<p>I have a site on my webhotel I would like to run some scheduled tasks on. What methods of achieving this would you recommend?</p> <p>What I’ve thought out so far is having a script included in the top of every page and then let this script check whether it’s time to run this job or not.</p> <p>This is just a quick example of what I was thinking about:</p> <pre><code>if ($alreadyDone == 0 &amp;&amp; time() &gt; $timeToRunMaintainance) { runTask(); $timeToRunMaintainance = time() + $interval; } </code></pre> <p>Anything else I should take into consideration or is there a better method than this?</p>
[ { "answer_id": 120236, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 5, "selected": false, "text": "<p>That's what cronjobs are made for. <code>man crontab</code> assuming you are running a linux server. If you don't have shell access or no way to setup cronjobs, there are free services that setup cronjobs on external servers and ping one of your URLs.</p>\n" }, { "answer_id": 120258, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 3, "selected": false, "text": "<p>if you're wondering how to actually run your PHP script from cron, there are two options: Call the PHP interpreter directly (i.e., \"php /foo/myscript.php\"), or use lynx (lynx <a href=\"http://mywebsite.com/myscript.php\" rel=\"noreferrer\">http://mywebsite.com/myscript.php</a>). Which one you choose depends mostly on how your script needs its environment configured - the paths and file access permissions will be different depending on whether you call it through the shell or the web browser. I'd recommend using lynx.</p>\n\n<p>One side effect is that you get an e-mail every time it runs. To get around this, I make my cron PHP scripts output nothing (and it has to be nothing, not even whitespace) if they complete successfully, and an error message if they fail. I then call them using a small PHP script from cron. This way, I only get an e-mail if it fails. This is basically the same as the lynx method, except my shell script makes the HTTP request and not lynx.</p>\n\n<p>Call this script \"docron\" or something (remember to chmod +x), and then use the command in your crontab: \"docron <a href=\"http://mydomain.com/myscript.php\" rel=\"noreferrer\">http://mydomain.com/myscript.php</a>\". It e-mails you the output of the page as an HTML e-mail, if the page returns something.</p>\n\n<pre><code>#!/usr/bin/php\n&lt;?php\n\n$h = @file_get_contents($_SERVER['argv'][1]);\n\nif ($h === false)\n{\n $h = \"&lt;b&gt;Failed to open file&lt;/b&gt;: \" . $_SERVER['argv'][1];\n}\n\nif ($h != '')\n{\n @mail(\"[email protected]\", $_SERVER['argv']['1'], $h, \"From: [email protected]\\nMIME-Version: 1.0\\nContent-type: text/html; charset=iso-8859-1\");\n}\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 122158, "author": "Gavin M. Roy", "author_id": 13203, "author_profile": "https://Stackoverflow.com/users/13203", "pm_score": 0, "selected": false, "text": "<p>Command line PHP + cron would be the way I would go. It's simple and should fit the bill. It is usually installed with PHP as a matter of course.</p>\n" }, { "answer_id": 122168, "author": "David McLaughlin", "author_id": 3404, "author_profile": "https://Stackoverflow.com/users/3404", "pm_score": 4, "selected": false, "text": "<p>If you have a cPanel host, you can add cron jobs through the web interface.Go to Advanced -> Cron Jobs and use the non-advanced form to set up the cron frequency. You want a command like this:</p>\n\n<pre><code>/usr/bin/php /path/to/your/php/script.php\n</code></pre>\n" }, { "answer_id": 194083, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "<p>If you want to avoid setting up cron jobs and whatnot (though I'd suggest it's a better method), the solution you've provided is pretty good. On a number of projects, I've had the PHP script itself do the check to see whether it's time to run the update.</p>\n\n<p>The down-side (okay, <em>one</em> of the down sides) is that if no one is using the app during a certain period then the script won't run.</p>\n\n<p>The up-side is that if no one is using the app during a certain period then the script won't run. The tasks I've got it set up to do are things like \"update a cache file\", \"do a daily backup\" and whatnot. If someone isn't using the app, then you aren't going to need updated cache files, nor are there going to be any database changes to backup.</p>\n\n<p>The only modification to your method which I'd suggest is that you only run those checks when someone successfully logs in. You don't need to check on every page load.</p>\n" }, { "answer_id": 371486, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>I'm answering this now because no-one seems to have mentioned this exact solution.</p>\n\n<p>On a site I'm currently working on, we've set up a cron job using cPanel, but instead of running the PHP Interpreter directly (because we're using CodeIgniter and our code is mapped to a controller function, this probably isn't a great idea) we're using <code>wget</code>.</p>\n\n<pre><code>wget -q -O cron_job.log http://somehost/controller/method\n</code></pre>\n\n<p><code>-q</code> is so that wget won't generate any output (so you won't keep getting emails). <code>-O cron_job.log</code> will save the contents of whatever your controller generates to a log file (overwritten each time so it won't keep growing).</p>\n\n<p>I've found this to be the easiest way of getting 'proper' cron working.</p>\n" }, { "answer_id": 3098531, "author": "mixdev", "author_id": 6109, "author_profile": "https://Stackoverflow.com/users/6109", "pm_score": 2, "selected": false, "text": "<p>Cron is a general purpose solution for scheduling problems. But when you go big and schedules go high in frequency, there can be reliability/overlapping issues. If you see such problems, consider something like <a href=\"http://cr.yp.to/daemontools/install.html\" rel=\"nofollow noreferrer\">supervise</a> or more sophisticated <a href=\"http://mmonit.com/monit/\" rel=\"nofollow noreferrer\">monit</a>.</p>\n" }, { "answer_id": 11235786, "author": "meeeeeh", "author_id": 1481228, "author_profile": "https://Stackoverflow.com/users/1481228", "pm_score": 0, "selected": false, "text": "<p>If you do not have the option to setup a cronjob you can call the script with cUrl (as alternative to wget - same functionality). Just do a scheduled task on your local machine that executes the cUrl function.</p>\n" }, { "answer_id": 15157355, "author": "Tim Visée", "author_id": 1000145, "author_profile": "https://Stackoverflow.com/users/1000145", "pm_score": 1, "selected": false, "text": "<p>The method you are using is fine, if you don't want to use cronjobs or anything external, but these can be heavy to check each time a page loads.</p>\n\n<p>At first, some cronjobs can probably be replaced. For example if you have a counter for how many users have registered on your website, you can simply update this number when a user registers, so you don't have to use a cronjob or any scheduled task for this.</p>\n\n<p>If you want to use scheduled tasks, I suggest you to use the method you are using right now, but with a little modification. If you're site has enough hits on a day, you can simply make the tasks run (or the tasks check function run) only for 1% or maybe 0.01% of the hits instead of all of them, the percentage you should use depends on the page hits you have and how many times you want to run the task. So, simply add a randomizer to achieve this feature.</p>\n\n<p>You could simply use a function like this;</p>\n\n<pre><code>if(rand (1, 100) &lt;= 1) { // 1, 100 is used to generate a number between 1 and 100. 1 is for one percent.\n // Run the tasks system\n}\n</code></pre>\n" }, { "answer_id": 18443030, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Have you ever looked <a href=\"http://atrigger.com/\" rel=\"noreferrer\">ATrigger</a>? The <a href=\"http://atrigger.com/docs/wiki/14/library-php\" rel=\"noreferrer\">PHP library</a> is also available to start creating scheduled tasks without any overhead.</p>\n\n<p>Disclaimer: I'm among their team.</p>\n" }, { "answer_id": 30456312, "author": "mokiSRB", "author_id": 3676352, "author_profile": "https://Stackoverflow.com/users/3676352", "pm_score": 2, "selected": false, "text": "<p>If you using cpanel u should add this like: </p>\n\n<pre><code>/usr/local/bin/php -q /home/yoursite/public_html/yourfile.php\n</code></pre>\n" }, { "answer_id": 30807535, "author": "Lorenzo Sinisi", "author_id": 2890843, "author_profile": "https://Stackoverflow.com/users/2890843", "pm_score": 1, "selected": false, "text": "<p>I would outsource the cronjobs with www.guardiano.pm and call a url every X minute. When your url (i.e www.yoursite.com/dothis.php) is called than you execute some code. If you don't want to let the web request the page when you want you can allow only request in POST and send some parameter that only you know with guardiano.pm </p>\n\n<p>Thats what I would do because I do that on my pet projects. Have fun! </p>\n" }, { "answer_id": 45449952, "author": "XuDing", "author_id": 406358, "author_profile": "https://Stackoverflow.com/users/406358", "pm_score": 0, "selected": false, "text": "<p>If you want something more abstract, you might consider using something like a PHP scheduler. \nFor example: </p>\n\n<ul>\n<li><a href=\"https://github.com/lavary/crunz\" rel=\"nofollow noreferrer\">https://github.com/lavary/crunz</a></li>\n<li><a href=\"https://github.com/peppeocchi/php-cron-scheduler\" rel=\"nofollow noreferrer\">https://github.com/peppeocchi/php-cron-scheduler</a></li>\n</ul>\n\n<p>And also, to parse the cron expression, you could use an existing library such as <a href=\"https://github.com/mtdowling/cron-expression\" rel=\"nofollow noreferrer\">https://github.com/mtdowling/cron-expression</a>. It provides a lot of useful methods to help you figure out information of a cron job.</p>\n\n<p>Hope that helps.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15214/" ]
I have a site on my webhotel I would like to run some scheduled tasks on. What methods of achieving this would you recommend? What I’ve thought out so far is having a script included in the top of every page and then let this script check whether it’s time to run this job or not. This is just a quick example of what I was thinking about: ``` if ($alreadyDone == 0 && time() > $timeToRunMaintainance) { runTask(); $timeToRunMaintainance = time() + $interval; } ``` Anything else I should take into consideration or is there a better method than this?
That's what cronjobs are made for. `man crontab` assuming you are running a linux server. If you don't have shell access or no way to setup cronjobs, there are free services that setup cronjobs on external servers and ping one of your URLs.
120,244
<p>I'm trying to put together a selector in SASS that will operate on the visted, hovered state of a link, but I can't quite seem to get the markup right, can someone enlighten me? I was writing it like this:</p> <pre><code> &amp;:visited:hover attribute: foo </code></pre>
[ { "answer_id": 120515, "author": "user6325", "author_id": 6325, "author_profile": "https://Stackoverflow.com/users/6325", "pm_score": 1, "selected": false, "text": "<pre><code>a\n &amp;:visited:hover\n :attribute foo\n</code></pre>\n\n<p>Try that - note that identation is two spaces, and the colon goes before attribute not after.</p>\n" }, { "answer_id": 6929064, "author": "crispy", "author_id": 231529, "author_profile": "https://Stackoverflow.com/users/231529", "pm_score": 4, "selected": true, "text": "<pre><code>a\n &amp;:visited:hover\n attribute: foo\n</code></pre>\n\n<p>Nowadays, this is the only valid form. Indention has to be consistent (2 spaces are recommended) and the colon follows the attribute.</p>\n" }, { "answer_id": 36032951, "author": "Sebastian", "author_id": 3923134, "author_profile": "https://Stackoverflow.com/users/3923134", "pm_score": 0, "selected": false, "text": "<p>Perfect for Hover and Before / After:</p>\n\n<pre><code>&amp;:hover {\n color:#FFFFFF;\n\n &amp;::before {\n color:#FFFFFF;\n }\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2977/" ]
I'm trying to put together a selector in SASS that will operate on the visted, hovered state of a link, but I can't quite seem to get the markup right, can someone enlighten me? I was writing it like this: ``` &:visited:hover attribute: foo ```
``` a &:visited:hover attribute: foo ``` Nowadays, this is the only valid form. Indention has to be consistent (2 spaces are recommended) and the colon follows the attribute.
120,250
<p>Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory. </p> <p>So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')?</p>
[ { "answer_id": 120256, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 5, "selected": false, "text": "<p>Nope. But you can use short integers in arrays:</p>\n\n<pre><code>from array import array\na = array(\"h\") # h = signed short, H = unsigned short\n</code></pre>\n\n<p>As long as the value stays in that array it will be a short integer.</p>\n\n<ul>\n<li>documentation for the <a href=\"http://docs.python.org/dev/library/array\" rel=\"noreferrer\">array module</a></li>\n</ul>\n" }, { "answer_id": 120449, "author": "Arnav", "author_id": 21029, "author_profile": "https://Stackoverflow.com/users/21029", "pm_score": 3, "selected": false, "text": "<p>Thanks to Armin for pointing out the 'array' module. I also found the 'struct' module that packs c-style structs in a string:</p>\n\n<p>From the documentation (<a href=\"https://docs.python.org/library/struct.html\" rel=\"nofollow noreferrer\">https://docs.python.org/library/struct.html</a>):</p>\n\n<pre><code>&gt;&gt;&gt; from struct import *\n&gt;&gt;&gt; pack('hhl', 1, 2, 3)\n'\\x00\\x01\\x00\\x02\\x00\\x00\\x00\\x03'\n&gt;&gt;&gt; unpack('hhl', '\\x00\\x01\\x00\\x02\\x00\\x00\\x00\\x03')\n(1, 2, 3)\n&gt;&gt;&gt; calcsize('hhl')\n8\n</code></pre>\n" }, { "answer_id": 120454, "author": "Tony Meyer", "author_id": 4966, "author_profile": "https://Stackoverflow.com/users/4966", "pm_score": 2, "selected": false, "text": "<p>Armin's suggestion of the array module is probably best. Two possible alternatives:</p>\n\n<ul>\n<li>You can create an extension module yourself that provides the data structure that you're after. If it's really just something like a collection of shorts, then\nthat's pretty simple to do.</li>\n<li>You can\ncheat and manipulate bits, so that\nyou're storing one number in the\nlower half of the Python int, and\nanother one in the upper half. \nYou'd write some utility functions\nto convert to/from these within your\ndata structure. Ugly, but it can be made to work.</li>\n</ul>\n\n<p>It's also worth realising that a Python integer object is not 4 bytes - there is additional overhead. So if you have a really large number of shorts, then you can save more than two bytes per number by using a C short in some way (e.g. the array module).</p>\n\n<p>I had to keep a large set of integers in memory a while ago, and a dictionary with integer keys and values was too large (I had 1GB available for the data structure IIRC). I switched to using a IIBTree (from ZODB) and managed to fit it. (The ints in a IIBTree are real C ints, not Python integers, and I hacked up an automatic switch to a IOBTree when the number was larger than 32 bits).</p>\n" }, { "answer_id": 59604315, "author": "user12658139", "author_id": 12658139, "author_profile": "https://Stackoverflow.com/users/12658139", "pm_score": 1, "selected": false, "text": "<p>You can also store multiple any size of integers in a single large integer.</p>\n\n<p>For example as seen below, in python3 on 64bit x86 system, 1024 bits are taking 164 bytes of memory storage. That means on average one byte can store around 6.24 bits. And if you go with even larger integers you can get even higher bits storage density. For example around 7.50 bits per byte with 2**20 bits wide integer.</p>\n\n<p>Obviously you will need some wrapper logic to access individual short numbers stored in the larger integer, which is easy to implement.</p>\n\n<p>One issue with this approach is your data access will slow down due use of the large integer operations.</p>\n\n<p>If you are accessing a big batch of consecutively stored integers at once to minimize the access to large integers, then the slower access to long integers won't be an issue.</p>\n\n<p>I guess use of numpy will be easier approach.</p>\n\n<pre><code>&gt;&gt;&gt; a = 2**1024\n&gt;&gt;&gt; sys.getsizeof(a)\n164\n&gt;&gt;&gt; 1024/164\n6.2439024390243905\n\n&gt;&gt;&gt; a = 2**(2**20)\n&gt;&gt;&gt; sys.getsizeof(a)\n139836\n&gt;&gt;&gt; 2**20 / 139836\n7.49861266054521\n</code></pre>\n" }, { "answer_id": 59618360, "author": "user12658139", "author_id": 12658139, "author_profile": "https://Stackoverflow.com/users/12658139", "pm_score": 1, "selected": false, "text": "<p>Using bytearray in python which is basically a C unsigned char array under the hood will be a better solution than using large integers. There is no overhead for manipulating a byte array and, it has much less storage overhead compared to large integers. It's possible to get storage density of 7.99+ bits per byte with bytearrays. </p>\n\n<pre><code>&gt;&gt;&gt; import sys\n&gt;&gt;&gt; a = bytearray(2**32)\n&gt;&gt;&gt; sys.getsizeof(a)\n4294967353\n&gt;&gt;&gt; 8 * 2**32 / 4294967353\n7.999999893829228\n</code></pre>\n" }, { "answer_id": 60190871, "author": "silvester_J", "author_id": 12886261, "author_profile": "https://Stackoverflow.com/users/12886261", "pm_score": 2, "selected": false, "text": "<p>You can use NumyPy's int as np.int8 or np.int16.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21029/" ]
Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory. So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')?
Nope. But you can use short integers in arrays: ``` from array import array a = array("h") # h = signed short, H = unsigned short ``` As long as the value stays in that array it will be a short integer. * documentation for the [array module](http://docs.python.org/dev/library/array)
120,262
<p>Say for instance I was writing a function that was designed to accept multiple argument types:</p> <pre><code>var overloaded = function (arg) { if (is_dom_element(arg)) { // Code for DOM Element argument... } }; </code></pre> <p>What's the best way to implement <strong><code>is_dom_element</code></strong> so that it works in a cross-browser, fairly accurate way?</p>
[ { "answer_id": 120275, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 2, "selected": false, "text": "<p>Probably this one here:</p>\n\n<pre><code>node instanceof HTMLElement\n</code></pre>\n\n<p>That should work in most browsers. Otherwise you have to duck-type it (eg. <code>typeof x.nodeType != 'undefined'</code>)</p>\n" }, { "answer_id": 120280, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 5, "selected": true, "text": "<p>jQuery checks the nodeType property. So you would have:</p>\n\n<pre><code>var overloaded = function (arg) {\n if (arg.nodeType) {\n // Code for DOM Element argument...\n }\n};\n</code></pre>\n\n<p>Although this would detect all DOM objects, not just elements. If you want elements alone, that would be:</p>\n\n<pre><code>var overloaded = function (arg) {\n if (arg.nodeType &amp;&amp; arg.nodeType == 1) {\n // Code for DOM Element argument...\n }\n};\n</code></pre>\n" }, { "answer_id": 120424, "author": "Wolfram Kriesing", "author_id": 21050, "author_profile": "https://Stackoverflow.com/users/21050", "pm_score": 0, "selected": false, "text": "<p>What about</p>\n\n<pre><code>obj instanceof HTMLElement\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10942/" ]
Say for instance I was writing a function that was designed to accept multiple argument types: ``` var overloaded = function (arg) { if (is_dom_element(arg)) { // Code for DOM Element argument... } }; ``` What's the best way to implement **`is_dom_element`** so that it works in a cross-browser, fairly accurate way?
jQuery checks the nodeType property. So you would have: ``` var overloaded = function (arg) { if (arg.nodeType) { // Code for DOM Element argument... } }; ``` Although this would detect all DOM objects, not just elements. If you want elements alone, that would be: ``` var overloaded = function (arg) { if (arg.nodeType && arg.nodeType == 1) { // Code for DOM Element argument... } }; ```
120,266
<p>In my database, I have a model which has a field which should be selected from one of a list of options. As an example, consider a model which needs to store a measurement, such as 5ft or 13cm or 12.24m3. The obvious way to achieve this is to have a decimal field and then some other field to store the unit of measurement. </p> <p>So what is the best way to store the unit of measurement? I've used a couple of approaches in the past:</p> <p>1) Storing the various options in another DB table (and associated model), and linking the two with a standard foreign key (and usually eager loading the associated model). This seems like overkill, as you are forcing the DB to perform a join on every query.</p> <p>2) Storing the options as a constant Hash, loaded in one of the initializers, where the key into the Hash is stored in the unit of measurement field. This way, you effectively do the join in Ruby (which may or may not be a performance increase), but you lose the ability to query from the "unit of measurement" side. This wouldn't be a problem provided it's unlikely you'd need to do queries like "find me all measurements with units of cm".</p> <p>Neither of these feel particularly elegant to me.. can anyone suggest something better?</p>
[ { "answer_id": 120281, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "<p>I would go with option one. How large will it be the UnitOfMeasurement table? And, if using an integer primary key, why do you worry so much about speed?</p>\n\n<p>Option 1 is the way to go for design reasons. Just declare it with an integer (even smallint) primary key and a field for the unit description.</p>\n" }, { "answer_id": 120318, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 1, "selected": false, "text": "<p>Has ActiveRecord gotten support for natural keys, yet? If it has, you can just make the <code>name</code> (or whatever) column of the <code>UnitOfMeasure</code> table the PK, that way the value of the FK column has all the info you need, and you still have a fully normalized DB with a canonical set of <code>UnitOfMeasurement</code> values.</p>\n" }, { "answer_id": 120352, "author": "xmjx", "author_id": 15259, "author_profile": "https://Stackoverflow.com/users/15259", "pm_score": 0, "selected": false, "text": "<p>Do you need to perform lookups on these values? If not, you could as well store them as a string and parse the string later on in the application that reads the values. While you risk storing unparseable data, you gain speed and reduce DB complexity. Sometimes normalizing a database is not helpful. In the end /something/ within your system needs to know that \"cm\" is a length measure and \"m3\" is a room measure and comparing \"3cm\" to \"1m3\" doesn't make any sense anyway. So you just as well can put all that knowledge in code.</p>\n\n<p>Let's say you are only going to display that data anyway, what is normalizing good for here?</p>\n" }, { "answer_id": 120524, "author": "Ben Scofield", "author_id": 6478, "author_profile": "https://Stackoverflow.com/users/6478", "pm_score": 3, "selected": false, "text": "<p>Have you seen <a href=\"http://github.com/vigetlabs/constant_cache/tree/master\" rel=\"nofollow noreferrer\">constant_cache</a>? It's sort of the combination of the best of 1 and 2 - lookup data is stored in the DB, but it's exposed as class constants on the lookup model and only loaded at application start, so you don't suffer the join penalties constantly. The following example comes from the README:</p>\n\n<p>migration:</p>\n\n<pre><code>create_table :account_statuses do |t|\n t.string :name, :description\nend\n\nAccountStatus.create!(:name =&gt; 'Active', :description =&gt; 'Active user account')\nAccountStatus.create!(:name =&gt; 'Pending', :description =&gt; 'Pending user account')\nAccountStatus.create!(:name =&gt; 'Disabled', :description =&gt; 'Disabled user account')\n</code></pre>\n\n<p>model:</p>\n\n<pre><code>class AccountStatus &lt; ActiveRecord::Base\n caches_constants\nend\n</code></pre>\n\n<p>using it:</p>\n\n<pre><code>Account.new(:username =&gt; 'preagan', :status =&gt; AccountStatus::PENDING)\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In my database, I have a model which has a field which should be selected from one of a list of options. As an example, consider a model which needs to store a measurement, such as 5ft or 13cm or 12.24m3. The obvious way to achieve this is to have a decimal field and then some other field to store the unit of measurement. So what is the best way to store the unit of measurement? I've used a couple of approaches in the past: 1) Storing the various options in another DB table (and associated model), and linking the two with a standard foreign key (and usually eager loading the associated model). This seems like overkill, as you are forcing the DB to perform a join on every query. 2) Storing the options as a constant Hash, loaded in one of the initializers, where the key into the Hash is stored in the unit of measurement field. This way, you effectively do the join in Ruby (which may or may not be a performance increase), but you lose the ability to query from the "unit of measurement" side. This wouldn't be a problem provided it's unlikely you'd need to do queries like "find me all measurements with units of cm". Neither of these feel particularly elegant to me.. can anyone suggest something better?
Have you seen [constant\_cache](http://github.com/vigetlabs/constant_cache/tree/master)? It's sort of the combination of the best of 1 and 2 - lookup data is stored in the DB, but it's exposed as class constants on the lookup model and only loaded at application start, so you don't suffer the join penalties constantly. The following example comes from the README: migration: ``` create_table :account_statuses do |t| t.string :name, :description end AccountStatus.create!(:name => 'Active', :description => 'Active user account') AccountStatus.create!(:name => 'Pending', :description => 'Pending user account') AccountStatus.create!(:name => 'Disabled', :description => 'Disabled user account') ``` model: ``` class AccountStatus < ActiveRecord::Base caches_constants end ``` using it: ``` Account.new(:username => 'preagan', :status => AccountStatus::PENDING) ```
120,334
<p>I currentyl have no clue on how to sort an array which contains UTF-8 encoded strings in PHP. The array comes from a LDAP server so sorting via a database (would be no problem) is no solution. The following does not work on my windows development machine (although I'd think that this should be at least a possible solution):</p> <pre><code>$array=array('Birnen', 'Äpfel', 'Ungetüme', 'Apfel', 'Ungetiere', 'Österreich'); $oldLocal=setlocale(LC_COLLATE, "0"); var_dump(setlocale(LC_COLLATE, 'German_Germany.65001')); usort($array, 'strcoll'); var_dump(setlocale(LC_COLLATE, $oldLocal)); var_dump($array); </code></pre> <p>The output is:</p> <pre><code>string(20) "German_Germany.65001" string(1) "C" array(6) { [0]=&gt; string(6) "Birnen" [1]=&gt; string(9) "Ungetiere" [2]=&gt; string(6) "Äpfel" [3]=&gt; string(5) "Apfel" [4]=&gt; string(9) "Ungetüme" [5]=&gt; string(11) "Österreich" } </code></pre> <p>This is complete nonsense. Using 1252 as the codepage for <code>setlocale()</code> gives another output but still a plainly wrong one:</p> <pre><code>string(19) "German_Germany.1252" string(1) "C" array(6) { [0]=&gt; string(11) "Österreich" [1]=&gt; string(6) "Äpfel" [2]=&gt; string(5) "Apfel" [3]=&gt; string(6) "Birnen" [4]=&gt; string(9) "Ungetüme" [5]=&gt; string(9) "Ungetiere" } </code></pre> <p>Is there a way to sort an array with UTF-8 strings locale aware?</p> <p><em>Just noted that this seems to be PHP on Windows problem, as the same snippet with <code>de_DE.utf8</code> used as locale works on a Linux machine. Nevertheless a solution for this Windows-specific problem would be nice...</em></p>
[ { "answer_id": 120361, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "<p>This is a very complex <a href=\"http://unicode.org/reports/tr10/\" rel=\"nofollow noreferrer\">issue</a>, since UTF-8 encoded data can contain any Unicode character (i.e. characters from many 8-bit encodings which collate differently in different locales).</p>\n\n<p>Perhaps if you converted your UTF-8 data into Unicode (not familiar with PHP unicode functions, sorry) and then normalized them into <a href=\"http://en.wikipedia.org/wiki/Unicode_normalization\" rel=\"nofollow noreferrer\">NFD or NFKD</a> and then sorting on code points might give some collation that would make sense to you (ie \"A\" before \"Ä\").</p>\n\n<p>Check the links I provided.</p>\n\n<p>EDIT: since you mention that your input data are clear (I assume they all fall in the \"windows-1252\" codepage), then you should do the following conversion: UTF-8 → Unicode → Windows-1252, on which Windows-1252 encoded data do a sort selecting the \"CP1252\" locale.</p>\n" }, { "answer_id": 120388, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 0, "selected": false, "text": "<p>Using your example with codepage 1252 worked perfectly fine here on my windows development machine.</p>\n\n<pre><code>$array=array('Birnen', 'Äpfel', 'Ungetüme', 'Apfel', 'Ungetiere', 'Österreich');\n$oldLocal=setlocale(LC_COLLATE, \"0\");\nvar_dump(setlocale(LC_COLLATE, 'German_Germany.1252'));\nusort($array, 'strcoll');\nvar_dump(setlocale(LC_COLLATE, $oldLocal));\nvar_dump($array);\n</code></pre>\n\n<p><em>...snip...</em></p>\n\n<p>This was with PHP 5.2.6. btw.\n<hr>\nThe above example is <strong>wrong</strong>, it uses ASCII encoding instead of UTF-8. I did trace the strcoll() calls and look what I found:</p>\n\n<pre><code>function traceStrColl($a, $b) {\n $outValue = strcoll($a, $b);\n echo \"$a $b $outValue\\r\\n\";\n return $outValue;\n}\n\n$array=array('Birnen', 'Äpfel', 'Ungetüme', 'Apfel', 'Ungetiere', 'Österreich');\nsetlocale(LC_COLLATE, 'German_Germany.65001');\nusort($array, 'traceStrColl');\nprint_r($array);\n</code></pre>\n\n<p>gives:</p>\n\n<pre>Ungetüme Äpfel 2147483647\nUngetüme Birnen 2147483647\nUngetüme Apfel 2147483647\nUngetüme Ungetiere 2147483647\nÖsterreich Ungetüme 2147483647\nÄpfel Ungetiere 2147483647\nÄpfel Birnen 2147483647\nApfel Äpfel 2147483647\nUngetiere Birnen 2147483647</pre>\n\n<p>I did find some <a href=\"http://bugs.php.net/\" rel=\"nofollow noreferrer\">bug reports</a> which have been flagged being <a href=\"http://bugs.php.net/bug.php?id=28527\" rel=\"nofollow noreferrer\">bogus</a>...\nThe best bet you have is filing a bug-report I suppose though...</p>\n" }, { "answer_id": 121445, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": -1, "selected": false, "text": "<p>Your collation needs to match the character set. Since your data is UTF-8 encoded, you should use a UTF-8 collation. It could be named differently on different platforms, but a good guess would be <code>de_DE.utf8</code>.</p>\n\n<p>On UNIX systems, you can get a list of currently installed locales with the command</p>\n\n<pre><code>locale -a\n</code></pre>\n" }, { "answer_id": 125879, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 4, "selected": true, "text": "<p>Eventually this problem cannot be solved in a simple way without using recoded strings (UTF-8 → Windows-1252 or ISO-8859-1) as suggested by ΤΖΩΤΖΙΟΥ due to an obvious PHP bug as discovered by Huppie.\nTo summarize the problem, I created the following code snippet which clearly demonstrates that the problem is the strcoll() function when using the 65001 Windows-UTF-8-codepage.</p>\n\n<pre><code>function traceStrColl($a, $b) {\n $outValue=strcoll($a, $b);\n echo \"$a $b $outValue\\r\\n\";\n return $outValue;\n}\n\n$locale=(defined('PHP_OS') &amp;&amp; stristr(PHP_OS, 'win')) ? 'German_Germany.65001' : 'de_DE.utf8';\n\n$string=\"ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÜabcdefghijklmnopqrstuvwxyzäöüß\";\n$array=array();\nfor ($i=0; $i&lt;mb_strlen($string, 'UTF-8'); $i++) {\n $array[]=mb_substr($string, $i, 1, 'UTF-8');\n}\n$oldLocale=setlocale(LC_COLLATE, \"0\");\nvar_dump(setlocale(LC_COLLATE, $locale));\nusort($array, 'traceStrColl');\nsetlocale(LC_COLLATE, $oldLocale);\nvar_dump($array);\n</code></pre>\n\n<p>The result is:</p>\n\n<pre><code>string(20) \"German_Germany.65001\"\na B 2147483647\n[...]\narray(59) {\n [0]=&gt;\n string(1) \"c\"\n [1]=&gt;\n string(1) \"B\"\n [2]=&gt;\n string(1) \"s\"\n [3]=&gt;\n string(1) \"C\"\n [4]=&gt;\n string(1) \"k\"\n [5]=&gt;\n string(1) \"D\"\n [6]=&gt;\n string(2) \"ä\"\n [7]=&gt;\n string(1) \"E\"\n [8]=&gt;\n string(1) \"g\"\n [...]\n</code></pre>\n\n<p>The same snippet works on a Linux machine without any problems producing the following output:</p>\n\n<pre><code>string(10) \"de_DE.utf8\"\na B -1\n[...]\narray(59) {\n [0]=&gt;\n string(1) \"a\"\n [1]=&gt;\n string(1) \"A\"\n [2]=&gt;\n string(2) \"ä\"\n [3]=&gt;\n string(2) \"Ä\"\n [4]=&gt;\n string(1) \"b\"\n [5]=&gt;\n string(1) \"B\"\n [6]=&gt;\n string(1) \"c\"\n [7]=&gt;\n string(1) \"C\"\n [...]\n</code></pre>\n\n<p>The snippet also works when using Windows-1252 (ISO-8859-1) encoded strings (of course the mb_* encodings and the locale must be changed then).</p>\n\n<p>I filed a bug report on <a href=\"http://bugs.php.net\" rel=\"noreferrer\">bugs.php.net</a>: <a href=\"http://bugs.php.net/bug.php?id=46165\" rel=\"noreferrer\">Bug #46165 strcoll() does not work with UTF-8 strings on Windows</a>. If you experience the same problem, you can give your feedback to the PHP team on the bug-report page (two other, probably related, bugs have been classified as <em>bogus</em> - I don't think that this bug is <em>bogus</em> ;-).</p>\n\n<p>Thanks to all of you.</p>\n" }, { "answer_id": 349036, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 3, "selected": false, "text": "<p>Update on this issue:</p>\n\n<p>Even though the discussion around this problem revealed that we could have discovered a PHP bug with <a href=\"http://de2.php.net/manual/en/function.strcoll.php\" rel=\"noreferrer\"><code>strcoll()</code></a> and/or <a href=\"http://de2.php.net/manual/en/function.setlocale.php\" rel=\"noreferrer\"><code>setlocale()</code></a>, this is clearly not the case. The problem is rather a limitation of the Windows CRT implementation of <a href=\"http://msdn.microsoft.com/en-us/library/x99tb11d.aspx\" rel=\"noreferrer\"><code>setlocale()</code></a> (PHPs <code>setlocale()</code> is just a thin wrapper around the CRT call). The following is a citation of the <a href=\"http://msdn.microsoft.com/en-us/library/x99tb11d.aspx\" rel=\"noreferrer\">MSDN page \"setlocale, _wsetlocale\"</a>:</p>\n\n<blockquote>\n <p>The set of available languages,\n country/region codes, and code pages\n includes all those supported by the\n Win32 NLS API <strong>except code pages that\n require more than two bytes per\n character, such as UTF-7 and UTF-8. If\n you provide a code page like UTF-7 or\n UTF-8, setlocale will fail, returning\n NULL.</strong> The set of language and\n country/region codes supported by\n setlocale is listed in Language and\n Country/Region Strings.</p>\n</blockquote>\n\n<p>It therefore is impossible to use locale-aware string operations within PHP on Windows when strings are multi-byte encoded.</p>\n" }, { "answer_id": 9576230, "author": "Delian Krustev", "author_id": 1227975, "author_profile": "https://Stackoverflow.com/users/1227975", "pm_score": 5, "selected": false, "text": "<pre><code>$a = array( 'Кръстев', 'Делян1', 'делян1', 'Делян2', 'делян3', 'кръстев' );\n$col = new \\Collator('bg_BG');\n$col-&gt;asort( $a );\nvar_dump( $a );\n</code></pre>\n\n<p>Prints:</p>\n\n<pre><code>array\n 2 =&gt; string 'делян1' (length=11)\n 1 =&gt; string 'Делян1' (length=11)\n 3 =&gt; string 'Делян2' (length=11)\n 4 =&gt; string 'делян3' (length=11)\n 5 =&gt; string 'кръстев' (length=14)\n 0 =&gt; string 'Кръстев' (length=14)\n</code></pre>\n\n<p>The <code>Collator</code> class is defined in <a href=\"http://www.php.net/manual/en/book.intl.php\" rel=\"noreferrer\">PECL intl extension</a>. It is distributed with PHP 5.3 sources but might be disabled for some builds. E.g. in Debian it is in package php5-intl .</p>\n\n<p><code>Collator::compare</code> is useful for <code>usort</code>.</p>\n" }, { "answer_id": 32779390, "author": "leymannx", "author_id": 2199525, "author_profile": "https://Stackoverflow.com/users/2199525", "pm_score": 1, "selected": false, "text": "<p>I <a href=\"https://stackoverflow.com/a/6856938/2199525\">found this following helper function</a> to convert all letters of a string to ASCII letters very helpful here.</p>\n\n<pre><code>function _all_letters_to_ASCII($string) {\n return strtr(utf8_decode($string), \n utf8_decode('ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ'),\n 'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy');\n}\n</code></pre>\n\n<p>After that a simple <code>array_multisort()</code> gives you what you want.</p>\n\n<pre><code>$array = array('Birnen', 'Äpfel', 'Ungetüme', 'Apfel', 'Ungetiere', 'Österreich');\n$reference_array = $array;\n\nforeach ($reference_array as $key =&gt; &amp;$value) {\n $value = _all_letters_to_ASCII($value);\n}\nvar_dump($reference_array);\n\narray_multisort($reference_array, $array);\nvar_dump($array);\n</code></pre>\n\n<p>Of course you can make the helper function fit more advanced needs. But for now, it looks pretty good.</p>\n\n<pre><code>array(6) {\n [0]=&gt; string(6) \"Birnen\"\n [1]=&gt; string(5) \"Apfel\"\n [2]=&gt; string(8) \"Ungetume\"\n [3]=&gt; string(5) \"Apfel\"\n [4]=&gt; string(9) \"Ungetiere\"\n [5]=&gt; string(10) \"Osterreich\"\n}\n\narray(6) {\n [0]=&gt; string(5) \"Apfel\"\n [1]=&gt; string(6) \"Äpfel\"\n [2]=&gt; string(6) \"Birnen\"\n [3]=&gt; string(11) \"Österreich\"\n [4]=&gt; string(9) \"Ungetiere\"\n [5]=&gt; string(9) \"Ungetüme\"\n}\n</code></pre>\n" }, { "answer_id": 39974761, "author": "Friedrich Siever", "author_id": 6997445, "author_profile": "https://Stackoverflow.com/users/6997445", "pm_score": 0, "selected": false, "text": "<p>I am confronted with the same problem with German \"Umlaute\". After some research, this worked for me: </p>\n\n<pre><code>$laender =array(\"Österreich\", \"Schweiz\", \"England\", \"France\", \"Ägypten\"); \n$laender = array_map(\"utf8_decode\", $laender); \nsetlocale(LC_ALL,\"de_DE@euro\", \"de_DE\", \"deu_deu\"); \nsort($laender, SORT_LOCALE_STRING); \n$laender = array_map(\"utf8_encode\", $laender); \nprint_r($laender);\n</code></pre>\n\n<p>The result: </p>\n\n<blockquote>\n <p>Array<br>\n (<br>\n [0] => Ägypten<br>\n [1] => England<br>\n [2] => France<br>\n [3] => Österreich<br>\n [4] => Schweiz<br>\n )</p>\n</blockquote>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11354/" ]
I currentyl have no clue on how to sort an array which contains UTF-8 encoded strings in PHP. The array comes from a LDAP server so sorting via a database (would be no problem) is no solution. The following does not work on my windows development machine (although I'd think that this should be at least a possible solution): ``` $array=array('Birnen', 'Äpfel', 'Ungetüme', 'Apfel', 'Ungetiere', 'Österreich'); $oldLocal=setlocale(LC_COLLATE, "0"); var_dump(setlocale(LC_COLLATE, 'German_Germany.65001')); usort($array, 'strcoll'); var_dump(setlocale(LC_COLLATE, $oldLocal)); var_dump($array); ``` The output is: ``` string(20) "German_Germany.65001" string(1) "C" array(6) { [0]=> string(6) "Birnen" [1]=> string(9) "Ungetiere" [2]=> string(6) "Äpfel" [3]=> string(5) "Apfel" [4]=> string(9) "Ungetüme" [5]=> string(11) "Österreich" } ``` This is complete nonsense. Using 1252 as the codepage for `setlocale()` gives another output but still a plainly wrong one: ``` string(19) "German_Germany.1252" string(1) "C" array(6) { [0]=> string(11) "Österreich" [1]=> string(6) "Äpfel" [2]=> string(5) "Apfel" [3]=> string(6) "Birnen" [4]=> string(9) "Ungetüme" [5]=> string(9) "Ungetiere" } ``` Is there a way to sort an array with UTF-8 strings locale aware? *Just noted that this seems to be PHP on Windows problem, as the same snippet with `de_DE.utf8` used as locale works on a Linux machine. Nevertheless a solution for this Windows-specific problem would be nice...*
Eventually this problem cannot be solved in a simple way without using recoded strings (UTF-8 → Windows-1252 or ISO-8859-1) as suggested by ΤΖΩΤΖΙΟΥ due to an obvious PHP bug as discovered by Huppie. To summarize the problem, I created the following code snippet which clearly demonstrates that the problem is the strcoll() function when using the 65001 Windows-UTF-8-codepage. ``` function traceStrColl($a, $b) { $outValue=strcoll($a, $b); echo "$a $b $outValue\r\n"; return $outValue; } $locale=(defined('PHP_OS') && stristr(PHP_OS, 'win')) ? 'German_Germany.65001' : 'de_DE.utf8'; $string="ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÜabcdefghijklmnopqrstuvwxyzäöüß"; $array=array(); for ($i=0; $i<mb_strlen($string, 'UTF-8'); $i++) { $array[]=mb_substr($string, $i, 1, 'UTF-8'); } $oldLocale=setlocale(LC_COLLATE, "0"); var_dump(setlocale(LC_COLLATE, $locale)); usort($array, 'traceStrColl'); setlocale(LC_COLLATE, $oldLocale); var_dump($array); ``` The result is: ``` string(20) "German_Germany.65001" a B 2147483647 [...] array(59) { [0]=> string(1) "c" [1]=> string(1) "B" [2]=> string(1) "s" [3]=> string(1) "C" [4]=> string(1) "k" [5]=> string(1) "D" [6]=> string(2) "ä" [7]=> string(1) "E" [8]=> string(1) "g" [...] ``` The same snippet works on a Linux machine without any problems producing the following output: ``` string(10) "de_DE.utf8" a B -1 [...] array(59) { [0]=> string(1) "a" [1]=> string(1) "A" [2]=> string(2) "ä" [3]=> string(2) "Ä" [4]=> string(1) "b" [5]=> string(1) "B" [6]=> string(1) "c" [7]=> string(1) "C" [...] ``` The snippet also works when using Windows-1252 (ISO-8859-1) encoded strings (of course the mb\_\* encodings and the locale must be changed then). I filed a bug report on [bugs.php.net](http://bugs.php.net): [Bug #46165 strcoll() does not work with UTF-8 strings on Windows](http://bugs.php.net/bug.php?id=46165). If you experience the same problem, you can give your feedback to the PHP team on the bug-report page (two other, probably related, bugs have been classified as *bogus* - I don't think that this bug is *bogus* ;-). Thanks to all of you.
120,420
<p>I would like to have information about the icons which are displayed alongside the site URLs on a web browser. Is this some browser specific feature? Where do we specify the icon source, ie, is it in some tag on the web page itself ?</p>
[ { "answer_id": 120427, "author": "Chris", "author_id": 15578, "author_profile": "https://Stackoverflow.com/users/15578", "pm_score": -1, "selected": false, "text": "<p>It was originally a windows icon format file, stored under the URL <a href=\"http://site/favicon.ico\" rel=\"nofollow noreferrer\">http://site/favicon.ico</a>. Most sites still use favicon.ico, and many browsers still automatically look there, regardless of the meta tags.</p>\n" }, { "answer_id": 120428, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 7, "selected": true, "text": "<p>These icons are called <a href=\"http://en.wikipedia.org/wiki/Favicon\" rel=\"noreferrer\">favicons</a></p>\n\n<p>Most web browsers support <a href=\"http://mysite.com/favicon.ico\" rel=\"noreferrer\">http://mysite.com/favicon.ico</a> but the proper way to do it is to include an icon meta tag in the head profile.</p>\n\n<pre><code>&lt;head profile=\"http://www.w3.org/2005/10/profile\"&gt;\n&lt;link rel=\"icon\" \n type=\"image/png\" \n href=\"/somewhere/myicon.png\" /&gt;\n[…]\n&lt;/head&gt;\n</code></pre>\n\n<p><a href=\"http://www.w3.org/2005/10/howto-favicon\" rel=\"noreferrer\">Source from the W3C itself.</a></p>\n\n<p>Your best bet is to probably do both with the same icon image.</p>\n" }, { "answer_id": 120435, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 0, "selected": false, "text": "<p>These are <a href=\"http://en.wikipedia.org/wiki/Favicon\" rel=\"nofollow noreferrer\">favicons</a> - more info on that page.</p>\n\n<p>Basically, .ico files in the root directory on the webserver.</p>\n" }, { "answer_id": 120442, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 2, "selected": false, "text": "<p>It's called a favicon.</p>\n\n<p>You might want to check out these three questions:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/37073/what-is-currently-the-best-way-to-get-a-favicon-to-display-in-all-browsers-that\">What is currently the best way to get a favicon to display in all browsers that support Favicons?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/6732/why-no-favicon-for-my-web-site\">Why no favicon for my web site?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/6642/preferred-way-to-use-favicons\">Preferred way to use favicons?</a></li>\n</ul>\n" }, { "answer_id": 120445, "author": "Rich Adams", "author_id": 10018, "author_profile": "https://Stackoverflow.com/users/10018", "pm_score": 4, "selected": false, "text": "<p>I believe you're referring to the <a href=\"http://en.wikipedia.org/wiki/Favicon\" rel=\"noreferrer\">Favicon</a>, which allows a website to specify a 16x16 (or larger) image which is displayed in the address bar next to the URL in most modern browsers.</p>\n\n<p>Some browsers just pick the file called favicon.ico which is in the root of your web folder, whereas others require it to be specified in the <code>&lt;head&gt;</code> of the HTML using the following code,</p>\n\n<pre><code>&lt;link rel=\"shortcut icon\" href=\"favicon.ico\" type=\"image/x-icon\" /&gt;\n</code></pre>\n\n<p>This was originally the way it was done with IE, but that doesn't conform to standards (because of the space in the rel), so most browsers now let you do it as follows, where you can use any standard image format, not just .ico</p>\n\n<pre><code>&lt;link rel=\"icon\" href=\"favicon.png\" type=\"image/png\" /&gt;\n</code></pre>\n" }, { "answer_id": 120512, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>I will just add that some sites use an animated Gif as favicon. Which can be seen as über cool or supremely annoying, depending on your tastes... And probably not supported by all browsers.</p>\n" }, { "answer_id": 499232, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The easiest way to get that info is by this simple web app</p>\n\n<p><a href=\"http://www.getfavicon.org\" rel=\"nofollow noreferrer\">link text</a></p>\n\n<p>You only have to type the url of the page and it returns all the image properties</p>\n" }, { "answer_id": 499313, "author": "hydrapheetz", "author_id": 23305, "author_profile": "https://Stackoverflow.com/users/23305", "pm_score": 0, "selected": false, "text": "<p>They're <a href=\"http://en.wikipedia.org/wiki/Favicon\" rel=\"nofollow noreferrer\">favicons</a>. Browsers look at / on a server for favicon.ico</p>\n" }, { "answer_id": 16667736, "author": "Hisham", "author_id": 2390924, "author_profile": "https://Stackoverflow.com/users/2390924", "pm_score": 0, "selected": false, "text": "<p>This is called favicon you can look on this tutorial using favicon in asp.net application <a href=\"http://www.c-sharpcorner.com/uploadfile/afenster/add-a-favicon-to-your-Asp-Net-page/\" rel=\"nofollow\">LINK</a></p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11614/" ]
I would like to have information about the icons which are displayed alongside the site URLs on a web browser. Is this some browser specific feature? Where do we specify the icon source, ie, is it in some tag on the web page itself ?
These icons are called [favicons](http://en.wikipedia.org/wiki/Favicon) Most web browsers support <http://mysite.com/favicon.ico> but the proper way to do it is to include an icon meta tag in the head profile. ``` <head profile="http://www.w3.org/2005/10/profile"> <link rel="icon" type="image/png" href="/somewhere/myicon.png" /> […] </head> ``` [Source from the W3C itself.](http://www.w3.org/2005/10/howto-favicon) Your best bet is to probably do both with the same icon image.
120,422
<p>How do I iterate over a set of records in RPG(LE) with embedded SQL?</p>
[ { "answer_id": 120993, "author": "Mike Wills", "author_id": 2535, "author_profile": "https://Stackoverflow.com/users/2535", "pm_score": 5, "selected": true, "text": "<p>Usually I'll create a cursor and fetch each record.</p>\n\n<pre><code> //***********************************************************************\n // Main - Main Processing Routine\n begsr Main;\n\n exsr BldSqlStmt;\n\n if OpenSqlCursor() = SQL_SUCCESS;\n\n dow FetchNextRow() = SQL_SUCCESS;\n exsr ProcessRow;\n enddo;\n\n if sqlStt = SQL_NO_MORE_ROWS;\n CloseSqlCursor();\n endif;\n\n endif;\n\n CloseSqlCursor();\n\n endsr; // Main \n</code></pre>\n\n<p>I have added more detail to this answer <a href=\"http://mikewills.me/blog/how-do-i-iterate-over-a-set-of-records-in-rpg-with-embedded-sql/\" rel=\"noreferrer\">in a post on my website</a>.</p>\n" }, { "answer_id": 1247484, "author": "James R. Perkins", "author_id": 152794, "author_profile": "https://Stackoverflow.com/users/152794", "pm_score": 3, "selected": false, "text": "<p>As Mike said, iterating over a cursor is the best solution. I would add to give slightly better performance, you might might want to fetch into an array to process in blocks rather than one record at a time.</p>\n\n<p>Example:</p>\n\n<pre><code> EXEC SQL \n OPEN order_history; \n\n // Set the length \n len = %elem(results); \n\n // Loop through all the results \n dow (SqlState = Sql_Success); \n EXEC SQL \n FETCH FROM order_history FOR :len ROWS INTO :results; \n if (SQLER3 &lt;&gt; *zeros); \n for i = 1 to SQLER3 by 1; \n // Load the output \n eval-corr output = results(i); \n // Do something \n endfor; \n endif; \n enddo; \n</code></pre>\n\n<p>HTH,\nJames R. Perkins </p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I iterate over a set of records in RPG(LE) with embedded SQL?
Usually I'll create a cursor and fetch each record. ``` //*********************************************************************** // Main - Main Processing Routine begsr Main; exsr BldSqlStmt; if OpenSqlCursor() = SQL_SUCCESS; dow FetchNextRow() = SQL_SUCCESS; exsr ProcessRow; enddo; if sqlStt = SQL_NO_MORE_ROWS; CloseSqlCursor(); endif; endif; CloseSqlCursor(); endsr; // Main ``` I have added more detail to this answer [in a post on my website](http://mikewills.me/blog/how-do-i-iterate-over-a-set-of-records-in-rpg-with-embedded-sql/).
120,467
<p>I would like to confirm that the following analysis is correct:</p> <p>I am building a web app in RoR. I have a data structure for my postgres db designed (around 70 tables; this design may need changes and additions during development to reflect Rails ways of doing things. EG, I designed some user and role tables - but if it makes sense to use Restful Authentication, I will scrub them and replace with whatever RA requires. ).</p> <p>I have a shellscript which calls a series of .sql files to populate the empty database with tables and initial data (eg, Towns gets pre-filled with post towns) as well as test data (eg, Companies gets a few dummy companies so I have data to play with). </p> <p>for example:</p> <pre><code>CREATE TABLE towns ( id integer PRIMARY KEY DEFAULT nextval ('towns_seq'), county_id integer REFERENCES counties ON DELETE RESTRICT ON UPDATE CASCADE, country_id integer REFERENCES countries ON DELETE RESTRICT ON UPDATE CASCADE NOT NULL, name text NOT NULL UNIQUE ); </code></pre> <p>Proposition 0: Data lasts longer than apps, so I am convinced that I want referential integrity enforced at the DB level as well as validations in my RoR models, despite the lack of DRYNESS.</p> <p>Proposition 1: If I replace the script and sql files with Migrations, it is currently impossible to tell my Postgres database about the Foreign Key and other constraints I currently set in SQL DDL files within the migration code. </p> <p>Proposition 2: The touted benefit of migrations is that changes to the schema are versioned along with the RoR model code. But if I keep my scripts and .sql files in railsapp/db, I can version them just as easily.</p> <p>Proposition 3: Given that migrations lack functionality I want, and provide benefits I can replicate, there is little reason for me to consider using them. So I should --skipmigrations at script/generate model time. </p> <p>My question: If Proposition 0 is accepted, are Propositions 1,2,3 true or false, and why?</p> <p>Thanks!</p>
[ { "answer_id": 120491, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 2, "selected": false, "text": "<p>Proposition 1 is mistaken : you can definitely define referential integrity using migrations if only by using direct SQL inside the migration, see <a href=\"http://www.robbyonrails.com/articles/2005/11/11/rails-migrations-and-postgresql-constraints\" rel=\"nofollow noreferrer\">this post</a> for more details.</p>\n\n<p>Proposition 2: The touted interest of migrations is to be able to define your database model incrementally while keeping track of what each change added and be able to easily rollback any such change at a later time.</p>\n\n<p>You have to be careful with the order you create/modify things in but you can do it. </p>\n\n<p>One thing to keep in mind : rails is better suited for application-centri design. in the Rails Way(tm) the database is only ever accessed through the application active record layer and exposes data to the outside using webservices</p>\n" }, { "answer_id": 120494, "author": "Ben Scofield", "author_id": 6478, "author_profile": "https://Stackoverflow.com/users/6478", "pm_score": 4, "selected": true, "text": "<p>Proposition 1 is false in at least two situations - you can use plugins like <a href=\"http://github.com/vigetlabs/foreign_key_migrations/tree\" rel=\"noreferrer\">foreign_key_migrations</a> to do the following:</p>\n\n<pre><code>def self.up\n create_table :users do |t|\n t.column :department_id, :integer, :references =&gt; :departments\n end\nend\n</code></pre>\n\n<p>which creates the appropriate foreign key constraint in your DB.</p>\n\n<p>Of course, you might have other things that you want to do in your DDL, in which case the second situation becomes more compelling: you're not forced to use the Ruby DSL in migrations. Try the <code>execute</code> method, instead:</p>\n\n<pre><code>def self.up\n execute 'YOUR SQL HERE'\nend\n</code></pre>\n\n<p>With that, you can keep the contents of your SQL scripts in migrations, gaining the benefits of the latter (most prominently the <code>down</code> methods, which you didn't address in your original question) and retaining the lower-level control you prefer.</p>\n" }, { "answer_id": 120507, "author": "h3rald", "author_id": 21048, "author_profile": "https://Stackoverflow.com/users/21048", "pm_score": 1, "selected": false, "text": "<p>1: You may want to try out <a href=\"http://www.redhillonrails.org/foreign_key_migrations.html\" rel=\"nofollow noreferrer\">this plugin</a>. I didn't try it myself though, but it seems to be able to add foreign key constraints through migrations.</p>\n\n<p>2: The real benefit of migration is the ability to <em>go back and forth</em> in the history of your database. That's not as easy with your .sql files.</p>\n\n<p>3: See if the above-mentioned plugin works for you, then decide :) At any rate, it's not a capital sin if you don't use them!</p>\n" }, { "answer_id": 599259, "author": "Mike Berrow", "author_id": 17251, "author_profile": "https://Stackoverflow.com/users/17251", "pm_score": 0, "selected": false, "text": "<p>Since you are using Postgres and may not want to install the foreign_key_migrations plugin, here is what I do when I want to use both migrations and foreign key constraints.</p>\n\n<p>I add a SchemaStatements method to ActiveRecord::SchemaStatements called \"add_fk_constraint\".\nThis could go in some centralized file, but in the example migration file below, I have just put it inline.</p>\n\n<hr>\n\n<pre><code>module ActiveRecord\n module ConnectionAdapters # :nodoc:\n module SchemaStatements\n # Example call:\n # add_fk_constraint 'orders','advertiser_id','advertisers','id'\n # \"If you want add/alter a 'orders' record, then its 'advertiser_id' had\n # better point to an existing 'advertisers' record with corresponsding 'id'\"\n def add_fk_constraint(table_name, referencing_col, referenced_table, referenced_col)\n fk_name = \"#{table_name}_#{referencing_col}\"\n sql = &lt;&lt;-ENDSQL\n ALTER TABLE #{table_name}\n ADD CONSTRAINT #{fk_name}\n FOREIGN KEY (#{referencing_col}) REFERENCES #{referenced_table} (#{referenced_col})\n ON UPDATE NO ACTION ON DELETE CASCADE; \n CREATE INDEX fki_#{fk_name} ON #{table_name}(#{referencing_col});\n ENDSQL\n execute sql\n end\n end\n end\nend\n\nclass AdvertisersOrders &lt; ActiveRecord::Migration\n def self.up\n create_table :advertisers do |t|\n t.column :name, :string, :null =&gt; false\n t.column :net_id, :integer, :null =&gt; false\n t.column :source_service_id, :integer, :null =&gt; false, :default =&gt; 1\n t.column :source_id, :integer, :null =&gt; false \n end\n\n create_table :orders do |t|\n t.column :name, :string, :null =&gt; false\n t.column :advertiser_id, :integer, :null =&gt; false\n t.column :source_id, :integer, :null =&gt; false\n end\n add_fk_constraint 'orders','advertiser_id','advertisers','id'\n end\n\n def self.down\n drop_table :orders\n drop_table :advertisers\n end\nend\n</code></pre>\n\n<hr>\n\n<p>I hopes this helps someone. It has been very useful to me since I need to load a lot of externally supplied data with SQL \"COPY\" calls, yet I find the migrations system very convenient.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6941/" ]
I would like to confirm that the following analysis is correct: I am building a web app in RoR. I have a data structure for my postgres db designed (around 70 tables; this design may need changes and additions during development to reflect Rails ways of doing things. EG, I designed some user and role tables - but if it makes sense to use Restful Authentication, I will scrub them and replace with whatever RA requires. ). I have a shellscript which calls a series of .sql files to populate the empty database with tables and initial data (eg, Towns gets pre-filled with post towns) as well as test data (eg, Companies gets a few dummy companies so I have data to play with). for example: ``` CREATE TABLE towns ( id integer PRIMARY KEY DEFAULT nextval ('towns_seq'), county_id integer REFERENCES counties ON DELETE RESTRICT ON UPDATE CASCADE, country_id integer REFERENCES countries ON DELETE RESTRICT ON UPDATE CASCADE NOT NULL, name text NOT NULL UNIQUE ); ``` Proposition 0: Data lasts longer than apps, so I am convinced that I want referential integrity enforced at the DB level as well as validations in my RoR models, despite the lack of DRYNESS. Proposition 1: If I replace the script and sql files with Migrations, it is currently impossible to tell my Postgres database about the Foreign Key and other constraints I currently set in SQL DDL files within the migration code. Proposition 2: The touted benefit of migrations is that changes to the schema are versioned along with the RoR model code. But if I keep my scripts and .sql files in railsapp/db, I can version them just as easily. Proposition 3: Given that migrations lack functionality I want, and provide benefits I can replicate, there is little reason for me to consider using them. So I should --skipmigrations at script/generate model time. My question: If Proposition 0 is accepted, are Propositions 1,2,3 true or false, and why? Thanks!
Proposition 1 is false in at least two situations - you can use plugins like [foreign\_key\_migrations](http://github.com/vigetlabs/foreign_key_migrations/tree) to do the following: ``` def self.up create_table :users do |t| t.column :department_id, :integer, :references => :departments end end ``` which creates the appropriate foreign key constraint in your DB. Of course, you might have other things that you want to do in your DDL, in which case the second situation becomes more compelling: you're not forced to use the Ruby DSL in migrations. Try the `execute` method, instead: ``` def self.up execute 'YOUR SQL HERE' end ``` With that, you can keep the contents of your SQL scripts in migrations, gaining the benefits of the latter (most prominently the `down` methods, which you didn't address in your original question) and retaining the lower-level control you prefer.
120,470
<p>I'm using nhibernate to store some user settings for an app in a SQL Server Compact Edition table.</p> <p>This is an excerpt the mapping file:</p> <pre><code>&lt;property name="Name" type="string" /&gt; &lt;property name="Value" type="string" /&gt; </code></pre> <p>Name is a regular string/nvarchar(50), and Value is set as ntext in the DB</p> <p>I'm trying to write a large amount of xml to the "Value" property. I get an exception every time:</p> <pre><code>@p1 : String truncation: max=4000, len=35287, value='&lt;lots of xml..../&gt;' </code></pre> <p>I've googled it quite a bit, and tried a number of different mapping configurations:</p> <pre><code>&lt;property name="Name" type="string" /&gt; &lt;property name="Value" type="string" &gt; &lt;column name="Value" sql-type="StringClob" /&gt; &lt;/property&gt; </code></pre> <p>That's one example. Other configurations include "ntext" instead of "StringClob". Those configurations that don't throw mapping exceptions still throw the string truncation exception.</p> <p>Is this a problem ("feature") with SQL CE? Is it possible to put more than 4000 characters into a SQL CE database with nhibernate? If so, can anyone tell me how?</p> <p>Many thanks!</p>
[ { "answer_id": 120560, "author": "Jimmeh", "author_id": 20749, "author_profile": "https://Stackoverflow.com/users/20749", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;property name=\"Value\" type=\"string\" /&gt;\n &lt;column name=\"Value\" sql-type=\"StringClob\" /&gt;\n&lt;/property&gt;\n</code></pre>\n\n<p>I'm assuming this is a small typo, since you've closed the property tag twice. Just pointing this out, in case it wasn't a typo.</p>\n" }, { "answer_id": 120745, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 0, "selected": false, "text": "<p>Try <code>&lt;property name=\"Value\" type=\"string\" length=\"4001\" /&gt;</code></p>\n" }, { "answer_id": 120899, "author": "Reiste", "author_id": 21033, "author_profile": "https://Stackoverflow.com/users/21033", "pm_score": 0, "selected": false, "text": "<p>Tried:</p>\n\n<pre><code>&lt;property name=\"Value\" type=\"string\" length=\"4001\" /&gt;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>&lt;property name=\"Value\" type=\"string\" &gt;\n &lt;column name=\"Value\" sql-type=\"StringClob\" length=\"5000\"/&gt;\n&lt;/property&gt;\n</code></pre>\n\n<p>Neither worked, I'm afraid... Same exception - it still says that the max value is 4000.</p>\n" }, { "answer_id": 132250, "author": "Reiste", "author_id": 21033, "author_profile": "https://Stackoverflow.com/users/21033", "pm_score": 4, "selected": true, "text": "<p>Okay, with many thanks to Artur in <a href=\"http://groups.google.com/group/nhusers/browse_thread/thread/4f865f0f516234ca\" rel=\"nofollow noreferrer\">this thread</a>, here's the solution:\nInherit from the SqlServerCeDriver with a new one, and override the InitializeParamter method:</p>\n\n<pre><code>using System.Data;\nusing System.Data.SqlServerCe;\nusing NHibernate.Driver;\nusing NHibernate.SqlTypes;\n\nnamespace MySqlServerCeDriverNamespace\n{\n /// &lt;summary&gt;\n /// Overridden Nhibernate SQL CE Driver,\n /// so that ntext fields are not truncated at 4000 characters\n /// &lt;/summary&gt;\n public class MySqlServerCeDriver : SqlServerCeDriver\n {\n protected override void InitializeParameter(\n IDbDataParameter dbParam,\n string name,\n SqlType sqlType)\n {\n base.InitializeParameter(dbParam, name, sqlType);\n\n if (sqlType is StringClobSqlType)\n {\n var parameter = (SqlCeParameter)dbParam;\n parameter.SqlDbType = SqlDbType.NText;\n }\n\n }\n }\n}\n</code></pre>\n\n<p>Then, use this driver instead of NHibernate's in your app.config</p>\n\n<pre><code>&lt;nhibernateDriver&gt;MySqlServerCeDriverNamespace.MySqlServerCeDriver , MySqlServerCeDriverNamespace&lt;/nhibernateDriver&gt;\n</code></pre>\n\n<p>I saw a lot of other posts where people had this problem, and solved it by just changing the sql-type attribute to \"StringClob\" - as attempted in this thread.</p>\n\n<p>I'm not sure why it wouldn't work for me, but I suspect it is the fact that I'm using SQL CE and not some other DB. But, there you have it!</p>\n" }, { "answer_id": 214311, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 0, "selected": false, "text": "<p>Why are you using the sub-element syntax?</p>\n\n<p>try:</p>\n\n<pre><code>&lt;property name='Value' type='StringClob' /&gt;\n</code></pre>\n" }, { "answer_id": 724703, "author": "Kim Johansson", "author_id": 88000, "author_profile": "https://Stackoverflow.com/users/88000", "pm_score": 0, "selected": false, "text": "<p>On my current deplyoment of SQL CE and NHibernate I use a length of 4001. Then NHibernate generates the stuff as NTEXT instead of NVARCHAR.</p>\n\n<p>Try that.</p>\n\n<p>Another thing to use with NHibernate and SQL CE is:</p>\n\n<pre><code>&lt;session-factory&gt;\n ...\n &lt;property name=\"connection.release_mode\"&gt;on_close&lt;/property&gt;\n&lt;/session-factory&gt;\n</code></pre>\n\n<p>That solves some other problems for me atleast.</p>\n" }, { "answer_id": 7270955, "author": "wal", "author_id": 224410, "author_profile": "https://Stackoverflow.com/users/224410", "pm_score": 0, "selected": false, "text": "<p>After reading your post this modification got it working in my code</p>\n\n<pre><code>protected override void InitializeParameter(IDbDataParameter dbParam,string name,SqlType sqlType)\n {\n base.InitializeParameter(dbParam, name, sqlType);\n\n var stringType = sqlType as StringSqlType;\n if (stringType != null &amp;&amp; stringType.LengthDefined &amp;&amp; stringType.Length &gt; 4000)\n {\n var parameter = (SqlCeParameter)dbParam;\n parameter.SqlDbType = SqlDbType.NText;\n }\n\n }\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21033/" ]
I'm using nhibernate to store some user settings for an app in a SQL Server Compact Edition table. This is an excerpt the mapping file: ``` <property name="Name" type="string" /> <property name="Value" type="string" /> ``` Name is a regular string/nvarchar(50), and Value is set as ntext in the DB I'm trying to write a large amount of xml to the "Value" property. I get an exception every time: ``` @p1 : String truncation: max=4000, len=35287, value='<lots of xml..../>' ``` I've googled it quite a bit, and tried a number of different mapping configurations: ``` <property name="Name" type="string" /> <property name="Value" type="string" > <column name="Value" sql-type="StringClob" /> </property> ``` That's one example. Other configurations include "ntext" instead of "StringClob". Those configurations that don't throw mapping exceptions still throw the string truncation exception. Is this a problem ("feature") with SQL CE? Is it possible to put more than 4000 characters into a SQL CE database with nhibernate? If so, can anyone tell me how? Many thanks!
Okay, with many thanks to Artur in [this thread](http://groups.google.com/group/nhusers/browse_thread/thread/4f865f0f516234ca), here's the solution: Inherit from the SqlServerCeDriver with a new one, and override the InitializeParamter method: ``` using System.Data; using System.Data.SqlServerCe; using NHibernate.Driver; using NHibernate.SqlTypes; namespace MySqlServerCeDriverNamespace { /// <summary> /// Overridden Nhibernate SQL CE Driver, /// so that ntext fields are not truncated at 4000 characters /// </summary> public class MySqlServerCeDriver : SqlServerCeDriver { protected override void InitializeParameter( IDbDataParameter dbParam, string name, SqlType sqlType) { base.InitializeParameter(dbParam, name, sqlType); if (sqlType is StringClobSqlType) { var parameter = (SqlCeParameter)dbParam; parameter.SqlDbType = SqlDbType.NText; } } } } ``` Then, use this driver instead of NHibernate's in your app.config ``` <nhibernateDriver>MySqlServerCeDriverNamespace.MySqlServerCeDriver , MySqlServerCeDriverNamespace</nhibernateDriver> ``` I saw a lot of other posts where people had this problem, and solved it by just changing the sql-type attribute to "StringClob" - as attempted in this thread. I'm not sure why it wouldn't work for me, but I suspect it is the fact that I'm using SQL CE and not some other DB. But, there you have it!
120,503
<p>I'm trying to populate a TDBGrid with the results of the following TQuery against the file Journal.db:</p> <pre><code>select * from Journal where Journal.where = "RainPump" </code></pre> <p>I've tried both <code>Journal."Where"</code> and <code>Journal.[Where]</code> to no avail.</p> <p>I've also tried: <code>select Journal.[Where] as "Location"</code> with the same result.</p> <p>Journal.db is a file created by a third party and I am unable to change the field names.</p> <p>The problem is that the field I'm interested in is called 'where' and understandably causes the above error. How do I reference this field without causing the BDE (presumably) to explode?</p>
[ { "answer_id": 120518, "author": "Johan Bresler", "author_id": 3535708, "author_profile": "https://Stackoverflow.com/users/3535708", "pm_score": 0, "selected": false, "text": "<pre><code>select * from Journal where Journal.\"where\" = \"RainPump\"\n</code></pre>\n" }, { "answer_id": 120519, "author": "Branko", "author_id": 5362, "author_profile": "https://Stackoverflow.com/users/5362", "pm_score": 2, "selected": false, "text": "<p>Rewrite it like this, should work:</p>\n\n<pre><code>select * from Journal where Journal.[where] = \"RainPump\"\n</code></pre>\n" }, { "answer_id": 120620, "author": "mj2008", "author_id": 5544, "author_profile": "https://Stackoverflow.com/users/5544", "pm_score": 0, "selected": false, "text": "<p>Me, I'd rename the awkward column.</p>\n" }, { "answer_id": 120756, "author": "Johan Bresler", "author_id": 3535708, "author_profile": "https://Stackoverflow.com/users/3535708", "pm_score": 3, "selected": true, "text": "<p>You can insert the resultset into a new table with \"values\" (specifying no column names) where you have given your own column names in the new table and then do a select from that table, Using a TQuery, something like:</p>\n\n<pre><code>Query1.sql.clear;\nquery1,sql.add('Insert into newtable values (select * from Journal);');\nquery1.sql.add('Select * from newtable where newcolumn = \"Rainpump\";');\nquery1.open;\n</code></pre>\n" }, { "answer_id": 120984, "author": "Baldric", "author_id": 11781, "author_profile": "https://Stackoverflow.com/users/11781", "pm_score": 2, "selected": false, "text": "<p>Aah, I'm loving delphi again... I found a workaround. The TQuery component has the Filter property :-)<br>\nI omitted the \"Where=\" where clause from the query whilst still keeping all the other 'and' conditions.<br>\nI set the Filter property to \"Where = 'RainPump'\".<br>\nI set the Filtered property to True and life is good again.<br></p>\n\n<p>I'm still wondering if there's a smarter way to do this using this old technology but if it's stupid and it works, then it's not stupid.</p>\n" }, { "answer_id": 121767, "author": "Graza", "author_id": 11820, "author_profile": "https://Stackoverflow.com/users/11820", "pm_score": 0, "selected": false, "text": "<p>In MySQL, table/column names can be enclosed in `` (the angled single quotes). I'm not sure what the BDE allows, but you could try replacing [where] with `where`</p>\n" }, { "answer_id": 398201, "author": "A. I. Breveleri", "author_id": 45506, "author_profile": "https://Stackoverflow.com/users/45506", "pm_score": 2, "selected": false, "text": "<p>I'm afraid that someone reading this thread will get the impression that the BDE SQL engine cannot handle the query:</p>\n\n<pre><code>select * from Journal where Journal.\"Where\" = \"RainPump\"\n</code></pre>\n\n<p>and will waste their time unnecessarily circumlocuting around it.</p>\n\n<p>In fact this construction works fine. The quotes around \"Where\" keeps the BDE from interpreting it as a keyword, just as you would expect.</p>\n\n<p>I don't know what is wrong in Baldric's particular situation, or what he tried in what order. He describes the problem as querying a *.db table, but his SQL error looks more like something you'd get in passthrough mode. Or, possibly he simplified his code for submission, thus eliminating the true cause of the error.</p>\n\n<p>My tests performed with:\nBDE v.5.2 (5.2.0.2)\nParadox for Windows v. 7 (32b)\nDelphi 5.0 (5.62)</p>\n\n<p>Various versions of the statement that succeed:</p>\n\n<pre><code>select * from Journal D0 where D0.\"Where\" = \"RainPump\"\nselect * from Journal where Journal.\"Where\" = \"RainPump\"\nselect * from \":common:Journal\" D0 where D0.\"Where\" = \"RainPump\"\nselect * from \":common:Journal\" where \":common:Journal\".\"Where\" = \"RainPump\"\nselect * from :common:Journal where Journal.\"Where\" = \"RainPump\"\nselect * from \":common:Journal\" D0 where D0.\"GUMPIK\" = 3\nselect * from \":common:Journal\" where \":common:Journal\".\"GUMPIK\" = 3\nselect * from :common:Journal where Journal.\"GUMPIK\" = 3\n</code></pre>\n\n<p>Versions of the statement that look correct but fail with \"Invalid use of keyword\":</p>\n\n<pre><code>select * from \":common:Journal\" where :common:Journal.\"Where\" = \"RainPump\"\nselect * from :common:Journal where :common:Journal.\"Where\" = \"RainPump\"\nselect * from \":common:Journal\" where :common:Journal.\"GUMPIK\" = 3\nselect * from :common:Journal where :common:Journal.\"GUMPIK\" = 3\n</code></pre>\n\n<p>-Al.</p>\n" }, { "answer_id": 8029854, "author": "FlyingGuy", "author_id": 1032500, "author_profile": "https://Stackoverflow.com/users/1032500", "pm_score": 0, "selected": false, "text": "<p>Ok, so naming columns after keyboards is bad in ANY SQL system. Would you name a column \"select\" or \"count\" or \"alter\" or \"table\" or perhaps just for the fun of it \"truncate\" or \"drop\"? I would hope not.</p>\n\n<p>Even if you build in the work around for <strong>this</strong> instance you are creating a mine field for whomever comes after you. Do what mj2008 said and rename the bloody column.</p>\n\n<p>Allowing this column name to persist is the worst example of someone who is building a system and would get you on the poop list for any project manager.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11781/" ]
I'm trying to populate a TDBGrid with the results of the following TQuery against the file Journal.db: ``` select * from Journal where Journal.where = "RainPump" ``` I've tried both `Journal."Where"` and `Journal.[Where]` to no avail. I've also tried: `select Journal.[Where] as "Location"` with the same result. Journal.db is a file created by a third party and I am unable to change the field names. The problem is that the field I'm interested in is called 'where' and understandably causes the above error. How do I reference this field without causing the BDE (presumably) to explode?
You can insert the resultset into a new table with "values" (specifying no column names) where you have given your own column names in the new table and then do a select from that table, Using a TQuery, something like: ``` Query1.sql.clear; query1,sql.add('Insert into newtable values (select * from Journal);'); query1.sql.add('Select * from newtable where newcolumn = "Rainpump";'); query1.open; ```
120,504
<p>I'm trying to run the following SQL statement in Oracle, and it takes ages to run:</p> <pre><code>SELECT orderID FROM tasks WHERE orderID NOT IN (SELECT DISTINCT orderID FROM tasks WHERE engineer1 IS NOT NULL AND engineer2 IS NOT NULL) </code></pre> <p>If I run just the sub-part that is in the IN clause, that runs very quickly in Oracle, i.e.</p> <pre><code>SELECT DISTINCT orderID FROM tasks WHERE engineer1 IS NOT NULL AND engineer2 IS NOT NULL </code></pre> <p>Why does the whole statement take such a long time in Oracle? In SQL Server the whole statement runs quickly.</p> <p>Alternatively is there a simpler/different/better SQL statement I should use?</p> <p>Some more details about the problem:</p> <ul> <li>Each order is made of many tasks</li> <li>Each order will be allocated (one or more of its task will have engineer1 and engineer2 set) or the order can be unallocated (all its task have null values for the engineer fields)</li> <li>I am trying to find all the orderIDs that are unallocated.</li> </ul> <p>Just in case it makes any difference, there are ~120k rows in the table, and 3 tasks per order, so ~40k different orders.</p> <p>Responses to answers:</p> <ul> <li>I would prefer a SQL statement that works in both SQL Server and Oracle.</li> <li>The tasks only has an index on the orderID and taskID.</li> <li>I tried the NOT EXISTS version of the statement but it ran for over 3 minutes before I cancelled it. Perhaps need a JOIN version of the statement?</li> <li>There is an "orders" table as well with the orderID column. But I was trying to simplify the question by not including it in the original SQL statement.</li> </ul> <p>I guess that in the original SQL statement the sub-query is run every time for each row in the first part of the SQL statement - even though it is static and should only need to be run once?</p> <p>Executing</p> <pre><code>ANALYZE TABLE tasks COMPUTE STATISTICS; </code></pre> <p>made my original SQL statement execute much faster. </p> <p>Although I'm still curious why I have to do this, and if/when I would need to run it again?</p> <blockquote> <p>The statistics give Oracle's cost-based optimzer information that it needs to determine the efficiency of different execution plans: for example, the number of rowsin a table, the average width of rows, highest and lowest values per column, number of distinct values per column, clustering factor of indexes etc.</p> <p>In a small database you can just setup a job to gather statistics every night and leave it alone. In fact, this is the default under 10g. For larger implementations you usually have to weigh the stability of the execution plans against the way that the data changes, which is a tricky balance.</p> <p>Oracle also has a feature called "dynamic sampling" that is used to sample tables to determine relevant statistics at execution time. It's much more often used with data warehouses where the overhead of the sampling it outweighed by the potential performance increase for a long-running query.</p> </blockquote>
[ { "answer_id": 120516, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": 2, "selected": false, "text": "<p>The \"IN\" - clause is known in Oracle to be pretty slow. In fact, the internal query optimizer in Oracle cannot handle statements with \"IN\" pretty good. try using \"EXISTS\":</p>\n\n<pre><code>SELECT orderID FROM tasks WHERE orderID NOT EXISTS \n (SELECT DISTINCT orderID FROM tasks WHERE\n engineer1 IS NOT NULL AND engineer2 IS NOT NULL)`print(\"code sample\");`\n</code></pre>\n\n<p>Caution: Please check if the query builds the same data results.</p>\n\n<p>Edith says: ooops, the query is not well formed, but the general idea is correct. Oracle has to fulfill a full table scan for the second (inner) query, build the results and then compare them to the first (outer) query, that's why it's slowing down. Try</p>\n\n<pre><code>SELECT orderID AS oid FROM tasks WHERE NOT EXISTS \n (SELECT DISTINCT orderID AS oid2 FROM tasks WHERE\n engineer1 IS NOT NULL AND engineer2 IS NOT NULL and oid=oid2)\n</code></pre>\n\n<p>or something similiar ;-)</p>\n" }, { "answer_id": 120531, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "<p>Isn't your query the same as</p>\n\n<pre><code>SELECT orderID FROM tasks\nWHERE engineer1 IS NOT NULL OR engineer2 IS NOT NULL\n</code></pre>\n\n<p>?</p>\n" }, { "answer_id": 120545, "author": "Mac", "author_id": 8696, "author_profile": "https://Stackoverflow.com/users/8696", "pm_score": 0, "selected": false, "text": "<p>How about :</p>\n\n<pre><code>SELECT DISTINCT orderID FROM tasks t1 WHERE NOT EXISTS (SELECT * FROM tasks t2 WHERE t2.orderID=t1.orderID AND (engineer1 IS NOT NULL OR engineer2 IS NOT NULL));\n</code></pre>\n\n<p>I am not a guru of optimization, but maybe you also overlooked some indexes in your Oracle database.</p>\n" }, { "answer_id": 120558, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<p>Another option is to use MINUS (EXCEPT on MSSQL)</p>\n\n<pre><code>SELECT orderID FROM tasks\nMINUS\nSELECT DISTINCT orderID FROM tasks WHERE engineer1 IS NOT NULL \nAND engineer2 IS NOT NULL\n</code></pre>\n" }, { "answer_id": 120583, "author": "Michel", "author_id": 17316, "author_profile": "https://Stackoverflow.com/users/17316", "pm_score": -1, "selected": false, "text": "<p>Sub-queries are \"bad\" with Oracle. It's generally better do use joins.</p>\n\n<p>Here's an article on how to rewrite your subqueries with join : \n<a href=\"http://www.dba-oracle.com/sql/t_rewrite_subqueries_performance.htm\" rel=\"nofollow noreferrer\">http://www.dba-oracle.com/sql/t_rewrite_subqueries_performance.htm</a></p>\n" }, { "answer_id": 120597, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": -1, "selected": false, "text": "<p>Here is an alternate approach which I think gives what you want:</p>\n\n<pre><code>SELECT orderID\n FROM tasks\n GROUP BY orderID\n HAVING COUNT(engineer1) = 0 OR COUNT(engineer2) = 0\n</code></pre>\n\n<p>I'm not sure if you want \"AND\" or \"OR\" in the HAVING clause. It sounds like according to business logic these two fields should either both be populated or both be NULL; if this is guaranteed then you could reduce the condition to just checking engineer1.</p>\n\n<p>Your original query would, I think, give multiple rows per orderID, whereas mine will only give one. I am guessing this is OK since you are only fetching the orderID.</p>\n" }, { "answer_id": 120602, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": false, "text": "<p>Some questions:</p>\n\n<ul>\n<li>How many rows are there in tasks?</li>\n<li>What indexes are defined on it?</li>\n<li>Has the table been analyzed recently?</li>\n</ul>\n\n<p>Another way to write the same query would be:</p>\n\n<pre><code>select orderid from tasks\nminus\nselect orderid from tasks\nwhere engineer1 IS NOT NULL AND engineer2 IS NOT NULL\n</code></pre>\n\n<p>However, I would rather expect the query to involve an \"orders\" table:</p>\n\n<pre><code>select orderid from ORDERS\nminus\nselect orderid from tasks\nwhere engineer1 IS NOT NULL AND engineer2 IS NOT NULL\n</code></pre>\n\n<p>or </p>\n\n<pre><code>select orderid from ORDERS\nwhere orderid not in\n( select orderid from tasks\n where engineer1 IS NOT NULL AND engineer2 IS NOT NULL\n)\n</code></pre>\n\n<p>or </p>\n\n<pre><code>select orderid from ORDERS\nwhere not exists\n( select null from tasks\n where tasks.orderid = orders.orderid\n and engineer1 IS NOT NULL OR engineer2 IS NOT NULL\n)\n</code></pre>\n" }, { "answer_id": 120664, "author": "Ethan Post", "author_id": 4527, "author_profile": "https://Stackoverflow.com/users/4527", "pm_score": 2, "selected": false, "text": "<p>I agree with TZQTZIO, I don't get your query.</p>\n\n<p>If we assume the query did make sense then you might want to try using EXISTS as some suggest and avoid IN. IN is not always bad and there are likely cases which one could show it actually performs better than EXISTS.</p>\n\n<p>The question title is not very helpful. I could set this query up in one Oracle database and make it run slow and make it run fast in another. There are many factors that determine how the database resolves the query, object statistics, SYS schema statistics, and parameters, as well as server performance. Sqlserver vs. Oracle isn't the problem here.</p>\n\n<p>For those interested in query tuning and performance and want to learn more some of the google terms to search are \"oak table oracle\" and \"oracle jonathan lewis\".</p>\n" }, { "answer_id": 120780, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 2, "selected": false, "text": "<p>I would try using joins instead</p>\n\n<pre><code>SELECT \n t.orderID \nFROM \n tasks t\n LEFT JOIN tasks t1\n ON t.orderID = t1.orderID\n AND t1.engineer1 IS NOT NULL \n AND t1.engineer2 IS NOT NULL\nWHERE\n t1.orderID IS NULL \n</code></pre>\n\n<p>also your original query would probably be easier to understand if it was specified as:</p>\n\n<pre><code>SELECT orderID FROM orders WHERE orderID NOT IN \n(SELECT DISTINCT orderID FROM tasks WHERE\n engineer1 IS NOT NULL AND engineer2 IS NOT NULL)\n</code></pre>\n\n<p>(assuming you have orders table with all the orders listed)</p>\n\n<p>which can be then rewritten using joins as:</p>\n\n<pre><code>SELECT \n o.orderID \nFROM \n orders o\n LEFT JOIN tasks t\n ON o.orderID = t.orderID\n AND t.engineer1 IS NOT NULL \n AND t.engineer2 IS NOT NULL\nWHERE\n t.orderID IS NULL \n</code></pre>\n" }, { "answer_id": 120790, "author": "Jim Birchall", "author_id": 989, "author_profile": "https://Stackoverflow.com/users/989", "pm_score": -1, "selected": false, "text": "<p>If you have no index over the Engineer1 and Engineer2 columns then you are always going to generate a Table Scan in SQL Server and the equivalent whatever that may be in Oracle.</p>\n\n<p>If you just need the Orders that have unallocated tasks then the following should work just fine on both platforms, but you should also consider adding the indexes to the Tasks table to improve query perfomance.</p>\n\n<pre><code>SELECT DISTINCT orderID \nFROM tasks \nWHERE (engineer1 IS NULL OR engineer2 IS NULL)\n</code></pre>\n" }, { "answer_id": 120927, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you decide to create an ORDERS table, I'd add an ALLOCATED flag to it, and create a bitmap index. This approach also forces you to modify the business logic to keep the flag updated, but the queries will be lightning fast. It depends on how critical are the queries for the application. </p>\n\n<p>Regarding the answers, the simpler the better in this case. Forget subqueries, joins, distinct and group bys, they are not needed at all!</p>\n" }, { "answer_id": 120998, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 1, "selected": false, "text": "<p>I think several people have pretty much the right SQL, but are missing a join between the inner and outer queries.<br>\nTry this: </p>\n\n<pre><code>SELECT t1.orderID \nFROM tasks t1\nWHERE NOT EXISTS\n (SELECT 1 \n FROM tasks t2 \n WHERE t2.orderID = t1.orderID\n AND t2.engineer1 IS NOT NULL \n AND t2.engineer2 IS NOT NULL)\n</code></pre>\n" }, { "answer_id": 121161, "author": "hamishmcn", "author_id": 3590, "author_profile": "https://Stackoverflow.com/users/3590", "pm_score": 4, "selected": true, "text": "<p>Often this type of problem goes away if you analyze the tables involved (so Oracle has a better idea of the distribution of the data)</p>\n\n<pre><code>ANALYZE TABLE tasks COMPUTE STATISTICS;\n</code></pre>\n" }, { "answer_id": 121183, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 0, "selected": false, "text": "<p>What proportion of the rows in the table meet the condition \"engineer1 IS NOT NULL AND engineer2 IS NOT NULL\"?</p>\n\n<p>This tells you (roughly) whether it might be worth trying to use an index to retrieve the associated orderid's.</p>\n\n<p>Another way to write the query in Oracle that would handle unindexed cases very well would be:</p>\n\n<pre><code>select distinct orderid\nfrom\n(\nselect orderid,\n max(case when engineer1 is null and engineer2 is null then 0 else 1)\n over (partition by orderid)\n as max_null_finder\nfrom tasks\n)\nwhere max_null_finder = 0\n</code></pre>\n" }, { "answer_id": 121214, "author": "JoshL", "author_id": 20625, "author_profile": "https://Stackoverflow.com/users/20625", "pm_score": 0, "selected": false, "text": "<p>The Oracle optimizer does a good job of processing MINUS statements. If you re-write your query using MINUS, it is likely to run quite quickly:</p>\n\n<pre><code>SELECT orderID FROM tasks\nMINUS\nSELECT DISTINCT orderID FROM tasks WHERE\n engineer1 IS NOT NULL AND engineer2 IS NOT NULL\n</code></pre>\n" }, { "answer_id": 121538, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "<p>New take.</p>\n\n<p><strong>Iff</strong>:</p>\n\n<ul>\n<li>The COUNT() function does not count NULL values</li>\n</ul>\n\n<p><strong>and</strong></p>\n\n<ul>\n<li>You want the orderID of all tasks where <strong>none</strong> of the tasks have either engineer1 or engineer2 set to a value</li>\n</ul>\n\n<p><strong>then</strong> this should do what you want:</p>\n\n<pre><code>SELECT orderID\nFROM tasks\nGROUP BY orderID\nHAVING COUNT(engineer1) = 0 AND COUNT(engineer2) = 0\n</code></pre>\n\n<p>Please test it.</p>\n" }, { "answer_id": 121679, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 1, "selected": false, "text": "<p>\"Although I'm still curious why I have to do this, and if/when I would need to run it again?\"</p>\n\n<p>The statistics give Oracle's cost-based optimzer information that it needs to determine the efficiency of different execution plans: for example, the number of rowsin a table, the average width of rows, highest and lowest values per column, number of distinct values per column, clustering factor of indexes etc.</p>\n\n<p>In a small database you can just setup a job to gather statistics every night and leave it alone. In fact, this is the default under 10g. For larger implementations you usually have to weigh the stability of the execution plans against the way that the data changes, which is a tricky balance.</p>\n\n<p>Oracle also has a feature called \"dynamic sampling\" that is used to sample tables to determine relevant statistics at execution time. It's much more often used with data warehouses where the overhead of the sampling it outweighed by the potential performance increase for a long-running query.</p>\n" }, { "answer_id": 195779, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 0, "selected": false, "text": "<p>I agree with ΤΖΩΤΖΙΟΥ and wearejimbo that your query should be...</p>\n\n<pre><code>SELECT DISTINCT orderID FROM Tasks \nWHERE Engineer1 IS NULL OR Engineer2 IS NULL;\n</code></pre>\n\n<p>I don't know about SQL Server, but this query won't be able to take advantage of any indexes because null rows aren't in indexes. The solution to this would be to re-write the query in a way that would allow a function based index to be created that only includes the null value rows. This could be done with NVL2, but would likely not be portable to SQL Server.</p>\n\n<p>I think the best answer is not one that meets your criteria and that is write a different statement for each platform that is best for that platform.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7261/" ]
I'm trying to run the following SQL statement in Oracle, and it takes ages to run: ``` SELECT orderID FROM tasks WHERE orderID NOT IN (SELECT DISTINCT orderID FROM tasks WHERE engineer1 IS NOT NULL AND engineer2 IS NOT NULL) ``` If I run just the sub-part that is in the IN clause, that runs very quickly in Oracle, i.e. ``` SELECT DISTINCT orderID FROM tasks WHERE engineer1 IS NOT NULL AND engineer2 IS NOT NULL ``` Why does the whole statement take such a long time in Oracle? In SQL Server the whole statement runs quickly. Alternatively is there a simpler/different/better SQL statement I should use? Some more details about the problem: * Each order is made of many tasks * Each order will be allocated (one or more of its task will have engineer1 and engineer2 set) or the order can be unallocated (all its task have null values for the engineer fields) * I am trying to find all the orderIDs that are unallocated. Just in case it makes any difference, there are ~120k rows in the table, and 3 tasks per order, so ~40k different orders. Responses to answers: * I would prefer a SQL statement that works in both SQL Server and Oracle. * The tasks only has an index on the orderID and taskID. * I tried the NOT EXISTS version of the statement but it ran for over 3 minutes before I cancelled it. Perhaps need a JOIN version of the statement? * There is an "orders" table as well with the orderID column. But I was trying to simplify the question by not including it in the original SQL statement. I guess that in the original SQL statement the sub-query is run every time for each row in the first part of the SQL statement - even though it is static and should only need to be run once? Executing ``` ANALYZE TABLE tasks COMPUTE STATISTICS; ``` made my original SQL statement execute much faster. Although I'm still curious why I have to do this, and if/when I would need to run it again? > > The statistics give Oracle's > cost-based optimzer information that > it needs to determine the efficiency > of different execution plans: for > example, the number of rowsin a table, > the average width of rows, highest and > lowest values per column, number of > distinct values per column, clustering > factor of indexes etc. > > > In a small database you can just setup > a job to gather statistics every night > and leave it alone. In fact, this is > the default under 10g. For larger > implementations you usually have to > weigh the stability of the execution > plans against the way that the data > changes, which is a tricky balance. > > > Oracle also has a feature called > "dynamic sampling" that is used to > sample tables to determine relevant > statistics at execution time. It's > much more often used with data > warehouses where the overhead of the > sampling it outweighed by the > potential performance increase for a > long-running query. > > >
Often this type of problem goes away if you analyze the tables involved (so Oracle has a better idea of the distribution of the data) ``` ANALYZE TABLE tasks COMPUTE STATISTICS; ```
120,540
<p>I´m programming a .NET Compact Framework application which shows maps on a PDA.</p> <p>I´ve created an ad hoc component that paints it´s own piece of the whole map, using several of this components the big picture is composed. I did it this way to avoid the latency of painting the whole map in a single step.</p> <p>What I would like to do now is to paint this pieces in their own thread, so the map appears to grow as a single entity and (also, and more important) to avoid freezing the rest of the user interface.</p> <p>Right know each piece of the map is painted in its onPaint method. My idea is to, somehow, tell the system "execute this code in a thread please".</p> <p>Something like:</p> <pre><code>protected override void OnPaint(PaintEventArgs e) { // &lt;code to be executed in a thread&gt; e.Graphics.paintTHis(); e.Graphics.paintThat(); whateverItTakesToPaintThisPieceOfTheMap(); // &lt;/code to be executed in a thread&gt; } </code></pre> <p>Do you know how to do this? Or is my approach simply wrong?</p> <p>Thanks for your time!</p>
[ { "answer_id": 120553, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 2, "selected": false, "text": "<p>The approach is wrong. Code that updates the ui has to run on the ui thread. You'll get an exception if you update the ui from another thread.</p>\n" }, { "answer_id": 120568, "author": "Gustavo Carreno", "author_id": 8167, "author_profile": "https://Stackoverflow.com/users/8167", "pm_score": 0, "selected": false, "text": "<p>I would suggest that you have some kind of messaging system from the underlying threads to the main UI thread.</p>\n\n<p>This way the main UI thread makes all the changes and is triggered from the underlying threads. Also make sure you can send some data with those messages, in case you want to send some complex information back to the main UI thread.</p>\n" }, { "answer_id": 120571, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>In order to call a function that updates the UI from another thread use the Invoke function of the Form.</p>\n\n<p>Here is a good reference</p>\n\n<p><a href=\"http://weblogs.asp.net/justin_rogers/articles/126345.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/justin_rogers/articles/126345.aspx</a></p>\n\n<p>Edit: as pointed out in comments BeginInvoke would be better if you want the calling code not to wait for the UI thread.</p>\n" }, { "answer_id": 121277, "author": "ima", "author_id": 5733, "author_profile": "https://Stackoverflow.com/users/5733", "pm_score": 1, "selected": false, "text": "<p>Draw map in memory in a background thread, then render (in the UI thread) that raster image to screen when ready. Use BufferedGraphics if possible, GDI otherwise.</p>\n" }, { "answer_id": 142515, "author": "Martin Liesén", "author_id": 20715, "author_profile": "https://Stackoverflow.com/users/20715", "pm_score": 1, "selected": false, "text": "<p>If rendering the map is time consuming and you don't want to freeze the GUI thread (make you app unresponsive) you could divide the screen into cells. Use a background thread to render a cell as a bitmap, use Invoke to tell the GUI thread to draw the finished cell, when invoke returns, let the thread continue on with the next cell.</p>\n\n<p>You will need to draw direcly onto the control (not inside Paint()) or you will need to call a invalidateRect and have some logic to make sure your calculated image matches what the system wants you to draw.</p>\n\n<p>This will make your image appear gradually, and your UI will be responsive. If the user makes some kind of action that makes it unnecessary to continue drawing, just abort the thread.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/623/" ]
I´m programming a .NET Compact Framework application which shows maps on a PDA. I´ve created an ad hoc component that paints it´s own piece of the whole map, using several of this components the big picture is composed. I did it this way to avoid the latency of painting the whole map in a single step. What I would like to do now is to paint this pieces in their own thread, so the map appears to grow as a single entity and (also, and more important) to avoid freezing the rest of the user interface. Right know each piece of the map is painted in its onPaint method. My idea is to, somehow, tell the system "execute this code in a thread please". Something like: ``` protected override void OnPaint(PaintEventArgs e) { // <code to be executed in a thread> e.Graphics.paintTHis(); e.Graphics.paintThat(); whateverItTakesToPaintThisPieceOfTheMap(); // </code to be executed in a thread> } ``` Do you know how to do this? Or is my approach simply wrong? Thanks for your time!
The approach is wrong. Code that updates the ui has to run on the ui thread. You'll get an exception if you update the ui from another thread.
120,561
<p>We have a vxWorks design which requires one task to process both high and low priority messages sent over two message queues.<br> The messages for a given priority have to be processed in FIFO order. </p> <p>For example, process all the high priority messages in the order they were received, then process the low priority messages. If there is no high priority message, then process the low priority message immediately.</p> <p>Is there a way to do this?</p>
[ { "answer_id": 120788, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 1, "selected": false, "text": "<p>In vxWorks, you can't wait directly on multiple queues. You can however use the OS events (from eventLib) to achieve this result.\nHere is a simple code snippet:</p>\n\n<pre><code>\nMSG_Q_ID lowQ, hiQ;\n\nvoid Init() {\n// Task Initialization Code. This should be called from the task that will\n// be receiving the messages\n...\nhiQ = msgQCreate(...);\nlowQ = msgQCreate(...);\nmsgQEvStart(hiQ, VX_EV01); // Event 1 sent when hiQ receives message\nmsgQEvStart(loQ, VX_EV02); // Event 2 sent when loQ receives message\n...\n}\nvoid RxMessages() {\n...\n UINT32 ev; // Event received\n\n // Blocks until we receive Event 1 or 2\n eventReceive(VX_EV01 | VX_EV02, EVENT_WAIT_ANY, WAIT_FOREVER, &ev);\n if(ev & VX_EV01) {\n msgQReceive(hiQ, ...);\n }\n if(ev & VX_EV02) {\n msgQReceive(loQ, ...);\n }\n}\n</code></pre>\n\n<p>Note that you need to modify that code to make sure you drain all your queues in case there is more than one message that was received.</p>\n\n<p>The same mechanism can also be applied to Binary semaphores using the semEvStart() function.</p>\n" }, { "answer_id": 142002, "author": "JayG", "author_id": 5823, "author_profile": "https://Stackoverflow.com/users/5823", "pm_score": 3, "selected": true, "text": "<p>If you use named pipes (pipeDevCreate(), write(), read()) instead of message queues, you can use select() to block until there are messages in either pipe. <br></p>\n\n<p>Whenever select() triggers, you process all messages in the high priority pipe. Then you process a single message from the low priority pipe. Then call select again (loop).</p>\n\n<p>Example Code snippets:</p>\n\n<pre><code> // Initialization: Create high and low priority named pipes\n pipeDrv(); //initialize pipe driver\n int fdHi = pipeDevCreate(\"/pipe/high\",numMsgs,msgSize);\n int fdLo = pipeDevCreate(\"/pipe/low\",numMsgs,msgSize);\n\n ...\n\n // Message sending thread: Add messages to pipe\n write(fdHi, buf, sizeof(buf));\n\n ...\n\n // Message processing Thread: select loop\n fd_set rdFdSet;\n\n while(1)\n {\n FD_ZERO(&amp;rdFdSet);\n FD_SET(fdHi, &amp;rdFdSet);\n FD_SET(fdLo, &amp;rdFdSet;\n\n if (select(FD_SETSIZE, &amp;rdFdSet, NULL, NULL, NULL) != ERROR)\n {\n if (FD_ISSET(fdHi, &amp;rdFdSet))\n {\n // process all high-priority messages\n while(read(fdHi,buf,size) &gt; 0)\n {\n //process high-priority\n }\n }\n\n if (FD_ISSET(fdLo, &amp;rdFdSet))\n {\n // process a single low priority message\n if (read(fdLo,buf,size) &gt; 0)\n {\n // process low priority\n }\n }\n }\n }\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
We have a vxWorks design which requires one task to process both high and low priority messages sent over two message queues. The messages for a given priority have to be processed in FIFO order. For example, process all the high priority messages in the order they were received, then process the low priority messages. If there is no high priority message, then process the low priority message immediately. Is there a way to do this?
If you use named pipes (pipeDevCreate(), write(), read()) instead of message queues, you can use select() to block until there are messages in either pipe. Whenever select() triggers, you process all messages in the high priority pipe. Then you process a single message from the low priority pipe. Then call select again (loop). Example Code snippets: ``` // Initialization: Create high and low priority named pipes pipeDrv(); //initialize pipe driver int fdHi = pipeDevCreate("/pipe/high",numMsgs,msgSize); int fdLo = pipeDevCreate("/pipe/low",numMsgs,msgSize); ... // Message sending thread: Add messages to pipe write(fdHi, buf, sizeof(buf)); ... // Message processing Thread: select loop fd_set rdFdSet; while(1) { FD_ZERO(&rdFdSet); FD_SET(fdHi, &rdFdSet); FD_SET(fdLo, &rdFdSet; if (select(FD_SETSIZE, &rdFdSet, NULL, NULL, NULL) != ERROR) { if (FD_ISSET(fdHi, &rdFdSet)) { // process all high-priority messages while(read(fdHi,buf,size) > 0) { //process high-priority } } if (FD_ISSET(fdLo, &rdFdSet)) { // process a single low priority message if (read(fdLo,buf,size) > 0) { // process low priority } } } } ```
120,584
<p>In a <a href="http://www.pygame.org/" rel="nofollow noreferrer">pyGame</a> application, I would like to render resolution-free GUI widgets described in SVG.</p> <p>How can I achieve this?</p> <p>(I like the <a href="http://ocemp.sourceforge.net/gui.html" rel="nofollow noreferrer">OCEMP GUI</a> toolkit but it seems to be bitmap dependent for its rendering)</p>
[ { "answer_id": 120794, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"http://www.cairographics.org/\" rel=\"noreferrer\">Cairo</a> (with PyCairo), which has support for rendering SVGs. The PyGame webpage has a <a href=\"http://www.pygame.org/wiki/CairoPygame\" rel=\"noreferrer\">HOWTO</a> for rendering into a buffer with a Cairo, and using that buffer directly with PyGame.</p>\n" }, { "answer_id": 121651, "author": "Alec Thomas", "author_id": 7980, "author_profile": "https://Stackoverflow.com/users/7980", "pm_score": 2, "selected": false, "text": "<p>I realise this doesn't exactly answer your question, but there's a library called <a href=\"http://www.supereffective.org/?p=14\" rel=\"nofollow noreferrer\">Squirtle</a> that will render SVG files using either Pyglet or PyOpenGL.</p>\n" }, { "answer_id": 121653, "author": "Pierre-Jean Coudert", "author_id": 8450, "author_profile": "https://Stackoverflow.com/users/8450", "pm_score": 2, "selected": false, "text": "<p>Cairo cannot render SVG out of the box.\nIt seems we have to use librsvg.</p>\n\n<p>Just found those two pages:</p>\n\n<ul>\n<li><a href=\"http://www.cairographics.org/cookbook/librsvgpython/\" rel=\"nofollow noreferrer\">Rendering SVG with libRSVG,Python and c-types</a> </li>\n<li><a href=\"http://www.cairographics.org/pyrsvg/\" rel=\"nofollow noreferrer\">How to use librsvg from Python</a></li>\n</ul>\n\n<p>Something like this should probably work (render <strong>test.svg</strong> to <strong>test.png</strong>):</p>\n\n<pre><code>import cairo\nimport rsvg\n\nWIDTH, HEIGHT = 256, 256\nsurface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)\n\nctx = cairo.Context (surface)\n\nsvg = rsvg.Handle(file=\"test.svg\")\nsvg.render_cairo(ctx)\n\nsurface.write_to_png(\"test.png\")\n</code></pre>\n" }, { "answer_id": 152222, "author": "Dickon Reed", "author_id": 22668, "author_profile": "https://Stackoverflow.com/users/22668", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://paul.giannaros.org/sandbox_pygamesvg\" rel=\"nofollow noreferrer\">pygamesvg</a> seems to do what you want (though I haven't tried it).</p>\n" }, { "answer_id": 341742, "author": "Johan Dahlin", "author_id": 14337, "author_profile": "https://Stackoverflow.com/users/14337", "pm_score": 5, "selected": true, "text": "<p>This is a complete example which combines hints by other people here.\nIt should render a file called test.svg from the current directory. It was tested on Ubuntu 10.10, python-cairo 1.8.8, python-pygame 1.9.1, python-rsvg 2.30.0.</p>\n\n<pre><code>#!/usr/bin/python\n\nimport array\nimport math\n\nimport cairo\nimport pygame\nimport rsvg\n\nWIDTH = 512\nHEIGHT = 512\n\ndata = array.array('c', chr(0) * WIDTH * HEIGHT * 4)\nsurface = cairo.ImageSurface.create_for_data(\n data, cairo.FORMAT_ARGB32, WIDTH, HEIGHT, WIDTH * 4)\n\npygame.init()\nwindow = pygame.display.set_mode((WIDTH, HEIGHT))\nsvg = rsvg.Handle(file=\"test.svg\")\nctx = cairo.Context(surface)\nsvg.render_cairo(ctx)\n\nscreen = pygame.display.get_surface()\nimage = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),\"ARGB\")\nscreen.blit(image, (0, 0)) \npygame.display.flip() \n\nclock = pygame.time.Clock()\nwhile True:\n clock.tick(15)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n raise SystemExit\n</code></pre>\n" }, { "answer_id": 4950448, "author": "Dave", "author_id": 610409, "author_profile": "https://Stackoverflow.com/users/610409", "pm_score": 1, "selected": false, "text": "<p>The last comment crashed when I ran it because svg.render_cairo() is expecting a cairo context and not a cairo surface. I created and tested the following function and it seems to run fine on my system.</p>\n\n<pre><code>import array,cairo, pygame,rsvg\n\ndef loadsvg(filename,surface,position):\n WIDTH = surface.get_width()\n HEIGHT = surface.get_height()\n data = array.array('c', chr(0) * WIDTH * HEIGHT * 4)\n cairosurface = cairo.ImageSurface.create_for_data(data, cairo.FORMAT_ARGB32, WIDTH, HEIGHT, WIDTH * 4)\n svg = rsvg.Handle(filename)\n svg.render_cairo(cairo.Context(cairosurface))\n image = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),\"ARGB\")\n surface.blit(image, position) \n\nWIDTH = 800\nHEIGHT = 600\npygame.init()\nwindow = pygame.display.set_mode((WIDTH, HEIGHT))\nscreen = pygame.display.get_surface()\n\nloadsvg(\"test.svg\",screen,(0,0))\n\npygame.display.flip() \n\nclock = pygame.time.Clock()\nwhile True:\n clock.tick(15)\n event = pygame.event.get()\n for e in event:\n if e.type == 12:\n raise SystemExit\n</code></pre>\n" }, { "answer_id": 26188526, "author": "loopbackbee", "author_id": 1595865, "author_profile": "https://Stackoverflow.com/users/1595865", "pm_score": 0, "selected": false, "text": "<p>Based on other answers, here's a function to read a SVG file into a pygame image - including correcting color channel order and scaling:</p>\n\n<pre><code>def pygame_svg( svg_file, scale=1 ):\n svg = rsvg.Handle(file=svg_file)\n width, height= map(svg.get_property, (\"width\", \"height\"))\n width*=scale; height*=scale\n data = array.array('c', chr(0) * width * height * 4)\n surface = cairo.ImageSurface.create_for_data( data, cairo.FORMAT_ARGB32, width, height, width*4)\n ctx = cairo.Context(surface)\n ctx.scale(scale, scale)\n svg.render_cairo(ctx)\n\n #seemingly, cairo and pygame expect channels in a different order...\n #if colors/alpha are funny, mess with the next lines\n import numpy\n data= numpy.fromstring(data, dtype='uint8')\n data.shape= (height, width, 4)\n c= data.copy()\n data[::,::,0]=c[::,::,1]\n data[::,::,1]=c[::,::,0]\n data[::,::,2]=c[::,::,3]\n data[::,::,3]=c[::,::,2]\n\n image = pygame.image.frombuffer(data.tostring(), (width, height),\"ARGB\")\n return image\n</code></pre>\n" }, { "answer_id": 51058233, "author": "zgoda", "author_id": 12138, "author_profile": "https://Stackoverflow.com/users/12138", "pm_score": 4, "selected": false, "text": "<p>The question is quite old but 10 years passed and there is new possibility that works and does not require <code>librsvg</code> anymore. There is <a href=\"https://github.com/ethanhs/pynanosvg\" rel=\"noreferrer\">Cython wrapper over nanosvg library</a> and it works:</p>\n\n<pre><code>from svg import Parser, Rasterizer\n\n\ndef load_svg(filename, surface, position, size=None):\n if size is None:\n w = surface.get_width()\n h = surface.get_height()\n else:\n w, h = size\n svg = Parser.parse_file(filename)\n rast = Rasterizer()\n buff = rast.rasterize(svg, w, h)\n image = pygame.image.frombuffer(buff, (w, h), 'ARGB')\n surface.blit(image, position)\n</code></pre>\n\n<p>I found Cairo/rsvg solution too complicated to get to work because of dependencies are quite obscure to install.</p>\n" }, { "answer_id": 64598021, "author": "Rabbid76", "author_id": 5577765, "author_profile": "https://Stackoverflow.com/users/5577765", "pm_score": 4, "selected": false, "text": "<p><strong>SVG files are supported with Pygame Version 2.0</strong>. Since Version 2.0.2, SDL Image supports SVG (<a href=\"https://en.wikipedia.org/wiki/Scalable_Vector_Graphics\" rel=\"noreferrer\">Scalable Vector Graphics</a>) files (see <a href=\"https://www.libsdl.org/projects/SDL_image\" rel=\"noreferrer\">SDL_image 2.0</a>). Therefore, with pygame version 2.0.1, SVG files can be loaded into a <a href=\"https://www.pygame.org/docs/ref/surface.html\" rel=\"noreferrer\"><code>pygame.Surface</code></a> object with <a href=\"http://www.pygame.org/docs/ref/image.html\" rel=\"noreferrer\"><code>pygame.image.load()</code></a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>surface = pygame.image.load('my.svg')\n</code></pre>\n<p>Before Pygame 2, you had to implement <a href=\"https://en.wikipedia.org/wiki/Scalable_Vector_Graphics\" rel=\"noreferrer\">Scalable Vector Graphics</a> loading with other libraries. Below are some ideas on how to do this.</p>\n<hr />\n<p>A very simple solution is to use <a href=\"https://cairosvg.org/\" rel=\"noreferrer\">CairoSVG</a>. With the function <code>cairosvg.svg2png</code>, an <a href=\"https://de.wikipedia.org/wiki/Scalable_Vector_Graphics\" rel=\"noreferrer\">Vector Graphics (SVG)</a> files can be directly converted to an [Portable Network Graphics (PNG)] file</p>\n<p>Install <a href=\"https://pypi.org/project/CairoSVG/\" rel=\"noreferrer\">CairoSVG</a>.</p>\n<pre class=\"lang-none prettyprint-override\"><code>pip install CairoSVG\n</code></pre>\n<p>Write a function that converts a SVF file to a PNG (<a href=\"https://docs.python.org/3/library/io.html\" rel=\"noreferrer\"><code>ByteIO</code></a>) and creates a <a href=\"https://www.pygame.org/docs/ref/surface.html\" rel=\"noreferrer\"><code>pygame.Surface</code></a> object may look as follows:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import cairosvg\nimport io\n\ndef load_svg(filename):\n new_bites = cairosvg.svg2png(url = filename)\n byte_io = io.BytesIO(new_bites)\n return pygame.image.load(byte_io)\n</code></pre>\n<p>See also <a href=\"https://github.com/Rabbid76/PyGameExamplesAndAnswers/blob/master/documentation/pygame/pygame_surface_and_image.md#load-svg\" rel=\"noreferrer\">Load SVG</a></p>\n<hr />\n<p>An alternative is to use <em>svglib</em>. However, there seems to be a problem with transparent backgrounds. There is an issue about this topic <a href=\"https://github.com/deeplook/svglib/issues/171\" rel=\"noreferrer\">How to make the png background transparent? #171</a>.</p>\n<p>Install <a href=\"https://pypi.org/project/svglib/\" rel=\"noreferrer\">svglib</a>.</p>\n<pre class=\"lang-none prettyprint-override\"><code>pip install svglib\n</code></pre>\n<p>A function that parses and rasterizes an SVG file and creates a <a href=\"https://www.pygame.org/docs/ref/surface.html\" rel=\"noreferrer\"><code>pygame.Surface</code></a> object may look as follows:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from svglib.svglib import svg2rlg\nimport io\n\ndef load_svg(filename):\n drawing = svg2rlg(filename)\n str = drawing.asString(&quot;png&quot;)\n byte_io = io.BytesIO(str)\n return pygame.image.load(byte_io)\n</code></pre>\n<hr />\n<p>Anther simple solution is to use <em>pynanosvg</em>. The downside of this solution is that <em>nanosvg</em> is no longer actively supported and does not work with Python 3.9. <a href=\"https://github.com/ethanhs/pynanosvg\" rel=\"noreferrer\">pynanosvg</a> can be used to load and rasterize <a href=\"https://de.wikipedia.org/wiki/Scalable_Vector_Graphics\" rel=\"noreferrer\">Vector Graphics (SVG)</a> files. Install <a href=\"https://cython.org/\" rel=\"noreferrer\">Cython</a> and <a href=\"https://github.com/ethanhs/pynanosvg\" rel=\"noreferrer\">pynanosvg</a>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>pip install Cython\npip install pynanosvg\n</code></pre>\n<p>The SVG file can be read, rasterized and loaded into a <a href=\"https://www.pygame.org/docs/ref/surface.html\" rel=\"noreferrer\"><code>pygame.Surface</code></a> object with the following function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from svg import Parser, Rasterizer\n\ndef load_svg(filename, scale=None, size=None, clip_from=None, fit_to=None, foramt='RGBA'):\n svg = Parser.parse_file(filename)\n scale = min((fit_to[0] / svg.width, fit_to[1] / svg.height)\n if fit_to else ([scale if scale else 1] * 2))\n width, height = size if size else (svg.width, svg.height)\n surf_size = round(width * scale), round(height * scale)\n buffer = Rasterizer().rasterize(svg, *surf_size, scale, *(clip_from if clip_from else 0, 0))\n return pygame.image.frombuffer(buffer, surf_size, foramt)\n</code></pre>\n<hr />\n<p>Minimal example:</p>\n<p><a href=\"https://i.stack.imgur.com/LOMwY.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/LOMwY.png\" alt=\"\" /></a></p>\n<pre class=\"lang-py prettyprint-override\"><code>import cairosvg\nimport pygame\nimport io\n\ndef load_svg(filename):\n new_bites = cairosvg.svg2png(url = filename)\n byte_io = io.BytesIO(new_bites)\n return pygame.image.load(byte_io)\n\npygame.init()\nwindow = pygame.display.set_mode((300, 300))\nclock = pygame.time.Clock()\n\npygame_surface = load_svg('Ice-001.svg')\nsize = pygame_surface.get_size()\nscale = min(window.get_width() / size[0], window.get_width() / size[1]) * 0.8\npygame_surface = pygame.transform.scale(pygame_surface, (round(size[0] * scale), round(size[1] * scale)))\n\nrun = True\nwhile run:\n clock.tick(60)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n window.fill((127, 127, 127))\n window.blit(pygame_surface, pygame_surface.get_rect(center = window.get_rect().center))\n pygame.display.flip()\n\npygame.quit()\nexit()\n</code></pre>\n" }, { "answer_id": 74401182, "author": "MestreLion", "author_id": 624066, "author_profile": "https://Stackoverflow.com/users/624066", "pm_score": 0, "selected": false, "text": "<p>Despite <a href=\"https://stackoverflow.com/a/64598021/624066\">Pygame/SDL new support for SVG files</a>, its rendering features are still very limited, so LibRsvg might still be needed. This is a 2022 update for the <a href=\"https://stackoverflow.com/a/341742/624066\">accepted answer</a> that works with modern versions of Python, Pygame and Pycairo:</p>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python3\nimport sys\n\nimport cairo\nimport gi\nimport PIL.Image\nimport pygame\ngi.require_version('Rsvg', '2.0')\nfrom gi.repository import Rsvg\n\nWIDTH = 512\nHEIGHT = 512\nPATH = sys.argv[1] if len(sys.argv) &gt; 1 else &quot;test.svg&quot;\n\n\ndef load_svg(path: str, size: tuple) -&gt; pygame.Surface:\n &quot;&quot;&quot;Render an SVG file to a new pygame surface and return that surface.&quot;&quot;&quot;\n svg = Rsvg.Handle.new_from_file(path)\n\n # Create a Cairo surface.\n # Nominally ARGB, but in little-endian architectures it is effectively BGRA\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *size)\n\n # Create a Cairo context and scale it\n context = cairo.Context(surface)\n context.scale(size[0]/svg.props.width, size[1]/svg.props.height)\n\n # Render the SVG\n svg.render_cairo(context)\n\n # Get image data buffer\n data = surface.get_data()\n if sys.byteorder == 'little':\n # Convert from effective BGRA to actual RGBA.\n # PIL is surprisingly faster than NumPy, but can be done without neither\n data = PIL.Image.frombuffer('RGBA', size, data.tobytes(),\n 'raw', 'BGRA', 0, 1).tobytes()\n\n return pygame.image.frombuffer(data, size, &quot;RGBA&quot;).convert_alpha()\n\n\npygame.init()\nwindow = pygame.display.set_mode((WIDTH, HEIGHT))\nimage = load_svg(PATH, (WIDTH, HEIGHT))\nwindow.blit(image, (0, 0))\npygame.display.update()\n\nclock = pygame.time.Clock()\nwhile True:\n if pygame.event.get([pygame.QUIT]):\n break\n clock.tick(30)\npygame.quit()\n\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8450/" ]
In a [pyGame](http://www.pygame.org/) application, I would like to render resolution-free GUI widgets described in SVG. How can I achieve this? (I like the [OCEMP GUI](http://ocemp.sourceforge.net/gui.html) toolkit but it seems to be bitmap dependent for its rendering)
This is a complete example which combines hints by other people here. It should render a file called test.svg from the current directory. It was tested on Ubuntu 10.10, python-cairo 1.8.8, python-pygame 1.9.1, python-rsvg 2.30.0. ``` #!/usr/bin/python import array import math import cairo import pygame import rsvg WIDTH = 512 HEIGHT = 512 data = array.array('c', chr(0) * WIDTH * HEIGHT * 4) surface = cairo.ImageSurface.create_for_data( data, cairo.FORMAT_ARGB32, WIDTH, HEIGHT, WIDTH * 4) pygame.init() window = pygame.display.set_mode((WIDTH, HEIGHT)) svg = rsvg.Handle(file="test.svg") ctx = cairo.Context(surface) svg.render_cairo(ctx) screen = pygame.display.get_surface() image = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),"ARGB") screen.blit(image, (0, 0)) pygame.display.flip() clock = pygame.time.Clock() while True: clock.tick(15) for event in pygame.event.get(): if event.type == pygame.QUIT: raise SystemExit ```
120,587
<p>I would like to trash the mail received by a single qmail alias. I don't want any mail delivery errors, and I want qmail to be happy about having delivered the mail.</p> <p>How can I do this, preferably without adding another local email account?</p>
[ { "answer_id": 120771, "author": "Roman Odaisky", "author_id": 21055, "author_profile": "https://Stackoverflow.com/users/21055", "pm_score": 2, "selected": false, "text": "<p>Create an alias by creating a file /var/qmail/aliases/.qmail-<em>blackhole</em> with this content:</p>\n\n<pre><code>|cat &gt;/dev/null\n</code></pre>\n\n<p>Then redirect whatever you want to this ‘blackhole’ alias (or use whatever you want in place of ‘blackhole’). Merely using /dev/null won’t work (<code>Unable_to_write_/dev/null</code>).</p>\n\n<p>The messages will still be logged, however. Though it’s more of a feature than a bug.</p>\n" }, { "answer_id": 129168, "author": "pcorcoran", "author_id": 15992, "author_profile": "https://Stackoverflow.com/users/15992", "pm_score": 0, "selected": false, "text": "<p>A meta-question: why would this get rated down? Is it not appropriate for the site?</p>\n" }, { "answer_id": 655324, "author": "drench", "author_id": 73779, "author_profile": "https://Stackoverflow.com/users/73779", "pm_score": 2, "selected": true, "text": "<p>Create an alias with only a comment and no delivery instructions, like:</p>\n\n<pre><code>echo \"# drop all messages on the floor\" &gt; ~alias/.qmail-devnull\n</code></pre>\n\n<p>Replace \"devnull\" with whatever alias name you need of course.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15992/" ]
I would like to trash the mail received by a single qmail alias. I don't want any mail delivery errors, and I want qmail to be happy about having delivered the mail. How can I do this, preferably without adding another local email account?
Create an alias with only a comment and no delivery instructions, like: ``` echo "# drop all messages on the floor" > ~alias/.qmail-devnull ``` Replace "devnull" with whatever alias name you need of course.
120,588
<p>I'm using Hibernate for ORM of my Java app to an Oracle database (not that the database vendor matters, we may switch to another database one day), and I want to retrieve objects from the database according to user-provided strings. For example, when searching for people, if the user is looking for people who live in 'fran', I want to be able to give her people in San Francisco.</p> <p>SQL is not my strong suit, and I prefer Hibernate's <code>Criteria</code> building code to hard-coded strings as it is. Can anyone point me in the right direction about how to do this in code, and if impossible, how the hard-coded SQL should look like?</p> <p>Thanks,</p> <p>Yuval =8-)</p>
[ { "answer_id": 120600, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "<p>Most default database collations are not case-sensitive, but in the SQL Server world it can be set at the instance, the database, and the column level.</p>\n" }, { "answer_id": 120605, "author": "Paul Whelan", "author_id": 3050, "author_profile": "https://Stackoverflow.com/users/3050", "pm_score": 0, "selected": false, "text": "<p>You could look at using Compass a wrapper above lucene.</p>\n\n<p><a href=\"http://www.compass-project.org/\" rel=\"nofollow noreferrer\">http://www.compass-project.org/</a></p>\n\n<p>By adding a few annotations to your domain objects you get achieve this kind of thing.</p>\n\n<p>Compass provides a simple API for working with Lucene. If you know how to use an ORM, then you will feel right at home with Compass with simple operations for save, and delete &amp; query.</p>\n\n<p>From the site itself.\n\"Building on top of Lucene, Compass simplifies common usage patterns of Lucene such as google-style search, index updates as well as more advanced concepts such as caching and index sharding (sub indexes). Compass also uses built in optimizations for concurrent commits and merges.\"</p>\n\n<p>I have used this in the past and I find it great.</p>\n" }, { "answer_id": 120622, "author": "Richard", "author_id": 20038, "author_profile": "https://Stackoverflow.com/users/20038", "pm_score": 2, "selected": false, "text": "<p>The usual approach to ignoring case is to convert both the database values and the input value to upper or lower case - the resultant sql would have something like</p>\n\n<pre><code>select f.name from f where TO_UPPER(f.name) like '%FRAN%'\n</code></pre>\n\n<p>In hibernate criteria restrictions.like(...).ignoreCase()</p>\n\n<p>I'm more familiar with Nhibernate so the syntax might not be 100% accurate</p>\n\n<p>for some more info see <a href=\"http://books.google.co.uk/books?id=AM1Od544ei0C&amp;pg=PA136&amp;lpg=PA136&amp;dq=restrictions.like+case+insensitive&amp;source=web&amp;ots=5xx49wOSoS&amp;sig=sgNywi0_xScHaAeRnySueLVU_x0&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=4&amp;ct=result\" rel=\"nofollow noreferrer\">pro hibernate 3 extract</a> and <a href=\"http://www.hibernate.org/hib_docs/reference/en/html/querycriteria-narrowing.html\" rel=\"nofollow noreferrer\">hibernate docs 15.2. Narrowing the result set</a></p>\n" }, { "answer_id": 120641, "author": "Cowan", "author_id": 17041, "author_profile": "https://Stackoverflow.com/users/17041", "pm_score": 7, "selected": true, "text": "<p>For the simple case you describe, look at Restrictions.ilike(), which does a case-insensitive search.</p>\n\n<pre><code>Criteria crit = session.createCriteria(Person.class);\ncrit.add(Restrictions.ilike('town', '%fran%');\nList results = crit.list();\n</code></pre>\n" }, { "answer_id": 121413, "author": "Arthur Thomas", "author_id": 14009, "author_profile": "https://Stackoverflow.com/users/14009", "pm_score": 2, "selected": false, "text": "<p>You also do not have to put in the '%' wildcards. You can pass <a href=\"http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/criterion/MatchMode.html\" rel=\"nofollow noreferrer\">MatchMode</a> (<a href=\"http://www.hibernate.org/hib_docs/v3/api/org/hibernate/criterion/MatchMode.html\" rel=\"nofollow noreferrer\">docs for previous releases here</a>) in to tell the search how to behave. <code>START</code>, <code>ANYWHERE</code>, <code>EXACT</code>, and <code>END</code> matches are the options.</p>\n" }, { "answer_id": 227212, "author": "SamS", "author_id": 14068, "author_profile": "https://Stackoverflow.com/users/14068", "pm_score": 3, "selected": false, "text": "<p>If you use Spring's HibernateTemplate to interact with Hibernate, here is how you would do a case insensitive search on a user's email address:</p>\n\n<pre><code>getHibernateTemplate().find(\"from User where upper(email)=?\", emailAddr.toUpperCase());\n</code></pre>\n" }, { "answer_id": 290156, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<pre><code>Criteria crit = session.createCriteria(Person.class);\ncrit.add(Restrictions.ilike('town', 'fran', MatchMode.ANYWHERE);\nList results = crit.list();\n</code></pre>\n" }, { "answer_id": 4089895, "author": "Casey", "author_id": 147373, "author_profile": "https://Stackoverflow.com/users/147373", "pm_score": 1, "selected": false, "text": "<p>This can also be done using the criterion Example, in the org.hibernate.criterion package.</p>\n\n<pre><code>public List findLike(Object entity, MatchMode matchMode) {\n Example example = Example.create(entity);\n example.enableLike(matchMode);\n example.ignoreCase();\n return getSession().createCriteria(entity.getClass()).add(\n example).list();\n}\n</code></pre>\n\n<p>Just another way that I find useful to accomplish the above.</p>\n" }, { "answer_id": 58017459, "author": "gawi", "author_id": 1127920, "author_profile": "https://Stackoverflow.com/users/1127920", "pm_score": 1, "selected": false, "text": "<p>Since Hibernate 5.2 <code>session.createCriteria</code> is deprecated. Below is solution using JPA 2 CriteriaBuilder. It uses <code>like</code> and <code>upper</code>:</p>\n\n<pre><code> CriteriaBuilder builder = session.getCriteriaBuilder();\n CriteriaQuery&lt;Person&gt; criteria = builder.createQuery(Person.class);\n Root&lt;Person&gt; root = criteria.from(Person.class);\n\n Expression&lt;String&gt; upper = builder.upper(root.get(\"town\"));\n criteria.where(builder.like(upper, \"%FRAN%\"));\n\n session.createQuery(criteria.select(root)).getResultList();\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2819/" ]
I'm using Hibernate for ORM of my Java app to an Oracle database (not that the database vendor matters, we may switch to another database one day), and I want to retrieve objects from the database according to user-provided strings. For example, when searching for people, if the user is looking for people who live in 'fran', I want to be able to give her people in San Francisco. SQL is not my strong suit, and I prefer Hibernate's `Criteria` building code to hard-coded strings as it is. Can anyone point me in the right direction about how to do this in code, and if impossible, how the hard-coded SQL should look like? Thanks, Yuval =8-)
For the simple case you describe, look at Restrictions.ilike(), which does a case-insensitive search. ``` Criteria crit = session.createCriteria(Person.class); crit.add(Restrictions.ilike('town', '%fran%'); List results = crit.list(); ```
120,607
<p>I am trying to separate some asp logic out into a separate page. For now, I am trying to call a simple function. </p> <p>Here is the simple index page that I am using</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Calling a webservice from classic ASP&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;% If Request.ServerVariables("REQUEST_METHOD") = "POST" Then %&gt; &lt;!--#include file="aspFunctions.asp"--&gt; &lt;% doStuff() End If %&gt; &lt;FORM method=POST name="form1" ID="Form1"&gt; ID: &lt;INPUT type="text" name="corpId" ID="id" value="050893"&gt; &lt;BR&gt;&lt;BR&gt; &lt;INPUT type="submit" value="GO" name="submit1" ID="Submit1" &gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here is aspfunctions.asp</p> <pre><code>sub doStuff() Response.Write("In Do Stuff") end sub </code></pre> <p>When i hit the submit button on my form i get the below sub doStuff() Response.Write("In Do Stuff") end sub</p> <p>Microsoft VBScript runtime error '800a000d'</p> <p>Does anyone have any idea what i could be doing wrong?</p> <p>Any help is greatly appreciated</p> <p>Thanks Damien Type mismatch: 'doStuff'</p> <p>/uat/damien/index.asp, line 15 </p>
[ { "answer_id": 120619, "author": "Matthias Meid", "author_id": 17713, "author_profile": "https://Stackoverflow.com/users/17713", "pm_score": 1, "selected": false, "text": "<p>If I remember correctly, you need no brackets for calls without a return value (untested solution):</p>\n\n<pre><code>doStuff\n</code></pre>\n" }, { "answer_id": 120623, "author": "Gautam Jain", "author_id": 15065, "author_profile": "https://Stackoverflow.com/users/15065", "pm_score": 3, "selected": false, "text": "<p>You must have the asp functions inside the &lt;% %> tag.</p>\n" }, { "answer_id": 120632, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 4, "selected": true, "text": "<p><code>aspfunctions.asp</code> should be inside tags so the asp is &quot;executed&quot;, e.g.</p>\n<p>aspfunctions.asp file:</p>\n<pre><code>&lt;%\nsub doStuff()\n Response.Write(&quot;In Do Stuff&quot;)\nend sub\n%&gt;\n</code></pre>\n<p>Otherwise the asp in <code>aspfunctions.asp</code> is just seen as plain-text, so as far as the server is concerned, <code>doStuff</code> has never been defined.</p>\n" }, { "answer_id": 120855, "author": "AdamH", "author_id": 21081, "author_profile": "https://Stackoverflow.com/users/21081", "pm_score": 3, "selected": false, "text": "<p>You're including the other file within an if statement. This does not mean that it's dynamically included, it's not. It will always be included.</p>\n\n<p>To see this in action try this sample:</p>\n\n<pre><code>&lt;%\nIf 1=0 Then\n'We never get here\n%&gt;\n &lt;!--#include file=\"aspFunctions.asp\"--&gt;\n&lt;%\n dostuff()\nEnd If\ndostuff()\n%&gt;\n</code></pre>\n" }, { "answer_id": 12139094, "author": "polin", "author_id": 1624049, "author_profile": "https://Stackoverflow.com/users/1624049", "pm_score": -1, "selected": false, "text": "<p>Make changes in two places:</p>\n\n<ol>\n<li>In aspfunctions.asp write \"sub doStuff\" instead of <code>sub doStuff()</code></li>\n<li>Call the function as <code>doStuff</code> not <code>doStuff()</code></li>\n</ol>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11612/" ]
I am trying to separate some asp logic out into a separate page. For now, I am trying to call a simple function. Here is the simple index page that I am using ``` <html> <head> <title>Calling a webservice from classic ASP</title> </head> <body> <% If Request.ServerVariables("REQUEST_METHOD") = "POST" Then %> <!--#include file="aspFunctions.asp"--> <% doStuff() End If %> <FORM method=POST name="form1" ID="Form1"> ID: <INPUT type="text" name="corpId" ID="id" value="050893"> <BR><BR> <INPUT type="submit" value="GO" name="submit1" ID="Submit1" > </form> </body> </html> ``` Here is aspfunctions.asp ``` sub doStuff() Response.Write("In Do Stuff") end sub ``` When i hit the submit button on my form i get the below sub doStuff() Response.Write("In Do Stuff") end sub Microsoft VBScript runtime error '800a000d' Does anyone have any idea what i could be doing wrong? Any help is greatly appreciated Thanks Damien Type mismatch: 'doStuff' /uat/damien/index.asp, line 15
`aspfunctions.asp` should be inside tags so the asp is "executed", e.g. aspfunctions.asp file: ``` <% sub doStuff() Response.Write("In Do Stuff") end sub %> ``` Otherwise the asp in `aspfunctions.asp` is just seen as plain-text, so as far as the server is concerned, `doStuff` has never been defined.
120,618
<p>What logging solutions exist for j2me? </p> <p>I'm specifically interested in easily excluding logging for "release" version, to have a smaller package &amp; memory footprint. </p>
[ { "answer_id": 120772, "author": "Scott Bennett-McLeish", "author_id": 1915, "author_profile": "https://Stackoverflow.com/users/1915", "pm_score": 1, "selected": false, "text": "<p>I've used <a href=\"http://www.mobilelandscape.uklinux.net/j2medownload/MIDPLogger.php\" rel=\"nofollow noreferrer\">MIDPLogger</a> to some acceptable level in a production application, although I have found it has more use after integrating into the application rather than as another Midlet in suite or so forth. I also found <a href=\"http://microlog.sourceforge.net/\" rel=\"nofollow noreferrer\">MicroLog</a> but haven't used it to any great detail.</p>\n" }, { "answer_id": 120913, "author": "darius", "author_id": 5896, "author_profile": "https://Stackoverflow.com/users/5896", "pm_score": 4, "selected": false, "text": "<p>MicroLog is sure bet. It is a small logging library for Java ME (J2ME) like Log4j. It has support for logging to console, file, RecordStore, Canvas, Form, Bluetooth, a serial port (Bluetooth, IR, USB), Socket(incl SSL), UDP, Syslog, MMS, SMS, e-mail or to Amazon S3.</p>\n\n<p><a href=\"http://sourceforge.net/projects/microlog/\" rel=\"noreferrer\">http://sourceforge.net/projects/microlog/</a></p>\n" }, { "answer_id": 121077, "author": "JaanusSiim", "author_id": 706, "author_profile": "https://Stackoverflow.com/users/706", "pm_score": 5, "selected": true, "text": "<p>If you are using preprocessing and obfuscation with Proguard, then you can have a simple logging class.</p>\n\n<pre><code>public class Log {\n public static void debug(final String message) {\n //#if !release.build\n System.out.println(message);\n //#endif\n }\n}\n</code></pre>\n\n<p>Or do logging where ever you need to. Now, if release.build property is set to true, this code will be commented out, that will result in an empty method. Proguard will remove all usages of empty method - In effect release build will have all debug messages removed.</p>\n\n<p>Edit:</p>\n\n<p>Thinking about it on library level (I'm working on mapping J2ME library) I have, probably, found a better solution.</p>\n\n<pre><code>public class Log {\n private static boolean showDebug;\n\n public static void debug(final String message) {\n if (showDebug) {\n System.out.println(message);\n }\n }\n\n public static void setShowDebug(final boolean show) {\n showDebug = show;\n }\n}\n</code></pre>\n\n<p>This way end developer can enable log levels inside library that he/she is interested in. If nothing will be enabled, all logging code will be removed in end product obfuscation. Sweet :)</p>\n\n<p>/JaanusSiim</p>\n" }, { "answer_id": 126725, "author": "michael aubert", "author_id": 17867, "author_profile": "https://Stackoverflow.com/users/17867", "pm_score": 2, "selected": false, "text": "<p>The Series60 and UIQ phone that have a Sun virtual machine modified by Symbian itself have Standard Output redirection.</p>\n\n<p>Not only can you capture System.out but Throwable.printStackTrace() also works.</p>\n\n<p>On early handsets, You would need to write a C++ application that hooks into the standard library server process. Symbian produced the Redirector application that could capture the VM standard output to a console or a file.</p>\n\n<p>On newer handsets, a \"redirect://\" GCF protocol was introduced that could read the VM standard output into a Java byte[] or String object (you would want to do that in a separate MIDlet) and the Redirector application was rewritten in Java.</p>\n\n<p>On the newest J9 VM used in Series60 3rd Edition Feature Pack 2 handsets (and later), you may need to try \"redirect://test\" instead.</p>\n" }, { "answer_id": 166156, "author": "edsumner", "author_id": 24072, "author_profile": "https://Stackoverflow.com/users/24072", "pm_score": 3, "selected": false, "text": "<p>You can use the -assumenosideaffects in proguard to completley remove your logging class:</p>\n\n<pre><code>-assumenosideeffects public class logger.Logger {*;}\n</code></pre>\n\n<p>Rather than having to preprocess.</p>\n" }, { "answer_id": 202264, "author": "nharding", "author_id": 26228, "author_profile": "https://Stackoverflow.com/users/26228", "pm_score": 0, "selected": false, "text": "<p>I wrote a bytecode optimizer, and because of the format of class files you can point to the UTF encoding of classname &amp; function which allows you to output logs with MyClass.someFunc() (you can process the signature if you want to get the types) which allows you to do something like the C style debug using <strong>LINE</strong> &amp; <strong>FILE</strong> macros.</p>\n" }, { "answer_id": 274777, "author": "Otm Shank", "author_id": 5695, "author_profile": "https://Stackoverflow.com/users/5695", "pm_score": 0, "selected": false, "text": "<p>Using conditional compilation of the logger class does not solve the problem of completely removing logging statements because you will quite often log more than a simple string. You will look up variable values and then assemble them into strings, e.g.: WhateverLog.log( \"Loaded \" + someclass.size() + \" foos\" ). </p>\n\n<p>Now if you only leave out the body of WhateverLog.log (as shown in the accepted solution), you will still leave a lot of unnecessary code in, including String concatenation (and thus a StringBuffer creation). That's why you'd better use a byte code post processing tool like proguard (already mentioned). Proguard's -assumenosideeffects will allow its optimizer to remove not only the logging statements but also all code whose results would only be used by the logging call.</p>\n" }, { "answer_id": 10069550, "author": "Megha", "author_id": 645937, "author_profile": "https://Stackoverflow.com/users/645937", "pm_score": 0, "selected": false, "text": "<p>LWUIT framework of the J2ME provide the Logging form which can have a log the statement inside it. You can add the log at each and every place you think may generate the exception.</p>\n\n<p>Example : Log.getInstance().showLog();\nBy adding the above line you can able to track the logging in the J2ME devices.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6827/" ]
What logging solutions exist for j2me? I'm specifically interested in easily excluding logging for "release" version, to have a smaller package & memory footprint.
If you are using preprocessing and obfuscation with Proguard, then you can have a simple logging class. ``` public class Log { public static void debug(final String message) { //#if !release.build System.out.println(message); //#endif } } ``` Or do logging where ever you need to. Now, if release.build property is set to true, this code will be commented out, that will result in an empty method. Proguard will remove all usages of empty method - In effect release build will have all debug messages removed. Edit: Thinking about it on library level (I'm working on mapping J2ME library) I have, probably, found a better solution. ``` public class Log { private static boolean showDebug; public static void debug(final String message) { if (showDebug) { System.out.println(message); } } public static void setShowDebug(final boolean show) { showDebug = show; } } ``` This way end developer can enable log levels inside library that he/she is interested in. If nothing will be enabled, all logging code will be removed in end product obfuscation. Sweet :) /JaanusSiim
120,627
<p>I would like to replace the default malloc at link time to use a custom malloc. But when I try to redefine malloc in my program, I get this error:</p> <pre><code>MSVCRT.lib(MSVCR80.dll) : error LNK2005: _malloc already defined in test.lib(test.obj) </code></pre> <p>This works perfectly on any Unix, and it works on Windows with most functions, but not with malloc. How can I do this? And what is different with malloc that disallow overriding it?</p> <p>I know I could replace every call to malloc with my custom malloc, or use a macro to do this, but I would rather not modify every third party library.</p>
[ { "answer_id": 120650, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 2, "selected": false, "text": "<p>I think it depends in which order you link the files. I think you need to link your custom function first, then the import library.</p>\n" }, { "answer_id": 120663, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 5, "selected": true, "text": "<p>There is really good discussion of how hard this is here:</p>\n\n<p><a href=\"http://benjamin.smedbergs.us/blog/2008-01-10/patching-the-windows-crt/\" rel=\"noreferrer\">http://benjamin.smedbergs.us/blog/2008-01-10/patching-the-windows-crt/</a></p>\n\n<p><s>Apparently, you need to patch the CRT</s></p>\n\n<p>Edit: actually, a MS employee gave the technique in the discussion. You need to move your malloc to a lib, and then link it before the CRT</p>\n\n<p>\"he also mentions that if you link your malloc as a lib <em>before</em> the CRT (i.e. make sure to turn on ‘ignore default libs’ and explictly include the CRT), you’ll get what you want, and can redistribute this lib without problems.\"</p>\n" }, { "answer_id": 120672, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 1, "selected": false, "text": "<p>From version 3.0 Firefox uses a custom allocator (AFAIR jmalloc) -- you could check how they did it. I read that they had some problems with it. You may check this <a href=\"http://blog.pavlov.net/2008/01/12/jemalloc-builds/\" rel=\"nofollow noreferrer\">blog post</a>.</p>\n" }, { "answer_id": 4216966, "author": "Alex", "author_id": 512381, "author_profile": "https://Stackoverflow.com/users/512381", "pm_score": 1, "selected": false, "text": "<p>What about defining malloc=_custom_malloc in the project makefile.\nThan adding a file such as:</p>\n\n<pre><code>my_memory.c\n#undef malloc\n#undef calloc\n...\nvoid *_custom_malloc(int size) { return jmalloc(size); }\nvoid *_custom_calloc(int size) { return jcalloc(size); }\n...\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14443/" ]
I would like to replace the default malloc at link time to use a custom malloc. But when I try to redefine malloc in my program, I get this error: ``` MSVCRT.lib(MSVCR80.dll) : error LNK2005: _malloc already defined in test.lib(test.obj) ``` This works perfectly on any Unix, and it works on Windows with most functions, but not with malloc. How can I do this? And what is different with malloc that disallow overriding it? I know I could replace every call to malloc with my custom malloc, or use a macro to do this, but I would rather not modify every third party library.
There is really good discussion of how hard this is here: <http://benjamin.smedbergs.us/blog/2008-01-10/patching-the-windows-crt/> ~~Apparently, you need to patch the CRT~~ Edit: actually, a MS employee gave the technique in the discussion. You need to move your malloc to a lib, and then link it before the CRT "he also mentions that if you link your malloc as a lib *before* the CRT (i.e. make sure to turn on ‘ignore default libs’ and explictly include the CRT), you’ll get what you want, and can redistribute this lib without problems."
120,648
<p>I use Assert.Fail a lot when doing TDD. I'm usually working on one test at a time but when I get ideas for things I want to implement later I quickly write an empty test where the name of the test method indicates what I want to implement as sort of a todo-list. To make sure I don't forget I put an Assert.Fail() in the body.</p> <p>When trying out xUnit.Net I found they hadn't implemented Assert.Fail. Of course you can always Assert.IsTrue(false) but this doesn't communicate my intention as well. I got the impression Assert.Fail wasn't implemented on purpose. Is this considered bad practice? If so why?</p> <hr> <p>@Martin Meredith That's not exactly what I do. I do write a test first and then implement code to make it work. Usually I think of several tests at once. Or I think about a test to write when I'm working on something else. That's when I write an empty failing test to remember. By the time I get to writing the test I neatly work test-first.</p> <p>@Jimmeh That looks like a good idea. Ignored tests don't fail but they still show up in a separate list. Have to try that out.</p> <p>@Matt Howells Great Idea. NotImplementedException communicates intention better than assert.Fail() in this case</p> <p>@Mitch Wheat That's what I was looking for. It seems it was left out to prevent it being abused in another way I abuse it.</p>
[ { "answer_id": 120670, "author": "Jimmeh", "author_id": 20749, "author_profile": "https://Stackoverflow.com/users/20749", "pm_score": 3, "selected": false, "text": "<p>I use MbUnit for my Unit Testing. They have an option to Ignore tests, which show up as Orange (rather than Green or Red) in the test suite. Perhaps xUnit has something similar, and would mean you don't even have to put any assert into the method, because it would show up in an annoyingly different colour making it hard to miss?</p>\n\n<p>Edit: </p>\n\n<p>In MbUnit it is in the following way:</p>\n\n<pre><code>[Test]\n[Ignore]\npublic void YourTest()\n{ } \n</code></pre>\n" }, { "answer_id": 120671, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 0, "selected": false, "text": "<p>If you're writing a test that just fails, and then writing the code for it, then writing the test. This isn't Test Driven Development.</p>\n\n<p>Technically, Assert.fail() shouldn't be needed if you're using test driven development correctly.</p>\n\n<p>Have you thought of using a Todo List, or applying a GTD methodology to your work?</p>\n" }, { "answer_id": 120678, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 4, "selected": false, "text": "<p>It was deliberately left out. This is Brad Wilson's reply as to why is there no Assert.Fail():</p>\n\n<blockquote>\n <p>We didn't overlook this, actually. I\n find Assert.Fail is a crutch which\n implies that there is probably an\n assertion missing. Sometimes it's just\n the way the test is structured, and\n sometimes it's because Assert could\n use another assertion.</p>\n</blockquote>\n" }, { "answer_id": 120679, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 7, "selected": true, "text": "<p>For this scenario, rather than calling Assert.Fail, I do the following (in C# / NUnit)</p>\n\n<pre><code>[Test]\npublic void MyClassDoesSomething()\n{\n throw new NotImplementedException();\n}\n</code></pre>\n\n<p>It is more explicit than an Assert.Fail.</p>\n\n<p>There seems to be general agreement that it is preferable to use more explicit assertions than Assert.Fail(). Most frameworks have to include it though because they don't offer a better alternative. For example, NUnit (and others) provide an ExpectedExceptionAttribute to test that some code throws a particular class of exception. However in order to test that a property on the exception is set to a particular value, one cannot use it. Instead you have to resort to Assert.Fail:</p>\n\n<pre><code>[Test]\npublic void ThrowsExceptionCorrectly()\n{\n const string BAD_INPUT = \"bad input\";\n try\n {\n new MyClass().DoSomething(BAD_INPUT);\n Assert.Fail(\"No exception was thrown\");\n }\n catch (MyCustomException ex)\n {\n Assert.AreEqual(BAD_INPUT, ex.InputString); \n }\n}\n</code></pre>\n\n<p>The xUnit.Net method Assert.Throws makes this a lot neater without requiring an Assert.Fail method. By not including an Assert.Fail() method xUnit.Net encourages developers to find and use more explicit alternatives, and to support the creation of new assertions where necessary.</p>\n" }, { "answer_id": 120714, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<p>MS Test has <strong>Assert.Fail()</strong> but it also has <strong>Assert.Inconclusive()</strong>. I think that the most appropriate use for Assert.Fail() is if you have some in-line logic that would be awkward to put in an assertion, although I can't even think of any good examples. For the most part, if the test framework supports something other than Assert.Fail() then use that.</p>\n" }, { "answer_id": 120721, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 2, "selected": false, "text": "<p>Personally I have no problem with using a test suite as a todo list like this as long as you eventually get around to writing the test <em>before</em> you implement the code to pass. </p>\n\n<p>Having said that, I used to use this approach myself, although now I'm finding that doing so leads me down a path of writing too many tests upfront, which in a weird way is like the reverse problem of not writing tests at all: you end up making decisions about design a little too early IMHO.</p>\n\n<p>Incidentally in MSTest, the standard Test template uses Assert.Inconclusive at the end of its samples. </p>\n\n<p>AFAIK the xUnit.NET framework is intended to be extremely lightweight and yes they did cut Fail deliberately, to encourage the developer to use an explicit failure condition. </p>\n" }, { "answer_id": 120742, "author": "Craig Trader", "author_id": 12895, "author_profile": "https://Stackoverflow.com/users/12895", "pm_score": 4, "selected": false, "text": "<p>I've always used Assert.Fail() for handling cases where you've detected that a test should fail through logic beyond simple value comparison. As an example:</p>\n\n<pre><code>try \n{\n // Some code that should throw ExceptionX\n Assert.Fail(\"ExceptionX should be thrown\")\n} \ncatch ( ExceptionX ex ) \n{\n // test passed\n}\n</code></pre>\n\n<p>Thus the lack of Assert.Fail() in the framework looks like a mistake to me. I'd suggest patching the Assert class to include a Fail() method, and then submitting the patch to the framework developers, along with your reasoning for adding it.</p>\n\n<p>As for your practice of creating tests that intentionally fail in your workspace, to remind yourself to implement them before committing, that seems like a fine practice to me.</p>\n" }, { "answer_id": 120760, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 2, "selected": false, "text": "<p>Wild guess: withholding Assert.Fail is intended to stop you thinking that a good way to write test code is as a huge heap of spaghetti leading to an Assert.Fail in the bad cases. [Edit to add: other people's answers broadly confirm this, but with quotations]</p>\n\n<p>Since that's not what you're doing, it's possible that xUnit.Net is being over-protective. </p>\n\n<p>Or maybe they just think it's so rare and so unorthogonal as to be unnecessary.</p>\n\n<p>I prefer to implement a function called ThisCodeHasNotBeenWrittenYet (actually something shorter, for ease of typing). Can't communicate intention more clearly than that, and you have a precise search term.</p>\n\n<p>Whether that fails, or is not implemented (to provoke a linker error), or is a macro that doesn't compile, can be changed to suit your current preference. For instance when you want to run something that <em>is</em> finished, you want a fail. When you're sitting down to get rid of them all, you may want a compile error.</p>\n" }, { "answer_id": 121173, "author": "Daniel Fanjul", "author_id": 16135, "author_profile": "https://Stackoverflow.com/users/16135", "pm_score": 2, "selected": false, "text": "<p>With the good code I usually do:</p>\n\n<pre><code>void goodCode() {\n // TODO void goodCode()\n throw new NotSupportedOperationException(\"void goodCode()\");\n}\n</code></pre>\n\n<p>With the test code I usually do:</p>\n\n<pre><code>@Test\nvoid testSomething() {\n // TODO void test Something\n Assert.assert(\"Some descriptive text about what to test\")\n}\n</code></pre>\n\n<p>If using JUnit, and don't want to get the failure, but the error, then I usually do:</p>\n\n<pre><code>@Test\nvoid testSomething() {\n // TODO void test Something\n throw new NotSupportedOperationException(\"Some descriptive text about what to test\")\n}\n</code></pre>\n" }, { "answer_id": 235812, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Why would you use <code>Assert.Fail</code> for saying that an exception should be thrown? That is unnecessary. Why not just use the <code>ExpectedException</code> attribute?</p>\n" }, { "answer_id": 1048617, "author": "lexx", "author_id": 67014, "author_profile": "https://Stackoverflow.com/users/67014", "pm_score": 2, "selected": false, "text": "<p>This is the pattern that I use when writting a test for code that I want to throw an exception by design:</p>\n\n<pre><code>[TestMethod]\npublic void TestForException()\n{\n Exception _Exception = null;\n\n try\n {\n //Code that I expect to throw the exception.\n MyClass _MyClass = null;\n _MyClass.SomeMethod();\n //Code that I expect to throw the exception.\n }\n catch(Exception _ThrownException)\n { \n _Exception = _ThrownException\n }\n finally\n {\n Assert.IsNotNull(_Exception);\n //Replace NullReferenceException with expected exception.\n Assert.IsInstanceOfType(_Exception, typeof(NullReferenceException));\n }\n}\n</code></pre>\n\n<p>IMHO this is a better way of testing for exceptions over using Assert.Fail(). The reason for this is that not only do I test for an exception being thrown at all but I also test for the exception type. I realise that this is similar to the answer from Matt Howells but IMHO using the finally block is more robust.</p>\n\n<p>Obviously it would still be possible to include other Assert methods to test the exceptions input string etc. I would be grateful for your comments and views on my pattern.</p>\n" }, { "answer_id": 25546983, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 1, "selected": false, "text": "<p>Beware <code>Assert.Fail</code> and its corrupting influence to make developers write silly or broken tests. For example:</p>\n\n<pre><code>[TestMethod]\npublic void TestWork()\n{\n try {\n Work();\n }\n catch {\n Assert.Fail();\n }\n}\n</code></pre>\n\n<p>This is silly, because the try-catch is redundant. A test fails if it throws an exception.</p>\n\n<p>Also</p>\n\n<pre><code>[TestMethod]\npublic void TestDivide()\n{\n try {\n Divide(5,0);\n Assert.Fail();\n } catch { }\n}\n</code></pre>\n\n<p>This is broken, the test will always pass whatever the outcome of the Divide function. Again, a test fails if and only if it throws an exception.</p>\n" }, { "answer_id": 46619925, "author": "Roland Roos", "author_id": 4411047, "author_profile": "https://Stackoverflow.com/users/4411047", "pm_score": 0, "selected": false, "text": "<p>I think you should ask yourselves what (upfront) testing should do.</p>\n\n<p>First, you write a (set of) test without implmentation.\nMaybe, also the rainy day scenarios.</p>\n\n<p>All those tests must fail, to be correct tests:\nSo you want to achieve two things:\n1) Verify that your implementation is correct;\n2) Verify that your unit tests are correct.</p>\n\n<p>Now, if you do upfront TDD, you want to execute all your tests, also, the NYI parts.\nThe result of your total test run passes if:\n1) All implemented stuff succeeds\n2) All NYI stuff fails</p>\n\n<p>After all, it would be a unit test ommision if your unit tests succeeds whilst there is no implementation, isnt it?</p>\n\n<p>You want to end up with something of a mail of your continous integration test that checks all implemented and not implemented code, and is sent if any implemented code fails, or any not implemented code succeeds. Both are undesired results.</p>\n\n<p>Just write an [ignore] tests wont do the job.\nNeither, an asserts that stops an the first assert failure, not running other tests lines in the test.</p>\n\n<p>Now, how to acheive this then?\nI think it requires some more advanced organisation of your testing.\nAnd it requires some other mechanism then asserts to achieve these goals.</p>\n\n<p>I think you have to split up your tests and create some tests that completly run but must fail, and vice versa.</p>\n\n<p>Ideas are to split your tests over multiple assemblies, use grouping of tests (ordered tests in mstest may do the job).</p>\n\n<p>Still, a CI build that mails if not all tests in the NYI department fail is not easy and straight-forward.</p>\n" }, { "answer_id": 61803226, "author": "Steve Hurcombe", "author_id": 2550322, "author_profile": "https://Stackoverflow.com/users/2550322", "pm_score": 0, "selected": false, "text": "<p>This is our use case for <strong>Assert.Fail()</strong>.</p>\n\n<p>One important goal for our Unit tests is that they <em>don't touch the database</em>. </p>\n\n<p>Sometimes mocking doesn't happen properly, or application code is modified and a database call is inadvertently made. </p>\n\n<p>This can be quite deep in the call stack. The exception may be caught so it won't bubble up, or because the tests are running initially with a database the call will work.</p>\n\n<p>What we've done is add a config value to the unit test project so that when the database connection is first requested we can call <strong>Assert.Fail(\"Database accessed\");</strong></p>\n\n<p>Assert.Fail() acts globally, even in different libraries. This therefore acts as a catch-all for all of the unit tests. </p>\n\n<p>If any one of them hits the database in a unit test project then they will fail. </p>\n\n<p>We therefore fail fast.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3320/" ]
I use Assert.Fail a lot when doing TDD. I'm usually working on one test at a time but when I get ideas for things I want to implement later I quickly write an empty test where the name of the test method indicates what I want to implement as sort of a todo-list. To make sure I don't forget I put an Assert.Fail() in the body. When trying out xUnit.Net I found they hadn't implemented Assert.Fail. Of course you can always Assert.IsTrue(false) but this doesn't communicate my intention as well. I got the impression Assert.Fail wasn't implemented on purpose. Is this considered bad practice? If so why? --- @Martin Meredith That's not exactly what I do. I do write a test first and then implement code to make it work. Usually I think of several tests at once. Or I think about a test to write when I'm working on something else. That's when I write an empty failing test to remember. By the time I get to writing the test I neatly work test-first. @Jimmeh That looks like a good idea. Ignored tests don't fail but they still show up in a separate list. Have to try that out. @Matt Howells Great Idea. NotImplementedException communicates intention better than assert.Fail() in this case @Mitch Wheat That's what I was looking for. It seems it was left out to prevent it being abused in another way I abuse it.
For this scenario, rather than calling Assert.Fail, I do the following (in C# / NUnit) ``` [Test] public void MyClassDoesSomething() { throw new NotImplementedException(); } ``` It is more explicit than an Assert.Fail. There seems to be general agreement that it is preferable to use more explicit assertions than Assert.Fail(). Most frameworks have to include it though because they don't offer a better alternative. For example, NUnit (and others) provide an ExpectedExceptionAttribute to test that some code throws a particular class of exception. However in order to test that a property on the exception is set to a particular value, one cannot use it. Instead you have to resort to Assert.Fail: ``` [Test] public void ThrowsExceptionCorrectly() { const string BAD_INPUT = "bad input"; try { new MyClass().DoSomething(BAD_INPUT); Assert.Fail("No exception was thrown"); } catch (MyCustomException ex) { Assert.AreEqual(BAD_INPUT, ex.InputString); } } ``` The xUnit.Net method Assert.Throws makes this a lot neater without requiring an Assert.Fail method. By not including an Assert.Fail() method xUnit.Net encourages developers to find and use more explicit alternatives, and to support the creation of new assertions where necessary.
120,656
<p>How do I get a list of all files (and directories) in a given directory in Python?</p>
[ { "answer_id": 120676, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 9, "selected": false, "text": "<p>You can use</p>\n\n<pre><code>os.listdir(path)\n</code></pre>\n\n<p>For reference and more os functions look here:</p>\n\n<ul>\n<li>Python 2 docs: <a href=\"https://docs.python.org/2/library/os.html#os.listdir\" rel=\"noreferrer\">https://docs.python.org/2/library/os.html#os.listdir</a></li>\n<li>Python 3 docs: <a href=\"https://docs.python.org/3/library/os.html#os.listdir\" rel=\"noreferrer\">https://docs.python.org/3/library/os.html#os.listdir</a></li>\n</ul>\n" }, { "answer_id": 120692, "author": "curtisk", "author_id": 17651, "author_profile": "https://Stackoverflow.com/users/17651", "pm_score": 6, "selected": false, "text": "<pre><code>import os\n\nfor filename in os.listdir(\"C:\\\\temp\"):\n print filename\n</code></pre>\n" }, { "answer_id": 120695, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>import os\nfor top, dirs, files in os.walk('./'):\n for nm in files: \n print os.path.join(top, nm)\n</code></pre>\n" }, { "answer_id": 120701, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 10, "selected": true, "text": "<p>This is a way to traverse every file and directory in a directory tree:</p>\n\n<pre><code>import os\n\nfor dirname, dirnames, filenames in os.walk('.'):\n # print path to all subdirectories first.\n for subdirname in dirnames:\n print(os.path.join(dirname, subdirname))\n\n # print path to all filenames.\n for filename in filenames:\n print(os.path.join(dirname, filename))\n\n # Advanced usage:\n # editing the 'dirnames' list will stop os.walk() from recursing into there.\n if '.git' in dirnames:\n # don't go into any .git directories.\n dirnames.remove('.git')\n</code></pre>\n" }, { "answer_id": 120948, "author": "giltay", "author_id": 21106, "author_profile": "https://Stackoverflow.com/users/21106", "pm_score": 7, "selected": false, "text": "<p>Here's a helper function I use quite often:</p>\n\n<pre><code>import os\n\ndef listdir_fullpath(d):\n return [os.path.join(d, f) for f in os.listdir(d)]\n</code></pre>\n" }, { "answer_id": 11753937, "author": "Sam Watkins", "author_id": 218294, "author_profile": "https://Stackoverflow.com/users/218294", "pm_score": 2, "selected": false, "text": "<p>I wrote a long version, with all the options I might need: <a href=\"http://sam.nipl.net/code/python/find.py\" rel=\"nofollow\">http://sam.nipl.net/code/python/find.py</a></p>\n\n<p>I guess it will fit here too:</p>\n\n<pre><code>#!/usr/bin/env python\n\nimport os\nimport sys\n\ndef ls(dir, hidden=False, relative=True):\n nodes = []\n for nm in os.listdir(dir):\n if not hidden and nm.startswith('.'):\n continue\n if not relative:\n nm = os.path.join(dir, nm)\n nodes.append(nm)\n nodes.sort()\n return nodes\n\ndef find(root, files=True, dirs=False, hidden=False, relative=True, topdown=True):\n root = os.path.join(root, '') # add slash if not there\n for parent, ldirs, lfiles in os.walk(root, topdown=topdown):\n if relative:\n parent = parent[len(root):]\n if dirs and parent:\n yield os.path.join(parent, '')\n if not hidden:\n lfiles = [nm for nm in lfiles if not nm.startswith('.')]\n ldirs[:] = [nm for nm in ldirs if not nm.startswith('.')] # in place\n if files:\n lfiles.sort()\n for nm in lfiles:\n nm = os.path.join(parent, nm)\n yield nm\n\ndef test(root):\n print \"* directory listing, with hidden files:\"\n print ls(root, hidden=True)\n print\n print \"* recursive listing, with dirs, but no hidden files:\"\n for f in find(root, dirs=True):\n print f\n print\n\nif __name__ == \"__main__\":\n test(*sys.argv[1:])\n</code></pre>\n" }, { "answer_id": 12572822, "author": "kenny", "author_id": 667847, "author_profile": "https://Stackoverflow.com/users/667847", "pm_score": 4, "selected": false, "text": "<p>If you need globbing abilities, there's a module for that as well. For example:</p>\n\n<pre><code>import glob\nglob.glob('./[0-9].*')\n</code></pre>\n\n<p>will return something like:</p>\n\n<pre><code>['./1.gif', './2.txt']\n</code></pre>\n\n<p>See the documentation <a href=\"http://docs.python.org/library/glob.html\">here</a>.</p>\n" }, { "answer_id": 13528334, "author": "Alok", "author_id": 1847405, "author_profile": "https://Stackoverflow.com/users/1847405", "pm_score": 0, "selected": false, "text": "<pre><code>#import modules\nimport os\n\n_CURRENT_DIR = '.'\n\n\ndef rec_tree_traverse(curr_dir, indent):\n \"recurcive function to traverse the directory\"\n #print \"[traverse_tree]\"\n\n try :\n dfList = [os.path.join(curr_dir, f_or_d) for f_or_d in os.listdir(curr_dir)]\n except:\n print \"wrong path name/directory name\"\n return\n\n for file_or_dir in dfList:\n\n if os.path.isdir(file_or_dir):\n #print \"dir : \",\n print indent, file_or_dir,\"\\\\\"\n rec_tree_traverse(file_or_dir, indent*2)\n\n if os.path.isfile(file_or_dir):\n #print \"file : \",\n print indent, file_or_dir\n\n #end if for loop\n#end of traverse_tree()\n\ndef main():\n\n base_dir = _CURRENT_DIR\n\n rec_tree_traverse(base_dir,\" \")\n\n raw_input(\"enter any key to exit....\")\n#end of main()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n" }, { "answer_id": 25390299, "author": "moylop260", "author_id": 3753497, "author_profile": "https://Stackoverflow.com/users/3753497", "pm_score": 0, "selected": false, "text": "<p>FYI Add a filter of extension or ext file\n import os</p>\n\n<pre><code>path = '.'\nfor dirname, dirnames, filenames in os.walk(path):\n # print path to all filenames with extension py.\n for filename in filenames:\n fname_path = os.path.join(dirname, filename)\n fext = os.path.splitext(fname_path)[1]\n if fext == '.py':\n print fname_path\n else:\n continue\n</code></pre>\n" }, { "answer_id": 27713560, "author": "fivetentaylor", "author_id": 2998052, "author_profile": "https://Stackoverflow.com/users/2998052", "pm_score": 1, "selected": false, "text": "<p>A nice one liner to list only the files recursively. I used this in my setup.py package_data directive:</p>\n\n<pre><code>import os\n\n[os.path.join(x[0],y) for x in os.walk('&lt;some_directory&gt;') for y in x[2]]\n</code></pre>\n\n<p>I know it's not the answer to the question, but may come in handy</p>\n" }, { "answer_id": 30471791, "author": "Arnaldo P. Figueira Figueira", "author_id": 1579731, "author_profile": "https://Stackoverflow.com/users/1579731", "pm_score": 3, "selected": false, "text": "<p>A recursive implementation</p>\n\n<pre><code>import os\n\ndef scan_dir(dir):\n for name in os.listdir(dir):\n path = os.path.join(dir, name)\n if os.path.isfile(path):\n print path\n else:\n scan_dir(path)\n</code></pre>\n" }, { "answer_id": 35628738, "author": "bng44270", "author_id": 198259, "author_profile": "https://Stackoverflow.com/users/198259", "pm_score": 0, "selected": false, "text": "<p>If figured I'd throw this in. Simple and dirty way to do wildcard searches.</p>\n\n<pre><code>import re\nimport os\n\n[a for a in os.listdir(\".\") if re.search(\"^.*\\.py$\",a)]\n</code></pre>\n" }, { "answer_id": 38609425, "author": "Dave Engineer", "author_id": 1959038, "author_profile": "https://Stackoverflow.com/users/1959038", "pm_score": 4, "selected": false, "text": "<p>For files in current working directory without specifying a path</p>\n<p><strong>Python 2.7:</strong></p>\n<pre><code>import os\nos.listdir('.')\n</code></pre>\n<p><strong>Python 3.x:</strong></p>\n<pre><code>import os\nos.listdir()\n</code></pre>\n" }, { "answer_id": 38941184, "author": "Alejandro Blasco", "author_id": 3589567, "author_profile": "https://Stackoverflow.com/users/3589567", "pm_score": 1, "selected": false, "text": "<h1>For Python 2</h1>\n\n<pre><code>#!/bin/python2\n\nimport os\n\ndef scan_dir(path):\n print map(os.path.abspath, os.listdir(pwd))\n</code></pre>\n\n<h1>For Python 3</h1>\n\n<p>For filter and map, you need wrap them with list()</p>\n\n<pre><code>#!/bin/python3\n\nimport os\n\ndef scan_dir(path):\n print(list(map(os.path.abspath, os.listdir(pwd))))\n</code></pre>\n\n<p>The recommendation now is that you replace your usage of map and filter with generators expressions or list comprehensions:</p>\n\n<pre><code>#!/bin/python\n\nimport os\n\ndef scan_dir(path):\n print([os.path.abspath(f) for f in os.listdir(path)])\n</code></pre>\n" }, { "answer_id": 45229467, "author": "Heenashree Khandelwal", "author_id": 8017535, "author_profile": "https://Stackoverflow.com/users/8017535", "pm_score": 0, "selected": false, "text": "<p>Below code will list directories and the files within the dir</p>\n\n<pre><code>def print_directory_contents(sPath):\n import os \n for sChild in os.listdir(sPath): \n sChildPath = os.path.join(sPath,sChild)\n if os.path.isdir(sChildPath):\n print_directory_contents(sChildPath)\n else:\n print(sChildPath)\n</code></pre>\n" }, { "answer_id": 45242048, "author": "salehinejad", "author_id": 4538031, "author_profile": "https://Stackoverflow.com/users/4538031", "pm_score": 0, "selected": false, "text": "<p>Here is a one line Pythonic version:</p>\n\n<pre><code>import os\ndir = 'given_directory_name'\nfilenames = [os.path.join(os.path.dirname(os.path.abspath(__file__)),dir,i) for i in os.listdir(dir)]\n</code></pre>\n\n<p>This code lists the full path of all files and directories in the given directory name. </p>\n" }, { "answer_id": 47211494, "author": "apeter", "author_id": 7065873, "author_profile": "https://Stackoverflow.com/users/7065873", "pm_score": 0, "selected": false, "text": "<p>I know this is an old question. This is a neat way I came across if you are on a liunx machine. </p>\n\n<pre><code>import subprocess\nprint(subprocess.check_output([\"ls\", \"/\"]).decode(\"utf8\"))\n</code></pre>\n" }, { "answer_id": 49350260, "author": "HassanSh__3571619", "author_id": 3571619, "author_profile": "https://Stackoverflow.com/users/3571619", "pm_score": 2, "selected": false, "text": "<p>The one worked with me is kind of a modified version from Saleh's answer elsewhere on this page.</p>\n<p>The code is as follows:</p>\n<pre class=\"lang-py prettyprint-override\"><code>dir = 'given_directory_name'\nfilenames = [os.path.abspath(os.path.join(dir,i)) for i in os.listdir(dir)]\n</code></pre>\n" }, { "answer_id": 52180310, "author": "Khaino", "author_id": 4053000, "author_profile": "https://Stackoverflow.com/users/4053000", "pm_score": 2, "selected": false, "text": "<p>Here is another option.</p>\n\n<pre><code>os.scandir(path='.')\n</code></pre>\n\n<p>It returns an iterator of os.DirEntry objects corresponding to the entries (along with file attribute information) in the directory given by path. </p>\n\n<p><em>Example:</em></p>\n\n<pre><code>with os.scandir(path) as it:\n for entry in it:\n if not entry.name.startswith('.'):\n print(entry.name)\n</code></pre>\n\n<p><strong>Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information</strong>, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory. All os.DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; os.DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.</p>\n\n<p><a href=\"https://docs.python.org/3/library/os.html#os.scandir\" rel=\"nofollow noreferrer\">Python Docs</a></p>\n" }, { "answer_id": 53643569, "author": "Steve Tarver", "author_id": 1089228, "author_profile": "https://Stackoverflow.com/users/1089228", "pm_score": 3, "selected": false, "text": "<p>While <code>os.listdir()</code> is fine for generating a list of file and dir names, frequently you want to do more once you have those names - and in Python3, <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\">pathlib</a> makes those other chores simple. Let's take a look and see if you like it as much as I do.</p>\n\n<p>To list dir contents, construct a Path object and grab the iterator:</p>\n\n<pre><code>In [16]: Path('/etc').iterdir()\nOut[16]: &lt;generator object Path.iterdir at 0x110853fc0&gt;\n</code></pre>\n\n<p>If we want just a list of names of things:</p>\n\n<pre><code>In [17]: [x.name for x in Path('/etc').iterdir()]\nOut[17]:\n['emond.d',\n 'ntp-restrict.conf',\n 'periodic',\n</code></pre>\n\n<p>If you want just the dirs: </p>\n\n<pre><code>In [18]: [x.name for x in Path('/etc').iterdir() if x.is_dir()]\nOut[18]:\n['emond.d',\n 'periodic',\n 'mach_init.d',\n</code></pre>\n\n<p>If you want the names of all conf files in that tree:</p>\n\n<pre><code>In [20]: [x.name for x in Path('/etc').glob('**/*.conf')]\nOut[20]:\n['ntp-restrict.conf',\n 'dnsextd.conf',\n 'syslog.conf',\n</code></pre>\n\n<p>If you want a list of conf files in the tree >= 1K:</p>\n\n<pre><code>In [23]: [x.name for x in Path('/etc').glob('**/*.conf') if x.stat().st_size &gt; 1024]\nOut[23]:\n['dnsextd.conf',\n 'pf.conf',\n 'autofs.conf',\n</code></pre>\n\n<p>Resolving relative paths become easy:</p>\n\n<pre><code>In [32]: Path('../Operational Metrics.md').resolve()\nOut[32]: PosixPath('/Users/starver/code/xxxx/Operational Metrics.md')\n</code></pre>\n\n<p>Navigating with a Path is pretty clear (although unexpected):</p>\n\n<pre><code>In [10]: p = Path('.')\n\nIn [11]: core = p / 'web' / 'core'\n\nIn [13]: [x for x in core.iterdir() if x.is_file()]\nOut[13]:\n[PosixPath('web/core/metrics.py'),\n PosixPath('web/core/services.py'),\n PosixPath('web/core/querysets.py'),\n</code></pre>\n" }, { "answer_id": 71669709, "author": "Manav Patadia", "author_id": 3380823, "author_profile": "https://Stackoverflow.com/users/3380823", "pm_score": 0, "selected": false, "text": "<p>Easiest way:</p>\n<pre><code>list_output_files = [os.getcwd()+&quot;\\\\&quot;+f for f in os.listdir(os.getcwd())]\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ]
How do I get a list of all files (and directories) in a given directory in Python?
This is a way to traverse every file and directory in a directory tree: ``` import os for dirname, dirnames, filenames in os.walk('.'): # print path to all subdirectories first. for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # print path to all filenames. for filename in filenames: print(os.path.join(dirname, filename)) # Advanced usage: # editing the 'dirnames' list will stop os.walk() from recursing into there. if '.git' in dirnames: # don't go into any .git directories. dirnames.remove('.git') ```
120,657
<p>I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.</p> <p>The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions?</p> <p>To clarify from current responses:</p> <ol> <li>I am using the subprocess module</li> <li>I am passing the command line + arguments in as a list</li> <li>The issue is with the path to the command itself, not any of the arguments</li> <li>I've tried quoting the command. It causes a <code>[Error 123] The filename, directory name, or volume label syntax is incorrect</code> error</li> <li>I'm using no shell argument (so <code>shell=false</code>) </li> <li>In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin</li> <li>It is only for use on Windows currently, and works as expected in all other cases that I've tested so far.</li> <li>The command that is failing is: </li> </ol> <blockquote> <p>p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1)</p> </blockquote> <p>when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work.</p>
[ { "answer_id": 120705, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 1, "selected": false, "text": "<p>A proper answer will need more information than that. What are you actually doing? How does it fail? Are you using the subprocess module? Are you passing a list of arguments and shell=False (or no shell argument) or are you actually invoking the shell?</p>\n" }, { "answer_id": 120706, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 4, "selected": true, "text": "<p>Make sure you are using lists and no shell expansion:</p>\n\n<pre><code>subprocess.Popen(['command', 'argument1', 'argument2'], shell=False)\n</code></pre>\n" }, { "answer_id": 120708, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 0, "selected": false, "text": "<p>Try quoting the argument that contains the &amp;</p>\n\n<pre><code>wget \"http://foo.com/?bar=baz&amp;amp;baz=bar\"\n</code></pre>\n\n<p>Is usually what has to be done in a Linux shell</p>\n" }, { "answer_id": 120782, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 0, "selected": false, "text": "<p>To answer my own question:</p>\n\n<p>Quoting the actual command when passing the parameters as a list doesn't work correctly (command is first item of list) so to solve the issue I turned the list into a space separated string and passed that into subprocess instead.</p>\n\n<p>Better solutions still welcomed.</p>\n" }, { "answer_id": 120992, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "<p>\"escaping the ampersand with ^\"</p>\n\n<p>Are you sure <code>^</code> is an escape character to Windows? Shouldn't you use <code>\\</code>?</p>\n" }, { "answer_id": 20922266, "author": "rickyteng", "author_id": 3160495, "author_profile": "https://Stackoverflow.com/users/3160495", "pm_score": 0, "selected": false, "text": "<p>I try a situation as following:</p>\n\n<pre><code>exe = 'C:/Program Files (x86)/VideoLAN/VLC/VLC.exe'\nurl = 'http://translate.google.com/translate_tts?tl=en&amp;q=hello+world'\nsubprocess.Popen([exe, url.replace(\"&amp;\",\"^&amp;\")],shell=True)\n</code></pre>\n\n<p>This does work.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16035/" ]
I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting. The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions? To clarify from current responses: 1. I am using the subprocess module 2. I am passing the command line + arguments in as a list 3. The issue is with the path to the command itself, not any of the arguments 4. I've tried quoting the command. It causes a `[Error 123] The filename, directory name, or volume label syntax is incorrect` error 5. I'm using no shell argument (so `shell=false`) 6. In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin 7. It is only for use on Windows currently, and works as expected in all other cases that I've tested so far. 8. The command that is failing is: > > p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1) > > > when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work.
Make sure you are using lists and no shell expansion: ``` subprocess.Popen(['command', 'argument1', 'argument2'], shell=False) ```
120,662
<p>I'm trying to run SQuirreL SQL.<br> I've downloaded it and installed it, but when I try to run it I get this error message: </p> <blockquote> <p>Java Virtual Machine Launcher.<br> Could not find the main class.<br> Program will exit. </p> </blockquote> <p>I get the gist of this, but I have not idea how to fix it. Any help? </p> <h3>more info:</h3> <ul> <li>I'm on Windows XP pro. </li> <li>I have java 1.6 installed, and other apps are running OK. </li> <li>The install ran OK. </li> <li>I believe I've followed the installation instructions correctly. </li> <li>To run it, I'm invoking the <strong>squirrel-sql.bat</strong> file. </li> </ul> <h3>Update</h3> <p>This question: <a href="https://stackoverflow.com/questions/1417328/could-not-find-the-main-class">&quot;Could not find the main class: XX. Program will exit.&quot;</a> gives some background on this error from the point of view of a java developer. </p>
[ { "answer_id": 120698, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 2, "selected": false, "text": "<p>Have you followed these instructions:</p>\n\n<p><a href=\"http://www.squirrelsql.org/#installation\" rel=\"nofollow noreferrer\">http://www.squirrelsql.org/#installation</a></p>\n\n<p>If so, are you running the batch file or the shell script to run it?</p>\n" }, { "answer_id": 120729, "author": "MB.", "author_id": 11961, "author_profile": "https://Stackoverflow.com/users/11961", "pm_score": 5, "selected": true, "text": "<p>Is Java installed on your computer? Is the path to its bin directory set properly (in other words if you type 'java' from the command line do you get back a list of instructions or do you get something like \"java is not recognized as a .....\")?</p>\n\n<p>You could try try running <code>squirrel-sql.jar</code> from the command line (from the squirrel sql directory), using:</p>\n\n<pre><code>java -jar squirrel-sql.jar\n</code></pre>\n" }, { "answer_id": 121552, "author": "18Rabbit", "author_id": 12662, "author_profile": "https://Stackoverflow.com/users/12662", "pm_score": 3, "selected": false, "text": "<p>The classpath is the path that the system will follow when trying to find the classes that you're trying to run. In the batch file you're trying to execute it probably has a variable like CLASSPATH=blah;blah;etc or a java command that looks similar to</p>\n\n<pre><code>java -classpath \"c:\\directory\\lib\\squirrel-sql.jar\" com.some.squirrel.package.file\n</code></pre>\n\n<p>If you can find or add that classpath setting, make sure that it includes a path to the squirrel-sql.jar and any other jar files that it may depend on separated by semicolons (or the root /lib directory that may be included with the installation).</p>\n\n<p>Basically you just need to tell java where to find the class files that you're trying to execute. Wikipedia has a more indepth discussion about classpath and can offer you more insight. <a href=\"http://en.wikipedia.org/wiki/Classpath_(Java)\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Classpath_(Java)</a></p>\n" }, { "answer_id": 139007, "author": "tropikalista", "author_id": 15878, "author_profile": "https://Stackoverflow.com/users/15878", "pm_score": 2, "selected": false, "text": "<ol>\n<li>JAVA_HOME variable must be set, to point to the prog files/java/version???/bin</li>\n<li>open squirrel-sql.bat file with some text editor and see if the JAVA_HOME variable there is the same as the one in your enviroment variable</li>\n<li>change it if it doesn't match....and than run bat file again</li>\n</ol>\n" }, { "answer_id": 1312970, "author": "Nathan Feger", "author_id": 8563, "author_profile": "https://Stackoverflow.com/users/8563", "pm_score": 2, "selected": false, "text": "<p>Tweaking MB's answer for windows, will get rid of the console window:</p>\n\n<pre><code>start javaw -jar squirrel-sql.jar\n</code></pre>\n" }, { "answer_id": 2920018, "author": "huug", "author_id": 205785, "author_profile": "https://Stackoverflow.com/users/205785", "pm_score": 1, "selected": false, "text": "<p>The .bat file does not seem to work.</p>\n\n<p>Just double-click on:</p>\n\n<pre><code>squirrel-sql.jar\n</code></pre>\n\n<p>or type:</p>\n\n<pre><code>java -jar squirrel-sql.jar\n</code></pre>\n\n<p>in the command-line.</p>\n" }, { "answer_id": 3036246, "author": "Sohail Anwar", "author_id": 366198, "author_profile": "https://Stackoverflow.com/users/366198", "pm_score": 1, "selected": false, "text": "<p>You can place .; in classpath in environmental variables to overcome this problem.</p>\n" }, { "answer_id": 3134611, "author": "Patrick", "author_id": 273612, "author_profile": "https://Stackoverflow.com/users/273612", "pm_score": 1, "selected": false, "text": "<p>I tried to start SQUirrel 3.1 but I received a message stating \"Could not find the main class Files\\Rational\\ClearQuest\\cqjni.jar\" I noticed that C:\\Program Files\\Rational\\ClearQuest\\cqjni.jar is in my existing classpath as defined by the Windows environment variable, CLASSPATH. </p>\n\n<p>SQUirrel doesn't need my existing classpath, so I updated the SQUirrel bat file, squirrel-sql.bat. </p>\n\n<p><strong>REM SET SQUIRREL_CP=%TMP_CP%;%CLASSPATH%</strong></p>\n\n<p><strong>SET SQUIRREL_CP=%TMP_CP%</strong></p>\n\n<p>It no longer appends my existing classpath to its classpath and runs fine.</p>\n" }, { "answer_id": 23370426, "author": "Steve Gelman", "author_id": 967671, "author_profile": "https://Stackoverflow.com/users/967671", "pm_score": 1, "selected": false, "text": "<p>I had this problem when I \"upgraded\" to Windows 7, which is 64-bit. My go to Java JRE is a 64-bit JVM. I had a 32-bit JRE on my machine for my browser, so I set up a system variable:</p>\n\n<pre><code>JRE32=C:\\Program Files\\Java\\jre7\n</code></pre>\n\n<p>When I run:</p>\n\n<pre><code>\"%JRE32\\bin\\java\" -version\n</code></pre>\n\n<p>I get:</p>\n\n<pre><code>java version \"1.7.0_51\"\nJava(TM) SE Runtime Environment (build 1.7.0_51-b13)\nJava HotSpot(TM) Client VM (build 24.51-b03, mixed mode, sharing)\n</code></pre>\n\n<p>Which is a 32-bit JVM. It would say \"Java HotSpot(TM) <strong>64-Bit</strong>\" otherwise.</p>\n\n<p>I edited the \"squirrel-sql.bat\" file, REMarking out line 4 and adding line 5 as follows:</p>\n\n<pre><code>(4) rem set \"IZPACK_JAVA=%JAVA_HOME%\"\n(5) set IZPACK_JAVA=%JRE32%\n</code></pre>\n\n<p>And now everything works, fine and dandy.</p>\n" }, { "answer_id": 58540339, "author": "eby", "author_id": 5835746, "author_profile": "https://Stackoverflow.com/users/5835746", "pm_score": 0, "selected": false, "text": "<p>I had the same issue with a different application (BI Publisher) because I installed a 32 bit version of this application on a 64 bit version of Windows.</p>\n\n<pre><code>Java Virtual Machine Launcher - could not find the main class\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/UOQJv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UOQJv.png\" alt=\"enter image description here\"></a></p>\n\n<p>The solution for my case was to tell BI Publisher where to find the x86 version of JRE:</p>\n\n<p><a href=\"https://i.stack.imgur.com/bGU5f.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bGU5f.png\" alt=\"enter image description here\"></a></p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7211/" ]
I'm trying to run SQuirreL SQL. I've downloaded it and installed it, but when I try to run it I get this error message: > > Java Virtual Machine Launcher. > > Could not find the main class. > > Program will exit. > > > I get the gist of this, but I have not idea how to fix it. Any help? ### more info: * I'm on Windows XP pro. * I have java 1.6 installed, and other apps are running OK. * The install ran OK. * I believe I've followed the installation instructions correctly. * To run it, I'm invoking the **squirrel-sql.bat** file. ### Update This question: ["Could not find the main class: XX. Program will exit."](https://stackoverflow.com/questions/1417328/could-not-find-the-main-class) gives some background on this error from the point of view of a java developer.
Is Java installed on your computer? Is the path to its bin directory set properly (in other words if you type 'java' from the command line do you get back a list of instructions or do you get something like "java is not recognized as a .....")? You could try try running `squirrel-sql.jar` from the command line (from the squirrel sql directory), using: ``` java -jar squirrel-sql.jar ```
120,693
<p>I've got a function that runs a user generated Regex. However, if the user enters a regex that won't run then it stops and falls over. I've tried wrapping the line in a Try/Catch block but alas nothing happens.</p> <p>If it helps, I'm running jQuery but the code below does not have it as I'm guessing that it's a little more fundamental than that.</p> <p>Edit: Yes, I know that I am not escaping the "[", that's intentional and the point of the question. I'm accepting user input and I want to find a way to catch this sort of problem without the application falling flat on it's face.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Regex&lt;/title&gt; &lt;script type="text/javascript" charset="utf-8"&gt; var grep = new RegExp('gr['); try { var results = grep.exec('bob went to town'); } catch (e) { //Do nothing? } alert('If you can see this then the script kept going'); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 120716, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 3, "selected": false, "text": "<p>The problem is with this line:</p>\n\n<pre><code>var grep = new RegExp('gr[');\n</code></pre>\n\n<p>'[' is a special character so it needs to be escaped. Also this line is not wrapped in try...catch, so you still get the error.</p>\n\n<p><strong>Edit</strong>: You could also add an</p>\n\n<pre><code>alert(e.message);\n</code></pre>\n\n<p>in the catch clause to see the error message. It's useful for all kind of errors in javascript.</p>\n\n<p><strong>Edit 2</strong>: OK, I needed to read more carefully the question, but the answer is still there. In the example code the offending line is not wrapped in the try...catch block. I put it there and didn't get errors in Opera 9.5, FF3 and IE7.</p>\n" }, { "answer_id": 120720, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>your RegExp doesn't close the [</p>\n\n<p>In my FireFox, it never returns from the constructor -- looks like a bug in the implementation of RegExp, but if you provide a valid expression, it works</p>\n" }, { "answer_id": 120743, "author": "Paul Whelan", "author_id": 3050, "author_profile": "https://Stackoverflow.com/users/3050", "pm_score": 5, "selected": true, "text": "<p>Try this the new RegExp is throwing the exception</p>\n\n<p>\n\n\n Regex</p>\n\n<pre><code> &lt;script type=\"text/javascript\" charset=\"utf-8\"&gt;\n var grep;\n\n try {\n grep = new RegExp(\"gr[\");\n }\n catch(e) {\n alert(e);\n\n }\n try\n {\n var results = grep.exec('bob went to town');\n }\n catch (e)\n {\n //Do nothing?\n }\n\n alert('If you can see this then the script kept going');\n &lt;/script&gt;\n</code></pre>\n\n<p>\n</p>\n\n<p>\n</p>\n" }, { "answer_id": 120800, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 0, "selected": false, "text": "<p>One option is to validate the user-generated expressions. That is; escape characters that you know will stall your script.</p>\n" }, { "answer_id": 120809, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 2, "selected": false, "text": "<pre><code>var grep, results;\n\ntry {\n grep = new RegExp(\"gr[\");\n results = grep.exec('bob went to town');\n}\ncatch(e) {\n alert(e);\n}\nalert('If you can see this then the script kept going');\n</code></pre>\n" }, { "answer_id": 121802, "author": "Filini", "author_id": 21162, "author_profile": "https://Stackoverflow.com/users/21162", "pm_score": 2, "selected": false, "text": "<p>putting the RegExp initialization inside the try/catch will work (just tested in FireFox)</p>\n\n<pre><code>\nvar grep, results;\n\ntry\n{\n grep = new RegExp(\"gr[\"); // your user input here\n}\ncatch(e)\n{\n alert(\"The RegExpr is invalid\");\n}\n\n// do your stuff with grep and results\n</code>\n</pre>\n\n<p>Escaping here is not the solution. Since the purpose of this snippet is to actually test a user-generated RegExpr, you will want to catch [ as an unclosed RegExpr container.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
I've got a function that runs a user generated Regex. However, if the user enters a regex that won't run then it stops and falls over. I've tried wrapping the line in a Try/Catch block but alas nothing happens. If it helps, I'm running jQuery but the code below does not have it as I'm guessing that it's a little more fundamental than that. Edit: Yes, I know that I am not escaping the "[", that's intentional and the point of the question. I'm accepting user input and I want to find a way to catch this sort of problem without the application falling flat on it's face. ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>Regex</title> <script type="text/javascript" charset="utf-8"> var grep = new RegExp('gr['); try { var results = grep.exec('bob went to town'); } catch (e) { //Do nothing? } alert('If you can see this then the script kept going'); </script> </head> <body> </body> </html> ```
Try this the new RegExp is throwing the exception Regex ``` <script type="text/javascript" charset="utf-8"> var grep; try { grep = new RegExp("gr["); } catch(e) { alert(e); } try { var results = grep.exec('bob went to town'); } catch (e) { //Do nothing? } alert('If you can see this then the script kept going'); </script> ```
120,702
<p>Using Scala's command line REPL:</p> <pre><code>def foo(x: Int): Unit = {} def foo(x: String): Unit = {println(foo(2))} </code></pre> <p>gives</p> <pre><code>error: type mismatch; found: Int(2) required: String </code></pre> <p>It seems that you can't define overloaded recursive methods in the REPL. I thought this was a bug in the Scala REPL and filed it, but it was almost instantly closed with "wontfix: I don't see any way this could be supported given the semantics of the interpreter, because these two methods must to be compiled together." He recommended putting the methods in an enclosing object.</p> <p>Is there a JVM language implementation or Scala expert who could explain why? I can see it would be a problem if the methods called each other for instance, but in this case?</p> <p>Or if this is too large a question and you think I need more prerequisite knowledge, does someone have any good links to books or sites about language implementations, especially on the JVM? (I know about John Rose's blog, and the book Programming Language Pragmatics... but that's about it. :)</p>
[ { "answer_id": 121647, "author": "user21167", "author_id": 21167, "author_profile": "https://Stackoverflow.com/users/21167", "pm_score": 2, "selected": false, "text": "<p>REPL will accept if you copy both lines and paste both at same time.</p>\n" }, { "answer_id": 122338, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 5, "selected": true, "text": "<p>The issue is due to the fact that the interpreter most often has to <em>replace</em> existing elements with a given name, rather than overload them. For example, I will often be running through experimenting with something, often creating a method called <code>test</code>:</p>\n\n<pre><code>def test(x: Int) = x + x\n</code></pre>\n\n<p>A little later on, let's say that I'm running a <em>different</em> experiment and I create another method named <code>test</code>, unrelated to the first:</p>\n\n<pre><code>def test(ls: List[Int]) = (0 /: ls) { _ + _ }\n</code></pre>\n\n<p>This isn't an entirely unrealistic scenario. In fact, it's precisely how most people use the interpreter, often without even realizing it. If the interpreter arbitrarily decided to keep both versions of <code>test</code> in scope, that could lead to confusing semantic differences in using test. For example, we might make a call to <code>test</code>, accidentally passing an <code>Int</code> rather than <code>List[Int]</code> (not the most unlikely accident in the world):</p>\n\n<pre><code>test(1 :: Nil) // =&gt; 1\ntest(2) // =&gt; 4 (expecting 2)\n</code></pre>\n\n<p>Over time, the root scope of the interpreter would get incredibly cluttered with various versions of methods, fields, etc. I tend to leave my interpreter open for days at a time, but if overloading like this were allowed, we would be forced to \"flush\" the interpreter every so often as things got to be too confusing.</p>\n\n<p>It's not a limitation of the JVM or the Scala compiler, it's a deliberate design decision. As mentioned in the bug, you can still overload if you're within something other than the root scope. Enclosing your test methods within a class seems like the best solution to me.</p>\n" }, { "answer_id": 3664567, "author": "psp", "author_id": 89872, "author_profile": "https://Stackoverflow.com/users/89872", "pm_score": 3, "selected": false, "text": "<pre><code>% scala28\nWelcome to Scala version 2.8.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_20).\nType in expressions to have them evaluated.\nType :help for more information.\n\nscala&gt; def foo(x: Int): Unit = () ; def foo(x: String): Unit = { println(foo(2)) } \nfoo: (x: String)Unit &lt;and&gt; (x: Int)Unit\nfoo: (x: String)Unit &lt;and&gt; (x: Int)Unit\n\nscala&gt; foo(5)\n\nscala&gt; foo(\"abc\")\n()\n</code></pre>\n" }, { "answer_id": 11276947, "author": "Daniel C. Sobral", "author_id": 53013, "author_profile": "https://Stackoverflow.com/users/53013", "pm_score": 1, "selected": false, "text": "<p>As shown by <a href=\"https://stackoverflow.com/users/89872/extempore\">extempore's</a> answer, it is possible to overload. <a href=\"https://stackoverflow.com/users/9815/daniel-spiewak\">Daniel's</a> comment about design decision is correct, but, I think, incomplete and a bit misleading. There's no <em>outlawing</em> of overloads (since they are possible), but they are not easily achieved.</p>\n\n<p>The design decisions that lead to this are:</p>\n\n<ol>\n<li>All previous definitions must be available.</li>\n<li>Only newly entered code is compiled, instead of recompiling everything ever entered every time.</li>\n<li>It must be possible to redefine definitions (as Daniel mentioned).</li>\n<li>It must be possible to define members such as vals and defs, not only classes and objects.</li>\n</ol>\n\n<p>The problem is... how to achieve all these goals? How do we process your example?</p>\n\n<pre><code>def foo(x: Int): Unit = {}\ndef foo(x: String): Unit = {println(foo(2))}\n</code></pre>\n\n<p>Starting with the 4th item, A <code>val</code> or <code>def</code> can only be defined inside a <code>class</code>, <code>trait</code>, <code>object</code> or <code>package object</code>. So, REPL puts the definitions inside objects, like this (<em>not actual representation!</em>)</p>\n\n<pre><code>package $line1 { // input line\n object $read { // what was read\n object $iw { // definitions\n def foo(x: Int): Unit = {}\n }\n // val res1 would be here somewhere if this was an expression\n }\n}\n</code></pre>\n\n<p>Now, due to how JVM works, once you defined one of them, you can't extend them. You could, of course, recompile everything, but we discarded that. So you need to place it in a different place:</p>\n\n<pre><code>package $line1 { // input line\n object $read { // what was read\n object $iw { // definitions\n def foo(x: String): Unit = { println(foo(2)) }\n }\n }\n}\n</code></pre>\n\n<p>And this explains why your examples are not overloads: they are defined in two different places. If you put them in the same line, they'd all be defined together, which would make them overloads, as shown in extempore's example.</p>\n\n<p>As for the other design decisions, each new package import definitions and \"res\" from previous packages, and the imports can shadow each other, which makes it possible to \"redefine\" stuff.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15627/" ]
Using Scala's command line REPL: ``` def foo(x: Int): Unit = {} def foo(x: String): Unit = {println(foo(2))} ``` gives ``` error: type mismatch; found: Int(2) required: String ``` It seems that you can't define overloaded recursive methods in the REPL. I thought this was a bug in the Scala REPL and filed it, but it was almost instantly closed with "wontfix: I don't see any way this could be supported given the semantics of the interpreter, because these two methods must to be compiled together." He recommended putting the methods in an enclosing object. Is there a JVM language implementation or Scala expert who could explain why? I can see it would be a problem if the methods called each other for instance, but in this case? Or if this is too large a question and you think I need more prerequisite knowledge, does someone have any good links to books or sites about language implementations, especially on the JVM? (I know about John Rose's blog, and the book Programming Language Pragmatics... but that's about it. :)
The issue is due to the fact that the interpreter most often has to *replace* existing elements with a given name, rather than overload them. For example, I will often be running through experimenting with something, often creating a method called `test`: ``` def test(x: Int) = x + x ``` A little later on, let's say that I'm running a *different* experiment and I create another method named `test`, unrelated to the first: ``` def test(ls: List[Int]) = (0 /: ls) { _ + _ } ``` This isn't an entirely unrealistic scenario. In fact, it's precisely how most people use the interpreter, often without even realizing it. If the interpreter arbitrarily decided to keep both versions of `test` in scope, that could lead to confusing semantic differences in using test. For example, we might make a call to `test`, accidentally passing an `Int` rather than `List[Int]` (not the most unlikely accident in the world): ``` test(1 :: Nil) // => 1 test(2) // => 4 (expecting 2) ``` Over time, the root scope of the interpreter would get incredibly cluttered with various versions of methods, fields, etc. I tend to leave my interpreter open for days at a time, but if overloading like this were allowed, we would be forced to "flush" the interpreter every so often as things got to be too confusing. It's not a limitation of the JVM or the Scala compiler, it's a deliberate design decision. As mentioned in the bug, you can still overload if you're within something other than the root scope. Enclosing your test methods within a class seems like the best solution to me.
120,731
<p>Let's assume you have one massive table with three columns as shown below:</p> <pre><code>[id] INT NOT NULL, [date] SMALLDATETIME NOT NULL, [sales] FLOAT NULL </code></pre> <p>Also assume you are limited to one physical disk and one filegroup (PRIMARY). You expect this table to hold sales for 10,000,000+ ids, across 100's of dates (easily 1B+ records).</p> <p>As with many data warehousing scenarios, the data will typically grow sequentially by date (i.e., each time you perform a data load, you will be inserting new dates, and maybe updating some of the more recent dates of data). For analytic purposes, the data will often be queried and aggregated for a random set of ~10,000 ids which will be specified via a join with another table. Often, these queries don't specify date ranges, or specify very wide date ranges, which leads me to my question: What is the best way to index / partition this table?</p> <p>I have thought about this for a while, but am stuck with conflicting solutions:</p> <p><strong>Option #1:</strong> As data will be loaded sequentially by date, define the clustered index (and primary key) as [date], [id]. Also create a "sliding window" partitioning function / scheme on date allowing rapid movement of new data in / out of the table. Potentially create a non-clustered index on id to help with querying.</p> <p><strong>Expected Outcome #1:</strong> This setup will be very fast for data loading purposes, but sub-optimal when it comes to analytic reads as, in a worst case scenario (no limiting by dates, unlucky with set of id's queried), 100% of the data pages may be read.</p> <p><strong>Option #2:</strong> As the data will be queried for only a small subset of ids at a time, define the clustered index (and primary key) as [id], [date]. Do not bother to create a partitioned table.</p> <p><strong>Expected Outcome #2:</strong> Expected huge performance hit when it comes to loading data as we can no longer quickly limit by date. Expected huge performance benefit when it comes to my analytic queries as it will minimize the number of data pages read.</p> <p><strong>Option #3:</strong> Clustered (and primary key) as follows: [id], [date]; "sliding window" partition function / scheme on date.</p> <p><strong>Expected Outcome #3:</strong> Not sure what to expect. Given that the first column in the clustered index is [id] and thus (it is my understanding) the data is arranged by ID, I would expect good performance from my analytic queries. However, the data is partitioned by date, which is contrary to the definition of the clustered index (but still aligned as date is part of the index). I haven't found much documentation that speaks to this scenario and what, if any, performance benefits I may get from this, which brings me to my final, bonus question:</p> <p>If I am creating a table on one filegroup on one disk, with a clustered index on one column, is there any benefit (besides partition switching when loading the data) that comes from defining a partition on the same column?</p>
[ { "answer_id": 120815, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 0, "selected": false, "text": "<p>If you are using the partitions in the select statements, then you cn gain some speed.</p>\n\n<p>If you are not using it, only using \"standard\" selects, then you have no benefit.</p>\n\n<p>On your original problem: I would recommend you option #1 with the non-clustered index on id included.</p>\n" }, { "answer_id": 120833, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 2, "selected": false, "text": "<p>A clustered index will give you performance benefits for queries when localising the I/O. Date is a traditional partitioning strategy as many D/W queries look at movements by date.</p>\n\n<p>A rule of thumb for a partitioned table suggests that partitions should be around 10m rows in size.</p>\n\n<p>It would be somewhat unusual to see much performance gain from a clustered index on a diverse analytic workload. The query optimiser will use a technique called <a href=\"http://www.databasejournal.com/features/mssql/article.php/1438821\" rel=\"nofollow noreferrer\">'Index Intersection'</a> to select rows without even hitting the fact table. See <a href=\"https://stackoverflow.com/questions/110032/star-schema-design#111044\">Here</a> for a post I did on another question that explains this in more depth with some links.\nA clustered index may or may not participate in the index intersection, so you may find that it gains you relatively little on a general query workload. </p>\n\n<p>You may find circumstances in loading where clustered indexes give you some gain, particularly if you have derived calculations (such as <a href=\"http://en.wikipedia.org/wiki/Earned_premium\" rel=\"nofollow noreferrer\">Earned Premium</a>) that are computed within the ETL process. In this case you may get some benefits. If you have a specific query that you know will be executed all the time it might make sense to use clustered indexes for this. Options #2 and #3 are only going to significantly benefit you if you expect this type of query to be the overwhelming majority of the work done by the application.</p>\n\n<p>For a flexible system, a simple date range partition with an index on the ID (and date if the partitions hold a range would probably get you as good a performance as any. You might get some benefit from clustering the index limited circumstances. You might also get some mileage from building a cube over the data and ensuring that the aggregations are set up correctly for this query. </p>\n" }, { "answer_id": 120846, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 0, "selected": false, "text": "<p>I would do the following:</p>\n\n<ul>\n<li>Non-Clustered Index on [Id]</li>\n<li>Clustered Index on [Date]</li>\n<li>Convert the [sales] datatype to numeric instead of float</li>\n</ul>\n" }, { "answer_id": 120882, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": false, "text": "<p>This table is awesomely narrow. If the real table will be this narrow, you should be happy to have table scans instead of index->lookups.</p>\n\n<p>I would do this:</p>\n\n<pre><code>CREATE TABLE Narrow\n(\n [id] INT NOT NULL,\n [date] SMALLDATETIME NOT NULL,\n [sales] FLOAT NULL,\n PRIMARY KEY(id, date) --EDIT, just noticed your id is not unique.\n)\n\nCREATE INDEX CoveringNarrow ON Narrow(date, id, sales)\n</code></pre>\n\n<p>This handles point queries with seeks and wide-range queries with limited scans against date criteria and id criteria. There is no per-record lookup from index. Yes, I've doubled the write time (and space used) but that's fine, imo.</p>\n\n<hr>\n\n<p>If there's some need for a specific piece of data (and that need is <strong>demonstrated by profiling</strong>!!), I'd create a clustered view targetting that section of the table.</p>\n\n<pre><code>CREATE VIEW Narrow200801\nAS\nSELECT * FROM Narrow WHERE '2008-01-01' &lt;= [date] AND [date] &lt; '2008-02-01'\n--There is some command that I don't have at my finger tips to make this a clustered view.\n</code></pre>\n\n<p>Clustered views can be used in queries by name, or the optimizer will choose to use the clustered views when the FROM and WHERE clause are appropriate. For example, this query will use the clustered view. Note that the base table is referred to in the query.</p>\n\n<pre><code>SELECT SUM(sales) FROM Narrow WHERE '2008-01-01' &lt;= [date] AND [date] &lt; '2008-02-01'\n</code></pre>\n\n<p>As <em>index</em> lets you make specific columns conveniently accessible... <em>Clustered view</em> lets you make specific rows conveniently accessible.</p>\n" }, { "answer_id": 121113, "author": "Thomas Wagner", "author_id": 13997, "author_profile": "https://Stackoverflow.com/users/13997", "pm_score": 0, "selected": false, "text": "<p>Partition the table by date. Several horizontal partitions will be more performant than one large table with that many rows. </p>\n" }, { "answer_id": 124251, "author": "Mladen", "author_id": 21404, "author_profile": "https://Stackoverflow.com/users/21404", "pm_score": 0, "selected": false, "text": "<p>Clustered index on the date column isn't good if you'll have inserts that will be inserted faster that the datetime resolution of 3.33 ms is.\nif you do you'll get 2 keys with the same value and your index will have to get another internal uniquifier which will increase its size.</p>\n\n<p>i'd go with #2 of your options.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4391/" ]
Let's assume you have one massive table with three columns as shown below: ``` [id] INT NOT NULL, [date] SMALLDATETIME NOT NULL, [sales] FLOAT NULL ``` Also assume you are limited to one physical disk and one filegroup (PRIMARY). You expect this table to hold sales for 10,000,000+ ids, across 100's of dates (easily 1B+ records). As with many data warehousing scenarios, the data will typically grow sequentially by date (i.e., each time you perform a data load, you will be inserting new dates, and maybe updating some of the more recent dates of data). For analytic purposes, the data will often be queried and aggregated for a random set of ~10,000 ids which will be specified via a join with another table. Often, these queries don't specify date ranges, or specify very wide date ranges, which leads me to my question: What is the best way to index / partition this table? I have thought about this for a while, but am stuck with conflicting solutions: **Option #1:** As data will be loaded sequentially by date, define the clustered index (and primary key) as [date], [id]. Also create a "sliding window" partitioning function / scheme on date allowing rapid movement of new data in / out of the table. Potentially create a non-clustered index on id to help with querying. **Expected Outcome #1:** This setup will be very fast for data loading purposes, but sub-optimal when it comes to analytic reads as, in a worst case scenario (no limiting by dates, unlucky with set of id's queried), 100% of the data pages may be read. **Option #2:** As the data will be queried for only a small subset of ids at a time, define the clustered index (and primary key) as [id], [date]. Do not bother to create a partitioned table. **Expected Outcome #2:** Expected huge performance hit when it comes to loading data as we can no longer quickly limit by date. Expected huge performance benefit when it comes to my analytic queries as it will minimize the number of data pages read. **Option #3:** Clustered (and primary key) as follows: [id], [date]; "sliding window" partition function / scheme on date. **Expected Outcome #3:** Not sure what to expect. Given that the first column in the clustered index is [id] and thus (it is my understanding) the data is arranged by ID, I would expect good performance from my analytic queries. However, the data is partitioned by date, which is contrary to the definition of the clustered index (but still aligned as date is part of the index). I haven't found much documentation that speaks to this scenario and what, if any, performance benefits I may get from this, which brings me to my final, bonus question: If I am creating a table on one filegroup on one disk, with a clustered index on one column, is there any benefit (besides partition switching when loading the data) that comes from defining a partition on the same column?
This table is awesomely narrow. If the real table will be this narrow, you should be happy to have table scans instead of index->lookups. I would do this: ``` CREATE TABLE Narrow ( [id] INT NOT NULL, [date] SMALLDATETIME NOT NULL, [sales] FLOAT NULL, PRIMARY KEY(id, date) --EDIT, just noticed your id is not unique. ) CREATE INDEX CoveringNarrow ON Narrow(date, id, sales) ``` This handles point queries with seeks and wide-range queries with limited scans against date criteria and id criteria. There is no per-record lookup from index. Yes, I've doubled the write time (and space used) but that's fine, imo. --- If there's some need for a specific piece of data (and that need is **demonstrated by profiling**!!), I'd create a clustered view targetting that section of the table. ``` CREATE VIEW Narrow200801 AS SELECT * FROM Narrow WHERE '2008-01-01' <= [date] AND [date] < '2008-02-01' --There is some command that I don't have at my finger tips to make this a clustered view. ``` Clustered views can be used in queries by name, or the optimizer will choose to use the clustered views when the FROM and WHERE clause are appropriate. For example, this query will use the clustered view. Note that the base table is referred to in the query. ``` SELECT SUM(sales) FROM Narrow WHERE '2008-01-01' <= [date] AND [date] < '2008-02-01' ``` As *index* lets you make specific columns conveniently accessible... *Clustered view* lets you make specific rows conveniently accessible.
120,751
<p>I have been trying to use routes.rb for creating a URL /similar-to-:product (where product is dynamic) for my website. The issue is that routes.rb readily supports URLs like /:product-similar but doesn't support the former because it requires :product to be preceded with a separator ('/' is a separator but '-' isn't). The list of separators is in ActionController::Routing::SEPARATORS.</p> <p>I can't add '-' as a separator because :product can also contain a hyphen. What is the best way of supporting a URL like this?</p> <p>One way that I have successfully tried is to not use routes.rb and put the URL parsing logic in the controller itself, but that isn't the cleanest way.</p>
[ { "answer_id": 120819, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 0, "selected": false, "text": "<p>I'm a little confused, but could you maybe add \"to-\" as a seperator? </p>\n" }, { "answer_id": 122498, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 2, "selected": false, "text": "<p>I would refactor your URLs so that they're simply \"similar-to/product\"</p>\n" }, { "answer_id": 1385217, "author": "Leonid Shevtsov", "author_id": 6678, "author_profile": "https://Stackoverflow.com/users/6678", "pm_score": 2, "selected": true, "text": "<p>In fact you can add <code>-</code> as a separator, then use route globbing.</p>\n\n<pre><code>map.similar_product '/similar-to-*product', :controller =&gt; 'products', :action =&gt; 'similar'\n</code></pre>\n\n<p>then, in ProductsController#similar</p>\n\n<pre><code>@product = Product.find_by_slug params[:product].join('-')\n</code></pre>\n\n<p>Though refactoring does seem nicer, since with this approach you'll need to specially handle all slugs that can contain hyphens.</p>\n" }, { "answer_id": 1476296, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>An easy solution is using a <a href=\"http://github.com/svenfuchs/routing-filter\" rel=\"nofollow noreferrer\">routing filter</a>. See README for details.</p>\n\n<p>With routing filter you can have a url <code>/similar-to-:product</code>, preprocess it to <code>/similar-to/:product</code> before it gets to routing recognition. You'll also want to post-process generated paths back from <code>/similar-to/:product</code> to <code>/similat-to-:product</code>.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17494/" ]
I have been trying to use routes.rb for creating a URL /similar-to-:product (where product is dynamic) for my website. The issue is that routes.rb readily supports URLs like /:product-similar but doesn't support the former because it requires :product to be preceded with a separator ('/' is a separator but '-' isn't). The list of separators is in ActionController::Routing::SEPARATORS. I can't add '-' as a separator because :product can also contain a hyphen. What is the best way of supporting a URL like this? One way that I have successfully tried is to not use routes.rb and put the URL parsing logic in the controller itself, but that isn't the cleanest way.
In fact you can add `-` as a separator, then use route globbing. ``` map.similar_product '/similar-to-*product', :controller => 'products', :action => 'similar' ``` then, in ProductsController#similar ``` @product = Product.find_by_slug params[:product].join('-') ``` Though refactoring does seem nicer, since with this approach you'll need to specially handle all slugs that can contain hyphens.
120,763
<p>I have a helper class pulling a string from an XML file. That string is a file path (so it has backslashes in it). I need to use that string as it is... How can I use it like I would with the literal command?</p> <p>Instead of this:</p> <pre><code>string filePath = @"C:\somepath\file.txt"; </code></pre> <p>I want to do this:</p> <pre><code>string filePath = @helper.getFilePath(); //getFilePath returns a string </code></pre> <p>This isn't how I am actually using it; it is just to make what I mean a little clearer. Is there some sort of .ToLiteral() or something?</p>
[ { "answer_id": 120776, "author": "brock.holum", "author_id": 15860, "author_profile": "https://Stackoverflow.com/users/15860", "pm_score": 5, "selected": true, "text": "<p>I don't think you have to worry about it if you already have the value. The @ operator is for when you're specifying the string (like in your first code snippet).</p>\n\n<p>What are you attempting to do with the path string that isn't working?</p>\n" }, { "answer_id": 120785, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 2, "selected": false, "text": "<p>I'm not sure if I understand. In your example: if <code>helper.getFilePath()</code> returns <code>\"c:\\somepath\\file.txt\"</code>, there will be no problem, since the <code>@</code> is only needed if you are explicitely specifying a string with \"\". </p>\n\n<p>When Functions <em>talk to each other</em>, you will always get the literal path. If the XML contains <code>c:\\somepath\\file.txt</code> and your function returns <code>c:\\somepath\\file.txt</code>, then string filePath will also contain <code>c:\\somepath\\file.txt</code> as a valid path.</p>\n" }, { "answer_id": 120796, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 2, "selected": false, "text": "<p>In C# the @ symbol combined with doubles quotes allows you to write escaped strings. E.g.</p>\n\n<pre><code>print(@\"c:\\mydir\\dont\\have\\to\\escape\\backslashes\\etc\");\n</code></pre>\n\n<p>If you dont use it then you need to use the escape character in your strings.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx</a></p>\n\n<p>You dont need to specify it anywhere else in code. In fact doing so should cause a compiler error.</p>\n" }, { "answer_id": 120805, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 1, "selected": false, "text": "<p>You've got it backwards. The @-operator is for turning literals into strings, while keeping all funky characters. Your path is already a string - you don't need to do anything at all to it. Just lose the @.</p>\n\n<pre><code>string filePath = helper.getFilePath();\n</code></pre>\n" }, { "answer_id": 120831, "author": "Gary Willoughby", "author_id": 13227, "author_profile": "https://Stackoverflow.com/users/13227", "pm_score": 1, "selected": false, "text": "<p>The string returned from your helper class is not a literal string so you don't need to use the '@' character to remove the behaviour of the backslashes.</p>\n" }, { "answer_id": 120837, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 2, "selected": false, "text": "<p>The @&quot;&quot; just makes it easier to write string literals.</p>\n<p><a href=\"http://msdn.microsoft.com/en-us/library/362314fe.aspx\" rel=\"nofollow noreferrer\">string (C# Reference, MSDN)</a></p>\n<blockquote>\n<p>Verbatim string literals start with @ and are also enclosed in double quotation marks. For example:</p>\n<blockquote>\n<p><code>@&quot;good morning&quot; // a string literal</code></p>\n</blockquote>\n<p>The advantage of verbatim strings is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:</p>\n<blockquote>\n<p><code>@&quot;c:\\Docs\\Source\\a.txt&quot; // rather than &quot;c:\\\\Docs\\\\Source\\\\a.txt&quot;</code></p>\n</blockquote>\n</blockquote>\n<p>One place where I've used it is in a regex pattern:</p>\n<pre>string pattern = @\"\\b[DdFf][0-9]+\\b\";</pre>\n<p>If you have a string in a variable, you do not need to make a &quot;literal&quot; out of it, since if it is well formed, it already has the correct contents.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
I have a helper class pulling a string from an XML file. That string is a file path (so it has backslashes in it). I need to use that string as it is... How can I use it like I would with the literal command? Instead of this: ``` string filePath = @"C:\somepath\file.txt"; ``` I want to do this: ``` string filePath = @helper.getFilePath(); //getFilePath returns a string ``` This isn't how I am actually using it; it is just to make what I mean a little clearer. Is there some sort of .ToLiteral() or something?
I don't think you have to worry about it if you already have the value. The @ operator is for when you're specifying the string (like in your first code snippet). What are you attempting to do with the path string that isn't working?
120,766
<p>I have several &lt;li> elements with different id's on ASP.NET page:</p> <pre><code>&lt;li id="li1" class="class1"&gt; &lt;li id="li2" class="class1"&gt; &lt;li id="li3" class="class1"&gt; </code></pre> <p>and can change their class using JavaScript like this:</p> <pre><code>li1.className="class2" </code></pre> <p>But is there a way to change &lt;li> element class using ASP.NET? It could be something like:</p> <pre><code>WebControl control = (WebControl)FindControl("li1"); control.CssClass="class2"; </code></pre> <p>But FindControl() doesn't work as I expected. Any suggestions?</p> <p>Thanks in advance!</p>
[ { "answer_id": 120774, "author": "stefano m", "author_id": 19261, "author_profile": "https://Stackoverflow.com/users/19261", "pm_score": 2, "selected": false, "text": "<p>you must set runat=\"server\" like:</p>\n\n<pre><code>&lt;li id=\"li1\" runat=\"server\"&gt;stuff&lt;/li&gt;\n</code></pre>\n" }, { "answer_id": 120777, "author": "naspinski", "author_id": 14777, "author_profile": "https://Stackoverflow.com/users/14777", "pm_score": 4, "selected": false, "text": "<p>FindControl will work if you include runat=\"server\" in the &lt;li&gt;</p>\n\n<pre><code>&lt;li id=\"li1\" runat=\"server\"&gt;stuff&lt;/li&gt;\n</code></pre>\n\n<p>Otherwise you server side code can't 'see' it.</p>\n" }, { "answer_id": 120894, "author": "Richard Yorkshire", "author_id": 21001, "author_profile": "https://Stackoverflow.com/users/21001", "pm_score": 4, "selected": true, "text": "<p>The FindControl method searches for server controls. That is, it looks for controls with the attribute \"runat\" set to \"server\", as in:</p>\n\n<pre><code>&lt;li runat=\"server ... &gt;&lt;/li&gt;\n</code></pre>\n\n<p>Because your &lt;li&gt; tags are not server controls, FindControl cannot find them. You can add the \"runat\" attribute to these controls or use ClientScript.RegisterStartupScript to include some client side script to manipulate the class, e.g.</p>\n\n<pre><code>System.Text.StringBuilder sb = new System.Text.StringBuilder();\nsb.Append(\"&lt;script language=\\\"javascript\\\"&gt;\");\nsb.Append(\"document.getElementById(\\\"li1\\\").className=\\\"newClass\\\";\")\nsb.Append(\"&lt;/script&gt;\");\nClientScript.RegisterStartupScript(this.GetType(), \"MyScript\", sb.ToString());\n</code></pre>\n" }, { "answer_id": 397821, "author": "user49845", "author_id": 49845, "author_profile": "https://Stackoverflow.com/users/49845", "pm_score": 5, "selected": false, "text": "<p>Add \n<code>runat=\"server\"</code> in your HTML page</p>\n\n<p>then use the attribute property in your asp.Net page like this</p>\n\n<pre><code>li1.Attributes[\"Class\"] = \"class1\";\nli2.Attributes[\"Class\"] = \"class2\";\n</code></pre>\n" }, { "answer_id": 2099341, "author": "cweston", "author_id": 37966, "author_profile": "https://Stackoverflow.com/users/37966", "pm_score": 3, "selected": false, "text": "<p>This will find the li element and set a CSS class on it. </p>\n\n<pre><code>using System.Web.UI.HtmlControls;\n\nHtmlGenericControl liItem = (HtmlGenericControl) ctl.FindControl(\"liItemID\");\nliItem.Attributes.Add(\"class\", \"someCssClass\");\n</code></pre>\n\n<p>Remember to add your <code>runat=\"server\"</code> attribute as mentioned by others.</p>\n" }, { "answer_id": 10911810, "author": "ebram khalil", "author_id": 1295905, "author_profile": "https://Stackoverflow.com/users/1295905", "pm_score": 0, "selected": false, "text": "<p>You also can try this too if u want to add some few styles:</p>\n\n<pre><code>li1.Style.add(\"color\",\"Blue\");\nli2.Style.add(\"text-decoration\",\"line-through\");\n</code></pre>\n" }, { "answer_id": 11357836, "author": "Amareswar sai Mulumudi", "author_id": 1506068, "author_profile": "https://Stackoverflow.com/users/1506068", "pm_score": 1, "selected": false, "text": "<p>Leaf Dev provided the solution for this, but in the place of \"ctl\" you need to insert \"Master\".</p>\n\n<p>It's working for me anyway:</p>\n\n<pre><code>using System.Web.UI.HtmlControls;\n\nHtmlGenericControl liItem = (HtmlGenericControl) ctl.FindControl(\"liItemID\");\nliItem.Attributes.Add(\"class\", \"someCssClass\");\n</code></pre>\n" }, { "answer_id": 11879780, "author": "Vimal Patel", "author_id": 1488039, "author_profile": "https://Stackoverflow.com/users/1488039", "pm_score": 2, "selected": false, "text": "<p>Please try this if you want to apply style:</p>\n\n<pre><code>li1.Style.Add(\"background-color\", \"black\");\n</code></pre>\n\n<p>For CSS, you can try below syntax :</p>\n\n<pre><code>li1.Attributes.Add(\"class\", \"clsItem\");\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
I have several <li> elements with different id's on ASP.NET page: ``` <li id="li1" class="class1"> <li id="li2" class="class1"> <li id="li3" class="class1"> ``` and can change their class using JavaScript like this: ``` li1.className="class2" ``` But is there a way to change <li> element class using ASP.NET? It could be something like: ``` WebControl control = (WebControl)FindControl("li1"); control.CssClass="class2"; ``` But FindControl() doesn't work as I expected. Any suggestions? Thanks in advance!
The FindControl method searches for server controls. That is, it looks for controls with the attribute "runat" set to "server", as in: ``` <li runat="server ... ></li> ``` Because your <li> tags are not server controls, FindControl cannot find them. You can add the "runat" attribute to these controls or use ClientScript.RegisterStartupScript to include some client side script to manipulate the class, e.g. ``` System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append("<script language=\"javascript\">"); sb.Append("document.getElementById(\"li1\").className=\"newClass\";") sb.Append("</script>"); ClientScript.RegisterStartupScript(this.GetType(), "MyScript", sb.ToString()); ```
120,783
<p>Currently I have this (edited after reading advice):</p> <pre><code>struct Pair&lt;T, K&gt; : IEqualityComparer&lt;Pair&lt;T, K&gt;&gt; { readonly private T _first; readonly private K _second; public Pair(T first, K second) { _first = first; _second = second; } public T First { get { return _first; } } public K Second { get { return _second; } } #region IEqualityComparer&lt;Pair&lt;T,K&gt;&gt; Members public bool Equals(Pair&lt;T, K&gt; x, Pair&lt;T, K&gt; y) { return x.GetHashCode(x) == y.GetHashCode(y); } public int GetHashCode(Pair&lt;T, K&gt; obj) { int hashCode = obj.First == null ? 0 : obj._first.GetHashCode(); hashCode ^= obj.Second == null ? 0 : obj._second.GetHashCode(); return hashCode; } #endregion public override int GetHashCode() { return this.GetHashCode(this); } public override bool Equals(object obj) { return (obj != null) &amp;&amp; (obj is Pair&lt;T, K&gt;) &amp;&amp; this.Equals(this, (Pair&lt;T, K&gt;) obj); } } </code></pre> <p>The problem is that First and Second may not be reference types (VS actually warns me about this), but the code still compiles. Should I cast them (First and Second) to objects before I compare them, or is there a better way to do this?</p> <p>Edit: Note that I <em>want</em> this struct to support value and reference types (in other words, constraining by class is not a valid solution)</p> <p>Edit 2: As to what I'm trying to achieve, I want this to work in a Dictionary. Secondly, SRP isn't important to me right now because that isn't really the essence of this problem - it can always be refactored later. Thirdly, comparing to default(T) will not work in lieu of comparing to null - try it.</p>
[ { "answer_id": 120812, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 2, "selected": false, "text": "<p>Your IEqualityComparer implementation should be a different class (and definately not a struct as you want to reuse the reference). </p>\n\n<p>Also, your hashcode should never be cached, as the default GetHashcode implementation for a struct (which you do not override) will take that member into account.</p>\n" }, { "answer_id": 120814, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 0, "selected": false, "text": "<p>Regarding the warning, you can use default(T) and default(K) instead of null.</p>\n\n<p>I can't see what you're trying to achieve, but you shouldn't be using the hashcode to compare for equality - there is no guarantee that two different objects won't have the same hashcode. Also even though your struct is immutable, the members _first and _second aren't.</p>\n" }, { "answer_id": 120820, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "<p>First of all this code violates SRP principle. Pair class used to hold pairs if items, right? It's incorrect to delegate equality comparing functionality to it. </p>\n\n<p>Next let take a look at your code:</p>\n\n<p>Equals method will fail if one of the arguments is null - no good. Equals uses hash code of Pair class, but take a look at the definition of GetHashCode, it just a combination of pair members hash codes - it's has nothing to do with equality of items. I would expect that Equals method will compare actual data. I'm too busy at the moment to provide correct implementation, unfortunately. But from the first look, you code seems to be wrong. It would be better if you provide us description of what you want to achieve. I'm sure SO members will be able to give you some advices.</p>\n" }, { "answer_id": 120826, "author": "Alexandre Brisebois", "author_id": 18619, "author_profile": "https://Stackoverflow.com/users/18619", "pm_score": 0, "selected": false, "text": "<p>Might I suggest the use of Lambda expressions as a parameter ?\nthis would allow you to specify how to compare the internal generic types.</p>\n" }, { "answer_id": 120834, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 0, "selected": false, "text": "<p>I don't get any warning when compiling about this but I assume you are talking about the == null comparison? A cast seems like it would make this all somewhat cleaner, yes.</p>\n\n<p>PS. You really should use a separate class for the comparer. This class that fills two roles (being a pair and comparing pairs) is plain ugly.</p>\n" }, { "answer_id": 120843, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 2, "selected": false, "text": "<p>If you use hashcodes in comparing methods, you should check for \"realy value\" if the hash codes are same.</p>\n\n<pre><code>bool result = ( x._hashCode == y._hashCode );\nif ( result ) { result = ( x._first == y._first &amp;&amp; x._second == y._second ); }\n// OR?: if ( result ) { result = object.Equals( x._first, y._first ) &amp;&amp; object.Equals( x._second, y._second ); }\n// OR?: if ( result ) { result = object.ReferenceEquals( x._first, y._first ) &amp;&amp; object.Equals( x._second, y._second ); }\nreturn result;\n</code></pre>\n\n<p>But there is littlebit problem with comparing \"_first\" and \"_second\" fields.\nBy default reference types uses fore equality comparing \"object.ReferenceEquals\" method, bud they can override them. So the correct solution depends on the \"what exactly should do\" the your comparing method. Should use \"Equals\" method of the \"_first\" &amp; \"_second\" fields, or object.ReferenceEquals ? Or something more complex?</p>\n" }, { "answer_id": 121642, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 3, "selected": true, "text": "<p>It looks like you need IEquatable instead:</p>\n\n<pre><code>internal struct Pair&lt;T, K&gt; : IEquatable&lt;Pair&lt;T, K&gt;&gt;\n{\n private readonly T _first;\n private readonly K _second;\n\n public Pair(T first, K second)\n {\n _first = first;\n _second = second;\n }\n\n public T First\n {\n get { return _first; }\n }\n\n public K Second\n {\n get { return _second; }\n }\n\n public bool Equals(Pair&lt;T, K&gt; obj)\n {\n return Equals(obj._first, _first) &amp;&amp; Equals(obj._second, _second);\n }\n\n public override bool Equals(object obj)\n {\n return obj is Pair&lt;T, K&gt; &amp;&amp; Equals((Pair&lt;T, K&gt;) obj);\n }\n\n public override int GetHashCode()\n {\n unchecked\n {\n return (_first != null ? _first.GetHashCode() * 397 : 0) ^ (_second != null ? _second.GetHashCode() : 0);\n }\n }\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
Currently I have this (edited after reading advice): ``` struct Pair<T, K> : IEqualityComparer<Pair<T, K>> { readonly private T _first; readonly private K _second; public Pair(T first, K second) { _first = first; _second = second; } public T First { get { return _first; } } public K Second { get { return _second; } } #region IEqualityComparer<Pair<T,K>> Members public bool Equals(Pair<T, K> x, Pair<T, K> y) { return x.GetHashCode(x) == y.GetHashCode(y); } public int GetHashCode(Pair<T, K> obj) { int hashCode = obj.First == null ? 0 : obj._first.GetHashCode(); hashCode ^= obj.Second == null ? 0 : obj._second.GetHashCode(); return hashCode; } #endregion public override int GetHashCode() { return this.GetHashCode(this); } public override bool Equals(object obj) { return (obj != null) && (obj is Pair<T, K>) && this.Equals(this, (Pair<T, K>) obj); } } ``` The problem is that First and Second may not be reference types (VS actually warns me about this), but the code still compiles. Should I cast them (First and Second) to objects before I compare them, or is there a better way to do this? Edit: Note that I *want* this struct to support value and reference types (in other words, constraining by class is not a valid solution) Edit 2: As to what I'm trying to achieve, I want this to work in a Dictionary. Secondly, SRP isn't important to me right now because that isn't really the essence of this problem - it can always be refactored later. Thirdly, comparing to default(T) will not work in lieu of comparing to null - try it.
It looks like you need IEquatable instead: ``` internal struct Pair<T, K> : IEquatable<Pair<T, K>> { private readonly T _first; private readonly K _second; public Pair(T first, K second) { _first = first; _second = second; } public T First { get { return _first; } } public K Second { get { return _second; } } public bool Equals(Pair<T, K> obj) { return Equals(obj._first, _first) && Equals(obj._second, _second); } public override bool Equals(object obj) { return obj is Pair<T, K> && Equals((Pair<T, K>) obj); } public override int GetHashCode() { unchecked { return (_first != null ? _first.GetHashCode() * 397 : 0) ^ (_second != null ? _second.GetHashCode() : 0); } } } ```
120,797
<p>Many times, a Java app needs to connect to the Internet. The most common example happens when it is reading an XML file and needs to download its schema.</p> <p>I am behind a proxy server. How can I set my JVM to use the proxy ?</p>
[ { "answer_id": 120802, "author": "Leonel", "author_id": 15649, "author_profile": "https://Stackoverflow.com/users/15649", "pm_score": 10, "selected": true, "text": "<p>From the Java documentation (<em>not</em> the javadoc API):</p>\n<p><a href=\"http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html\" rel=\"noreferrer\">http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html</a></p>\n<p>Set the JVM flags <code>http.proxyHost</code> and <code>http.proxyPort</code> when starting your JVM on the command line.\nThis is usually done in a shell script (in Unix) or bat file (in Windows). Here's the example with the Unix shell script:</p>\n<pre><code>JAVA_FLAGS=-Dhttp.proxyHost=10.0.0.100 -Dhttp.proxyPort=8800\njava ${JAVA_FLAGS} ...\n</code></pre>\n<p>When using containers such as JBoss or WebLogic, my solution is to edit the start-up scripts supplied by the vendor.</p>\n<p>Many developers are familiar with the Java API (javadocs), but many times the rest of the documentation is overlooked. It contains a lot of interesting information: <a href=\"http://download.oracle.com/javase/6/docs/technotes/guides/\" rel=\"noreferrer\">http://download.oracle.com/javase/6/docs/technotes/guides/</a></p>\n<hr />\n<p><strong>Update :</strong> If you do not want to use proxy to resolve some local/intranet hosts, check out the comment from @Tomalak:</p>\n<blockquote>\n<p>Also don't forget the http.nonProxyHosts property!</p>\n</blockquote>\n<pre><code>-Dhttp.nonProxyHosts=&quot;localhost|127.0.0.1|10.*.*.*|*.example.com|etc&quot;\n</code></pre>\n" }, { "answer_id": 120818, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": 6, "selected": false, "text": "<p>You can set those flags programmatically this way:</p>\n\n<pre><code>if (needsProxy()) {\n System.setProperty(\"http.proxyHost\",getProxyHost());\n System.setProperty(\"http.proxyPort\",getProxyPort());\n} else {\n System.setProperty(\"http.proxyHost\",\"\");\n System.setProperty(\"http.proxyPort\",\"\");\n}\n</code></pre>\n\n<p>Just return the right values from the methods <code>needsProxy()</code>, <code>getProxyHost()</code> and <code>getProxyPort()</code> and you can call this code snippet whenever you want.</p>\n" }, { "answer_id": 122355, "author": "John M", "author_id": 20734, "author_profile": "https://Stackoverflow.com/users/20734", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>reading an XML file and needs to download its schema</p>\n</blockquote>\n\n<p>If you are counting on retrieving schemas or DTDs over the internet, you're building a slow, chatty, fragile application. What happens when that remote server hosting the file takes planned or unplanned downtime? Your app breaks. Is that OK?</p>\n\n<p>See <a href=\"http://xml.apache.org/commons/components/resolver/resolver-article.html#s.catalog.files\" rel=\"noreferrer\">http://xml.apache.org/commons/components/resolver/resolver-article.html#s.catalog.files</a></p>\n\n<p>URL's for schemas and the like are best thought of as unique identifiers. Not as requests to actually access that file remotely. Do some google searching on \"XML catalog\". An XML catalog allows you to host such resources locally, resolving the slowness, chattiness and fragility.</p>\n\n<p>It's basically a permanently cached copy of the remote content. And that's OK, since the remote content will never change. If there's ever an update, it'd be at a different URL. Making the actual retrieval of the resource over the internet especially silly.</p>\n" }, { "answer_id": 122579, "author": "Alex. S.", "author_id": 18300, "author_profile": "https://Stackoverflow.com/users/18300", "pm_score": 4, "selected": false, "text": "<p>You can set some properties about the proxy server as jvm parameters</p>\n\n<p>-Dhttp.proxyPort=8080, proxyHost, etc.</p>\n\n<p>but if you need pass through an authenticating proxy, you need an authenticator like this example:</p>\n\n<p><strong>ProxyAuthenticator.java</strong></p>\n\n<pre><code>import java.net.*;\nimport java.io.*;\n\npublic class ProxyAuthenticator extends Authenticator {\n\n private String userName, password;\n\n protected PasswordAuthentication getPasswordAuthentication() {\n return new PasswordAuthentication(userName, password.toCharArray());\n }\n\n public ProxyAuthenticator(String userName, String password) {\n this.userName = userName;\n this.password = password;\n }\n}\n</code></pre>\n\n<p><strong>Example.java</strong></p>\n\n<pre><code> import java.net.Authenticator;\n import ProxyAuthenticator;\n\npublic class Example {\n\n public static void main(String[] args) {\n String username = System.getProperty(\"proxy.authentication.username\");\n String password = System.getProperty(\"proxy.authentication.password\");\n\n if (username != null &amp;&amp; !username.equals(\"\")) {\n Authenticator.setDefault(new ProxyAuthenticator(username, password));\n }\n\n // here your JVM will be authenticated\n\n }\n}\n</code></pre>\n\n<p>Based on this reply:\n<a href=\"http://mail-archives.apache.org/mod_mbox/jakarta-jmeter-user/200208.mbox/%3C494FD350388AD511A9DD00025530F33102F1DC2C@MMSX006%3E\" rel=\"noreferrer\">http://mail-archives.apache.org/mod_mbox/jakarta-jmeter-user/200208.mbox/%3C494FD350388AD511A9DD00025530F33102F1DC2C@MMSX006%3E</a></p>\n" }, { "answer_id": 137174, "author": "Chris Carruthers", "author_id": 1119, "author_profile": "https://Stackoverflow.com/users/1119", "pm_score": 6, "selected": false, "text": "<p>To set an HTTP/HTTPS and/or SOCKS proxy programmatically:</p>\n\n<pre><code>...\n\npublic void setProxy() {\n if (isUseHTTPProxy()) {\n // HTTP/HTTPS Proxy\n System.setProperty(\"http.proxyHost\", getHTTPHost());\n System.setProperty(\"http.proxyPort\", getHTTPPort());\n System.setProperty(\"https.proxyHost\", getHTTPHost());\n System.setProperty(\"https.proxyPort\", getHTTPPort());\n if (isUseHTTPAuth()) {\n String encoded = new String(Base64.encodeBase64((getHTTPUsername() + \":\" + getHTTPPassword()).getBytes()));\n con.setRequestProperty(\"Proxy-Authorization\", \"Basic \" + encoded);\n Authenticator.setDefault(new ProxyAuth(getHTTPUsername(), getHTTPPassword()));\n }\n }\n if (isUseSOCKSProxy()) {\n // SOCKS Proxy\n System.setProperty(\"socksProxyHost\", getSOCKSHost());\n System.setProperty(\"socksProxyPort\", getSOCKSPort());\n if (isUseSOCKSAuth()) {\n System.setProperty(\"java.net.socks.username\", getSOCKSUsername());\n System.setProperty(\"java.net.socks.password\", getSOCKSPassword());\n Authenticator.setDefault(new ProxyAuth(getSOCKSUsername(), getSOCKSPassword()));\n }\n }\n}\n\n...\n\npublic class ProxyAuth extends Authenticator {\n private PasswordAuthentication auth;\n\n private ProxyAuth(String user, String password) {\n auth = new PasswordAuthentication(user, password == null ? new char[]{} : password.toCharArray());\n }\n\n protected PasswordAuthentication getPasswordAuthentication() {\n return auth;\n }\n}\n\n...\n</code></pre>\n\n<p>Remember that HTTP proxies and SOCKS proxies operate at different levels in the network stack, so you can use one or the other or both.</p>\n" }, { "answer_id": 2321168, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>You can utilize the http.proxy* JVM variables if you're within a standalone JVM but you SHOULD NOT modify their startup scripts and/or do this within your application server (except maybe jboss or tomcat). Instead you should utilize the JAVA Proxy API (not System.setProperty) or utilize the vendor's own configuration options. Both WebSphere and WebLogic have very defined ways of setting up the proxies that are far more powerful than the J2SE one. Additionally, for WebSphere and WebLogic you will likely break your application server in little ways by overriding the startup scripts (particularly the server's interop processes as you might be telling them to use your proxy as well...). </p>\n" }, { "answer_id": 2409610, "author": "dma_k", "author_id": 267197, "author_profile": "https://Stackoverflow.com/users/267197", "pm_score": 2, "selected": false, "text": "<p>Recently I've discovered the way to allow JVM to use browser proxy settings. What you need to do is to add <code>${java.home}/lib/deploy.jar</code> to your project and to init the library like the following:</p>\n\n<pre><code>import com.sun.deploy.net.proxy.DeployProxySelector;\nimport com.sun.deploy.services.PlatformType;\nimport com.sun.deploy.services.ServiceManager;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\n\npublic abstract class ExtendedProxyManager {\n\n private static final Log logger = LogFactory.getLog(ExtendedProxyManager.class);\n\n /**\n * After calling this method, proxy settings can be magically retrieved from default browser settings.\n */\n public static boolean init() {\n logger.debug(\"Init started\");\n\n // Initialization code was taken from com.sun.deploy.ClientContainer:\n ServiceManager\n .setService(System.getProperty(\"os.name\").toLowerCase().indexOf(\"windows\") != -1 ? PlatformType.STANDALONE_TIGER_WIN32\n : PlatformType.STANDALONE_TIGER_UNIX);\n\n try {\n // This will call ProxySelector.setDefault():\n DeployProxySelector.reset();\n } catch (Throwable throwable) {\n logger.error(\"Unable to initialize extended dynamic browser proxy settings support.\", throwable);\n\n return false;\n }\n\n return true;\n }\n}\n</code></pre>\n\n<p>Afterwards the proxy settings are available to Java API via <code>java.net.ProxySelector</code>.</p>\n\n<p>The only problem with this approach is that you need to start JVM with <code>deploy.jar</code> in bootclasspath e.g. <code>java -Xbootclasspath/a:\"%JAVA_HOME%\\jre\\lib\\deploy.jar\" -jar my.jar</code>. If somebody knows how to overcome this limitation, let me know.</p>\n" }, { "answer_id": 8001659, "author": "nylas", "author_id": 1028540, "author_profile": "https://Stackoverflow.com/users/1028540", "pm_score": -1, "selected": false, "text": "<p>I think configuring <a href=\"http://www.deconf.com/en/networking/windows-update-using-proxy/\" rel=\"nofollow\">WINHTTP</a> will also work.</p>\n\n<p>Many programs including Windows Updates are having problems behind proxy. By setting up WINHTTP will always fix this kind of problems</p>\n" }, { "answer_id": 11527488, "author": "gr5", "author_id": 957476, "author_profile": "https://Stackoverflow.com/users/957476", "pm_score": 7, "selected": false, "text": "<p>To use the system proxy setup:</p>\n\n<pre><code>java -Djava.net.useSystemProxies=true ...\n</code></pre>\n\n<p>Or programatically:</p>\n\n<pre><code>System.setProperty(\"java.net.useSystemProxies\", \"true\");\n</code></pre>\n\n<p>Source: <a href=\"http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html\">http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html</a></p>\n" }, { "answer_id": 12295125, "author": "Pallavi", "author_id": 978180, "author_profile": "https://Stackoverflow.com/users/978180", "pm_score": 3, "selected": false, "text": "<p>I am also behind firewall, this worked for me!!</p>\n\n<pre><code>System.setProperty(\"http.proxyHost\", \"proxy host addr\");\nSystem.setProperty(\"http.proxyPort\", \"808\");\nAuthenticator.setDefault(new Authenticator() {\n protected PasswordAuthentication getPasswordAuthentication() {\n\n return new PasswordAuthentication(\"domain\\\\user\",\"password\".toCharArray());\n }\n});\n\nURL url = new URL(\"http://www.google.com/\");\nURLConnection con = url.openConnection();\n\nBufferedReader in = new BufferedReader(new InputStreamReader(\n con.getInputStream()));\n\n// Read it ...\nString inputLine;\nwhile ((inputLine = in.readLine()) != null)\n System.out.println(inputLine);\n\nin.close();\n</code></pre>\n" }, { "answer_id": 12995494, "author": "Sorter", "author_id": 1097600, "author_profile": "https://Stackoverflow.com/users/1097600", "pm_score": 2, "selected": false, "text": "<p>Add this before you connect to a URL behind a proxy.</p>\n\n<pre><code>System.getProperties().put(\"http.proxyHost\", \"someProxyURL\");\nSystem.getProperties().put(\"http.proxyPort\", \"someProxyPort\");\nSystem.getProperties().put(\"http.proxyUser\", \"someUserName\");\nSystem.getProperties().put(\"http.proxyPassword\", \"somePassword\");\n</code></pre>\n" }, { "answer_id": 13967127, "author": "patdevelop", "author_id": 920859, "author_profile": "https://Stackoverflow.com/users/920859", "pm_score": 1, "selected": false, "text": "<p>As is pointed out in other answers, if you need to use Authenticated proxies, there's no reliable way to do this purely using command-line variables - which is annoying if you're using someone else's application and don't want to mess with the source code.</p>\n\n<p><a href=\"https://stackoverflow.com/users/311440/will-iverson\">Will Iverson</a> makes the helpful suggestion over at <a href=\"https://stackoverflow.com/questions/5678000/using-httpproxy-to-connect-to-a-host-with-preemtive-authentication\">Using HttpProxy to connect to a host with preemtive authentication</a> to use a Proxy-management tool such as Proxifier ( <a href=\"http://www.proxifier.com/\" rel=\"nofollow noreferrer\">http://www.proxifier.com/</a> for Mac OS X and Windows) to handle this.</p>\n\n<p>For example with Proxifier you can set it up to only intercept java commands to be managed and redirected through its (authenticated) proxy. You're going to want to set the proxyHost and proxyPort values to blank in this case though, e.g. pass in <code>-Dhttp.proxyHost= -Dhttp.proxyPort=</code> to your java commands.</p>\n" }, { "answer_id": 24551536, "author": "Viet Tran", "author_id": 1148069, "author_profile": "https://Stackoverflow.com/users/1148069", "pm_score": 2, "selected": false, "text": "<p>That works for me:</p>\n\n<pre><code>public void setHttpProxy(boolean isNeedProxy) {\n if (isNeedProxy) {\n System.setProperty(\"http.proxyHost\", getProxyHost());\n System.setProperty(\"http.proxyPort\", getProxyPort());\n } else {\n System.clearProperty(\"http.proxyHost\");\n System.clearProperty(\"http.proxyPort\");\n }\n}\n</code></pre>\n\n<p>P/S: I base on GHad's answer.</p>\n" }, { "answer_id": 27919196, "author": "sarath", "author_id": 1491081, "author_profile": "https://Stackoverflow.com/users/1491081", "pm_score": 5, "selected": false, "text": "<p>JVM uses the proxy to make HTTP calls</p>\n\n<pre><code>System.getProperties().put(\"http.proxyHost\", \"someProxyURL\");\nSystem.getProperties().put(\"http.proxyPort\", \"someProxyPort\");\n</code></pre>\n\n<p>This may use user setting proxy</p>\n\n<pre><code>System.setProperty(\"java.net.useSystemProxies\", \"true\");\n</code></pre>\n" }, { "answer_id": 32511851, "author": "Mihai Capotă", "author_id": 200234, "author_profile": "https://Stackoverflow.com/users/200234", "pm_score": 4, "selected": false, "text": "<p>Set the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/net/doc-files/net-properties.html\" rel=\"noreferrer\"><code>java.net.useSystemProxies</code></a> property to <code>true</code>. You can set it, for example, through the <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/envvars002.html\" rel=\"noreferrer\">JAVA_TOOL_OPTIONS</a> environmental variable. In Ubuntu, you can, for example, add the following line to <code>.bashrc</code>:</p>\n\n<blockquote>\n <p>export JAVA_TOOL_OPTIONS+=\" -Djava.net.useSystemProxies=true\"</p>\n</blockquote>\n" }, { "answer_id": 32897878, "author": "Philip M.", "author_id": 4813037, "author_profile": "https://Stackoverflow.com/users/4813037", "pm_score": 2, "selected": false, "text": "<p>This is a minor update, but since Java 7, proxy connections can now be created programmatically rather than through system properties. This may be useful if:</p>\n\n<ol>\n<li>Proxy needs to be dynamically rotated during the program's runtime</li>\n<li>Multiple parallel proxies need to be used</li>\n<li>Or just make your code cleaner :)</li>\n</ol>\n\n<p>Here's a contrived example in groovy:</p>\n\n<pre><code>// proxy configuration read from file resource under \"proxyFileName\"\nString proxyFileName = \"proxy.txt\"\nString proxyPort = \"1234\"\nString url = \"http://www.promised.land\"\nFile testProxyFile = new File(proxyFileName)\nURLConnection connection\n\nif (!testProxyFile.exists()) {\n\n logger.debug \"proxyFileName doesn't exist. Bypassing connection via proxy.\"\n connection = url.toURL().openConnection()\n\n} else {\n String proxyAddress = testProxyFile.text\n connection = url.toURL().openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort)))\n}\n\ntry {\n connection.connect()\n}\ncatch (Exception e) {\n logger.error e.printStackTrace()\n}\n</code></pre>\n\n<p>Full Reference:\n<a href=\"http://docs.oracle.com/javase/7/docs/technotes/guides/net/proxies.html\" rel=\"nofollow\">http://docs.oracle.com/javase/7/docs/technotes/guides/net/proxies.html</a></p>\n" }, { "answer_id": 41862236, "author": "Andreas Panagiotidis", "author_id": 823368, "author_profile": "https://Stackoverflow.com/users/823368", "pm_score": 4, "selected": false, "text": "<p>The following shows how to set in Java a proxy with <strong>proxy user and proxy password</strong> from the command line, which is a very common case. You should not save passwords and hosts in the code, as a rule in the first place. </p>\n\n<p>Passing the system properties in command line with -D and setting them in the code with System.setProperty(\"name\", \"value\") is equivalent. </p>\n\n<p><strong>But note this</strong></p>\n\n<p>Example that works: </p>\n\n<pre><code>C:\\temp&gt;java -Dhttps.proxyHost=host -Dhttps.proxyPort=port -Dhttps.proxyUser=user -Dhttps.proxyPassword=\"password\" -Djavax.net.ssl.trustStore=c:/cacerts -Djavax.net.ssl.trustStorePassword=changeit com.andreas.JavaNetHttpConnection\n</code></pre>\n\n<p>But the following <strong>does not work</strong>:</p>\n\n<pre><code>C:\\temp&gt;java com.andreas.JavaNetHttpConnection -Dhttps.proxyHost=host -Dhttps.proxyPort=port -Dhttps=proxyUser=user -Dhttps.proxyPassword=\"password\" -Djavax.net.ssl.trustStore=c:/cacerts -Djavax.net.ssl.trustStorePassword=changeit\n</code></pre>\n\n<p>The only difference is the position of the system properties! (before and after the class)</p>\n\n<p>If you have special characters in password, you are allowed to put it in quotes \"@MyPass123%\", like in the above example. </p>\n\n<p>If you access an HTTPS service, you have to use <code>https.proxyHost</code>, <code>https.proxyPort</code> etc. </p>\n\n<p>If you access an HTTP service, you have to use <code>http.proxyHost</code>, <code>http.proxyPort</code> etc. </p>\n" }, { "answer_id": 45060126, "author": "MadBoomy", "author_id": 2135941, "author_profile": "https://Stackoverflow.com/users/2135941", "pm_score": 4, "selected": false, "text": "<p>Combining Sorter's and javabrett/Leonel's answers:</p>\n\n<pre><code>java -Dhttp.proxyHost=10.10.10.10 -Dhttp.proxyPort=8080 -Dhttp.proxyUser=username -Dhttp.proxyPassword=password -jar myJar.jar\n</code></pre>\n" }, { "answer_id": 47583369, "author": "Marcelo C.", "author_id": 1907282, "author_profile": "https://Stackoverflow.com/users/1907282", "pm_score": 3, "selected": false, "text": "<p>If you want \"Socks Proxy\", inform the \"socksProxyHost\" and \"socksProxyPort\" VM arguments.</p>\n\n<p>e.g.</p>\n\n<pre><code>java -DsocksProxyHost=127.0.0.1 -DsocksProxyPort=8080 org.example.Main\n</code></pre>\n" }, { "answer_id": 72875447, "author": "nuclear_party", "author_id": 12793815, "author_profile": "https://Stackoverflow.com/users/12793815", "pm_score": 0, "selected": false, "text": "<p>This is a complete example that worked for me - note that for HTTPS there are separate properties (as per <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/net/proxies.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/8/docs/technotes/guides/net/proxies.html</a>).</p>\n<p>Code below sends a request to <a href=\"https://api.myip.com\" rel=\"nofollow noreferrer\">https://api.myip.com</a> API and prints the response.</p>\n<pre><code>public static void main(String[] args) throws IOException {\n System.setProperty(&quot;java.net.useSystemProxies&quot;, &quot;true&quot;);\n final String proxyUser = &quot;lum-customer-c_f95783f5-zone-datacenter-ip-92.240.207.56&quot;;\n final String proxyPass = &quot;s3mgwrx2b628&quot;;\n final String host = &quot;zproxy.lum-superproxy.io&quot;;\n final Integer port = 22225;\n\n // http\n System.setProperty(&quot;http.proxyHost&quot;,host);\n System.setProperty(&quot;http.proxyPort&quot;, String.valueOf(port));\n System.setProperty(&quot;http.proxyUser&quot;, proxyUser);\n System.setProperty(&quot;http.proxyPassword&quot;, proxyPass);\n\n // https\n System.setProperty(&quot;https.proxyHost&quot;,host);\n System.setProperty(&quot;https.proxyPort&quot;, String.valueOf(port));\n System.setProperty(&quot;https.proxyUser&quot;, proxyUser);\n System.setProperty(&quot;https.proxyPassword&quot;, proxyPass);\n\n System.setProperty(&quot;jdk.http.auth.tunneling.disabledSchemes&quot;, &quot;&quot;);\n System.setProperty(&quot;jdk.https.auth.tunneling.disabledSchemes&quot;, &quot;&quot;);\n\n Authenticator.setDefault(new Authenticator() {\n @Override\n public PasswordAuthentication getPasswordAuthentication() {\n return new PasswordAuthentication(proxyUser, proxyPass.toCharArray());\n }\n }\n );\n\n // create and send a https request to myip.com API\n URL url = new URL(&quot;https://api.myip.com&quot;);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(&quot;GET&quot;);\n int status = connection.getResponseCode();\n \n // read the response\n BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));\n String responseLine;\n StringBuffer responseContent = new StringBuffer();\n while ((responseLine = in.readLine()) != null) \n responseContent.append(responseLine);\n \n in.close();\n connection.disconnect();\n \n // print the response\n System.out.println(status);\n System.out.println(responseContent);\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15649/" ]
Many times, a Java app needs to connect to the Internet. The most common example happens when it is reading an XML file and needs to download its schema. I am behind a proxy server. How can I set my JVM to use the proxy ?
From the Java documentation (*not* the javadoc API): <http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html> Set the JVM flags `http.proxyHost` and `http.proxyPort` when starting your JVM on the command line. This is usually done in a shell script (in Unix) or bat file (in Windows). Here's the example with the Unix shell script: ``` JAVA_FLAGS=-Dhttp.proxyHost=10.0.0.100 -Dhttp.proxyPort=8800 java ${JAVA_FLAGS} ... ``` When using containers such as JBoss or WebLogic, my solution is to edit the start-up scripts supplied by the vendor. Many developers are familiar with the Java API (javadocs), but many times the rest of the documentation is overlooked. It contains a lot of interesting information: <http://download.oracle.com/javase/6/docs/technotes/guides/> --- **Update :** If you do not want to use proxy to resolve some local/intranet hosts, check out the comment from @Tomalak: > > Also don't forget the http.nonProxyHosts property! > > > ``` -Dhttp.nonProxyHosts="localhost|127.0.0.1|10.*.*.*|*.example.com|etc" ```
120,804
<p>I am going through John Resig's excellent <a href="http://ejohn.org/apps/learn/#47" rel="noreferrer">Advanced javascript tutorial</a> and I do not thoroughly understand what's the difference between the following calls: (please note that 'arguments' is a builtin javascript word and is not exactly an array hence the hacking with the Array.slice instead of simply calling arguments.slice)</p> <pre><code>&gt;&gt;&gt; arguments [3, 1, 2, 3] &gt;&gt;&gt; Array.slice.call( arguments ) 3,1,2,3 0=3 1=1 2=2 3=3 &gt;&gt;&gt; Array.slice.call( arguments, 1 ) [] &gt;&gt;&gt; Array().slice.call( arguments ) 3,1,2,3 0=3 1=1 2=2 3=3 &gt;&gt;&gt; Array().slice.call( arguments, 1 ) 1,2,3 0=1 1=2 2=3 </code></pre> <p>Basically my misunderstanding boils down to the difference between Array.slice and Array().slice. What exactly is the difference between these two and why does not Array.slice.call behave as expected? (which is giving back all but the first element of the arguments list).</p>
[ { "answer_id": 121054, "author": "ujh", "author_id": 4936, "author_profile": "https://Stackoverflow.com/users/4936", "pm_score": 3, "selected": false, "text": "<p>Array is just a function, albeit a special one (used to initialize arrays). Array.slice is a reference to the slice() function in the Array prototype. It can only be called on an array object and not on the Constructor (i.e. Array) itself. Array seems to behave specially though, as Array() returns an empty array. This doesn't seem to work for non-builtin Constructor functions (there you have to use new). So</p>\n\n<pre><code>Array().slice.call\n</code></pre>\n\n<p>is the same as </p>\n\n<pre><code>[].slice.call\n</code></pre>\n" }, { "answer_id": 121080, "author": "Brad8118", "author_id": 7617, "author_profile": "https://Stackoverflow.com/users/7617", "pm_score": -1, "selected": false, "text": "<p>Well,</p>\n\n<p>Looking at <a href=\"http://www.devguru.com/Technologies/ecmascript/quickref/slice.html\" rel=\"nofollow noreferrer\">http://www.devguru.com/Technologies/ecmascript/quickref/slice.html</a> </p>\n\n<p>Array().slice is a function (constructor)in the array class, It cant be used as a data member. If you didn't want to use the '()' you would need to call it on the array. ie - arguments.slice(1)</p>\n" }, { "answer_id": 121087, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": -1, "selected": false, "text": "<p>My guess is that Array is a prototype while Array() is an actual array object. Depending on the JavaScript interpretation, directly calling the prototype method of a builtin object type might work or it might not. I don't believe the spec says it has to work, just that calling it on a instantiated object works.</p>\n" }, { "answer_id": 121120, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 0, "selected": false, "text": "<p>I believe <em>Array</em> is the type and <em>Array()</em> is the constructor function.</p>\n\n<p>Messing around in <a href=\"http://getfirebug.com/\" rel=\"nofollow noreferrer\">FireBug</a>:</p>\n\n<pre><code>&gt;&gt;&gt; Array === Array()\nfalse\n\n&gt;&gt;&gt; Array.constructor\nFunction()\n\n&gt;&gt;&gt; Array().constructor\nArray()\n</code></pre>\n" }, { "answer_id": 121302, "author": "kamens", "author_id": 1335, "author_profile": "https://Stackoverflow.com/users/1335", "pm_score": 6, "selected": true, "text": "<p>Not quite.</p>\n\n<p>Watch what happens when you call String.substring.call(\"foo\", 1) and String().substring.call(\"foo\", 2):</p>\n\n<pre><code>&gt;&gt;&gt; String.substring.call(\"foo\", 1)\n\"1\"\n\n&gt;&gt;&gt; String().substring.call(\"foo\", 1)\n\"oo\"\n</code></pre>\n\n<p>Array.slice is <em>neither</em> properly referencing the slice function attached to the Array prototype nor the slice function attached to any instantiated Array instance (such as Array() or []).</p>\n\n<p>The fact that Array.slice is even non-null at all is an incorrect implementation of the object (/function/constructor) itself. <strong>Try running the equivalent code in IE and you'll get an error that Array.slice is null</strong>.</p>\n\n<p>This is why Array.slice does not behave correctly (nor does String.substring).</p>\n\n<p>Proof (the following is something one should never expect based on the definition of slice()...just like substring() above):</p>\n\n<pre><code>&gt;&gt;&gt; Array.slice.call([1,2], [3,4])\n3,4\n</code></pre>\n\n<p>Now, if you properly call slice() on either an instantiated object <em>or</em> the Array prototype, you'll get what you expect:</p>\n\n<pre><code>&gt;&gt;&gt; Array.prototype.slice.call([4,5], 1)\n[5]\n&gt;&gt;&gt; Array().slice.call([4,5], 1)\n[5]\n</code></pre>\n\n<p>More proof...</p>\n\n<pre><code>&gt;&gt;&gt; Array.prototype.slice == Array().slice\ntrue\n&gt;&gt;&gt; Array.slice == Array().slice\nfalse\n</code></pre>\n" }, { "answer_id": 1813684, "author": "Bill", "author_id": 220622, "author_profile": "https://Stackoverflow.com/users/220622", "pm_score": 1, "selected": false, "text": "<p>How is any call to slice.call() working in the examples provided since a context parameter is not being supplied? Does slice implement it's own call method, thus overriding JavaScript's call method? The call and apply methods take as the first parameter an object to specify the context (this) object to apply to the invocation.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21075/" ]
I am going through John Resig's excellent [Advanced javascript tutorial](http://ejohn.org/apps/learn/#47) and I do not thoroughly understand what's the difference between the following calls: (please note that 'arguments' is a builtin javascript word and is not exactly an array hence the hacking with the Array.slice instead of simply calling arguments.slice) ``` >>> arguments [3, 1, 2, 3] >>> Array.slice.call( arguments ) 3,1,2,3 0=3 1=1 2=2 3=3 >>> Array.slice.call( arguments, 1 ) [] >>> Array().slice.call( arguments ) 3,1,2,3 0=3 1=1 2=2 3=3 >>> Array().slice.call( arguments, 1 ) 1,2,3 0=1 1=2 2=3 ``` Basically my misunderstanding boils down to the difference between Array.slice and Array().slice. What exactly is the difference between these two and why does not Array.slice.call behave as expected? (which is giving back all but the first element of the arguments list).
Not quite. Watch what happens when you call String.substring.call("foo", 1) and String().substring.call("foo", 2): ``` >>> String.substring.call("foo", 1) "1" >>> String().substring.call("foo", 1) "oo" ``` Array.slice is *neither* properly referencing the slice function attached to the Array prototype nor the slice function attached to any instantiated Array instance (such as Array() or []). The fact that Array.slice is even non-null at all is an incorrect implementation of the object (/function/constructor) itself. **Try running the equivalent code in IE and you'll get an error that Array.slice is null**. This is why Array.slice does not behave correctly (nor does String.substring). Proof (the following is something one should never expect based on the definition of slice()...just like substring() above): ``` >>> Array.slice.call([1,2], [3,4]) 3,4 ``` Now, if you properly call slice() on either an instantiated object *or* the Array prototype, you'll get what you expect: ``` >>> Array.prototype.slice.call([4,5], 1) [5] >>> Array().slice.call([4,5], 1) [5] ``` More proof... ``` >>> Array.prototype.slice == Array().slice true >>> Array.slice == Array().slice false ```
120,851
<p>We are creating an XBAP application that we need to have rounded corners in various locations in a single page and we would like to have a WPF Rounded Corner container to place a bunch of other elements within. Does anyone have some suggestions or sample code on how we can best accomplish this? Either with styles on a or with creating a custom control?</p>
[ { "answer_id": 120895, "author": "kobusb", "author_id": 1620, "author_profile": "https://Stackoverflow.com/users/1620", "pm_score": 9, "selected": true, "text": "<p>You don't need a custom control, just put your container in a border element:</p>\n\n<pre><code>&lt;Border BorderBrush=\"#FF000000\" BorderThickness=\"1\" CornerRadius=\"8\"&gt;\n &lt;Grid/&gt;\n&lt;/Border&gt;\n</code></pre>\n\n<p>You can replace the <code>&lt;Grid/&gt;</code> with any of the layout containers...</p>\n" }, { "answer_id": 209949, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 6, "selected": false, "text": "<p>I know that this isn't an answer to the initial question ... but you often want to clip the inner content of that rounded corner border you just created.</p>\n\n<p>Chris Cavanagh has come up with an <a href=\"http://chriscavanagh.wordpress.com/2008/10/03/wpf-easy-rounded-corners-for-anything/\" rel=\"noreferrer\">excellent way</a> to do just this.</p>\n\n<p>I have tried a couple different approaches to this ... and I think this one rocks.</p>\n\n<p>Here is the xaml below:</p>\n\n<pre><code>&lt;Page\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Background=\"Black\"\n&gt;\n &lt;!-- Rounded yellow border --&gt;\n &lt;Border\n HorizontalAlignment=\"Center\"\n VerticalAlignment=\"Center\"\n BorderBrush=\"Yellow\"\n BorderThickness=\"3\"\n CornerRadius=\"10\"\n Padding=\"2\"\n &gt;\n &lt;Grid&gt;\n &lt;!-- Rounded mask (stretches to fill Grid) --&gt;\n &lt;Border\n Name=\"mask\"\n Background=\"White\"\n CornerRadius=\"7\"\n /&gt;\n\n &lt;!-- Main content container --&gt;\n &lt;StackPanel&gt;\n &lt;!-- Use a VisualBrush of 'mask' as the opacity mask --&gt;\n &lt;StackPanel.OpacityMask&gt;\n &lt;VisualBrush Visual=\"{Binding ElementName=mask}\"/&gt;\n &lt;/StackPanel.OpacityMask&gt;\n\n &lt;!-- Any content --&gt;\n &lt;Image Source=\"http://chriscavanagh.files.wordpress.com/2006/12/chriss-blog-banner.jpg\"/&gt;\n &lt;Rectangle\n Height=\"50\"\n Fill=\"Red\"/&gt;\n &lt;Rectangle\n Height=\"50\"\n Fill=\"White\"/&gt;\n &lt;Rectangle\n Height=\"50\"\n Fill=\"Blue\"/&gt;\n &lt;/StackPanel&gt;\n &lt;/Grid&gt;\n &lt;/Border&gt;\n&lt;/Page&gt;\n</code></pre>\n" }, { "answer_id": 2776402, "author": "Daniel", "author_id": 329301, "author_profile": "https://Stackoverflow.com/users/329301", "pm_score": 1, "selected": false, "text": "<p>If you're trying to put a button in a rounded-rectangle border, you should check out <a href=\"http://msdn.microsoft.com/en-us/library/bb613545.aspx\" rel=\"nofollow noreferrer\">msdn's example</a>. I found this by googling for images of the problem (instead of text). Their bulky outer rectangle is (thankfully) easy to remove. </p>\n\n<p>Note that you will have to redefine the button's behavior (since you've changed the ControlTemplate). That is, you will need to define the button's behavior when clicked using a Trigger tag (Property=\"IsPressed\" Value=\"true\") in the ControlTemplate.Triggers tag. Hope this saves someone else the time I lost :)</p>\n" }, { "answer_id": 6945456, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 4, "selected": false, "text": "<p>I just had to do this myself, so I thought I would post another answer here.</p>\n\n<p>Here is another way to create a rounded corner border <em>and clip its inner content</em>. This is the straightforward way by using the Clip property. It's nice if you want to avoid a VisualBrush.</p>\n\n<p>The xaml:</p>\n\n<pre><code>&lt;Border\n Width=\"200\"\n Height=\"25\"\n CornerRadius=\"11\"\n Background=\"#FF919194\"\n&gt;\n &lt;Border.Clip&gt;\n &lt;RectangleGeometry\n RadiusX=\"{Binding CornerRadius.TopLeft, RelativeSource={RelativeSource AncestorType={x:Type Border}}}\"\n RadiusY=\"{Binding RadiusX, RelativeSource={RelativeSource Self}}\"\n &gt;\n &lt;RectangleGeometry.Rect&gt;\n &lt;MultiBinding\n Converter=\"{StaticResource widthAndHeightToRectConverter}\"\n &gt;\n &lt;Binding\n Path=\"ActualWidth\"\n RelativeSource=\"{RelativeSource AncestorType={x:Type Border}}\"\n /&gt;\n &lt;Binding\n Path=\"ActualHeight\"\n RelativeSource=\"{RelativeSource AncestorType={x:Type Border}}\"\n /&gt;\n &lt;/MultiBinding&gt;\n &lt;/RectangleGeometry.Rect&gt;\n &lt;/RectangleGeometry&gt;\n &lt;/Border.Clip&gt;\n\n &lt;Rectangle\n Width=\"100\"\n Height=\"100\"\n Fill=\"Blue\"\n HorizontalAlignment=\"Left\"\n VerticalAlignment=\"Center\"\n /&gt;\n&lt;/Border&gt;\n</code></pre>\n\n<p>The code for the converter:</p>\n\n<pre><code>public class WidthAndHeightToRectConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n double width = (double)values[0];\n double height = (double)values[1];\n return new Rect(0, 0, width, height);\n }\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n</code></pre>\n" }, { "answer_id": 12079207, "author": "BSalita", "author_id": 317797, "author_profile": "https://Stackoverflow.com/users/317797", "pm_score": 2, "selected": false, "text": "<p>VB.Net code based implementation of kobusb's Border control solution. I used it to populate a ListBox of Button controls. The Button controls are created from MEF extensions. Each extension uses MEF's ExportMetaData attribute for a Description of the extension. The extensions are VisiFire charting objects. The user pushes a button, selected from the list of buttons, to execute the desired chart.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code> ' Create a ListBox of Buttons, one button for each MEF charting component. \n For Each c As Lazy(Of ICharts, IDictionary(Of String, Object)) In ext.ChartDescriptions\n Dim brdr As New Border\n brdr.BorderBrush = Brushes.Black\n brdr.BorderThickness = New Thickness(2, 2, 2, 2)\n brdr.CornerRadius = New CornerRadius(8, 8, 8, 8)\n Dim btn As New Button\n AddHandler btn.Click, AddressOf GenericButtonClick\n brdr.Child = btn\n brdr.Background = btn.Background\n btn.Margin = brdr.BorderThickness\n btn.Width = ChartsLBx.ActualWidth - 22\n btn.BorderThickness = New Thickness(0, 0, 0, 0)\n btn.Height = 22\n btn.Content = c.Metadata(\"Description\")\n btn.Tag = c\n btn.ToolTip = \"Push button to see \" &amp; c.Metadata(\"Description\").ToString &amp; \" chart\"\n Dim lbi As New ListBoxItem\n lbi.Content = brdr\n ChartsLBx.Items.Add(lbi)\n Next\n\nPublic Event Click As RoutedEventHandler\n\nPrivate Sub GenericButtonClick(sender As Object, e As RoutedEventArgs)\n Dim btn As Button = DirectCast(sender, Button)\n Dim c As Lazy(Of ICharts, IDictionary(Of String, Object)) = DirectCast(btn.Tag, Lazy(Of ICharts, IDictionary(Of String, Object)))\n Dim w As Window = DirectCast(c.Value, Window)\n Dim cc As ICharts = DirectCast(c.Value, ICharts)\n c.Value.CreateChart()\n w.Show()\nEnd Sub\n\n&lt;System.ComponentModel.Composition.Export(GetType(ICharts))&gt; _\n&lt;System.ComponentModel.Composition.ExportMetadata(\"Description\", \"Data vs. Time\")&gt; _\nPublic Class DataTimeChart\n Implements ICharts\n\n Public Sub CreateChart() Implements ICharts.CreateChart\n End Sub\nEnd Class\n\nPublic Interface ICharts\n Sub CreateChart()\nEnd Interface\n\nPublic Class Extensibility\n Public Sub New()\n Dim catalog As New AggregateCatalog()\n\n catalog.Catalogs.Add(New AssemblyCatalog(GetType(Extensibility).Assembly))\n\n 'Create the CompositionContainer with the parts in the catalog\n ChartContainer = New CompositionContainer(catalog)\n\n Try\n ChartContainer.ComposeParts(Me)\n Catch ex As Exception\n Console.WriteLine(ex.ToString)\n End Try\n End Sub\n\n ' must use Lazy otherwise instantiation of Window will hold open app. Otherwise must specify Shutdown Mode of \"Shutdown on Main Window\".\n &lt;ImportMany()&gt; _\n Public Property ChartDescriptions As IEnumerable(Of Lazy(Of ICharts, IDictionary(Of String, Object)))\n\nEnd Class\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21096/" ]
We are creating an XBAP application that we need to have rounded corners in various locations in a single page and we would like to have a WPF Rounded Corner container to place a bunch of other elements within. Does anyone have some suggestions or sample code on how we can best accomplish this? Either with styles on a or with creating a custom control?
You don't need a custom control, just put your container in a border element: ``` <Border BorderBrush="#FF000000" BorderThickness="1" CornerRadius="8"> <Grid/> </Border> ``` You can replace the `<Grid/>` with any of the layout containers...
120,858
<p>Is it possible to, for instance, replace and free a TEdit with a subclassed component instantiated (conditionally) at runtime? If so, how and when it should be done? I've tried to set the parent to nil and to call free() in the form constructor and AfterConstruction methods but in both cases I got a runtime error.</p> <hr> <p>Being more specific, I got an Access violation error (EAccessViolation). It seems François is right when he says that freeing components at frame costruction messes with Form controls housekeeping.</p>
[ { "answer_id": 121091, "author": "Loesje", "author_id": 17559, "author_profile": "https://Stackoverflow.com/users/17559", "pm_score": 3, "selected": false, "text": "<p>You have to call RemoveControl of the TEdit's parent to remove the control. Use InsertControl to add the new control. </p>\n\n<pre><code>var Edit2: TEdit;\nbegin\n Edit2 := TEdit.Create(self);\n Edit2.Left := Edit1.Left;\n Edit2.Top := Edit2.Top;\n Edit1.Parent.Insertcontrol(Edit2);\n TWinControl(Edit1.parent).RemoveControl(Edit1);\n Edit1.Free;\nend;\n</code></pre>\n\n<p>Replace TEdit.Create to the class you want to use, and copy all properties you need like I did with Left and Top.</p>\n" }, { "answer_id": 122753, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 1, "selected": false, "text": "<p>You can actually use RTTI (look in the TypInfo unit) to clone all the matching properties. I wrote code for this a while back, but I can't find it now. I'll keep looking.</p>\n" }, { "answer_id": 122915, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 4, "selected": true, "text": "<p>This more generic routine works either with a Form or Frame (updated to use a subclass for the new control):</p>\n\n<pre><code>function ReplaceControlEx(AControl: TControl; const AControlClass: TControlClass; const ANewName: string; const IsFreed : Boolean = True): TControl;\nbegin\n if AControl = nil then\n begin\n Result := nil;\n Exit;\n end;\n Result := AControlClass.Create(AControl.Owner);\n CloneProperties(AControl, Result);// copy all properties to new control\n // Result.Left := AControl.Left; // or copy some properties manually...\n // Result.Top := AControl.Top;\n Result.Name := ANewName;\n Result.Parent := AControl.Parent; // needed for the InsertControl &amp; RemoveControl magic\n if IsFreed then\n FreeAndNil(AControl);\nend;\n\nfunction ReplaceControl(AControl: TControl; const ANewName: string; const IsFreed : Boolean = True): TControl;\nbegin\n if AControl = nil then\n Result := nil\n else\n Result := ReplaceControlEx(AControl, TControlClass(AControl.ClassType), ANewName, IsFreed);\nend;\n</code></pre>\n\n<p>using this routine to pass the properties to the new control </p>\n\n<pre><code>procedure CloneProperties(const Source: TControl; const Dest: TControl);\nvar\n ms: TMemoryStream;\n OldName: string;\nbegin\n OldName := Source.Name;\n Source.Name := ''; // needed to avoid Name collision\n try\n ms := TMemoryStream.Create;\n try\n ms.WriteComponent(Source);\n ms.Position := 0;\n ms.ReadComponent(Dest);\n finally\n ms.Free;\n end;\n finally\n Source.Name := OldName;\n end;\nend;\n</code></pre>\n\n<p>use it like:</p>\n\n<pre><code>procedure TFrame1.AfterConstruction;\nvar\n I: Integer;\n NewEdit: TMyEdit;\nbegin\n inherited;\n NewEdit := ReplaceControlEx(Edit1, TMyEdit, 'Edit2') as TMyEdit;\n if Assigned(NewEdit) then\n begin\n NewEdit.Text := 'My Brand New Edit';\n NewEdit.Author := 'Myself';\n end;\n for I:=0 to ControlCount-1 do\n begin\n ShowMessage(Controls[I].Name);\n end;\nend;\n</code></pre>\n\n<p><strong>CAUTION</strong>: If you are doing this inside the AfterConstruction of the Frame, beware that the hosting Form construction is not finished yet.<br>\nFreeing Controls there, might cause a lot of problems as you're messing up with Form controls housekeeping.<br>\nSee what you get if you try to read the new Edit Caption to display in the ShowMessage...<br>\nIn that case you would want to use<br>\n ...ReplaceControl(Edit1, 'Edit2', <strong>False</strong>)<br>\nand then do a<br>\n ...FreeAndNil(Edit1)<br>\nlater.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16120/" ]
Is it possible to, for instance, replace and free a TEdit with a subclassed component instantiated (conditionally) at runtime? If so, how and when it should be done? I've tried to set the parent to nil and to call free() in the form constructor and AfterConstruction methods but in both cases I got a runtime error. --- Being more specific, I got an Access violation error (EAccessViolation). It seems François is right when he says that freeing components at frame costruction messes with Form controls housekeeping.
This more generic routine works either with a Form or Frame (updated to use a subclass for the new control): ``` function ReplaceControlEx(AControl: TControl; const AControlClass: TControlClass; const ANewName: string; const IsFreed : Boolean = True): TControl; begin if AControl = nil then begin Result := nil; Exit; end; Result := AControlClass.Create(AControl.Owner); CloneProperties(AControl, Result);// copy all properties to new control // Result.Left := AControl.Left; // or copy some properties manually... // Result.Top := AControl.Top; Result.Name := ANewName; Result.Parent := AControl.Parent; // needed for the InsertControl & RemoveControl magic if IsFreed then FreeAndNil(AControl); end; function ReplaceControl(AControl: TControl; const ANewName: string; const IsFreed : Boolean = True): TControl; begin if AControl = nil then Result := nil else Result := ReplaceControlEx(AControl, TControlClass(AControl.ClassType), ANewName, IsFreed); end; ``` using this routine to pass the properties to the new control ``` procedure CloneProperties(const Source: TControl; const Dest: TControl); var ms: TMemoryStream; OldName: string; begin OldName := Source.Name; Source.Name := ''; // needed to avoid Name collision try ms := TMemoryStream.Create; try ms.WriteComponent(Source); ms.Position := 0; ms.ReadComponent(Dest); finally ms.Free; end; finally Source.Name := OldName; end; end; ``` use it like: ``` procedure TFrame1.AfterConstruction; var I: Integer; NewEdit: TMyEdit; begin inherited; NewEdit := ReplaceControlEx(Edit1, TMyEdit, 'Edit2') as TMyEdit; if Assigned(NewEdit) then begin NewEdit.Text := 'My Brand New Edit'; NewEdit.Author := 'Myself'; end; for I:=0 to ControlCount-1 do begin ShowMessage(Controls[I].Name); end; end; ``` **CAUTION**: If you are doing this inside the AfterConstruction of the Frame, beware that the hosting Form construction is not finished yet. Freeing Controls there, might cause a lot of problems as you're messing up with Form controls housekeeping. See what you get if you try to read the new Edit Caption to display in the ShowMessage... In that case you would want to use ...ReplaceControl(Edit1, 'Edit2', **False**) and then do a ...FreeAndNil(Edit1) later.
120,876
<p>What are the C++ rules for calling the base class constructor from a derived class?</p> <p>For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).</p>
[ { "answer_id": 120916, "author": "luke", "author_id": 16434, "author_profile": "https://Stackoverflow.com/users/16434", "pm_score": 11, "selected": true, "text": "<p>Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than \"super()\".</p>\n\n<pre><code>class SuperClass\n{\n public:\n\n SuperClass(int foo)\n {\n // do something with foo\n }\n};\n\nclass SubClass : public SuperClass\n{\n public:\n\n SubClass(int foo, int bar)\n : SuperClass(foo) // Call the superclass constructor in the subclass' initialization list.\n {\n // do something with bar\n }\n};\n</code></pre>\n\n<p>More info on the constructor's initialization list <a href=\"http://www.cprogramming.com/tutorial/initialization-lists-c++.html\" rel=\"noreferrer\">here</a> and <a href=\"http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 120920, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 5, "selected": false, "text": "<p>If you have a constructor without arguments it will be called before the derived class constructor gets executed.</p>\n\n<p>If you want to call a base-constructor with arguments you have to explicitly write that in the derived constructor like this: </p>\n\n<pre><code>class base\n{\n public:\n base (int arg)\n {\n }\n};\n\nclass derived : public base\n{\n public:\n derived () : base (number)\n {\n }\n};\n</code></pre>\n\n<p>You cannot construct a derived class without calling the parents constructor in C++. That either happens automatically if it's a non-arg C'tor, it happens if you call the derived constructor directly as shown above or your code won't compile.</p>\n" }, { "answer_id": 120931, "author": "CR.", "author_id": 20387, "author_profile": "https://Stackoverflow.com/users/20387", "pm_score": 4, "selected": false, "text": "<p>The only way to pass values to a parent constructor is through an initialization list. The initilization list is implemented with a : and then a list of classes and the values to be passed to that classes constructor.</p>\n\n<pre><code>Class2::Class2(string id) : Class1(id) {\n....\n}\n</code></pre>\n\n<p>Also remember that if you have a constructor that takes no parameters on the parent class, it will be called automatically prior to the child constructor executing.</p>\n" }, { "answer_id": 120943, "author": "puetzk", "author_id": 14312, "author_profile": "https://Stackoverflow.com/users/14312", "pm_score": 8, "selected": false, "text": "<p>In C++, the no-argument constructors for all superclasses and member variables are called for you, before entering your constructor. If you want to pass them arguments, there is a separate syntax for this called \"constructor chaining\", which looks like this:</p>\n\n<pre><code>class Sub : public Base\n{\n Sub(int x, int y)\n : Base(x), member(y)\n {\n }\n Type member;\n};\n</code></pre>\n\n<p>If anything run at this point throws, the bases/members which had previously completed construction have their destructors called and the exception is rethrown to to the caller. If you want to catch exceptions during chaining, you must use a function try block:</p>\n\n<pre><code>class Sub : public Base\n{\n Sub(int x, int y)\n try : Base(x), member(y)\n {\n // function body goes here\n } catch(const ExceptionType &amp;e) {\n throw kaboom();\n }\n Type member;\n};\n</code></pre>\n\n<p>In this form, note that the try block <strong>is</strong> the body of the function, rather than being inside the body of the function; this allows it to catch exceptions thrown by implicit or explicit member and base class initializations, as well as during the body of the function. However, if a function catch block does not throw a different exception, the runtime will rethrow the original error; exceptions during initialization <strong>cannot</strong> be ignored.</p>\n" }, { "answer_id": 120955, "author": "Dynite", "author_id": 16177, "author_profile": "https://Stackoverflow.com/users/16177", "pm_score": 3, "selected": false, "text": "<pre><code>CDerived::CDerived()\n: CBase(...), iCount(0) //this is the initialisation list. You can initialise member variables here too. (e.g. iCount := 0)\n {\n //construct body\n }\n</code></pre>\n" }, { "answer_id": 121024, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 6, "selected": false, "text": "<p>In C++ there is a concept of constructor's initialization list, which is where you can and should call the base class' constructor and where you should also initialize the data members. The initialization list comes after the constructor signature following a colon, and before the body of the constructor. Let's say we have a class A:</p>\n\n<pre><code>\nclass A : public B\n{\npublic:\n A(int a, int b, int c);\nprivate:\n int b_, c_;\n};\n</code></pre>\n\n<p>Then, assuming B has a constructor which takes an int, A's constructor may look like this:</p>\n\n<pre><code>\nA::A(int a, int b, int c) \n : B(a), b_(b), c_(c) // initialization list\n{\n // do something\n}\n</code></pre>\n\n<p>As you can see, the constructor of the base class is called in the initialization list. Initializing the data members in the initialization list, by the way, is preferable to assigning the values for b_, and c_ inside the body of the constructor, because you are saving the extra cost of assignment.</p>\n\n<p>Keep in mind, that data members are always initialized in the order in which they are declared in the class definition, regardless of their order in the initialization list. To avoid strange bugs, which may arise if your data members depend on each other, you should always make sure that the order of the members is the same in the initialization list and the class definition. For the same reason the base class constructor must be the first item in the initialization list. If you omit it altogether, then the default constructor for the base class will be called automatically. In that case, if the base class does not have a default constructor, you will get a compiler error.</p>\n" }, { "answer_id": 21392677, "author": "TT_ stands with Russia", "author_id": 2503111, "author_profile": "https://Stackoverflow.com/users/2503111", "pm_score": 5, "selected": false, "text": "<p>Everybody mentioned a constructor call through an initialization list, but nobody said that a parent class's constructor can be called explicitly from the derived member's constructor's body. See the question <a href=\"https://stackoverflow.com/questions/21395395/calling-a-constructor-of-the-base-class-from-a-subclass-constructor-body/21395443?noredirect=1#21395443\">Calling a constructor of the base class from a subclass&#39; constructor body</a>, for example. \nThe point is that if you use an explicit call to a parent class or super class constructor in the body of a derived class, this is actually just creating an instance of the parent class and it is not invoking the parent class constructor on the derived object. The only way to invoke a parent class or super class constructor on a derived class' object is through the initialization list and not in the derived class constructor body. So maybe it should not be called a \"superclass constructor call\". I put this answer here because somebody might get confused (as I did).</p>\n" }, { "answer_id": 22349031, "author": "Krishna Oza", "author_id": 1738222, "author_profile": "https://Stackoverflow.com/users/1738222", "pm_score": 3, "selected": false, "text": "<p>Nobody mentioned the sequence of constructor calls when a class derives from multiple classes. The sequence is as mentioned while deriving the classes.</p>\n" }, { "answer_id": 24765899, "author": "JayS", "author_id": 1812942, "author_profile": "https://Stackoverflow.com/users/1812942", "pm_score": 4, "selected": false, "text": "<p>If you have default parameters in your base constructor the base class will be called automatically. </p>\n\n<pre><code>using namespace std;\n\nclass Base\n{\n public:\n Base(int a=1) : _a(a) {}\n\n protected:\n int _a;\n};\n\nclass Derived : public Base\n{\n public:\n Derived() {}\n\n void printit() { cout &lt;&lt; _a &lt;&lt; endl; }\n};\n\nint main()\n{\n Derived d;\n d.printit();\n return 0;\n}\n</code></pre>\n\n<p>Output is: 1</p>\n" }, { "answer_id": 62698814, "author": "Markus Dutschke", "author_id": 7128154, "author_profile": "https://Stackoverflow.com/users/7128154", "pm_score": 2, "selected": false, "text": "<p>If you simply want to <strong>pass all constructor arguments to the base-class</strong> (=parent), here is a minimal example.</p>\n<p>This uses templates to forward every constructor call with 1, 2 or 3 arguments to the parent class <code>std::string</code>.</p>\n<p><strong>Code</strong></p>\n<p><a href=\"https://techiedelight.com/compiler/?D2g2\" rel=\"nofollow noreferrer\">Live-Version</a></p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nclass ChildString: public std::string\n{\n public:\n template&lt;typename... Args&gt;\n ChildString(Args... args): std::string(args...)\n {\n std::cout \n &lt;&lt; &quot;\\tConstructor call ChildString(nArgs=&quot;\n &lt;&lt; sizeof...(Args) &lt;&lt; &quot;): &quot; &lt;&lt; *this\n &lt;&lt; std::endl;\n }\n\n};\n\nint main()\n{\n std::cout &lt;&lt; &quot;Check out:&quot; &lt;&lt; std::endl;\n std::cout &lt;&lt; &quot;\\thttp://www.cplusplus.com/reference/string/string/string/&quot; &lt;&lt; std::endl;\n std::cout &lt;&lt; &quot;for available string constructors&quot; &lt;&lt; std::endl;\n\n std::cout &lt;&lt; std::endl;\n std::cout &lt;&lt; &quot;Initialization:&quot; &lt;&lt; std::endl;\n ChildString cs1 (&quot;copy (2)&quot;);\n\n char char_arr[] = &quot;from c-string (4)&quot;;\n ChildString cs2 (char_arr);\n\n std::string str = &quot;substring (3)&quot;;\n ChildString cs3 (str, 0, str.length());\n\n std::cout &lt;&lt; std::endl;\n std::cout &lt;&lt; &quot;Usage:&quot; &lt;&lt; std::endl;\n std::cout &lt;&lt; &quot;\\tcs1: &quot; &lt;&lt; cs1 &lt;&lt; std::endl;\n std::cout &lt;&lt; &quot;\\tcs2: &quot; &lt;&lt; cs2 &lt;&lt; std::endl;\n std::cout &lt;&lt; &quot;\\tcs3: &quot; &lt;&lt; cs3 &lt;&lt; std::endl;\n\n return 0;\n}\n</code></pre>\n<p><strong>Output</strong></p>\n<pre><code>Check out:\n http://www.cplusplus.com/reference/string/string/string/\nfor available string constructors\n\nInitialization:\n Constructor call ChildString(nArgs=1): copy (2)\n Constructor call ChildString(nArgs=1): from c-string (4)\n Constructor call ChildString(nArgs=3): substring (3)\n\nUsage:\n cs1: copy (2)\n cs2: from c-string (4)\n cs3: substring (3)\n</code></pre>\n<p><strong>Update: Using Variadic Templates</strong></p>\n<p>To generalize to n arguments and simplify</p>\n<pre><code> template &lt;class C&gt;\n ChildString(C arg): std::string(arg)\n {\n std::cout &lt;&lt; &quot;\\tConstructor call ChildString(C arg): &quot; &lt;&lt; *this &lt;&lt; std::endl;\n }\n template &lt;class C1, class C2&gt;\n ChildString(C1 arg1, C2 arg2): std::string(arg1, arg2)\n {\n std::cout &lt;&lt; &quot;\\tConstructor call ChildString(C1 arg1, C2 arg2, C3 arg3): &quot; &lt;&lt; *this &lt;&lt; std::endl;\n }\n template &lt;class C1, class C2, class C3&gt;\n ChildString(C1 arg1, C2 arg2, C3 arg3): std::string(arg1, arg2, arg3)\n {\n std::cout &lt;&lt; &quot;\\tConstructor call ChildString(C1 arg1, C2 arg2, C3 arg3): &quot; &lt;&lt; *this &lt;&lt; std::endl;\n }\n</code></pre>\n<p>to</p>\n<pre><code>template&lt;typename... Args&gt;\n ChildString(Args... args): std::string(args...)\n {\n std::cout \n &lt;&lt; &quot;\\tConstructor call ChildString(nArgs=&quot;\n &lt;&lt; sizeof...(Args) &lt;&lt; &quot;): &quot; &lt;&lt; *this\n &lt;&lt; std::endl;\n }\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4465/" ]
What are the C++ rules for calling the base class constructor from a derived class? For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).
Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()". ``` class SuperClass { public: SuperClass(int foo) { // do something with foo } }; class SubClass : public SuperClass { public: SubClass(int foo, int bar) : SuperClass(foo) // Call the superclass constructor in the subclass' initialization list. { // do something with bar } }; ``` More info on the constructor's initialization list [here](http://www.cprogramming.com/tutorial/initialization-lists-c++.html) and [here](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6).
120,886
<p>Suppose we have an iterator (an infinite one) that returns lists (or finite iterators), for example one returned by</p> <pre><code>infinite = itertools.cycle([[1,2,3]]) </code></pre> <p>What is a good Python idiom to get an iterator (obviously infinite) that will return each of the elements from the first iterator, then each from the second one, etc. In the example above it would return <code>1,2,3,1,2,3,...</code>. The iterator is infinite, so <code>itertools.chain(*infinite)</code> will not work.</p> <h3>Related</h3> <ul> <li><a href="https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li> </ul>
[ { "answer_id": 120905, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 4, "selected": false, "text": "<p>Use a generator:</p>\n\n<pre><code>(item for it in infinite for item in it)\n</code></pre>\n\n<p>The * construct unpacks into a tuple in order to pass the arguments, so there's no way to use it.</p>\n" }, { "answer_id": 120910, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 7, "selected": true, "text": "<p>Starting with Python 2.6, you can use <a href=\"https://docs.python.org/library/itertools.html#itertools.chain.from_iterable\" rel=\"noreferrer\"><code>itertools.chain.from_iterable</code></a>:</p>\n\n<pre><code>itertools.chain.from_iterable(iterables)\n</code></pre>\n\n<p>You can also do this with a nested generator comprehension:</p>\n\n<pre><code>def flatten(iterables):\n return (elem for iterable in iterables for elem in iterable)\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12166/" ]
Suppose we have an iterator (an infinite one) that returns lists (or finite iterators), for example one returned by ``` infinite = itertools.cycle([[1,2,3]]) ``` What is a good Python idiom to get an iterator (obviously infinite) that will return each of the elements from the first iterator, then each from the second one, etc. In the example above it would return `1,2,3,1,2,3,...`. The iterator is infinite, so `itertools.chain(*infinite)` will not work. ### Related * [Flattening a shallow list in python](https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python)
Starting with Python 2.6, you can use [`itertools.chain.from_iterable`](https://docs.python.org/library/itertools.html#itertools.chain.from_iterable): ``` itertools.chain.from_iterable(iterables) ``` You can also do this with a nested generator comprehension: ``` def flatten(iterables): return (elem for iterable in iterables for elem in iterable) ```
120,900
<p>I'm working on databases that have moving tables auto-generated by some obscure tools. By the way, we have to track information changes in the table via some triggers. And, of course, it occurs that some changes in the table structure broke some triggers, by removing a column or changing its type, for example.</p> <p>So, the question is: Is there a way to query the Oracle metadata to check is some triggers are broken, in order to send a report to the support team? </p> <p>The user_triggers give all the triggers and tells if they are enable or not, but does not indicate if they are still valid.</p>
[ { "answer_id": 120911, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 5, "selected": true, "text": "<pre><code>SELECT *\nFROM ALL_OBJECTS\nWHERE OBJECT_NAME = trigger_name\nAND OBJECT_TYPE = 'TRIGGER'\nAND STATUS &lt;&gt; 'VALID'\n</code></pre>\n" }, { "answer_id": 120942, "author": "Mike McAllister", "author_id": 16247, "author_profile": "https://Stackoverflow.com/users/16247", "pm_score": 0, "selected": false, "text": "<p>Have a look at SYS.OBJ$, specifically the STATUS column. </p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9396/" ]
I'm working on databases that have moving tables auto-generated by some obscure tools. By the way, we have to track information changes in the table via some triggers. And, of course, it occurs that some changes in the table structure broke some triggers, by removing a column or changing its type, for example. So, the question is: Is there a way to query the Oracle metadata to check is some triggers are broken, in order to send a report to the support team? The user\_triggers give all the triggers and tells if they are enable or not, but does not indicate if they are still valid.
``` SELECT * FROM ALL_OBJECTS WHERE OBJECT_NAME = trigger_name AND OBJECT_TYPE = 'TRIGGER' AND STATUS <> 'VALID' ```
120,917
<p>How to create a database using T SQL script on a specified location? Let's say, I want to create a SQL server database on <code>D:\temp\dbFolder</code>. How to do this?</p>
[ { "answer_id": 120940, "author": "Leah", "author_id": 5506, "author_profile": "https://Stackoverflow.com/users/5506", "pm_score": 6, "selected": true, "text": "<p>When you create the new database you specify the location. For example:</p>\n\n<pre><code>USE [master]\nGO\n\n CREATE DATABASE [AdventureWorks] ON PRIMARY \n ( NAME = N'AdventureWorks_Data', FILENAME = N'C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\AdventureWorks_Data.mdf' , SIZE = 167872KB , MAXSIZE = UNLIMITED, FILEGROWTH = 16384KB )\n LOG ON \n ( NAME = N'AdventureWorks_Log', FILENAME = N'C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\AdventureWorks_Log.ldf' , SIZE = 2048KB , MAXSIZE = 2048GB , FILEGROWTH = 16384KB )\n GO\n</code></pre>\n" }, { "answer_id": 120946, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": 4, "selected": false, "text": "<p>From the SQL Server Books an example where database filenames are explicitely defined:</p>\n\n<pre><code>USE master\nGO\nCREATE DATABASE Sales\nON \n( NAME = Sales_dat,\n FILENAME = 'c:\\program files\\microsoft sql server\\mssql\\data\\saledat.mdf',\n SIZE = 10,\n MAXSIZE = 50,\n FILEGROWTH = 5 )\nLOG ON\n( NAME = 'Sales_log',\n FILENAME = 'c:\\program files\\microsoft sql server\\mssql\\data\\salelog.ldf',\n SIZE = 5MB,\n MAXSIZE = 25MB,\n FILEGROWTH = 5MB )\nGO\n</code></pre>\n" }, { "answer_id": 17642564, "author": "landrew", "author_id": 1621021, "author_profile": "https://Stackoverflow.com/users/1621021", "pm_score": 2, "selected": false, "text": "<ol>\n<li>Create folder on your file system: D:\\temp\\dbFolder\\ </li>\n<li><p>Run the script: </p>\n\n<pre><code>USE master; \nGO \nCREATE DATABASE TestDB1 \nON ( NAME = Sales_dat, FILENAME = 'D:\\temp\\dbFolder\\TestDB1.mdf') \nLOG ON ( NAME = Sales_log, FILENAME = 'D:\\temp\\dbFolder\\TestDB1.ldf'); \nGO\n</code></pre></li>\n</ol>\n" }, { "answer_id": 18658543, "author": "Ardalan Shahgholi", "author_id": 2063547, "author_profile": "https://Stackoverflow.com/users/2063547", "pm_score": 0, "selected": false, "text": "<p>See this link : <a href=\"http://technet.microsoft.com/en-us/library/ms176061.aspx\" rel=\"nofollow\">CREATE DATABASE (Transact-SQL)</a></p>\n\n<pre><code>CREATE DATABASE [ADestinyDb] CONTAINMENT = NONE ON PRIMARY \n( NAME = N'ADestinyDb', \n FILENAME = N'D:\\temp\\dbFolder\\ADestinyDb.mdf' , \n SIZE = 3136 KB , MAXSIZE = UNLIMITED, \n FILEGROWTH = 1024 KB )\nLOG ON \n( NAME = N'ADestinyDb_log', \n FILENAME = N'D:\\temp\\dbFolder\\_log.ldf' , \n SIZE = 832KB , MAXSIZE = 2048 GB , FILEGROWTH = 10 %)\n</code></pre>\n" }, { "answer_id": 21545332, "author": "Avinash", "author_id": 1251692, "author_profile": "https://Stackoverflow.com/users/1251692", "pm_score": 0, "selected": false, "text": "<p>Create folder on your file system: D:\\temp\\dbFolder\\ and run the below script\n(try 'sa' login)</p>\n\n<pre><code> USE master\nCREATE DATABASE [faltu] ON PRIMARY \n( NAME = N'faltu', FILENAME = N'D:\\temp\\dbFolder\\faltu.mdf' , SIZE = 2048KB , FILEGROWTH = 1024KB )\n LOG ON \n( NAME = N'faltu_log', FILENAME = N'D:\\temp\\dbFolder\\faltu_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10%)\n</code></pre>\n" }, { "answer_id": 41548078, "author": "Brett Bieker", "author_id": 7394310, "author_profile": "https://Stackoverflow.com/users/7394310", "pm_score": 2, "selected": false, "text": "<p>Using variables in Studio Manager expanding on the previous examples.</p>\n\n<p>Create folders and subfolders.<br>\n Example: root folder E:\\MSSQL\\DATA\n subfolders E:\\MSSQL\\DATA\\DB and E:\\MSSQL\\DATA\\Logs.</p>\n\n<pre><code>MKDIR \"E:\\MSSQL\\DATA\\DB\"\nMKDIR \"E:\\MSSQL\\DATA\\Logs\"\n</code></pre>\n\n<p>Change Database name @DBNAME variable @Test_DB' to your 'DesiredName_DB'</p>\n\n<p>Change Root folder path @DataPath 'E:\\MSSQL\\DATA' to your as per above created folders.</p>\n\n<p>Run the below in Studio Manager</p>\n\n<pre><code>DECLARE @DBNAME VARCHAR(MAX)\nDECLARE @DataPath AS NVARCHAR(MAX)\nDECLARE @sql VARCHAR(MAX)\n\nSET @DBNAME = N'Test_DB'\nSET @DataPath = N'E:\\MSSQL\\DATA'\n\nSELECT @sql = 'USE MASTER'\nEXEC (@sql)\n\nSELECT @sql = 'CREATE DATABASE '+ quotename(@DBNAME) + ' \nON \nPRIMARY\n ( \n NAME = ''' + @DBNAME + '_DB'', \n FILENAME = ''' + @DataPath + '\\DB\\' + @DBNAME + '.mdf'', \n SIZE = 3136 KB , MAXSIZE = UNLIMITED, \n FILEGROWTH = 1024 KB\n ) \nLOG ON\n (\n NAME = '''+ @DBNAME + '_Log'', \n FILENAME = '''+ @DataPath + '\\Logs\\' + @DBNAME + '_log.ldf'', \n SIZE = 832KB , MAXSIZE = 2048 GB , FILEGROWTH = 10 %\n )'\n\n\nEXEC (@sql)\n</code></pre>\n\n<p>Or another variation on the above theme.</p>\n\n<pre><code>DECLARE @DBNAME VARCHAR(MAX)\nDECLARE @DataFilePath AS NVARCHAR(MAX)\nDECLARE @LogFilePath AS NVARCHAR(MAX)\nDECLARE @sql VARCHAR(MAX)\n\nSET @DBNAME = N'Test_DB'\nSET @DataFilePath = N'E:\\MSSQL\\DATA\\DB\\'\nSET @LogFilePath = N'E:\\MSSQL\\DATA\\Logs\\'\n\nSELECT @sql = 'USE MASTER'\nEXEC (@sql)\n\nSELECT @sql = 'CREATE DATABASE '+ quotename(@DBNAME) + ' \nON \nPRIMARY\n ( \n NAME = ''' + @DBNAME + '_DB'', \n FILENAME = ''' + @DataFilePath + @DBNAME + '.mdf'', \n SIZE = 3136 KB , MAXSIZE = UNLIMITED, \n FILEGROWTH = 1024 KB\n ) \nLOG ON\n (\n NAME = '''+ @DBNAME + '_Log'', \n FILENAME = '''+ @LogFilePath+ @DBNAME + '_log.ldf'', \n SIZE = 832KB , MAXSIZE = 2048 GB , FILEGROWTH = 10 %\n )'\n\n\nEXEC (@sql)\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
How to create a database using T SQL script on a specified location? Let's say, I want to create a SQL server database on `D:\temp\dbFolder`. How to do this?
When you create the new database you specify the location. For example: ``` USE [master] GO CREATE DATABASE [AdventureWorks] ON PRIMARY ( NAME = N'AdventureWorks_Data', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Data.mdf' , SIZE = 167872KB , MAXSIZE = UNLIMITED, FILEGROWTH = 16384KB ) LOG ON ( NAME = N'AdventureWorks_Log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Log.ldf' , SIZE = 2048KB , MAXSIZE = 2048GB , FILEGROWTH = 16384KB ) GO ```
120,928
<p>I have a web part that I've developed, and if I manually install the web part it is fine.</p> <p>However when I have packaged the web part following the instructions on this web site as a guide: <a href="http://www.theartofsharepoint.com/2007/05/how-to-build-solution-pack-wsp.html" rel="noreferrer">http://www.theartofsharepoint.com/2007/05/how-to-build-solution-pack-wsp.html</a></p> <p>I get this error in the log files:</p> <pre><code>09/23/2008 14:13:03.67 w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 8l4d Monitorable Error importing WebPart. Cannot import Project Filter. 09/23/2008 14:13:03.67 w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 89ku High Failed to add webpart http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter. Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter. at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(... 09/23/2008 14:13:03.67* w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 89ku High ...String eventArgument) </code></pre> <p>The pertinent bit is:</p> <pre><code>http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter. Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter. at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) </code></pre> <p>And that's accompanied by a rather terse error message: "Cannot import web part".</p> <p>I have checked and my .dll is registered as safe, it is in the GAC, the feature is activated, and the web parts appear in the web part library with all of the correct properties showing that the webpart files were read successfully.</p> <p>Everything appears to be in place, yet I get that error and little explanation from SharePoint of how to resolve it.</p> <p>Any help finding a solution is appreciated.</p>
[ { "answer_id": 121305, "author": "Keith Sirmons", "author_id": 1048, "author_profile": "https://Stackoverflow.com/users/1048", "pm_score": 0, "selected": false, "text": "<p>Have you recycled your worker process or reset IIS?</p>\n" }, { "answer_id": 121883, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>Figured it out.</p>\n\n<p>The error message is the one from the .webpart file:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;webParts&gt;\n &lt;webPart xmlns=\"http://schemas.microsoft.com/WebPart/v3\"&gt;\n &lt;metaData&gt;\n &lt;!--\n The following Guid is used as a reference to the web part class, \n and it will be automatically replaced with actual type name at deployment time.\n --&gt;\n &lt;type name=\"7F8C4D34-6311-4f22-87B4-A221FA8735BA\" /&gt;\n &lt;importErrorMessage&gt;Cannot import Project Filter.&lt;/importErrorMessage&gt;\n &lt;/metaData&gt;\n &lt;data&gt;\n &lt;properties&gt;\n &lt;property name=\"Title\" type=\"string\"&gt;Project Filter&lt;/property&gt;\n &lt;property name=\"Description\" type=\"string\"&gt;Provides a list of Projects that can be used to Filter other Web Parts.&lt;/property&gt;\n &lt;/properties&gt;\n &lt;/data&gt;\n &lt;/webPart&gt;\n&lt;/webParts&gt;\n</code></pre>\n\n<p>The problem is that the original .webpart file was created on a 32-bit system with Visual Studio Extensions for WSS installed.</p>\n\n<p>However as I'm now on a 64-bit machine VSEWSS is unavailable, and I believe that results in the above GUID not being substituted as I am not using those deployment tools.</p>\n\n<p>Replacing the GUID with the full type name works.</p>\n\n<p>So if you encounter the error message from your importErrorMessage node, then check that your type node in the .webpart file looks more like this (unrelated example):</p>\n\n<pre><code>&lt;type name=\"TitleWP.TitleWP, TitleWP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5\" /&gt;\n</code></pre>\n\n<p>This is in the format:\nClass, Namespace, Version, Culture, PublicKey</p>\n\n<p>You can grab that easily from the web.config file associated with your SharePoint instance, as it will be in the safe controls list.</p>\n" }, { "answer_id": 449535, "author": "Smxyhd", "author_id": 55728, "author_profile": "https://Stackoverflow.com/users/55728", "pm_score": 1, "selected": false, "text": "<p>Now I get a answer for similar problem as below:</p>\n\n<p>When I try to added a new wep part to the page, then sharepoint show me a error message, tell me--Can not import my web part, this error message define in .webpart file.</p>\n\n<p>So i tried to add some ohter web parts in the page , A strange quesiton appearance, some of them can be added , some of them can not be added.</p>\n\n<p>After I traced the code of my web part and anaylsis them, I found the reason:</p>\n\n<p>Old Code for web part ProjectInfo(my web part name) is:</p>\n\n<pre><code>namespace ProjectInfo\n....\n public class ProjectInfo:System.Web.UI.WebControls.WebParts.Web.part\n {\n .....\n private SPWeb _spWeb;\n private SPList _spList;\n private string _listName = \"ProjectDocs\";\n ......\n }\npublic ProjectInfo()\n {\n .....\n _spWeb = SPContext.Current.Web;\n //It show me a error here when i trace the code\n _spList = _spWeb.Lists[_listName]; \n .....\n }\n</code></pre>\n\n<p>Stop now, I thought that it maybe the web page init order problem. AS web page load web part control, constructrue function ProjectInfo() will be running at first. Actually, the web page havn't finish its init. by the time.</p>\n\n<p>so i did a test. firstly, I put a good web in the page, it's ok . then, I try to put the web part in the page which can not be added just now. ~~ OK!! It's working ...because the page already init. finished.</p>\n\n<p>Ok! I corrected my code:</p>\n\n<pre><code> namespace ProjectInfo\n ....\n public class ProjectInfo:System.Web.UI.WebControls.WebParts.Web.part\n {\n .....\n private SPWeb _spWeb;\n private SPList _spList;\n private string _listName = \"ProjectDocs\";\n ......\n }\n public ProjectInfo()\n {\n .....\n //Remove code in constructure function.\n //_spWeb = SPContext.Current.Web;\n //It show me a error here when i trace the code\n //_spList = _spWeb.Lists[_listName]; \n .....\n }\n\n protected override void CreateChildControls()\n {\n ....\n base.CreateChildControls();\n\n _spWeb = SPContext.Current.Web;\n _spList = _spWeb.Lists[_listName];\n ....\n }\n</code></pre>\n\n<p>After I test, the error message did't happed again..\n LoL ~~</p>\n\n<p>Hope this explain will help you .</p>\n" }, { "answer_id": 456810, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Solved mine.</p>\n\n<p>i was getting this error:</p>\n\n<pre><code>===========================================================================\nError importing WebPart. Cannot import ........ Web Part.\nFailed to add webpart \nException Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import ... Web Part. at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) \n===========================================================================\n</code></pre>\n\n<p>\"Cannot import webpart...\"</p>\n\n<p>The problem was: Non-matching GUIDS</p>\n\n<p>Check if the guid on webpart class , and in the .xml and in .webpart class are same.</p>\n\n<p>I was copy-pasting code from other webparts sources. ( Mutliple Document Upload Wepart on Codeplex) and forgot to fix guids.</p>\n" }, { "answer_id": 586165, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I have also experienced this error when the assemblies in the GAC that my web part referenced, was signed by a different strong name key file to what I was expecting.\nI found this out when deciding to update these DLLs. When inserting it into the GAC I noticed that there were 2 entries for the same DLL but they had different Public Key Tokens</p>\n" }, { "answer_id": 677930, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I got this error when I created a base class web part and then inherited a derived class from it. The base class was fine but the derived class failed when I tried to add it to a web page with the same error as the original post. In my case I had to add a <strong>public</strong> modifier to the class:</p>\n\n<pre><code>public class DerivedWebPart : BaseWebPart\n</code></pre>\n\n<p>Also I added a constructor in the derived class to call the base class one - although I think you shouldn't need this really:</p>\n\n<pre><code> public DerivedWebPart() : base()\n {\n }\n</code></pre>\n" }, { "answer_id": 1104726, "author": "Kirk Liemohn", "author_id": 74276, "author_profile": "https://Stackoverflow.com/users/74276", "pm_score": 3, "selected": false, "text": "<p>We had this same problem and found that the constructor of our web part was being called by the WebPartImporter and within the constructor we were doing SPSecurity.RunWithElevatedPrivileges.</p>\n\n<p>For some reason the WebPartImporter cannot handle this. So, we simply moved our code out of the constructor to OnInit (where it really belonged) and all is well.</p>\n" }, { "answer_id": 1228316, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I have seen this anomaly several times without a good resolution.</p>\n\n<p>Check that your Assembly, Namespace, Class name is correct EVERYWHERE. This has hung me up more than once.</p>\n\n<p>Make sure you have a valid SafeControls entry.</p>\n\n<p>Make sure your .webpart file is valid (let SharePoint create it for you if you can)</p>\n\n<p>If you are absolutely positive that everything is correct, well then you are stuck in a place that I have been several times. The only thing that I can come up with is that VS is compiling the assembly wrong. The ONLY fix that I have found is to create a new VS project and set it up how you need, then copy THE TEXT of your old CS files into your new CS files...do not copy the files themselves...the goal is to have everything fresh.</p>\n\n<p>This has worked for me. Good Luck.</p>\n" }, { "answer_id": 1695785, "author": "Shannon Bray", "author_id": 205950, "author_profile": "https://Stackoverflow.com/users/205950", "pm_score": 0, "selected": false, "text": "<p>I found that mine did not import the first time, but if I clicked 'New' and added it, it would work.</p>\n\n<p>From there I grabbed a copy of the XML and saved it to my project. The web part worked great after that.</p>\n\n<p>It only took me DAYS to get to this point. A lot of wasted time.</p>\n" }, { "answer_id": 4235161, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 0, "selected": false, "text": "<p>I had a problem very similar to this, but Guids weren't the problem: my webpart didn't have the <code>CLSCompliannt</code> attribute set to false. Like so:</p>\n\n<pre><code>namespace MyNamespace\n{\n\n [CLSCompliant(false)]\n [Guid(\"...\")]\n public class MyWidget : MyWebPartBaseClass\n {\n\n }\n}\n</code></pre>\n" }, { "answer_id": 9186420, "author": "PeterX", "author_id": 845584, "author_profile": "https://Stackoverflow.com/users/845584", "pm_score": 2, "selected": false, "text": "<p>All great suggestions. My problem was unique and silly: I had deployed the solution to the first Web Application but not to the second. SharePoint however still allowed me to activate the feature on the second Web App's Site Collection (not sure why). This meant the second Web App didn't have a safe control entry in this Web.config file (and I was stupidly checking the first Web.config).</p>\n\n<p>So, double-check you're looking at the correct web application/web.config.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a web part that I've developed, and if I manually install the web part it is fine. However when I have packaged the web part following the instructions on this web site as a guide: <http://www.theartofsharepoint.com/2007/05/how-to-build-solution-pack-wsp.html> I get this error in the log files: ``` 09/23/2008 14:13:03.67 w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 8l4d Monitorable Error importing WebPart. Cannot import Project Filter. 09/23/2008 14:13:03.67 w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 89ku High Failed to add webpart http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter. Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter. at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(... 09/23/2008 14:13:03.67* w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 89ku High ...String eventArgument) ``` The pertinent bit is: ``` http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter. Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter. at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) ``` And that's accompanied by a rather terse error message: "Cannot import web part". I have checked and my .dll is registered as safe, it is in the GAC, the feature is activated, and the web parts appear in the web part library with all of the correct properties showing that the webpart files were read successfully. Everything appears to be in place, yet I get that error and little explanation from SharePoint of how to resolve it. Any help finding a solution is appreciated.
Figured it out. The error message is the one from the .webpart file: ``` <?xml version="1.0" encoding="utf-8"?> <webParts> <webPart xmlns="http://schemas.microsoft.com/WebPart/v3"> <metaData> <!-- The following Guid is used as a reference to the web part class, and it will be automatically replaced with actual type name at deployment time. --> <type name="7F8C4D34-6311-4f22-87B4-A221FA8735BA" /> <importErrorMessage>Cannot import Project Filter.</importErrorMessage> </metaData> <data> <properties> <property name="Title" type="string">Project Filter</property> <property name="Description" type="string">Provides a list of Projects that can be used to Filter other Web Parts.</property> </properties> </data> </webPart> </webParts> ``` The problem is that the original .webpart file was created on a 32-bit system with Visual Studio Extensions for WSS installed. However as I'm now on a 64-bit machine VSEWSS is unavailable, and I believe that results in the above GUID not being substituted as I am not using those deployment tools. Replacing the GUID with the full type name works. So if you encounter the error message from your importErrorMessage node, then check that your type node in the .webpart file looks more like this (unrelated example): ``` <type name="TitleWP.TitleWP, TitleWP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5" /> ``` This is in the format: Class, Namespace, Version, Culture, PublicKey You can grab that easily from the web.config file associated with your SharePoint instance, as it will be in the safe controls list.
120,936
<p>I can add custom version strings to a C++ DLL in Visual Studio by editing the .rc file by hand. For example, if I add to the VersionInfo section of the .rc file</p> <pre><code>VALUE "BuildDate", "2008/09/19 15:42:52" </code></pre> <p>Then that date is visible in the file explorer, in the DLL's properties, under the Version tab.</p> <p>Can I do the same for a C# DLL? Not just for build date, but for other version information (such as source control information)</p> <p>UPDATE: I think there may be a way to do this by embedding a windows resource, so I've <a href="https://stackoverflow.com/questions/200485">asked how to do that</a>.</p>
[ { "answer_id": 120958, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 2, "selected": false, "text": "<p>In AssemblyInfo.cs, you can put:</p>\n\n<pre><code>[assembly: System.Reflection.AssemblyInformationalVersion(\"whatever you want\")]\n</code></pre>\n\n<p>It's a compiler warning if it's not a number like 1.2.3.4, but I'm fairly sure everything will work.</p>\n" }, { "answer_id": 122055, "author": "KyleLanser", "author_id": 12923, "author_profile": "https://Stackoverflow.com/users/12923", "pm_score": 3, "selected": false, "text": "<p>Expanding on the Khoth's answer, In AssemblyInfo.cs:</p>\n\n<p>You can do:</p>\n\n<pre><code>[assembly: CustomResource(\"Build Date\", \"12/12/2012\")]\n</code></pre>\n\n<p>Where CustomResource is defined as:</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.Assembly)]\npublic class CustomResourceAttribute : Attribute\n{ \n private string the_variable;\n public string Variable {get { return the_variable; }}\n\n private string the_value;\n public string Value {get { return the_value; }}\n\n public CustomResourceAttribute(string variable, string value)\n {\n this.the_variable = variable;\n this.the_value = value;\n }\n}\n</code></pre>\n\n<p>This solution is nice because it gives you the flexibility you need and it does not cause any compiler warnings. </p>\n\n<p>Unfortunately it is not possible to use a DateTime because the values entered in Attributes must be constants, and a DateTime is not a constant.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
I can add custom version strings to a C++ DLL in Visual Studio by editing the .rc file by hand. For example, if I add to the VersionInfo section of the .rc file ``` VALUE "BuildDate", "2008/09/19 15:42:52" ``` Then that date is visible in the file explorer, in the DLL's properties, under the Version tab. Can I do the same for a C# DLL? Not just for build date, but for other version information (such as source control information) UPDATE: I think there may be a way to do this by embedding a windows resource, so I've [asked how to do that](https://stackoverflow.com/questions/200485).
Expanding on the Khoth's answer, In AssemblyInfo.cs: You can do: ``` [assembly: CustomResource("Build Date", "12/12/2012")] ``` Where CustomResource is defined as: ``` [AttributeUsage(AttributeTargets.Assembly)] public class CustomResourceAttribute : Attribute { private string the_variable; public string Variable {get { return the_variable; }} private string the_value; public string Value {get { return the_value; }} public CustomResourceAttribute(string variable, string value) { this.the_variable = variable; this.the_value = value; } } ``` This solution is nice because it gives you the flexibility you need and it does not cause any compiler warnings. Unfortunately it is not possible to use a DateTime because the values entered in Attributes must be constants, and a DateTime is not a constant.
120,951
<p>I'd like to know do I normalize a URL in python. </p> <p>For example, If I have a url string like : "<a href="http://www.example.com/foo" rel="noreferrer">http://www.example.com/foo</a> goo/bar.html"</p> <p>I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.</p>
[ { "answer_id": 120959, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": false, "text": "<h3>Py3</h3>\n\n<pre><code>from urllib.parse import urlparse, urlunparse, quote\ndef myquote(url):\n parts = urlparse(url)\n return urlunparse(parts._replace(path=quote(parts.path)))\n\n&gt;&gt;&gt; myquote('https://www.example.com/~user/with space/index.html?a=1&amp;b=2')\n'https://www.example.com/~user/with%20space/index.html?a=1&amp;b=2'\n</code></pre>\n\n<h3>Py2</h3>\n\n<pre><code>import urlparse, urllib\ndef myquote(url):\n parts = urlparse.urlparse(url)\n return urlparse.urlunparse(parts[:2] + (urllib.quote(parts[2]),) + parts[3:])\n\n&gt;&gt;&gt; myquote('https://www.example.com/~user/with space/index.html?a=1&amp;b=2')\n'https://www.example.com/%7Euser/with%20space/index.html?a=1&amp;b=2'\n</code></pre>\n\n<p>This quotes only the path component.</p>\n" }, { "answer_id": 120971, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 5, "selected": false, "text": "<p>use <code>urllib.quote</code> or <code>urllib.quote_plus</code></p>\n\n<p>From the <a href=\"http://docs.python.org/lib/module-urllib.html\" rel=\"noreferrer\">urllib documentation</a>:</p>\n\n<blockquote>\n <p><strong>quote(string[, safe])</strong></p>\n \n <p>Replace special characters in string\n using the \"%xx\" escape. Letters,\n digits, and the characters \"_.-\" are\n never quoted. The optional safe\n parameter specifies additional\n characters that should not be quoted\n -- its default value is '/'.</p>\n \n <p>Example: <code>quote('/~connolly/')</code> yields <code>'/%7econnolly/'</code>. </p>\n \n <p><strong>quote_plus(string[, safe])</strong></p>\n \n <p>Like quote(), but also replaces spaces\n by plus signs, as required for quoting\n HTML form values. Plus signs in the\n original string are escaped unless\n they are included in safe. It also\n does not have safe default to '/'.</p>\n</blockquote>\n\n<p>EDIT: Using urllib.quote or urllib.quote_plus on the whole URL will mangle it, as @ΤΖΩΤΖΙΟΥ points out:</p>\n\n<pre><code>&gt;&gt;&gt; quoted_url = urllib.quote('http://www.example.com/foo goo/bar.html')\n&gt;&gt;&gt; quoted_url\n'http%3A//www.example.com/foo%20goo/bar.html'\n&gt;&gt;&gt; urllib2.urlopen(quoted_url)\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n File \"c:\\python25\\lib\\urllib2.py\", line 124, in urlopen\n return _opener.open(url, data)\n File \"c:\\python25\\lib\\urllib2.py\", line 373, in open\n protocol = req.get_type()\n File \"c:\\python25\\lib\\urllib2.py\", line 244, in get_type\n raise ValueError, \"unknown url type: %s\" % self.__original\nValueError: unknown url type: http%3A//www.example.com/foo%20goo/bar.html\n</code></pre>\n\n<p>@ΤΖΩΤΖΙΟΥ provides a function that uses <a href=\"http://docs.python.org/lib/module-urlparse.html\" rel=\"noreferrer\">urlparse.urlparse and urlparse.urlunparse</a> to parse the url and only encode the path. This may be more useful for you, although if you're building the URL from a known protocol and host but with a suspect path, you could probably do just as well to avoid urlparse and just quote the suspect part of the URL, concatenating with known safe parts.</p>\n" }, { "answer_id": 121017, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 6, "selected": false, "text": "<p>Have a look at this module: <a href=\"https://github.com/pallets/werkzeug/blob/master/src/werkzeug/urls.py\" rel=\"noreferrer\">werkzeug.utils</a>. (now in <code>werkzeug.urls</code>)</p>\n\n<p>The function you are looking for is called \"url_fix\" and works like this:</p>\n\n<pre><code>&gt;&gt;&gt; from werkzeug.urls import url_fix\n&gt;&gt;&gt; url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)')\n'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'\n</code></pre>\n\n<p>It's implemented in Werkzeug as follows:</p>\n\n<pre><code>import urllib\nimport urlparse\n\ndef url_fix(s, charset='utf-8'):\n \"\"\"Sometimes you get an URL by a user that just isn't a real\n URL because it contains unsafe characters like ' ' and so on. This\n function can fix some of the problems in a similar way browsers\n handle data entered by the user:\n\n &gt;&gt;&gt; url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)')\n 'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'\n\n :param charset: The target charset for the URL if the url was\n given as unicode string.\n \"\"\"\n if isinstance(s, unicode):\n s = s.encode(charset, 'ignore')\n scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)\n path = urllib.quote(path, '/%')\n qs = urllib.quote_plus(qs, ':&amp;=')\n return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))\n</code></pre>\n" }, { "answer_id": 845595, "author": "Oleg Sakharov", "author_id": 87057, "author_profile": "https://Stackoverflow.com/users/87057", "pm_score": 6, "selected": false, "text": "<p><a href=\"http://svn.python.org/view/python/trunk/Lib/urllib.py?r1=71780&amp;r2=71779&amp;pathrev=71780\" rel=\"noreferrer\">Real fix in Python 2.7 for that problem</a></p>\n\n<p>Right solution was:</p>\n\n<pre><code> # percent encode url, fixing lame server errors for e.g, like space\n # within url paths.\n fullurl = quote(fullurl, safe=\"%/:=&amp;?~#+!$,;'@()*[]\")\n</code></pre>\n\n<p>For more information see <a href=\"http://bugs.python.org/issue918368\" rel=\"noreferrer\">Issue918368: \"urllib doesn't correct server returned urls\"</a></p>\n" }, { "answer_id": 962248, "author": "cobra libre", "author_id": 61108, "author_profile": "https://Stackoverflow.com/users/61108", "pm_score": 4, "selected": false, "text": "<p>Because this page is a top result for Google searches on the topic, I think it's worth mentioning some work that has been done on URL normalization with Python that goes beyond urlencoding space characters. For example, dealing with default ports, character case, lack of trailing slashes, etc.</p>\n\n<p>When the Atom syndication format was being developed, there was some discussion on how to normalize URLs into canonical format; this is documented in the article <a href=\"http://www.intertwingly.net/wiki/pie/PaceCanonicalIds\" rel=\"noreferrer\">PaceCanonicalIds</a> on the Atom/Pie wiki. That article provides some good test cases.</p>\n\n<p>I believe that one result of this discussion was Mark Nottingham's <a href=\"http://www.mnot.net/python/urlnorm.py\" rel=\"noreferrer\">urlnorm.py</a> library, which I've used with good results on a couple projects. That script doesn't work with the URL given in this question, however. So a better choice might be <a href=\"http://intertwingly.net/blog/2004/08/04/Urlnorm\" rel=\"noreferrer\">Sam Ruby's version of urlnorm.py</a>, which handles that URL, and all of the aforementioned test cases from the Atom wiki.</p>\n" }, { "answer_id": 1912115, "author": "Mark Nottingham", "author_id": 152646, "author_profile": "https://Stackoverflow.com/users/152646", "pm_score": 2, "selected": false, "text": "<p>Just FYI, urlnorm has moved to github:\n <a href=\"http://gist.github.com/246089\" rel=\"nofollow noreferrer\">http://gist.github.com/246089</a></p>\n" }, { "answer_id": 24203504, "author": "WKPlus", "author_id": 552942, "author_profile": "https://Stackoverflow.com/users/552942", "pm_score": 1, "selected": false, "text": "<p>I encounter such an problem: need to quote the space only.</p>\n\n<p><code>fullurl = quote(fullurl, safe=\"%/:=&amp;?~#+!$,;'@()*[]\")</code> do help, but it's too complicated.</p>\n\n<p>So I used a simple way: <code>url = url.replace(' ', '%20')</code>, it's not perfect, but it's the simplest way and it works for this situation.</p>\n" }, { "answer_id": 42610024, "author": "Hélder Lima", "author_id": 1699147, "author_profile": "https://Stackoverflow.com/users/1699147", "pm_score": 2, "selected": false, "text": "<p>Valid for Python 3.5:</p>\n\n<pre><code>import urllib.parse\n\nurllib.parse.quote([your_url], \"\\./_-:\")\n</code></pre>\n\n<p>example:</p>\n\n<pre><code>import urllib.parse\n\nprint(urllib.parse.quote(\"http://www.example.com/foo goo/bar.html\", \"\\./_-:\"))\n</code></pre>\n\n<p>the output will be <a href=\"http://www.example.com/foo%20goo/bar.html\" rel=\"nofollow noreferrer\">http://www.example.com/foo%20goo/bar.html</a></p>\n\n<p>Font: <a href=\"https://docs.python.org/3.5/library/urllib.parse.html?highlight=quote#urllib.parse.quote\" rel=\"nofollow noreferrer\">https://docs.python.org/3.5/library/urllib.parse.html?highlight=quote#urllib.parse.quote</a></p>\n" }, { "answer_id": 73066013, "author": "Granitosaurus", "author_id": 3737009, "author_profile": "https://Stackoverflow.com/users/3737009", "pm_score": 0, "selected": false, "text": "<p>A lot of answers here talk about quoting URLs, not about <em>normalizing</em> them.</p>\n<p>The best tool to normalize urls (for deduplication etc.) in Python IMO is <a href=\"https://github.com/scrapy/w3lib\" rel=\"nofollow noreferrer\">w3lib</a>'s <code>w3lib.url.canonicalize_url</code> util.</p>\n<p>Taken from <a href=\"https://w3lib.readthedocs.io/en/latest/w3lib.html#w3lib.url.canonicalize_url\" rel=\"nofollow noreferrer\">the official docs</a>:</p>\n<pre><code>Canonicalize the given url by applying the following procedures:\n\n - sort query arguments, first by key, then by value\npercent encode paths ; non-ASCII characters are percent-encoded using UTF-8 (RFC-3986)\n - percent encode query arguments ; non-ASCII characters are percent-encoded using passed encoding (UTF-8 by default)\n - normalize all spaces (in query arguments) ‘+’ (plus symbol)\n - normalize percent encodings case (%2f -&gt; %2F)\n - remove query arguments with blank values (unless keep_blank_values is True)\n - remove fragments (unless keep_fragments is True)\n - List item\n\nThe url passed can be bytes or unicode, while the url returned is always a native str (bytes in Python 2, unicode in Python 3).\n\n&gt;&gt;&gt; import w3lib.url\n&gt;&gt;&gt;\n&gt;&gt;&gt; # sorting query arguments\n&gt;&gt;&gt; w3lib.url.canonicalize_url('http://www.example.com/do?c=3&amp;b=5&amp;b=2&amp;a=50')\n'http://www.example.com/do?a=50&amp;b=2&amp;b=5&amp;c=3'\n&gt;&gt;&gt;\n&gt;&gt;&gt; # UTF-8 conversion + percent-encoding of non-ASCII characters\n&gt;&gt;&gt; w3lib.url.canonicalize_url('http://www.example.com/r\\u00e9sum\\u00e9')\n'http://www.example.com/r%C3%A9sum%C3%A9'\n</code></pre>\n<p>I've used this util with great success when broad crawling the web to avoid duplicate requests because of minor url differences (different parameter order, anchors etc)</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13523/" ]
I'd like to know do I normalize a URL in python. For example, If I have a url string like : "<http://www.example.com/foo> goo/bar.html" I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.
Have a look at this module: [werkzeug.utils](https://github.com/pallets/werkzeug/blob/master/src/werkzeug/urls.py). (now in `werkzeug.urls`) The function you are looking for is called "url\_fix" and works like this: ``` >>> from werkzeug.urls import url_fix >>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)') 'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29' ``` It's implemented in Werkzeug as follows: ``` import urllib import urlparse def url_fix(s, charset='utf-8'): """Sometimes you get an URL by a user that just isn't a real URL because it contains unsafe characters like ' ' and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user: >>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)') 'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29' :param charset: The target charset for the URL if the url was given as unicode string. """ if isinstance(s, unicode): s = s.encode(charset, 'ignore') scheme, netloc, path, qs, anchor = urlparse.urlsplit(s) path = urllib.quote(path, '/%') qs = urllib.quote_plus(qs, ':&=') return urlparse.urlunsplit((scheme, netloc, path, qs, anchor)) ```
120,952
<p>I have an SP that takes 10 seconds to run about 10 times (about a second every time it is ran). The platform is asp .net, and the server is SQL Server 2005. I have indexed the table (not on the PK also), and that is not the issue. Some caveats:</p> <ul> <li>usp_SaveKeyword is not the issue. I commented out that entire SP and it made not difference. </li> <li>I set @SearchID to 1 and the time was significantly reduced, only taking about 15ms on average for the transaction. </li> <li>I commented out the entire stored procedure except the insert into tblSearches and strangely it took more time to execute. </li> </ul> <p>Any ideas of what could be going on? </p> <pre><code>set ANSI_NULLS ON go ALTER PROCEDURE [dbo].[usp_NewSearch] @Keyword VARCHAR(50), @SessionID UNIQUEIDENTIFIER, @time SMALLDATETIME = NULL, @CityID INT = NULL AS BEGIN SET NOCOUNT ON; IF @time IS NULL SET @time = GETDATE(); DECLARE @KeywordID INT; EXEC @KeywordID = usp_SaveKeyword @Keyword; PRINT 'KeywordID : ' PRINT @KeywordID DECLARE @SearchID BIGINT; SELECT TOP 1 @SearchID = SearchID FROM tblSearches WHERE SessionID = @SessionID AND KeywordID = @KeywordID; IF @SearchID IS NULL BEGIN INSERT INTO tblSearches (KeywordID, [time], SessionID, CityID) VALUES (@KeywordID, @time, @SessionID, @CityID) SELECT Scope_Identity(); END ELSE BEGIN SELECT @SearchID END END </code></pre>
[ { "answer_id": 120973, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>Triggers!</p>\n\n<p>They are insidious indeed.</p>\n" }, { "answer_id": 121009, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 2, "selected": false, "text": "<p>Enable \"Display Estimated Execution Plan\" in SQL Management Studio - where does the execution plan show you spending the time? It'll guide you on the heuristics being used to optimize the query (or not in this case). Generally the \"fatter\" lines are the ones to focus on - they're ones generating large amounts of I/O.</p>\n\n<p>Unfortunately even if you tell us the table schema, only you will be able to see actually how SQL chose to optimize the query. One last thing - have you got a clustered index on tblSearches?</p>\n" }, { "answer_id": 121094, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 3, "selected": true, "text": "<p>Why are you using <code>top 1 @SearchID</code> instead of <code>max (SearchID)</code> or <code>where exists</code> in this query? <code>top</code> requires you to run the query and retrieve the first row from the result set. If the result set is large this could consume quite a lot of resources before you get out the final result set.</p>\n\n<pre><code>SELECT TOP 1 @SearchID = SearchID \n FROM tblSearches \n WHERE SessionID = @SessionID \n AND KeywordID = @KeywordID;\n</code></pre>\n\n<p>I don't see any obvious reason for this - either of aforementioned constructs should get you something semantically equivalent to this with a very cheap index lookup. Unless I'm missing something you should be able to do something like</p>\n\n<pre><code>select @SearchID = isnull (max (SearchID), -1)\n from tblSearches\n where SessionID = @SessionID\n and KeywordID = @KeywordID\n</code></pre>\n\n<p>This ought to be fairly efficient and (unless I'm missing something) semantically equivalent. </p>\n" }, { "answer_id": 121118, "author": "John Naegle", "author_id": 8000, "author_profile": "https://Stackoverflow.com/users/8000", "pm_score": 1, "selected": false, "text": "<ol>\n<li>What is the clustered index on tblSearches? If the clustered index is not on primary key, the database may be spending a lot of time reordering. </li>\n<li>How many other indexes do you have?</li>\n<li>Do you have any triggers?</li>\n<li>Where does the execution plan indicate the time is being spent?</li>\n</ol>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952/" ]
I have an SP that takes 10 seconds to run about 10 times (about a second every time it is ran). The platform is asp .net, and the server is SQL Server 2005. I have indexed the table (not on the PK also), and that is not the issue. Some caveats: * usp\_SaveKeyword is not the issue. I commented out that entire SP and it made not difference. * I set @SearchID to 1 and the time was significantly reduced, only taking about 15ms on average for the transaction. * I commented out the entire stored procedure except the insert into tblSearches and strangely it took more time to execute. Any ideas of what could be going on? ``` set ANSI_NULLS ON go ALTER PROCEDURE [dbo].[usp_NewSearch] @Keyword VARCHAR(50), @SessionID UNIQUEIDENTIFIER, @time SMALLDATETIME = NULL, @CityID INT = NULL AS BEGIN SET NOCOUNT ON; IF @time IS NULL SET @time = GETDATE(); DECLARE @KeywordID INT; EXEC @KeywordID = usp_SaveKeyword @Keyword; PRINT 'KeywordID : ' PRINT @KeywordID DECLARE @SearchID BIGINT; SELECT TOP 1 @SearchID = SearchID FROM tblSearches WHERE SessionID = @SessionID AND KeywordID = @KeywordID; IF @SearchID IS NULL BEGIN INSERT INTO tblSearches (KeywordID, [time], SessionID, CityID) VALUES (@KeywordID, @time, @SessionID, @CityID) SELECT Scope_Identity(); END ELSE BEGIN SELECT @SearchID END END ```
Why are you using `top 1 @SearchID` instead of `max (SearchID)` or `where exists` in this query? `top` requires you to run the query and retrieve the first row from the result set. If the result set is large this could consume quite a lot of resources before you get out the final result set. ``` SELECT TOP 1 @SearchID = SearchID FROM tblSearches WHERE SessionID = @SessionID AND KeywordID = @KeywordID; ``` I don't see any obvious reason for this - either of aforementioned constructs should get you something semantically equivalent to this with a very cheap index lookup. Unless I'm missing something you should be able to do something like ``` select @SearchID = isnull (max (SearchID), -1) from tblSearches where SessionID = @SessionID and KeywordID = @KeywordID ``` This ought to be fairly efficient and (unless I'm missing something) semantically equivalent.
120,966
<p>I was writing a (seemingly) straight-forward SQL snippet that drops a column after it makes sure the column exists.<br> The problem: if the column does NOT exist, the code <em>inside</em> the IF clause complains that it can't find the column! Well, <em>doh</em>, that's why it's inside the IF clause!<br> So my question is, why does a piece of code that shouldn't be executed give errors?</p> <p>Here's the snippet:</p> <pre><code>IF exists (select * from syscolumns WHERE id=object_id('Table_MD') and name='timeout') BEGIN ALTER TABLE [dbo].[Table_MD] DROP COLUMN timeout END GO </code></pre> <p>...and here's the error:</p> <p><code>Error executing SQL script [...]. Invalid column name 'timeout'</code></p> <p>I'm using Microsoft SQL Server 2005 Express Edition.</p>
[ { "answer_id": 120974, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 0, "selected": false, "text": "<p>It may never be executed, but it's parsed for validity by Sql Server. The only way to \"get around\" this is to construct a block of dynamic sql and then selectively execute it</p>\n" }, { "answer_id": 120985, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 4, "selected": true, "text": "<pre><code>IF exists (select * from syscolumns\n WHERE id=object_id('Table_MD') and name='timeout')\nBEGIN\n DECLARE @SQL nvarchar(1000)\n SET @SQL = N'ALTER TABLE [dbo].[Table_MD] DROP COLUMN timeout'\n EXEC sp_executesql @SQL\nEND\nGO\n</code></pre>\n\n<p>Reason:\nWhen Sql server compiles the code, they check it for used objects ( if they exists ). This check procedure ignores any \"IF\", \"WHILE\", etc... constructs and simply check all used objects in code.</p>\n" }, { "answer_id": 121070, "author": "Cristian Diaconescu", "author_id": 11545, "author_profile": "https://Stackoverflow.com/users/11545", "pm_score": 0, "selected": false, "text": "<p>Here's how I got it to work:</p>\n\n<p>Inside the IF clause, I changed the <code>ALTER ... DROP ...</code> command with <code>exec ('ALTER ... DROP ...')</code></p>\n\n<p>It seems the SQL server does a validity check on the code when parsing it, and sees that a non-existing column gets referenced somewhere (even if that piece of code will never be executed).<br>\nUsing the <code>exec(ute)</code> command wraps the problematic code in a string, the parser doesn't complain, and the code only gets executed when necessary.\nHere's the modified snippet:</p>\n\n<pre><code>IF exists (select * from syscolumns\n WHERE id=object_id('Table_MD') and name='timeout')\nBEGIN\n exec ('ALTER TABLE [dbo].[Table_MD] DROP COLUMN timeout')\nEND\nGO\n</code></pre>\n" }, { "answer_id": 121196, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 0, "selected": false, "text": "<p>By the way, there is a similar issue in Oracle, and a similar workaround using the \"execute immediate\" clause.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11545/" ]
I was writing a (seemingly) straight-forward SQL snippet that drops a column after it makes sure the column exists. The problem: if the column does NOT exist, the code *inside* the IF clause complains that it can't find the column! Well, *doh*, that's why it's inside the IF clause! So my question is, why does a piece of code that shouldn't be executed give errors? Here's the snippet: ``` IF exists (select * from syscolumns WHERE id=object_id('Table_MD') and name='timeout') BEGIN ALTER TABLE [dbo].[Table_MD] DROP COLUMN timeout END GO ``` ...and here's the error: `Error executing SQL script [...]. Invalid column name 'timeout'` I'm using Microsoft SQL Server 2005 Express Edition.
``` IF exists (select * from syscolumns WHERE id=object_id('Table_MD') and name='timeout') BEGIN DECLARE @SQL nvarchar(1000) SET @SQL = N'ALTER TABLE [dbo].[Table_MD] DROP COLUMN timeout' EXEC sp_executesql @SQL END GO ``` Reason: When Sql server compiles the code, they check it for used objects ( if they exists ). This check procedure ignores any "IF", "WHILE", etc... constructs and simply check all used objects in code.
120,997
<p>I'm just getting started with Custom User Controls in C# and I'm wondering if there are any examples out there of how to write one which accepts nested tags?</p> <p>For example, when you create an <code>asp:repeater</code> you can add a nested tag for <code>itemtemplate</code>.</p>
[ { "answer_id": 121007, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 5, "selected": true, "text": "<p>I wrote a <a href=\"https://robertwray.co.uk/blog/describing-asp-net-control-properties-declaratively\" rel=\"nofollow noreferrer\">blog post</a> about this some time ago. In brief, if you had a control with the following markup:</p>\n\n<pre><code>&lt;Abc:CustomControlUno runat=\"server\" ID=\"Control1\"&gt;\n &lt;Children&gt;\n &lt;Abc:Control1Child IntegerProperty=\"1\" /&gt;\n &lt;/Children&gt;\n&lt;/Abc:CustomControlUno&gt;\n</code></pre>\n\n<p>You'd need the code in the control to be along the lines of:</p>\n\n<pre><code>[ParseChildren(true)]\n[PersistChildren(true)]\n[ToolboxData(\"&lt;{0}:CustomControlUno runat=server&gt;&lt;/{0}:CustomControlUno&gt;\")]\npublic class CustomControlUno : WebControl, INamingContainer\n{\n private Control1ChildrenCollection _children;\n\n [PersistenceMode(PersistenceMode.InnerProperty)]\n [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\n public Control1ChildrenCollection Children\n {\n get\n {\n if (_children == null)\n {\n _children = new Control1ChildrenCollection();\n }\n return _children;\n }\n }\n}\n\npublic class Control1ChildrenCollection : List&lt;Control1Child&gt;\n{\n}\n\npublic class Control1Child\n{\n public int IntegerProperty { get; set; }\n}\n</code></pre>\n" }, { "answer_id": 121022, "author": "Viktor Elofsson", "author_id": 15067, "author_profile": "https://Stackoverflow.com/users/15067", "pm_score": 1, "selected": false, "text": "<p>My guess is you're looking for something like this? <a href=\"http://msdn.microsoft.com/en-us/library/aa478964.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa478964.aspx</a></p>\n\n<p>Your tags were removed or are invisible, so can't really help you there.</p>\n" }, { "answer_id": 1102226, "author": "Guðmundur H", "author_id": 73256, "author_profile": "https://Stackoverflow.com/users/73256", "pm_score": 3, "selected": false, "text": "<p>I followed Rob's blog post, and made a slightly different control. The control is a conditional one, really just like an if-clause:</p>\n\n<pre><code>&lt;wc:PriceInfo runat=\"server\" ID=\"PriceInfo\"&gt;\n &lt;IfDiscount&gt;\n You don't have a discount.\n &lt;/IfDiscount&gt;\n &lt;IfNotDiscount&gt;\n Lucky you, &lt;b&gt;you have a discount!&lt;/b&gt;\n &lt;/IfNotDiscount&gt;\n&lt;/wc:PriceInfo&gt;\n</code></pre>\n\n<p>In the code I then set the <code>HasDiscount</code> property of the control to a boolean, which decides which clause is rendered. </p>\n\n<p>The big difference from Rob's solution, is that the clauses within the control really can hold arbitrary HTML/ASPX code.</p>\n\n<p>And here is the code for the control:</p>\n\n<pre><code>using System.ComponentModel;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\n\nnamespace WebUtilities\n{\n [ToolboxData(\"&lt;{0}:PriceInfo runat=server&gt;&lt;/{0}:PriceInfo&gt;\")]\n public class PriceInfo : WebControl, INamingContainer\n {\n private readonly Control ifDiscountControl = new Control();\n private readonly Control ifNotDiscountControl = new Control();\n\n public bool HasDiscount { get; set; }\n\n [PersistenceMode(PersistenceMode.InnerProperty)]\n [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\n public Control IfDiscount\n {\n get { return ifDiscountControl; }\n }\n\n [PersistenceMode(PersistenceMode.InnerProperty)]\n [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\n public Control IfNotDiscount\n {\n get { return ifNotDiscountControl; }\n }\n\n public override void RenderControl(HtmlTextWriter writer)\n {\n if (HasDiscount)\n ifDiscountControl.RenderControl(writer);\n else\n ifNotDiscountControl.RenderControl(writer);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 24000778, "author": "drzaus", "author_id": 1037948, "author_profile": "https://Stackoverflow.com/users/1037948", "pm_score": 2, "selected": false, "text": "<p>I ended up with something very similar to the answer by <a href=\"https://stackoverflow.com/a/121007/1037948\">Rob</a> (in <a href=\"http://web.archive.org/web/20120912013710/http://www.robertwray.co.uk/blog/2008/02/describing-aspnet-control-properties-declaratively.html\" rel=\"nofollow noreferrer\">wayback archive</a>) <a href=\"https://stackoverflow.com/a/1102226/1037948\">@gudmundur-h</a>, but I used <code>ITemplate</code> to get rid of that annoying \"You can't place content between X tags\" in the usage. I'm not entirely sure what is actually required or not, so it's all here just in case.</p>\n\n<h2>The partial/user control markup: <code>mycontrol.ascx</code></h2>\n\n<p>Note the important bits: <code>plcChild1</code> and <code>plcChild2</code>.</p>\n\n<pre><code>&lt;!-- markup, controls, etc --&gt;\n&lt;div class=\"shell\"&gt;\n &lt;!-- etc --&gt;\n\n &lt;!-- optional content with default, will map to `ChildContentOne` --&gt;\n &lt;asp:PlaceHolder ID=\"plcChild1\" runat=\"server\"&gt;\n Some default content in the first child.\n Will show this unless overwritten.\n Include HTML, controls, whatever.\n &lt;/asp:PlaceHolder&gt;\n\n &lt;!-- etc --&gt;\n\n &lt;!-- optional content, no default, will map to `ChildContentTwo` --&gt;\n &lt;asp:PlaceHolder ID=\"plcChild2\" runat=\"server\"&gt;&lt;/asp:PlaceHolder&gt;\n\n&lt;/div&gt;\n</code></pre>\n\n<h2>The partial/user control codebehind: <code>mycontrol.ascx.cs</code></h2>\n\n<pre><code>[ParseChildren(true), PersistChildren(true)]\n[ToolboxData(false /* don't care about drag-n-drop */)]\npublic partial class MyControlWithNestedContent: System.Web.UI.UserControl, INamingContainer {\n // expose properties as attributes, etc\n\n /// &lt;summary&gt;\n /// \"attach\" template to child controls\n /// &lt;/summary&gt;\n /// &lt;param name=\"template\"&gt;the exposed markup \"property\"&lt;/param&gt;\n /// &lt;param name=\"control\"&gt;the actual rendered control&lt;/param&gt;\n protected virtual void attachContent(ITemplate template, Control control) {\n if(null != template) template.InstantiateIn(control);\n }\n\n [PersistenceMode(PersistenceMode.InnerProperty),\n DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\n public virtual ITemplate ChildContentOne { get; set; }\n\n [PersistenceMode(PersistenceMode.InnerProperty), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\n public virtual ITemplate ChildContentTwo { get; set; }\n\n protected override void CreateChildControls() {\n // clear stuff, other setup, etc\n // needed?\n base.CreateChildControls();\n\n this.EnsureChildControls(); // cuz...we want them?\n\n // using the templates, set up the appropriate child controls\n attachContent(this.ChildContentOne, this.plcChild1);\n attachContent(this.ChildContentTwo, this.plcChild2);\n }\n}\n</code></pre>\n\n<p>Important bits (?):</p>\n\n<ul>\n<li><code>ParseChildren</code> -- so stuff <a href=\"http://msdn.microsoft.com/en-us/library/aa310907(v=vs.71).aspx\" rel=\"nofollow noreferrer\">shows up</a>?</li>\n<li><code>PersistChildren</code> -- so dynamically created stuff doesn't get reset?</li>\n<li><code>PersistenceMode(PersistenceMode.InnerProperty)</code> -- so controls are <a href=\"http://msdn.microsoft.com/en-us/library/aa479300.aspx#ccc-templ_topic7\" rel=\"nofollow noreferrer\">parsed correctly</a></li>\n<li><code>DesignerSerializationVisibility(DesignerSerializationVisibility.Content)</code> -- ditto?</li>\n</ul>\n\n<h2>The control usage</h2>\n\n<pre><code>&lt;%@ Register Src=\"~/App_Controls/MyStuff/mycontrol.ascx\" TagPrefix=\"me\" TagName=\"MyNestedControl\" %&gt;\n\n&lt;me:MyNestedControl SomeProperty=\"foo\" SomethingElse=\"bar\" runat=\"server\" ID=\"meWhatever\"&gt;\n &lt;%-- omit `ChildContentOne` to use default --%&gt;\n &lt;ChildContentTwo&gt;Stuff at the bottom! (not empty anymore)&lt;/ChildContentTwo&gt;\n&lt;/me:MyNestedControl&gt;\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11508/" ]
I'm just getting started with Custom User Controls in C# and I'm wondering if there are any examples out there of how to write one which accepts nested tags? For example, when you create an `asp:repeater` you can add a nested tag for `itemtemplate`.
I wrote a [blog post](https://robertwray.co.uk/blog/describing-asp-net-control-properties-declaratively) about this some time ago. In brief, if you had a control with the following markup: ``` <Abc:CustomControlUno runat="server" ID="Control1"> <Children> <Abc:Control1Child IntegerProperty="1" /> </Children> </Abc:CustomControlUno> ``` You'd need the code in the control to be along the lines of: ``` [ParseChildren(true)] [PersistChildren(true)] [ToolboxData("<{0}:CustomControlUno runat=server></{0}:CustomControlUno>")] public class CustomControlUno : WebControl, INamingContainer { private Control1ChildrenCollection _children; [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public Control1ChildrenCollection Children { get { if (_children == null) { _children = new Control1ChildrenCollection(); } return _children; } } } public class Control1ChildrenCollection : List<Control1Child> { } public class Control1Child { public int IntegerProperty { get; set; } } ```
121,000
<p>I'm trying to create an Extension Method for MVC's htmlHelper. The purpose is to enable or disable an ActionLink based on the AuthorizeAttribute set on the controller/action. Borrowing from the <a href="http://blog.maartenballiauw.be/post/2008/08/29/Building-an-ASPNET-MVC-sitemap-provider-with-security-trimming.aspx" rel="nofollow noreferrer">MVCSitemap</a><br> code that Maarten Balliauw created, I wanted to validate the user's permissions against the controller/action before deciding how to render the actionlink. When I try to get the MvcHandler, I get a null value. Is there a better way to the the attributes for the controller/action?</p> <p>Here is the code for the extension method:</p> <pre><code>public static class HtmlHelperExtensions { public static string SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller) { //simplified for brevity if (IsAccessibleToUser(action, controller)) { return htmlHelper.ActionLink(linkText, action,controller); } else { return String.Format("&lt;span&gt;{0}&lt;/span&gt;",linkText); } } public static bool IsAccessibleToUser(string action, string controller) { HttpContext context = HttpContext.Current; MvcHandler handler = context.Handler as MvcHandler; IController verifyController = ControllerBuilder .Current .GetControllerFactory() .CreateController(handler.RequestContext, controller); object[] controllerAttributes = verifyController.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true); object[] actionAttributes = verifyController.GetType().GetMethod(action).GetCustomAttributes(typeof(AuthorizeAttribute), true); if (controllerAttributes.Length == 0 &amp;&amp; actionAttributes.Length == 0) return true; IPrincipal principal = handler.RequestContext.HttpContext.User; string roles = ""; string users = ""; if (controllerAttributes.Length &gt; 0) { AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute; roles += attribute.Roles; users += attribute.Users; } if (actionAttributes.Length &gt; 0) { AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute; roles += attribute.Roles; users += attribute.Users; } if (string.IsNullOrEmpty(roles) &amp;&amp; string.IsNullOrEmpty(users) &amp;&amp; principal.Identity.IsAuthenticated) return true; string[] roleArray = roles.Split(','); string[] usersArray = users.Split(','); foreach (string role in roleArray) { if (role != "*" &amp;&amp; !principal.IsInRole(role)) return false; } foreach (string user in usersArray) { if (user != "*" &amp;&amp; (principal.Identity.Name == "" || principal.Identity.Name != user)) return false; } return true; } } </code></pre>
[ { "answer_id": 121353, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 0, "selected": false, "text": "<p>Your ViewPage has a reference to the view context, so you could make it an extension method on that instead.</p>\n\n<p>Then you can just say if Request.IsAuthenticated or Request.User.IsInRole(...)</p>\n\n<p>usage would be like <code>&lt;%= this.SecurityLink(text, demandRole, controller, action, values) %&gt;</code></p>\n" }, { "answer_id": 227890, "author": "Robert Dean", "author_id": 3396, "author_profile": "https://Stackoverflow.com/users/3396", "pm_score": 3, "selected": true, "text": "<p>Here is the working code:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Security.Principal;\nusing System.Web.Routing;\nusing System.Web.Mvc;\nusing System.Collections;\nusing System.Reflection;\nnamespace System.Web.Mvc.Html\n{\n public static class HtmlHelperExtensions\n {\n public static string SecurityTrimmedActionLink(\n this HtmlHelper htmlHelper,\n string linkText,\n string action,\n string controller)\n {\n return SecurityTrimmedActionLink(htmlHelper, linkText, action, controller, false);\n }\n public static string SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller, bool showDisabled)\n {\n if (IsAccessibleToUser(action, controller))\n {\n return htmlHelper.ActionLink(linkText, action, controller);\n }\n else\n {\n return showDisabled ? String.Format(\"&lt;span&gt;{0}&lt;/span&gt;\", linkText) : \"\";\n }\n }\n public static bool IsAccessibleToUser(string actionAuthorize, string controllerAuthorize)\n {\n Assembly assembly = Assembly.GetExecutingAssembly();\n GetControllerType(controllerAuthorize);\n Type controllerType = GetControllerType(controllerAuthorize);\n var controller = (IController)Activator.CreateInstance(controllerType);\n ArrayList controllerAttributes = new ArrayList(controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true));\n ArrayList actionAttributes = new ArrayList();\n MethodInfo[] methods = controller.GetType().GetMethods();\n foreach (MethodInfo method in methods)\n {\n object[] attributes = method.GetCustomAttributes(typeof(ActionNameAttribute), true);\n if ((attributes.Length == 0 &amp;&amp; method.Name == actionAuthorize) || (attributes.Length &gt; 0 &amp;&amp; ((ActionNameAttribute)attributes[0]).Name == actionAuthorize))\n {\n actionAttributes.AddRange(method.GetCustomAttributes(typeof(AuthorizeAttribute), true));\n }\n }\n if (controllerAttributes.Count == 0 &amp;&amp; actionAttributes.Count == 0)\n return true;\n\n IPrincipal principal = HttpContext.Current.User;\n string roles = \"\";\n string users = \"\";\n if (controllerAttributes.Count &gt; 0)\n {\n AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute;\n roles += attribute.Roles;\n users += attribute.Users;\n }\n if (actionAttributes.Count &gt; 0)\n {\n AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute;\n roles += attribute.Roles;\n users += attribute.Users;\n }\n\n if (string.IsNullOrEmpty(roles) &amp;&amp; string.IsNullOrEmpty(users) &amp;&amp; principal.Identity.IsAuthenticated)\n return true;\n\n string[] roleArray = roles.Split(',');\n string[] usersArray = users.Split(',');\n foreach (string role in roleArray)\n {\n if (role == \"*\" || principal.IsInRole(role))\n return true;\n }\n foreach (string user in usersArray)\n {\n if (user == \"*\" &amp;&amp; (principal.Identity.Name == user))\n return true;\n }\n return false;\n }\n\n public static Type GetControllerType(string controllerName)\n {\n Assembly assembly = Assembly.GetExecutingAssembly();\n foreach (Type type in assembly.GetTypes())\n {\n if (type.BaseType.Name == \"Controller\" &amp;&amp; (type.Name.ToUpper() == (controllerName.ToUpper() + \"Controller\".ToUpper())))\n {\n return type;\n }\n }\n return null;\n }\n }\n}\n</code></pre>\n\n<p>I don't like using reflection, but I can't get to the ControllerTypeCache. </p>\n" }, { "answer_id": 32997392, "author": "viggity", "author_id": 4572, "author_profile": "https://Stackoverflow.com/users/4572", "pm_score": 0, "selected": false, "text": "<p>I really liked the code from @Robert's post, but there were a few bugs and I wanted to cache the gathering of the roles and users because reflection can be a little time costly.</p>\n\n<p>Bugs fixed: if there is both a Controller attribute and an Action attribute, then when the roles get concatenated, an extra comma doesn't get inserted between the controller's roles and the action's roles which will not get analyzed correctly.</p>\n\n<pre><code>[Authorize(Roles = \"SuperAdmin,Executives\")]\npublic class SomeController() {\n [Authorize(Roles = \"Accounting\")] \n public ActionResult Stuff() {\n }\n}\n</code></pre>\n\n<p>then the roles string ends up being <code>SuperAdmin,ExecutivesAccounting</code>, my version ensures that Executives and Accounting is separate. </p>\n\n<p>My new code also ignores Auth on HttpPost actions because that could throw things off, albeit unlikely.</p>\n\n<p>Lastly, it returns <code>MvcHtmlString</code> instead of <code>string</code> for newer versions of MVC</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Reflection;\nusing System.Collections;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Html;\nusing System.Security.Principal;\n\n\npublic static class HtmlHelperExtensions\n{\n /// &lt;summary&gt;\n /// only show links the user has access to\n /// &lt;/summary&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static MvcHtmlString SecurityLink(this HtmlHelper htmlHelper, string linkText, string action, string controller, bool showDisabled = false)\n {\n if (IsAccessibleToUser(action, controller))\n {\n return htmlHelper.ActionLink(linkText, action, controller);\n }\n else\n {\n return new MvcHtmlString(showDisabled ? String.Format(\"&lt;span&gt;{0}&lt;/span&gt;\", linkText) : \"\");\n }\n }\n\n /// &lt;summary&gt;\n /// reflection can be kinda slow, lets cache auth info\n /// &lt;/summary&gt;\n private static Dictionary&lt;string, Tuple&lt;string[], string[]&gt;&gt; _controllerAndActionToRolesAndUsers = new Dictionary&lt;string, Tuple&lt;string[], string[]&gt;&gt;();\n\n\n private static Tuple&lt;string[], string[]&gt; GetAuthRolesAndUsers(string actionName, string controllerName)\n {\n var controllerAndAction = controllerName + \"~~\" + actionName;\n if (_controllerAndActionToRolesAndUsers.ContainsKey(controllerAndAction))\n return _controllerAndActionToRolesAndUsers[controllerAndAction];\n\n Type controllerType = GetControllerType(controllerName);\n MethodInfo matchingMethodInfo = null;\n\n foreach (MethodInfo method in controllerType.GetMethods())\n {\n if (method.GetCustomAttributes(typeof(HttpPostAttribute), true).Any())\n continue;\n if (method.GetCustomAttributes(typeof(HttpPutAttribute), true).Any())\n continue;\n if (method.GetCustomAttributes(typeof(HttpDeleteAttribute), true).Any())\n continue;\n\n var actionNameAttr = method.GetCustomAttributes(typeof(ActionNameAttribute), true).Cast&lt;ActionNameAttribute&gt;().FirstOrDefault();\n if ((actionNameAttr == null &amp;&amp; method.Name == actionName) || (actionNameAttr != null &amp;&amp; actionNameAttr.Name == actionName))\n {\n matchingMethodInfo = method;\n }\n }\n\n if (matchingMethodInfo == null)\n return new Tuple&lt;string[], string[]&gt;(new string[0], new string[0]);\n\n var authAttrs = new List&lt;AuthorizeAttribute&gt;();\n authAttrs.AddRange(controllerType.GetCustomAttributes(typeof(AuthorizeAttribute), true).Cast&lt;AuthorizeAttribute&gt;());\n\n var roles = new List&lt;string&gt;();\n var users = new List&lt;string&gt;();\n\n foreach(var authAttr in authAttrs)\n {\n roles.AddRange(authAttr.Roles.Split(','));\n users.AddRange(authAttr.Roles.Split(','));\n }\n\n var rolesAndUsers = new Tuple&lt;string[], string[]&gt;(roles.ToArray(), users.ToArray());\n try\n {\n _controllerAndActionToRolesAndUsers.Add(controllerAndAction, rolesAndUsers);\n }\n catch (System.ArgumentException ex)\n {\n //possible but unlikely that two threads hit this code at the exact same time and enter a race condition\n //instead of using a mutex, we'll just swallow the exception when the method gets added to dictionary \n //for the second time. mutex only allow single worker regardless of which action method they're getting\n //auth for. doing it this way eliminates permanent bottleneck in favor of a once in a bluemoon time hit\n }\n\n return rolesAndUsers;\n }\n\n public static bool IsAccessibleToUser(string actionName, string controllerName)\n {\n var rolesAndUsers = GetAuthRolesAndUsers(actionName, controllerName);\n var roles = rolesAndUsers.Item1;\n var users = rolesAndUsers.Item2;\n\n IPrincipal principal = HttpContext.Current.User;\n\n if (!roles.Any() &amp;&amp; !users.Any() &amp;&amp; principal.Identity.IsAuthenticated)\n return true;\n\n\n foreach (string role in roles)\n {\n if (role == \"*\" || principal.IsInRole(role))\n return true;\n }\n foreach (string user in users)\n {\n if (user == \"*\" &amp;&amp; (principal.Identity.Name == user))\n return true;\n }\n\n return false;\n }\n\n public static Type GetControllerType(string controllerName)\n {\n Assembly assembly = Assembly.GetExecutingAssembly();\n foreach (Type type in assembly.GetTypes())\n {\n if (type.BaseType.Name == \"Controller\" &amp;&amp; (type.Name.ToUpper() == (controllerName.ToUpper() + \"Controller\".ToUpper())))\n {\n return type;\n }\n }\n return null;\n }\n\n\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3396/" ]
I'm trying to create an Extension Method for MVC's htmlHelper. The purpose is to enable or disable an ActionLink based on the AuthorizeAttribute set on the controller/action. Borrowing from the [MVCSitemap](http://blog.maartenballiauw.be/post/2008/08/29/Building-an-ASPNET-MVC-sitemap-provider-with-security-trimming.aspx) code that Maarten Balliauw created, I wanted to validate the user's permissions against the controller/action before deciding how to render the actionlink. When I try to get the MvcHandler, I get a null value. Is there a better way to the the attributes for the controller/action? Here is the code for the extension method: ``` public static class HtmlHelperExtensions { public static string SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller) { //simplified for brevity if (IsAccessibleToUser(action, controller)) { return htmlHelper.ActionLink(linkText, action,controller); } else { return String.Format("<span>{0}</span>",linkText); } } public static bool IsAccessibleToUser(string action, string controller) { HttpContext context = HttpContext.Current; MvcHandler handler = context.Handler as MvcHandler; IController verifyController = ControllerBuilder .Current .GetControllerFactory() .CreateController(handler.RequestContext, controller); object[] controllerAttributes = verifyController.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true); object[] actionAttributes = verifyController.GetType().GetMethod(action).GetCustomAttributes(typeof(AuthorizeAttribute), true); if (controllerAttributes.Length == 0 && actionAttributes.Length == 0) return true; IPrincipal principal = handler.RequestContext.HttpContext.User; string roles = ""; string users = ""; if (controllerAttributes.Length > 0) { AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute; roles += attribute.Roles; users += attribute.Users; } if (actionAttributes.Length > 0) { AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute; roles += attribute.Roles; users += attribute.Users; } if (string.IsNullOrEmpty(roles) && string.IsNullOrEmpty(users) && principal.Identity.IsAuthenticated) return true; string[] roleArray = roles.Split(','); string[] usersArray = users.Split(','); foreach (string role in roleArray) { if (role != "*" && !principal.IsInRole(role)) return false; } foreach (string user in usersArray) { if (user != "*" && (principal.Identity.Name == "" || principal.Identity.Name != user)) return false; } return true; } } ```
Here is the working code: ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Security.Principal; using System.Web.Routing; using System.Web.Mvc; using System.Collections; using System.Reflection; namespace System.Web.Mvc.Html { public static class HtmlHelperExtensions { public static string SecurityTrimmedActionLink( this HtmlHelper htmlHelper, string linkText, string action, string controller) { return SecurityTrimmedActionLink(htmlHelper, linkText, action, controller, false); } public static string SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller, bool showDisabled) { if (IsAccessibleToUser(action, controller)) { return htmlHelper.ActionLink(linkText, action, controller); } else { return showDisabled ? String.Format("<span>{0}</span>", linkText) : ""; } } public static bool IsAccessibleToUser(string actionAuthorize, string controllerAuthorize) { Assembly assembly = Assembly.GetExecutingAssembly(); GetControllerType(controllerAuthorize); Type controllerType = GetControllerType(controllerAuthorize); var controller = (IController)Activator.CreateInstance(controllerType); ArrayList controllerAttributes = new ArrayList(controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true)); ArrayList actionAttributes = new ArrayList(); MethodInfo[] methods = controller.GetType().GetMethods(); foreach (MethodInfo method in methods) { object[] attributes = method.GetCustomAttributes(typeof(ActionNameAttribute), true); if ((attributes.Length == 0 && method.Name == actionAuthorize) || (attributes.Length > 0 && ((ActionNameAttribute)attributes[0]).Name == actionAuthorize)) { actionAttributes.AddRange(method.GetCustomAttributes(typeof(AuthorizeAttribute), true)); } } if (controllerAttributes.Count == 0 && actionAttributes.Count == 0) return true; IPrincipal principal = HttpContext.Current.User; string roles = ""; string users = ""; if (controllerAttributes.Count > 0) { AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute; roles += attribute.Roles; users += attribute.Users; } if (actionAttributes.Count > 0) { AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute; roles += attribute.Roles; users += attribute.Users; } if (string.IsNullOrEmpty(roles) && string.IsNullOrEmpty(users) && principal.Identity.IsAuthenticated) return true; string[] roleArray = roles.Split(','); string[] usersArray = users.Split(','); foreach (string role in roleArray) { if (role == "*" || principal.IsInRole(role)) return true; } foreach (string user in usersArray) { if (user == "*" && (principal.Identity.Name == user)) return true; } return false; } public static Type GetControllerType(string controllerName) { Assembly assembly = Assembly.GetExecutingAssembly(); foreach (Type type in assembly.GetTypes()) { if (type.BaseType.Name == "Controller" && (type.Name.ToUpper() == (controllerName.ToUpper() + "Controller".ToUpper()))) { return type; } } return null; } } } ``` I don't like using reflection, but I can't get to the ControllerTypeCache.
121,025
<p>How do I get the modified date/time of a file in Python?</p>
[ { "answer_id": 121030, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 6, "selected": true, "text": "<pre><code>os.path.getmtime(filepath)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>os.stat(filepath).st_mtime\n</code></pre>\n" }, { "answer_id": 6110132, "author": "Dingo", "author_id": 291667, "author_profile": "https://Stackoverflow.com/users/291667", "pm_score": 4, "selected": false, "text": "<p>Formated:</p>\n\n<pre><code>import time\nprint time.strftime(\"%m/%d/%Y %I:%M:%S %p\",time.localtime(os.path.getmtime(fname)))\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ]
How do I get the modified date/time of a file in Python?
``` os.path.getmtime(filepath) ``` or ``` os.stat(filepath).st_mtime ```
121,059
<p>What is the best way to divide a 32 bit integer into four (unsigned) chars in C#.</p>
[ { "answer_id": 121089, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 2, "selected": false, "text": "<p>It's not clear if this is really what you want, but:</p>\n\n<pre><code>int x = yourNumber();\nchar a = (char)(x &amp; 0xff);\nchar b = (char)((x &gt;&gt; 8) &amp; 0xff);\nchar c = (char)((x &gt;&gt; 16) &amp; 0xff);\nchar d = (char)((x &gt;&gt; 24) &amp; 0xff);\n</code></pre>\n\n<p>This assumes you want the bytes interpreted as the lowest range of Unicode characters.</p>\n" }, { "answer_id": 121093, "author": "Matthias Meid", "author_id": 17713, "author_profile": "https://Stackoverflow.com/users/17713", "pm_score": 0, "selected": false, "text": "<p>Do get the 8-byte-blocks:</p>\n\n<pre><code>int a = i &amp; 255; // bin 11111111\nint b = i &amp; 65280; // bin 1111111100000000\n</code></pre>\n\n<p>Do break the first three bytes down into a single byte, just divide them by the proper number and perform another logical and to get your final byte.</p>\n\n<p>Edit: Jason's solution with the bitshifts is much nicer of course.</p>\n" }, { "answer_id": 121106, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 3, "selected": false, "text": "<p>Char? Maybe you are looking for this handy little helper function?</p>\n\n<pre><code>Byte[] b = BitConverter.GetBytes(i);\nChar c = (Char)b[0];\n[...]\n</code></pre>\n" }, { "answer_id": 121107, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 4, "selected": true, "text": "<p>Quick'n'dirty:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>int value = 0x48454C4F;\nConsole.WriteLine(Encoding.ASCII.GetString(\n BitConverter.GetBytes(value).Reverse().ToArray()\n));\n</code></pre>\n<p>Converting the int to bytes, reversing the byte-array for the correct order and then getting the ASCII character representation from it.</p>\n<p>EDIT: The <code>Reverse</code> method is an extension method from .NET 3.5, just for info. Reversing the byte order may also not be needed in your scenario.</p>\n" }, { "answer_id": 121121, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 0, "selected": false, "text": "<p>.net uses Unicode, a char is 2 bytes not 1</p>\n\n<p>To convert between binary data containing non-unicode text use the System.Text.Encoding class.</p>\n\n<p>If you do want 4 bytes and not chars then replace the char with byte in Jason's answer</p>\n" }, { "answer_id": 121332, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 2, "selected": false, "text": "<p>I have tried it a few ways and clocked the time taken to convert 1000000 ints.</p>\n\n<p>Built-in convert method, 325000 ticks:</p>\n\n<pre><code>Encoding.ASCII.GetChars(BitConverter.GetBytes(x));\n</code></pre>\n\n<p>Pointer conversion, 100000 ticks:</p>\n\n<pre><code>static unsafe char[] ToChars(int x)\n{\n byte* p = (byte*)&amp;x)\n char[] chars = new char[4];\n chars[0] = (char)*p++;\n chars[1] = (char)*p++;\n chars[2] = (char)*p++;\n chars[3] = (char)*p;\n\n return chars;\n}\n</code></pre>\n\n<p>Bitshifting, 77000 ticks:</p>\n\n<pre><code>public static char[] ToCharsBitShift(int x)\n{\n char[] chars = new char[4];\n chars[0] = (char)(x &amp; 0xFF);\n chars[1] = (char)(x &gt;&gt; 8 &amp; 0xFF);\n chars[2] = (char)(x &gt;&gt; 16 &amp; 0xFF);\n chars[3] = (char)(x &gt;&gt; 24 &amp; 0xFF);\n return chars;\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14759/" ]
What is the best way to divide a 32 bit integer into four (unsigned) chars in C#.
Quick'n'dirty: ```csharp int value = 0x48454C4F; Console.WriteLine(Encoding.ASCII.GetString( BitConverter.GetBytes(value).Reverse().ToArray() )); ``` Converting the int to bytes, reversing the byte-array for the correct order and then getting the ASCII character representation from it. EDIT: The `Reverse` method is an extension method from .NET 3.5, just for info. Reversing the byte order may also not be needed in your scenario.
121,063
<p>I've recently acquired a second monitor and now run VS2008 SP1 maximized on my secondary (and bigger) monitor. This theoretically has the benefit of opening the application under development on the primary monitor, where -- as it seems to me -- all newly started applications go. So far, so good. The problem though is now, that the exception helper popup is <strong>not</strong> opened on the secondary monitor. Even worse, it is <strong>only</strong> shown when the Studio window is far enough on the primary monitor! If I drag the studio with an opened exception helper from the primary to the secondary monitor, the helper is dragged with the window until it hits the border between the two monitors, where it suddenly <strong>disappears</strong>.</p> <p>Has somebody experienced this too? Is there any workaround? Anything else I should try?</p>
[ { "answer_id": 121089, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 2, "selected": false, "text": "<p>It's not clear if this is really what you want, but:</p>\n\n<pre><code>int x = yourNumber();\nchar a = (char)(x &amp; 0xff);\nchar b = (char)((x &gt;&gt; 8) &amp; 0xff);\nchar c = (char)((x &gt;&gt; 16) &amp; 0xff);\nchar d = (char)((x &gt;&gt; 24) &amp; 0xff);\n</code></pre>\n\n<p>This assumes you want the bytes interpreted as the lowest range of Unicode characters.</p>\n" }, { "answer_id": 121093, "author": "Matthias Meid", "author_id": 17713, "author_profile": "https://Stackoverflow.com/users/17713", "pm_score": 0, "selected": false, "text": "<p>Do get the 8-byte-blocks:</p>\n\n<pre><code>int a = i &amp; 255; // bin 11111111\nint b = i &amp; 65280; // bin 1111111100000000\n</code></pre>\n\n<p>Do break the first three bytes down into a single byte, just divide them by the proper number and perform another logical and to get your final byte.</p>\n\n<p>Edit: Jason's solution with the bitshifts is much nicer of course.</p>\n" }, { "answer_id": 121106, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 3, "selected": false, "text": "<p>Char? Maybe you are looking for this handy little helper function?</p>\n\n<pre><code>Byte[] b = BitConverter.GetBytes(i);\nChar c = (Char)b[0];\n[...]\n</code></pre>\n" }, { "answer_id": 121107, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 4, "selected": true, "text": "<p>Quick'n'dirty:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>int value = 0x48454C4F;\nConsole.WriteLine(Encoding.ASCII.GetString(\n BitConverter.GetBytes(value).Reverse().ToArray()\n));\n</code></pre>\n<p>Converting the int to bytes, reversing the byte-array for the correct order and then getting the ASCII character representation from it.</p>\n<p>EDIT: The <code>Reverse</code> method is an extension method from .NET 3.5, just for info. Reversing the byte order may also not be needed in your scenario.</p>\n" }, { "answer_id": 121121, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 0, "selected": false, "text": "<p>.net uses Unicode, a char is 2 bytes not 1</p>\n\n<p>To convert between binary data containing non-unicode text use the System.Text.Encoding class.</p>\n\n<p>If you do want 4 bytes and not chars then replace the char with byte in Jason's answer</p>\n" }, { "answer_id": 121332, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 2, "selected": false, "text": "<p>I have tried it a few ways and clocked the time taken to convert 1000000 ints.</p>\n\n<p>Built-in convert method, 325000 ticks:</p>\n\n<pre><code>Encoding.ASCII.GetChars(BitConverter.GetBytes(x));\n</code></pre>\n\n<p>Pointer conversion, 100000 ticks:</p>\n\n<pre><code>static unsafe char[] ToChars(int x)\n{\n byte* p = (byte*)&amp;x)\n char[] chars = new char[4];\n chars[0] = (char)*p++;\n chars[1] = (char)*p++;\n chars[2] = (char)*p++;\n chars[3] = (char)*p;\n\n return chars;\n}\n</code></pre>\n\n<p>Bitshifting, 77000 ticks:</p>\n\n<pre><code>public static char[] ToCharsBitShift(int x)\n{\n char[] chars = new char[4];\n chars[0] = (char)(x &amp; 0xFF);\n chars[1] = (char)(x &gt;&gt; 8 &amp; 0xFF);\n chars[2] = (char)(x &gt;&gt; 16 &amp; 0xFF);\n chars[3] = (char)(x &gt;&gt; 24 &amp; 0xFF);\n return chars;\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4918/" ]
I've recently acquired a second monitor and now run VS2008 SP1 maximized on my secondary (and bigger) monitor. This theoretically has the benefit of opening the application under development on the primary monitor, where -- as it seems to me -- all newly started applications go. So far, so good. The problem though is now, that the exception helper popup is **not** opened on the secondary monitor. Even worse, it is **only** shown when the Studio window is far enough on the primary monitor! If I drag the studio with an opened exception helper from the primary to the secondary monitor, the helper is dragged with the window until it hits the border between the two monitors, where it suddenly **disappears**. Has somebody experienced this too? Is there any workaround? Anything else I should try?
Quick'n'dirty: ```csharp int value = 0x48454C4F; Console.WriteLine(Encoding.ASCII.GetString( BitConverter.GetBytes(value).Reverse().ToArray() )); ``` Converting the int to bytes, reversing the byte-array for the correct order and then getting the ASCII character representation from it. EDIT: The `Reverse` method is an extension method from .NET 3.5, just for info. Reversing the byte order may also not be needed in your scenario.
121,066
<p>I want to attach a click event to a button element and then later remove it, but I can't get <code>unclick()</code> or <code>unbind()</code> event(s) to work as expected. In the code below, the button is <code>tan</code> colour and the click event works.</p> <pre><code>window.onload = init; function init() { $("#startButton").css('background-color', 'beige').click(process_click); $("#startButton").css('background-color', 'tan').unclick(); } </code></pre> <p>How can I remove events from my elements?</p>
[ { "answer_id": 121084, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 2, "selected": false, "text": "<p>unbind is your friend.</p>\n\n<pre><code>$(\"#startButton\").unbind('click')\n</code></pre>\n" }, { "answer_id": 121142, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 5, "selected": true, "text": "<p>There's no such thing as <code>unclick()</code>. Where did you get that from?</p>\n\n<p>You can remove individual event handlers from an element by calling unbind:</p>\n\n<pre><code>$(\"#startButton\").unbind(\"click\", process_click);\n</code></pre>\n\n<p>If you want to remove all handlers, or you used an anonymous function as a handler, you can omit the second argument to <code>unbind()</code>:</p>\n\n<pre><code>$(\"#startButton\").unbind(\"click\");\n</code></pre>\n" }, { "answer_id": 121872, "author": "Filini", "author_id": 21162, "author_profile": "https://Stackoverflow.com/users/21162", "pm_score": 0, "selected": false, "text": "<p>Are you sure you want to unbind it? What if later on you want to bind it again, and again, and again? I don't like dynamic event-handling bind/unbind, since they tend to get out of hand, when called from different points of your code.</p>\n\n<p>You may want to consider alternate options:</p>\n\n<ul>\n<li>change the button \"disabled\" property</li>\n<li>implement your logic inside \"process_click\" function</li>\n</ul>\n\n<p>Just my 2 cents, not an universal solution.</p>\n" }, { "answer_id": 3719001, "author": "alessioalex", "author_id": 405799, "author_profile": "https://Stackoverflow.com/users/405799", "pm_score": 3, "selected": false, "text": "<p>Or you could have a situation where you want to unbind the click function just after you use it, like I had to:</p>\n\n<pre><code>$('#selector').click(function(event){\n alert(1);\n $(this).unbind(event);\n});\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
I want to attach a click event to a button element and then later remove it, but I can't get `unclick()` or `unbind()` event(s) to work as expected. In the code below, the button is `tan` colour and the click event works. ``` window.onload = init; function init() { $("#startButton").css('background-color', 'beige').click(process_click); $("#startButton").css('background-color', 'tan').unclick(); } ``` How can I remove events from my elements?
There's no such thing as `unclick()`. Where did you get that from? You can remove individual event handlers from an element by calling unbind: ``` $("#startButton").unbind("click", process_click); ``` If you want to remove all handlers, or you used an anonymous function as a handler, you can omit the second argument to `unbind()`: ``` $("#startButton").unbind("click"); ```
121,116
<p>I have a managed DLL (written in C++/CLI) that contains a class used by a C# executable. In the constructor of the class, I need to get access to the full path of the executable referencing the DLL. In the actual app I know I can use the Application object to do this, but how can I do it from a managed DLL?</p>
[ { "answer_id": 121137, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 5, "selected": true, "text": "<pre><code>Assembly.GetCallingAssembly()\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Assembly.GetExecutingAssembly()\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Assembly.GetEntryAssembly()\n</code></pre>\n\n<p>Depending on your need.</p>\n\n<p>Then use Location or CodeBase property (I never remember which one).</p>\n" }, { "answer_id": 121725, "author": "Brian Stewart", "author_id": 3114, "author_profile": "https://Stackoverflow.com/users/3114", "pm_score": 3, "selected": false, "text": "<p>@leppie: Thanks - that was the pointer I needed. </p>\n\n<p>For future reference, in C++/CLI this is the actual syntax that works:</p>\n\n<pre><code>String^ appPathString = Assembly::GetEntryAssembly()-&gt;Location;\n</code></pre>\n\n<p><code>GetExecutingAssembly()</code> provided the name of the DLL</p>\n\n<p><code>GetCallingAssembly()</code> returned something like System.Windows.Forms</p>\n\n<p><code>GetEntryAssembly</code> returned the full path, similar to <code>GetModulePath()</code> under Win32.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114/" ]
I have a managed DLL (written in C++/CLI) that contains a class used by a C# executable. In the constructor of the class, I need to get access to the full path of the executable referencing the DLL. In the actual app I know I can use the Application object to do this, but how can I do it from a managed DLL?
``` Assembly.GetCallingAssembly() ``` or ``` Assembly.GetExecutingAssembly() ``` or ``` Assembly.GetEntryAssembly() ``` Depending on your need. Then use Location or CodeBase property (I never remember which one).
121,117
<p>Are there any good webservices out there that provide good lookup information for Countries and States/Provinces?</p> <p>If so what ones do you use?</p>
[ { "answer_id": 121160, "author": "Owen", "author_id": 2109, "author_profile": "https://Stackoverflow.com/users/2109", "pm_score": 4, "selected": true, "text": "<p>If you only need US information, the US Postal Service provides a set of web services it calls WebTools for this exact thing. <a href=\"https://www.usps.com/business/web-tools-apis/welcome.htm\" rel=\"nofollow noreferrer\">https://www.usps.com/business/web-tools-apis/welcome.htm</a>. You will need to register to be able to use them but once you're registered they are really simple to use. You just send an XML request over HTTP and the server sends an XML response back and you just have to unpack it.</p>\n\n<p>Sample request:</p>\n\n<pre><code>http://SERVERNAME/ShippingAPITest.dll?API=Verify&amp;XML=&lt;AddressValidateRequest%20USERID=\"xxxxxxx\"&gt;&lt;Address ID=\"0\"&gt;&lt;Address1&gt;&lt;/Address1&gt;&lt;Address2&gt;6406 Ivy Lane&lt;/Address2&gt;&lt;City&gt;Greenbelt&lt;/City&gt;&lt;State&gt;MD&lt;/State&gt;&lt;Zip5&gt;&lt;/Zip5&gt;&lt;Zip4&gt;&lt;/Zip4&gt;&lt;/Address&gt;&lt;/AddressValidateRequest&gt;\n</code></pre>\n\n<p>Sample response:</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;AddressValidateResponse&gt;\n &lt;Address ID=\"0\"&gt;\n &lt;Address2&gt;6406 IVY LN&lt;/Address2&gt;\n &lt;City&gt;GREENBELT&lt;/City&gt;\n &lt;State&gt;MD&lt;/State&gt;\n &lt;Zip5&gt;20770&lt;/Zip5&gt;\n &lt;Zip4&gt;1441&lt;/Zip4&gt;\n &lt;/Address&gt;\n&lt;/AddressValidateResponse&gt;\n</code></pre>\n\n<p>Here's a link to the technical documentation: \n<a href=\"https://www.usps.com/business/web-tools-apis/documentation-updates.htm\" rel=\"nofollow noreferrer\">https://www.usps.com/business/web-tools-apis/documentation-updates.htm</a></p>\n" }, { "answer_id": 121188, "author": "Kyle Burton", "author_id": 19784, "author_profile": "https://Stackoverflow.com/users/19784", "pm_score": 1, "selected": false, "text": "<p>A good source of geographic data, including lookups and mapping data for the USA is the US Census Bureau's <a href=\"http://www.census.gov/geo/www/tiger/\" rel=\"nofollow noreferrer\">TIGER Data set</a>. They no longer actively track Zip code data, but they do have a <a href=\"http://www.2010census.biz/geo/www/tiger/zip1999.html\" rel=\"nofollow noreferrer\">1999 vintage file</a> still available.</p>\n\n<p>For countries, the ISO country code list is publicly available.</p>\n\n<p>I'm not aware of resources for information outside the US.</p>\n" }, { "answer_id": 141390, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://www.geonames.org/\" rel=\"noreferrer\">http://www.geonames.org/</a></p>\n\n<p>That's the best one I've found. They let you download and host the web service yourself, which is also nice.</p>\n" }, { "answer_id": 7563476, "author": "cjbarth", "author_id": 271351, "author_profile": "https://Stackoverflow.com/users/271351", "pm_score": 2, "selected": false, "text": "<p>A services that works well with .Net (because it leverages WSDL) is <a href=\"http://www.webservicex.net\" rel=\"nofollow\">http://www.webservicex.net</a>. They have a service for US ZIP codes available at <a href=\"http://www.webservicex.net/uszip.asmx\" rel=\"nofollow\">http://www.webservicex.net/uszip.asmx</a>. You can just add it as a service and Visual Studio will take care of the rest. The response comes as an XML response, so you'll have to parse it, but you can use something simple like <code>USZIP.GetInfoByZIP(ZIP).SelectSingleNode(\"//STATE\").InnerText</code>.</p>\n\n<p>For my application I then built an in-memory cache of the data using XML following these directions: <a href=\"http://www.15seconds.com/issue/010410.htm\" rel=\"nofollow\">http://www.15seconds.com/issue/010410.htm</a>. I used XML instead of a <code>HashTable</code> or <code>Dictionary(TKey, TValue)</code> because I wanted to be able to serialize it to a string so I could save the 'database' as a user setting.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8897/" ]
Are there any good webservices out there that provide good lookup information for Countries and States/Provinces? If so what ones do you use?
If you only need US information, the US Postal Service provides a set of web services it calls WebTools for this exact thing. <https://www.usps.com/business/web-tools-apis/welcome.htm>. You will need to register to be able to use them but once you're registered they are really simple to use. You just send an XML request over HTTP and the server sends an XML response back and you just have to unpack it. Sample request: ``` http://SERVERNAME/ShippingAPITest.dll?API=Verify&XML=<AddressValidateRequest%20USERID="xxxxxxx"><Address ID="0"><Address1></Address1><Address2>6406 Ivy Lane</Address2><City>Greenbelt</City><State>MD</State><Zip5></Zip5><Zip4></Zip4></Address></AddressValidateRequest> ``` Sample response: ``` <?xml version="1.0"?> <AddressValidateResponse> <Address ID="0"> <Address2>6406 IVY LN</Address2> <City>GREENBELT</City> <State>MD</State> <Zip5>20770</Zip5> <Zip4>1441</Zip4> </Address> </AddressValidateResponse> ``` Here's a link to the technical documentation: <https://www.usps.com/business/web-tools-apis/documentation-updates.htm>
121,147
<p>I'd like to be able to determine if a directory such as a '.app' is considered to be a package or bundle from Finder's point of view on the command line. I don't think this would be difficult to do with a small shell program, but I'd rather not re-invent the wheel if I don't have to.</p>
[ { "answer_id": 121181, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": -1, "selected": false, "text": "<p>A bundle should always have a file `./contents/Info.plist'. You can check for the existance of this in a directory, if so then it's a package/bundle.</p>\n" }, { "answer_id": 121703, "author": "Hagelin", "author_id": 5156, "author_profile": "https://Stackoverflow.com/users/5156", "pm_score": 2, "selected": false, "text": "<p>While you can identify some bundles based on the existence of './contents/Info.plist\", it isn't required for all bundle types (e.g. documents and legacy bundles). Finder also identifies a directory as a bundle based on file extension (.app, .bundle, etc) or if the bundle bit is set.</p>\n\n<p>To check the bundle bit from the command line use:</p>\n\n<pre><code>getFileInfo -aB directory_name\n</code></pre>\n\n<p>In order to catch all cases I would check:</p>\n\n<ul>\n<li>Is the bundle bit set?</li>\n<li>If not, does it have a file extension that identifies it as a bundle? (see <a href=\"https://stackoverflow.com/questions/121147/determine-if-a-directory-is-a-bundle-or-package-in-the-mac-os-x-terminal#122426\">Mecki's answer</a>)</li>\n<li>If not, it probably isn't a bundle.</li>\n</ul>\n" }, { "answer_id": 122426, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 3, "selected": true, "text": "<h2>Update:</h2>\n\n<p>On all systems with Spotlight, using <code>mdls</code> you can detect bundles looking at the kMDItemContentTypeTree property. E.g.:</p>\n\n<pre><code>mdls -name kMDItemContentTypeTree \"/Applications/Safari.app\"\n</code></pre>\n\n<p>produces the following output for me</p>\n\n<pre><code>kMDItemContentTypeTree = (\n \"com.apple.application-bundle\",\n \"com.apple.application\",\n \"public.executable\",\n \"com.apple.localizable-name-bundle\",\n \"com.apple.bundle\",\n \"public.directory\",\n \"public.item\",\n \"com.apple.package\"\n)\n</code></pre>\n\n<p>Whenever you see <code>com.apple.package</code> there, it is supposed to be displayed as a package by Finder. Of course, everything with \"bundle\" in the name implies that already but not all packages are bundles (bundles are a specific subset of packages that have a well defined directory structure).</p>\n\n<hr>\n\n<h2>Old Answer:</h2>\n\n<p>You can get a list of all registered file type extensions, using this command (OS X prior to Leopard):</p>\n\n<pre><code>/System/Library/Frameworks/ApplicationServices.framework/Frameworks\\\n/LaunchServices.framework/Support/lsregister -dump\n</code></pre>\n\n<p>or for Leopard and later:</p>\n\n<pre><code>/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks\\\n/LaunchServices.framework/Versions/A/Support/lsregister -dump\n</code></pre>\n\n<p>Every file extension there has flags. If the package flag is set, this is a package.</p>\n\n<p>E.g.</p>\n\n<pre><code> claim id: 806354944\n name: Bundle\n role: none\n flags: apple-internal relative-icon-path package \n icon: Contents/Resources/KEXT.icns\n bindings: .bundle\n --------------------------------------------------------\n claim id: 1276116992\n name: Plug-in\n role: none\n flags: apple-internal relative-icon-path package \n icon: Contents/Resources/KEXT.icns\n bindings: .plugin\n</code></pre>\n\n<p>Compare this to a file that is no bundle</p>\n\n<pre><code> claim id: 2484731904\n name: TEXT\n role: viewer\n flags: apple-internal \n icon: \n bindings: .txt, .text, 'TEXT'\n</code></pre>\n\n<p>The only way to really get all bundles is by looking up in the LaunchService database (the one we dumped above). If you just go by whether it has a plist or not or whether the bundle bit is set or not, you might catch some or even many bundles, but you can't catch all of them. This is the database Finder uses to determine</p>\n\n<ul>\n<li>Is this directory a bundle or not?</li>\n<li>Is this a known file extension or not?</li>\n<li>Which applications should be listed under \"Open With\" for this file type?</li>\n<li>Which icon should I use for displaying this file type?</li>\n</ul>\n\n<p>and some more stuff.</p>\n\n<p>[EDIT: Added path for Leopard, thanks to Hagelin for the update]</p>\n" }, { "answer_id": 742131, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>There ought to be a way to do it easily from the command line, because as an AppleScript user, I can do it using System Events. So if all else fails, you can execute the necessary AppleScript from the command line as follows:</p>\n\n<pre><code>$ FILE=/Users/myuser/Desktop/foo.rtfd\n$ osascript -e \"tell application \\\"System Events\\\" to get package folder of alias POSIX file \\\"${FILE}\\\"\"\n</code></pre>\n\n<p>result is </p>\n\n<pre><code>true\n</code></pre>\n" }, { "answer_id": 742145, "author": "Nicholas Riley", "author_id": 6372, "author_profile": "https://Stackoverflow.com/users/6372", "pm_score": 1, "selected": false, "text": "<p><code>&lt;plug&gt;</code></p>\n\n<p>My <a href=\"http://web.sabi.net/nriley/software/#launch\" rel=\"nofollow noreferrer\">launch</a> tool has a feature for this. For example:</p>\n\n<pre><code>% launch -f Guards.oo3 \nGuards.oo3: non-application package \n type: '' creator: ''\n kind: OmniOutliner 3\n content type ID: com.omnigroup.omnioutliner.oo3-package\n contents: 1 item\n created: 3/6/09 3:36:50 PM\n modified: 3/6/09 4:06:13 PM\n accessed: 4/12/09 1:10:36 PM [only updated by Mac OS X]\n backed up: 12/31/03 6:00:00 PM\n\n% launch -f /Applications/Safari.app\n/Applications/Safari.app: scriptable Mac OS X application package \n type: 'APPL' creator: 'sfri'\n architecture: PowerPC 7400, Intel 80x86\n bundle ID: com.apple.Safari\n version: 4 Public Beta\n kind: Application\n content type ID: com.apple.application-bundle\n contents: 1 item\n created: 8/21/07 5:11:33 PM\n modified: 2/24/09 7:29:51 PM\n accessed: 4/12/09 1:10:51 PM [only updated by Mac OS X]\n backed up: 12/31/03 6:00:00 PM\n</code></pre>\n\n<p>You should be able to get what you want by checking to see if the first line of output ends in 'package'.</p>\n\n<p><code>launch</code> is in Fink and MacPorts too.</p>\n\n<p><code>&lt;/plug&gt;</code></p>\n" }, { "answer_id": 12233785, "author": "Anonymous Coward", "author_id": 1641442, "author_profile": "https://Stackoverflow.com/users/1641442", "pm_score": 3, "selected": false, "text": "<p>This is a bit late, but: it seems you can detect bundles using the mdls command. Specifically, the (multi-line) output of:</p>\n\n<pre><code>mdls -name kMDItemContentTypeTree /Path/To/Directory\n</code></pre>\n\n<p>Will contain the string</p>\n\n<pre><code>\"com.apple.package\"\n</code></pre>\n\n<p>(including the quotation marks, at least as of Lion) somewhere if the directory is a package. If the package is also a bundle, the output will also contain</p>\n\n<pre><code>\"com.apple.bundle\"\n</code></pre>\n\n<p>and, last but not least, if it is specifically an application bundle, the output will also contain</p>\n\n<pre><code>\"com.apple.application-bundle\"\n</code></pre>\n\n<p>(That's according to some very limited testing, but from what Apple's documentation on Uniform Type Identifiers, and the man page for mdls, this should hold true. And for the items I tested, this was true for non-Apple-provided bundles as well, which is what you would expect given the purpose of UTIs.)</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4468/" ]
I'd like to be able to determine if a directory such as a '.app' is considered to be a package or bundle from Finder's point of view on the command line. I don't think this would be difficult to do with a small shell program, but I'd rather not re-invent the wheel if I don't have to.
Update: ------- On all systems with Spotlight, using `mdls` you can detect bundles looking at the kMDItemContentTypeTree property. E.g.: ``` mdls -name kMDItemContentTypeTree "/Applications/Safari.app" ``` produces the following output for me ``` kMDItemContentTypeTree = ( "com.apple.application-bundle", "com.apple.application", "public.executable", "com.apple.localizable-name-bundle", "com.apple.bundle", "public.directory", "public.item", "com.apple.package" ) ``` Whenever you see `com.apple.package` there, it is supposed to be displayed as a package by Finder. Of course, everything with "bundle" in the name implies that already but not all packages are bundles (bundles are a specific subset of packages that have a well defined directory structure). --- Old Answer: ----------- You can get a list of all registered file type extensions, using this command (OS X prior to Leopard): ``` /System/Library/Frameworks/ApplicationServices.framework/Frameworks\ /LaunchServices.framework/Support/lsregister -dump ``` or for Leopard and later: ``` /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks\ /LaunchServices.framework/Versions/A/Support/lsregister -dump ``` Every file extension there has flags. If the package flag is set, this is a package. E.g. ``` claim id: 806354944 name: Bundle role: none flags: apple-internal relative-icon-path package icon: Contents/Resources/KEXT.icns bindings: .bundle -------------------------------------------------------- claim id: 1276116992 name: Plug-in role: none flags: apple-internal relative-icon-path package icon: Contents/Resources/KEXT.icns bindings: .plugin ``` Compare this to a file that is no bundle ``` claim id: 2484731904 name: TEXT role: viewer flags: apple-internal icon: bindings: .txt, .text, 'TEXT' ``` The only way to really get all bundles is by looking up in the LaunchService database (the one we dumped above). If you just go by whether it has a plist or not or whether the bundle bit is set or not, you might catch some or even many bundles, but you can't catch all of them. This is the database Finder uses to determine * Is this directory a bundle or not? * Is this a known file extension or not? * Which applications should be listed under "Open With" for this file type? * Which icon should I use for displaying this file type? and some more stuff. [EDIT: Added path for Leopard, thanks to Hagelin for the update]
121,162
<p>What does the <code>explicit</code> keyword mean in C++?</p>
[ { "answer_id": 121163, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 13, "selected": true, "text": "<p>The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a <strong>single parameter</strong> to convert from one type to another in order to get the right type for a parameter.</p>\n<p>Here's an example class with a constructor that can be used for implicit conversions:</p>\n<pre><code>class Foo\n{\nprivate:\n int m_foo;\n\npublic:\n // single parameter constructor, can be used as an implicit conversion\n Foo (int foo) : m_foo (foo) {}\n\n int GetFoo () { return m_foo; }\n};\n</code></pre>\n<p>Here's a simple function that takes a <code>Foo</code> object:</p>\n<pre><code>void DoBar (Foo foo)\n{\n int i = foo.GetFoo ();\n}\n</code></pre>\n<p>and here's where the <code>DoBar</code> function is called:</p>\n<pre><code>int main ()\n{\n DoBar (42);\n}\n</code></pre>\n<p>The argument is not a <code>Foo</code> object, but an <code>int</code>. However, there exists a constructor for <code>Foo</code> that takes an <code>int</code> so this constructor can be used to convert the parameter to the correct type.</p>\n<p>The compiler is allowed to do this once for each parameter.</p>\n<p>Prefixing the <code>explicit</code> keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call <code>DoBar (42)</code>. It is now necessary to call for conversion explicitly with <code>DoBar (Foo (42))</code></p>\n<p>The reason you might want to do this is to avoid accidental construction that can hide bugs.<br />\nContrived example:</p>\n<ul>\n<li>You have a <code>MyString</code> class with a constructor that constructs a string of the given size. You have a function <code>print(const MyString&amp;)</code> (as well as an overload <code>print (char *string)</code>), and you call <code>print(3)</code> (when you <em>actually</em> intended to call <code>print(&quot;3&quot;)</code>). You expect it to print &quot;3&quot;, but it prints an empty string of length 3 instead.</li>\n</ul>\n" }, { "answer_id": 121216, "author": "Eddie", "author_id": 21116, "author_profile": "https://Stackoverflow.com/users/21116", "pm_score": 10, "selected": false, "text": "<p>Suppose, you have a class <code>String</code>:</p>\n\n<pre><code>class String {\npublic:\n String(int n); // allocate n bytes to the String object\n String(const char *p); // initializes object with char *p\n};\n</code></pre>\n\n<p>Now, if you try:</p>\n\n<pre><code>String mystring = 'x';\n</code></pre>\n\n<p>The character <code>'x'</code> will be implicitly converted to <code>int</code> and then the <code>String(int)</code> constructor will be called. But, this is not what the user might have intended. So, to prevent such conditions, we shall define the constructor as <code>explicit</code>:</p>\n\n<pre><code>class String {\npublic:\n explicit String (int n); //allocate n bytes\n String(const char *p); // initialize sobject with string p\n};\n</code></pre>\n" }, { "answer_id": 122174, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 8, "selected": false, "text": "<p>In C++, a constructor with only one required parameter is considered an implicit conversion function. It converts the parameter type to the class type. Whether this is a good thing or not depends on the semantics of the constructor.</p>\n\n<p>For example, if you have a string class with constructor <code>String(const char* s)</code>, that's probably exactly what you want. You can pass a <code>const char*</code> to a function expecting a <code>String</code>, and the compiler will automatically construct a temporary <code>String</code> object for you.</p>\n\n<p>On the other hand, if you have a buffer class whose constructor <code>Buffer(int size)</code> takes the size of the buffer in bytes, you probably don't want the compiler to quietly turn <code>int</code>s into <code>Buffer</code>s. To prevent that, you declare the constructor with the <code>explicit</code> keyword:</p>\n\n<pre><code>class Buffer { explicit Buffer(int size); ... }\n</code></pre>\n\n<p>That way,</p>\n\n<pre><code>void useBuffer(Buffer&amp; buf);\nuseBuffer(4);\n</code></pre>\n\n<p>becomes a compile-time error. If you want to pass a temporary <code>Buffer</code> object, you have to do so explicitly:</p>\n\n<pre><code>useBuffer(Buffer(4));\n</code></pre>\n\n<p>In summary, if your single-parameter constructor converts the parameter into an object of your class, you probably don't want to use the <code>explicit</code> keyword. But if you have a constructor that simply happens to take a single parameter, you should declare it as <code>explicit</code> to prevent the compiler from surprising you with unexpected conversions.</p>\n" }, { "answer_id": 1506749, "author": "fmuecke", "author_id": 105643, "author_profile": "https://Stackoverflow.com/users/105643", "pm_score": 5, "selected": false, "text": "<p>It is always a good coding practice to make your one argument constructors (including those with default values for <code>arg2</code>,<code>arg3</code>,...) as already stated. \nLike always with C++: if you don't - you'll wish you did...</p>\n\n<p>Another good practice for classes is to make copy construction and assignment private (a.k.a. disable it) unless you really need to implement it. This avoids having eventual copies of pointers when using the methods that C++ will create for you by default. An other way to do this is derive from <code>boost::noncopyable</code>.</p>\n" }, { "answer_id": 13485522, "author": "SankararaoMajji", "author_id": 1840657, "author_profile": "https://Stackoverflow.com/users/1840657", "pm_score": 6, "selected": false, "text": "<p>The <code>explicit</code> keyword makes a conversion constructor to non-conversion constructor. As a result, the code is less error prone. </p>\n" }, { "answer_id": 16539571, "author": "Helixirr", "author_id": 2028887, "author_profile": "https://Stackoverflow.com/users/2028887", "pm_score": 5, "selected": false, "text": "<p>The <code>explicit</code>-keyword can be used to enforce a constructor to be called <em>explicitly</em>.</p>\n<pre><code>class C {\npublic:\n explicit C() =default;\n};\n\nint main() {\n C c;\n return 0;\n}\n</code></pre>\n<p>the <code>explicit</code>-keyword in front of the constructor <code>C()</code> tells the compiler that only explicit call to this constructor is allowed.</p>\n<p>The <code>explicit</code>-keyword can also be used in user-defined type cast operators:</p>\n<pre><code>class C{\npublic:\n explicit inline operator bool() const {\n return true;\n }\n};\n\nint main() {\n C c;\n bool b = static_cast&lt;bool&gt;(c);\n return 0;\n}\n</code></pre>\n<p>Here, <code>explicit</code>-keyword enforces only explicit casts to be valid, so <code>bool b = c;</code> would be an invalid cast in this case. In situations like these <code>explicit</code>-keyword can help programmer to avoid implicit, unintended casts. This usage has been standardized in <a href=\"http://en.cppreference.com/w/cpp/language/cast_operator\" rel=\"nofollow noreferrer\">C++11</a>.</p>\n" }, { "answer_id": 19250874, "author": "Gautam", "author_id": 793930, "author_profile": "https://Stackoverflow.com/users/793930", "pm_score": 6, "selected": false, "text": "<p>This answer is about object creation with/without an explicit constructor since it is not covered in the other answers.</p>\n\n<p>Consider the following class without an explicit constructor:</p>\n\n<pre><code>class Foo\n{\npublic:\n Foo(int x) : m_x(x)\n {\n }\n\nprivate:\n int m_x;\n};\n</code></pre>\n\n<p>Objects of class Foo can be created in 2 ways:</p>\n\n<pre><code>Foo bar1(10);\n\nFoo bar2 = 20;\n</code></pre>\n\n<p>Depending upon the implementation, the second manner of instantiating class Foo may be confusing, or not what the programmer intended. Prefixing the <code>explicit</code> keyword to the constructor would generate a compiler error at <code>Foo bar2 = 20;</code>.</p>\n\n<p>It is <em>usually</em> good practice to declare single-argument constructors as <code>explicit</code>, unless your implementation specifically prohibits it.</p>\n\n<p>Note also that constructors with</p>\n\n<ul>\n<li>default arguments for all parameters, or</li>\n<li>default arguments for the second parameter onwards</li>\n</ul>\n\n<p>can both be used as single-argument constructors. So you may want to make these also <code>explicit</code>.</p>\n\n<p>An example when you would deliberately <strong><em>not</em></strong> want to make your single-argument constructor explicit is if you're creating a functor (look at the 'add_x' struct declared in <a href=\"https://stackoverflow.com/a/356993/793930\">this</a> answer). In such a case, creating an object as <code>add_x add30 = 30;</code> would probably make sense.</p>\n\n<p><a href=\"http://weblogs.asp.net/kennykerr/archive/2004/08/31/Explicit-Constructors.aspx\" rel=\"noreferrer\">Here</a> is a good write-up on explicit constructors.</p>\n" }, { "answer_id": 28106689, "author": "Konstantin Burlachenko", "author_id": 1154447, "author_profile": "https://Stackoverflow.com/users/1154447", "pm_score": 3, "selected": false, "text": "<p>Constructors append implicit conversion. To suppress this implicit conversion it is required to declare a constructor with a parameter explicit.</p>\n\n<p>In C++11 you can also specify an \"operator type()\" with such keyword <a href=\"http://en.cppreference.com/w/cpp/language/explicit\" rel=\"noreferrer\">http://en.cppreference.com/w/cpp/language/explicit</a> With such specification you can use operator in terms of explicit conversions, and direct initialization of object.</p>\n\n<p>P.S. When using transformations defined BY USER (via constructors and type conversion operator) it is allowed only one level of implicit conversions used.\nBut you can combine this conversions with other language conversions</p>\n\n<ul>\n<li>up integral ranks (char to int, float to double); </li>\n<li>standart conversions (int to double); </li>\n<li>convert pointers of objects to base class and to void*;</li>\n</ul>\n" }, { "answer_id": 31351956, "author": "Pixelchemist", "author_id": 951423, "author_profile": "https://Stackoverflow.com/users/951423", "pm_score": 6, "selected": false, "text": "<h3>The keyword <code>explicit</code> accompanies either</h3>\n\n<ul>\n<li><strong>a constructor of class X that cannot be used to implicitly convert the first (any only) parameter to type X</strong></li>\n</ul>\n\n<blockquote>\n <p><strong>C++ [class.conv.ctor]</strong></p>\n \n <p>1) A constructor declared without the function-specifier explicit specifies a conversion from the types of its parameters to the type of its class. Such a constructor is called a converting constructor.</p>\n \n <p>2) An explicit constructor constructs objects just like non-explicit constructors, but does so only where the direct-initialization syntax (8.5) or where casts (5.2.9, 5.4) are explicitly used. A default constructor may be an explicit constructor; such a constructor will be used to perform default-initialization or valueinitialization\n (8.5).</p>\n</blockquote>\n\n<ul>\n<li><strong>or a conversion function that is only considered for direct initialization and explicit conversion.</strong></li>\n</ul>\n\n<blockquote>\n <p><strong>C++ [class.conv.fct]</strong></p>\n \n <p>2) A conversion function may be explicit (7.1.2), in which case it is only considered as a user-defined conversion for direct-initialization (8.5). Otherwise, user-defined conversions are not restricted to use in assignments\n and initializations.</p>\n</blockquote>\n\n<h3>Overview</h3>\n\n<p>Explicit conversion functions and constructors can only be used for explicit conversions (direct initialization or explicit cast operation) while non-explicit constructors and conversion functions can be used for implicit as well as explicit conversions.</p>\n\n<pre><code>/*\n explicit conversion implicit conversion\n\n explicit constructor yes no\n\n constructor yes yes\n\n explicit conversion function yes no\n\n conversion function yes yes\n\n*/\n</code></pre>\n\n<h3>Example using structures <code>X, Y, Z</code> and functions <code>foo, bar, baz</code>:</h3>\n\n<p>Let's look at a small setup of structures and functions to see the difference between <code>explicit</code> and non-<code>explicit</code> conversions.</p>\n\n<pre><code>struct Z { };\n\nstruct X { \n explicit X(int a); // X can be constructed from int explicitly\n explicit operator Z (); // X can be converted to Z explicitly\n};\n\nstruct Y{\n Y(int a); // int can be implicitly converted to Y\n operator Z (); // Y can be implicitly converted to Z\n};\n\nvoid foo(X x) { }\nvoid bar(Y y) { }\nvoid baz(Z z) { }\n</code></pre>\n\n<h3>Examples regarding constructor:</h3>\n\n<p>Conversion of a function argument:</p>\n\n<pre><code>foo(2); // error: no implicit conversion int to X possible\nfoo(X(2)); // OK: direct initialization: explicit conversion\nfoo(static_cast&lt;X&gt;(2)); // OK: explicit conversion\n\nbar(2); // OK: implicit conversion via Y(int) \nbar(Y(2)); // OK: direct initialization\nbar(static_cast&lt;Y&gt;(2)); // OK: explicit conversion\n</code></pre>\n\n<p>Object initialization:</p>\n\n<pre><code>X x2 = 2; // error: no implicit conversion int to X possible\nX x3(2); // OK: direct initialization\nX x4 = X(2); // OK: direct initialization\nX x5 = static_cast&lt;X&gt;(2); // OK: explicit conversion \n\nY y2 = 2; // OK: implicit conversion via Y(int)\nY y3(2); // OK: direct initialization\nY y4 = Y(2); // OK: direct initialization\nY y5 = static_cast&lt;Y&gt;(2); // OK: explicit conversion\n</code></pre>\n\n<h3>Examples regarding conversion functions:</h3>\n\n<pre><code>X x1{ 0 };\nY y1{ 0 };\n</code></pre>\n\n<p>Conversion of a function argument:</p>\n\n<pre><code>baz(x1); // error: X not implicitly convertible to Z\nbaz(Z(x1)); // OK: explicit initialization\nbaz(static_cast&lt;Z&gt;(x1)); // OK: explicit conversion\n\nbaz(y1); // OK: implicit conversion via Y::operator Z()\nbaz(Z(y1)); // OK: direct initialization\nbaz(static_cast&lt;Z&gt;(y1)); // OK: explicit conversion\n</code></pre>\n\n<p>Object initialization:</p>\n\n<pre><code>Z z1 = x1; // error: X not implicitly convertible to Z\nZ z2(x1); // OK: explicit initialization\nZ z3 = Z(x1); // OK: explicit initialization\nZ z4 = static_cast&lt;Z&gt;(x1); // OK: explicit conversion\n\nZ z1 = y1; // OK: implicit conversion via Y::operator Z()\nZ z2(y1); // OK: direct initialization\nZ z3 = Z(y1); // OK: direct initialization\nZ z4 = static_cast&lt;Z&gt;(y1); // OK: explicit conversion\n</code></pre>\n\n<h3>Why use <code>explicit</code> conversion functions or constructors?</h3>\n\n<p><strong>Conversion constructors and non-explicit conversion functions may introduce ambiguity.</strong></p>\n\n<p>Consider a structure <code>V</code>, convertible to <code>int</code>, a structure <code>U</code> implicitly constructible from <code>V</code> and a function <code>f</code> overloaded for <code>U</code> and <code>bool</code> respectively.</p>\n\n<pre><code>struct V {\n operator bool() const { return true; }\n};\n\nstruct U { U(V) { } };\n\nvoid f(U) { }\nvoid f(bool) { }\n</code></pre>\n\n<p>A call to <code>f</code> is ambiguous if passing an object of type <code>V</code>.</p>\n\n<pre><code>V x;\nf(x); // error: call of overloaded 'f(V&amp;)' is ambiguous\n</code></pre>\n\n<p>The compiler does not know wether to use the constructor of <code>U</code> or the conversion function to convert the <code>V</code> object into a type for passing to <code>f</code>. </p>\n\n<p>If either the constructor of <code>U</code> or the conversion function of <code>V</code> would be <code>explicit</code>, there would be no ambiguity since only the non-explicit conversion would be considered. If both are explicit the call to <code>f</code> using an object of type <code>V</code> would have to be done using an explicit conversion or cast operation.</p>\n\n<p><strong>Conversion constructors and non-explicit conversion functions may lead to unexpected behaviour.</strong></p>\n\n<p>Consider a function printing some vector:</p>\n\n<pre><code>void print_intvector(std::vector&lt;int&gt; const &amp;v) { for (int x : v) std::cout &lt;&lt; x &lt;&lt; '\\n'; }\n</code></pre>\n\n<p>If the size-constructor of the vector would not be explicit it would be possible to call the function like this:</p>\n\n<pre><code>print_intvector(3);\n</code></pre>\n\n<p>What would one expect from such a call? One line containing <code>3</code> or three lines containing <code>0</code>? (Where the second one is what happens.)</p>\n\n<h3>Using the explicit keyword in a class interface enforces the user of the interface to be explicit about a desired conversion.</h3>\n\n<p>As Bjarne Stroustrup puts it (in \"The C++ Programming Language\", 4th Ed., 35.2.1, pp. 1011) on the question why <code>std::duration</code> cannot be implicitly constructed from a plain number:</p>\n\n<blockquote>\n <p>If you know what you mean, be explicit about it.</p>\n</blockquote>\n" }, { "answer_id": 39054305, "author": "selfboot", "author_id": 1380954, "author_profile": "https://Stackoverflow.com/users/1380954", "pm_score": 5, "selected": false, "text": "<p>Cpp Reference is always helpful!!! Details about explicit specifier can be found <a href=\"http://en.cppreference.com/w/cpp/language/explicit\">here</a>. You may need to look at <a href=\"http://en.cppreference.com/w/cpp/language/implicit_conversion\">implicit conversions</a> and <a href=\"http://en.cppreference.com/w/cpp/language/copy_initialization\">copy-initialization</a> too.</p>\n\n<p>Quick look</p>\n\n<blockquote>\n <p>The explicit specifier specifies that a constructor or conversion function (since C++11) doesn't allow implicit conversions or copy-initialization. </p>\n</blockquote>\n\n<p>Example as follows:</p>\n\n<pre><code>struct A\n{\n A(int) { } // converting constructor\n A(int, int) { } // converting constructor (C++11)\n operator bool() const { return true; }\n};\n\nstruct B\n{\n explicit B(int) { }\n explicit B(int, int) { }\n explicit operator bool() const { return true; }\n};\n\nint main()\n{\n A a1 = 1; // OK: copy-initialization selects A::A(int)\n A a2(2); // OK: direct-initialization selects A::A(int)\n A a3 {4, 5}; // OK: direct-list-initialization selects A::A(int, int)\n A a4 = {4, 5}; // OK: copy-list-initialization selects A::A(int, int)\n A a5 = (A)1; // OK: explicit cast performs static_cast\n if (a1) cout &lt;&lt; \"true\" &lt;&lt; endl; // OK: A::operator bool()\n bool na1 = a1; // OK: copy-initialization selects A::operator bool()\n bool na2 = static_cast&lt;bool&gt;(a1); // OK: static_cast performs direct-initialization\n\n// B b1 = 1; // error: copy-initialization does not consider B::B(int)\n B b2(2); // OK: direct-initialization selects B::B(int)\n B b3 {4, 5}; // OK: direct-list-initialization selects B::B(int, int)\n// B b4 = {4, 5}; // error: copy-list-initialization does not consider B::B(int,int)\n B b5 = (B)1; // OK: explicit cast performs static_cast\n if (b5) cout &lt;&lt; \"true\" &lt;&lt; endl; // OK: B::operator bool()\n// bool nb1 = b2; // error: copy-initialization does not consider B::operator bool()\n bool nb2 = static_cast&lt;bool&gt;(b2); // OK: static_cast performs direct-initialization\n}\n</code></pre>\n" }, { "answer_id": 71926068, "author": "Manojkumar Khotele", "author_id": 3009968, "author_profile": "https://Stackoverflow.com/users/3009968", "pm_score": -1, "selected": false, "text": "<p>Other answers are missing one important factor which I am going to mention here.</p>\n<p>Along with &quot;delete&quot; keyword, &quot;explicit&quot; allows you to control the way compiler is going to generate special member functions - default constructor, copy constructor, copy-assignment operator, destructor, move constructor and move-assignment.</p>\n<p>Refer <a href=\"https://learn.microsoft.com/en-us/cpp/cpp/explicitly-defaulted-and-deleted-functions\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/cpp/cpp/explicitly-defaulted-and-deleted-functions</a></p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1898/" ]
What does the `explicit` keyword mean in C++?
The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a **single parameter** to convert from one type to another in order to get the right type for a parameter. Here's an example class with a constructor that can be used for implicit conversions: ``` class Foo { private: int m_foo; public: // single parameter constructor, can be used as an implicit conversion Foo (int foo) : m_foo (foo) {} int GetFoo () { return m_foo; } }; ``` Here's a simple function that takes a `Foo` object: ``` void DoBar (Foo foo) { int i = foo.GetFoo (); } ``` and here's where the `DoBar` function is called: ``` int main () { DoBar (42); } ``` The argument is not a `Foo` object, but an `int`. However, there exists a constructor for `Foo` that takes an `int` so this constructor can be used to convert the parameter to the correct type. The compiler is allowed to do this once for each parameter. Prefixing the `explicit` keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call `DoBar (42)`. It is now necessary to call for conversion explicitly with `DoBar (Foo (42))` The reason you might want to do this is to avoid accidental construction that can hide bugs. Contrived example: * You have a `MyString` class with a constructor that constructs a string of the given size. You have a function `print(const MyString&)` (as well as an overload `print (char *string)`), and you call `print(3)` (when you *actually* intended to call `print("3")`). You expect it to print "3", but it prints an empty string of length 3 instead.
121,167
<p>What are some of the lesser-known but useful features and techniques that people are using in their Greasemonkey scripts?</p> <p>(Please, just one feature per answer.)</p> <p>Similar threads:</p> <ul> <li><a href="https://stackoverflow.com/questions/61088/hidden-features-of-javascript">Hidden Features of JavaScript</a></li> <li><a href="https://stackoverflow.com/questions/15496/hidden-features-of-java">Hidden Features of Java</a></li> <li><a href="https://stackoverflow.com/questions/75538/hidden-features-of-c">Hidden Features of C++</a></li> <li><a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden Features of C#</a></li> </ul>
[ { "answer_id": 121197, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 3, "selected": false, "text": "<p>Data can be persisted across page loads by storing it as a mozilla preference value via <code>GM_setValue(keyname, value)</code>.</p>\n\n<p>Here is a simple example that tallys the number of times your script has been executed - by a given browser:</p>\n\n<pre>\nvar od = GM_getValue(\"odometer\", 0);\nod++;\nGM_setValue(\"odometer\", od);\nGM_log(\"odometer=\" + od);\n</pre>\n\n<p>GM values are analogous to cookies in that cookie values can only be accessed by the originated domain, GM values can only be accessed by the script that created them.</p>\n" }, { "answer_id": 121327, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 2, "selected": false, "text": "<p>Anonymous statistics</p>\n\n<p>Assuming you have a basic hosting service that provides access logging, you can easily track basic usage statistics for your script.</p>\n\n<ol>\n<li>Place a gif file (eg, a logo image) on your own website.</li>\n<li>In your script, attach an img element to the page that references the gif:</li>\n</ol>\n\n<pre>\nvar img = document.createElement(\"img\");\nimg.src = \"http://mysite.com/logo.gif\";\ndocument.body.appendChild(img);\n</pre>\n\n<p>Now, each time a user executes your script, your hosting service will register a hit on that gif file.</p>\n\n<p>To track more than one script, use a different gif file for each. Or add some kind of differentiating parameter to the URL, (eg: <code>http://mysite.com/logo.gif?zippyver=1.0</code>).</p>\n" }, { "answer_id": 121601, "author": "Robert J. Walker", "author_id": 4287, "author_profile": "https://Stackoverflow.com/users/4287", "pm_score": 4, "selected": false, "text": "<p>Greasemonkey scripts often need to search for content on a page. Instead of digging through the DOM, try using XPath to locate nodes of interest. The <code>document.evaluate()</code> method lets you provide an XPath expression and will return a collection of matching nodes. Here's a nice <a href=\"http://www-xray.ast.cam.ac.uk/~jgraham/mozilla/xpath-tutorial.html\" rel=\"noreferrer\">tutorial</a> to get you started. As an example, here's a script I wrote that causes links in phpBB3 posts to open in a new tab (in the default skin):</p>\n\n<pre><code>// ==UserScript==\n// @name New Tab in phpBB3\n// @namespace http://robert.walkertribe.com/\n// @description Makes links in posts in phpBB3 boards open new tabs.\n// ==/UserScript==\n\nvar newWin = function(ev) {\n var win = window.open(ev.target.href);\n if (win) ev.preventDefault();\n};\n\nvar links = document.evaluate(\n \"//div[@class='content']//a[not(@onclick) and not(@href='#')]\",\n document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);\n\nfor (var i = 0; i &lt; links.snapshotLength; i++) {\n var link = links.snapshotItem(i);\n link.addEventListener(\"click\", newWin, true);\n}\n</code></pre>\n\n<p>The XPath expression used in the code identifies all <code>a</code> elements that 1) do not have an <code>onclick</code> attribute, 2) whose <code>href</code> attribute is not set to <code>\"#\"</code>, and 3) are found inside <code>div</code>s whose <code>class</code> attribute is set to <code>\"content\"</code>.</p>\n" }, { "answer_id": 125006, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 1, "selected": false, "text": "<p>Script header values, (@name, @description, @version, etc), can be made retrievable. This is preferable to maintaining the same constant values in multiple places in your script.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/104568/accessing-greasemonkey-metadata-from-within-your-script#112148\">Accessing Greasemonkey metadata from within your script?</a></p>\n" }, { "answer_id": 127901, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 3, "selected": false, "text": "<p>Your script can add graphics into a page, even if you don't have any place to host files, via data URIs.</p>\n\n<p>For example, here is a little button graphic:</p>\n\n<pre>\nvar button = document.createElement(\"img\");\nbutton.src = \"data:image/gif;base64,\"\n + \"R0lGODlhEAAQAKEDAAAA/wAAAMzMzP///yH5BAEAAAMALAAAAAAQABAAAAIhnI+pywOtwINHTmpvy3rx\"\n + \"nnABlAUCKZkYoGItJZzUTCMFACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==\"\nsomenode.appendChild(button);\n</pre>\n\n<p>Here is an online <a href=\"http://www.scalora.org/projects/uriencoder/\" rel=\"noreferrer\">image encoder</a>.</p>\n\n<p>And a <a href=\"http://en.wikipedia.org/wiki/Data:_URI_scheme\" rel=\"noreferrer\">wikipedia article</a> about the Data URI standard.</p>\n" }, { "answer_id": 133560, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 2, "selected": false, "text": "<p>A useful XPath technique is to specify your match relative to a node that you have already found. As a contrived example for stackoverflow:</p>\n\n<pre>\n// first we got the username link at the top of the page\nvar hdrdiv = document.evaluate(\n \"//div[@id='headerlinks']/a[1]\", document, null,\n XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;\n\n// now we can retrieve text that follows it, (user's reputation score)\n// (note that hdrdiv is now the contextNode argument, rather than document)\nvar reptext = document.evaluate(\n \"following-sibling::span\", hdrdiv, null,\n XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;\n\nalert(\"Reputation Score: \" + reptext.textContent);\n</pre>\n\n<p>You can match in any direction relative to the contextNode, ancestors, descendants, previous, following.\nHere is a helpful\n<a href=\"http://zvon.org/xxl/XSLTreference/Output/index.html\" rel=\"nofollow noreferrer\">XPath reference</a>.</p>\n" }, { "answer_id": 137077, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 2, "selected": false, "text": "<p>GreaseMonkey scripts run when the DOM is ready, so you don't need to add onload events, you just start manipulating the DOM straight away in your GreaseMonkey script.</p>\n" }, { "answer_id": 144415, "author": "mislav", "author_id": 11687, "author_profile": "https://Stackoverflow.com/users/11687", "pm_score": 4, "selected": false, "text": "<pre><code>==UserScript==\n...\n@require http://ajax.googleapis.com/ajax/framework-of-your/choice.js\n==/UserScript==\n</code></pre>\n" }, { "answer_id": 664485, "author": "PotatoEngineer", "author_id": 26257, "author_profile": "https://Stackoverflow.com/users/26257", "pm_score": 3, "selected": false, "text": "<p>GM_setValue normally only stores 32-bit integers, strings, and booleans, but you can take advantage of the uneval() method (and a later eval() on retrieval) to store any object. If you're dealing with pure JSON values (rather than JavaScript objects), use JSON.stringify to store and JSON.parse to retrieve; this will be both faster and safer.</p>\n\n<pre><code>var foo={people:['Bob','George','Smith','Grognak the Destroyer'],pie:true};\nGM_setValue('myVeryOwnFoo',uneval(foo));\nvar fooReborn=eval(GM_getValue('myVeryOwnFoo','new Object()'));\nGM_log('People: '+fooReborn.people+' Pie:'+fooReborn.pie);\n</code></pre>\n\n<p>I tend to use \"new Object()\" as my default in this case, but you could also use \"({})\". Just remember that \"{}\" evaluates as a string, not an object. As usual, eval() with care.</p>\n" }, { "answer_id": 8764806, "author": "Darth Egregious", "author_id": 973810, "author_profile": "https://Stackoverflow.com/users/973810", "pm_score": 1, "selected": false, "text": "<p><strong>Obsolete:</strong> Firefox dropped support for E4X, in Greasemonkey scripts, with FF version 17. Use <code>GM_info</code> to get metadata.</p>\n\n<hr>\n\n<p>You can use e4x to access your ==UserScript== information as a variable:</p>\n\n<pre><code>var metadata=&lt;&gt; \n// ==UserScript==\n// @name search greasemonkey\n// @namespace foo\n// @include http://*.google.com/*\n// @include http://*.google.ca/*\n// @include http://search.*.com/*\n// @include http://*.yahoo.com/*\n// ==/UserScript==\n&lt;/&gt;.toString();\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14749/" ]
What are some of the lesser-known but useful features and techniques that people are using in their Greasemonkey scripts? (Please, just one feature per answer.) Similar threads: * [Hidden Features of JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript) * [Hidden Features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java) * [Hidden Features of C++](https://stackoverflow.com/questions/75538/hidden-features-of-c) * [Hidden Features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
Greasemonkey scripts often need to search for content on a page. Instead of digging through the DOM, try using XPath to locate nodes of interest. The `document.evaluate()` method lets you provide an XPath expression and will return a collection of matching nodes. Here's a nice [tutorial](http://www-xray.ast.cam.ac.uk/~jgraham/mozilla/xpath-tutorial.html) to get you started. As an example, here's a script I wrote that causes links in phpBB3 posts to open in a new tab (in the default skin): ``` // ==UserScript== // @name New Tab in phpBB3 // @namespace http://robert.walkertribe.com/ // @description Makes links in posts in phpBB3 boards open new tabs. // ==/UserScript== var newWin = function(ev) { var win = window.open(ev.target.href); if (win) ev.preventDefault(); }; var links = document.evaluate( "//div[@class='content']//a[not(@onclick) and not(@href='#')]", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); for (var i = 0; i < links.snapshotLength; i++) { var link = links.snapshotItem(i); link.addEventListener("click", newWin, true); } ``` The XPath expression used in the code identifies all `a` elements that 1) do not have an `onclick` attribute, 2) whose `href` attribute is not set to `"#"`, and 3) are found inside `div`s whose `class` attribute is set to `"content"`.
121,199
<p>How is it possible in Eclipse JDT to convert a multiline selection to String. Like the following</p> <p>From:</p> <pre><code>xxxx yyyy zzz </code></pre> <p>To:</p> <pre><code>"xxxx " + "yyyy " + "zzz" </code></pre> <p>I tried the following template </p> <pre><code>"${line_selection}${cursor}"+ </code></pre> <p>but that way I only get the whole block surrounded not each line separately. How can I achieve a multiline processing like commenting the selected block?</p>
[ { "answer_id": 121420, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 2, "selected": false, "text": "<p>This may not be exactly the answer you're looking for. You can easily achieve what you're asking by using the sed stream editor. This is available on all flavors of Unix, and also on Windows, by downloading a toolkit like <a href=\"http://www.cygwin.com/\" rel=\"nofollow noreferrer\">cygwin</a>. On the Unix shell command line run the command</p>\n\n<pre><code>sed 's/^/\"/;s/$/\"+/'\n</code></pre>\n\n<p>and paste the text you want to convert. On its output you'll obtain the converted text. The argument passed to sed says substitute (s) the beginning of a line (^) with a quote, and substitute (s) the end of each line ($) with a quote and a plus.</p>\n\n<p>If the text you want to convert is large you may want to redirect sed's input and output through files. In such a case run something like</p>\n\n<pre><code> sed 's/^/\"/;s/$/\"+/' &lt;inputfile &gt;outputfile\n</code></pre>\n\n<p>On Windows you can also use the winclip command of the <a href=\"http://www.spinellis.gr/sw/outwit/\" rel=\"nofollow noreferrer\">Outwit</a> tool suite to directly change what's in the clipboard. Simply run</p>\n\n<pre><code>winclip -p | sed 's/^/\"/;s/$/\"+/' | winclip -c\n</code></pre>\n\n<p>The above command will paste the clipboard's contents into sed and the result back into the clipboard. </p>\n\n<p>Finally, if you're often using this command, it makes sense placing it into a shell script file, so that you can easily run it. You can then even assign an Eclipse keyboard shortcut to it.</p>\n" }, { "answer_id": 121428, "author": "Rafał Dowgird", "author_id": 12166, "author_profile": "https://Stackoverflow.com/users/12166", "pm_score": 2, "selected": false, "text": "<p>Find/Replace with the regex option turned on. Find:</p>\n\n<pre><code>^(.*)$\n</code></pre>\n\n<p>Replace with:</p>\n\n<pre><code>\"$1\" +\n</code></pre>\n\n<p>Well, the last line will have a surplus <code>+</code>, you have to delete it manually.</p>\n" }, { "answer_id": 121513, "author": "Grundlefleck", "author_id": 4120, "author_profile": "https://Stackoverflow.com/users/4120", "pm_score": 6, "selected": false, "text": "<p>Maybe this is not what you mean but...</p>\n\n<p>If I'm on a line in Eclipse and I enter double quotation marks, then inside that paste a multiline selection (like your xyz example) it will paste out like this:</p>\n\n<pre><code>\"xxxx\\n\" + \n\"yyyy\\n\" + \n\"zzz\"\n</code></pre>\n\n<p>Then you could just find/replace in a selection for <code>\"\\n\"</code> to <code>\"\"</code>, if you didn't intend the newlines.</p>\n\n<p>I think the option to enable this is in <code>Window/Preferences</code>, under <code>Java/Editor/Typing/</code>, check the box next to <code>\"Escape text when pasting into a string literal\"</code>. (<code>Eclipse 3.4 Ganymede</code>)</p>\n" }, { "answer_id": 121603, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": false, "text": "<p>I would go with a Find/Replace eclipse in regexp mode:</p>\n\n<ul>\n<li><p>Find:</p>\n\n<p>^((?:\\s(?)<em>\\S?)((?:\\s(?![\\r\\n]))</em>)</p></li>\n<li><p>Replace with</p>\n\n<p>\\1\"\\2\"\\3 +</p></li>\n</ul>\n\n<p>Will preserve <strong>exactly</strong> whatever space or tabs you have before and after each string, and will surround them with the needed double-quotes. (last '+' needs to be removed)</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How is it possible in Eclipse JDT to convert a multiline selection to String. Like the following From: ``` xxxx yyyy zzz ``` To: ``` "xxxx " + "yyyy " + "zzz" ``` I tried the following template ``` "${line_selection}${cursor}"+ ``` but that way I only get the whole block surrounded not each line separately. How can I achieve a multiline processing like commenting the selected block?
Maybe this is not what you mean but... If I'm on a line in Eclipse and I enter double quotation marks, then inside that paste a multiline selection (like your xyz example) it will paste out like this: ``` "xxxx\n" + "yyyy\n" + "zzz" ``` Then you could just find/replace in a selection for `"\n"` to `""`, if you didn't intend the newlines. I think the option to enable this is in `Window/Preferences`, under `Java/Editor/Typing/`, check the box next to `"Escape text when pasting into a string literal"`. (`Eclipse 3.4 Ganymede`)
121,202
<p>I work with quite a bit of multi-platform C/C++ code, separated by common #defines (#if WIN, #if UNIX, etc). It would be nice if I could have vim automatically fold the sections I'm currently not interested in when I open a file. I've searched through the vim script archives, but I haven't found anything useful. Any suggestions? Places to start?</p>
[ { "answer_id": 121278, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 3, "selected": false, "text": "<p>Just add a folding region to your syntax\n<a href=\"http://vim.wikia.com/wiki/Syntax_folding_of_Vim_scripts#Syntax_definitions\" rel=\"noreferrer\">http://vim.wikia.com/wiki/Syntax_folding_of_Vim_scripts#Syntax_definitions</a></p>\n\n<pre><code>:syn region myFold start=\"\\#IF\" end=\"\\#ENDIF\" transparent fold\n:syn sync fromstart\n:set foldmethod=syntax\n</code></pre>\n" }, { "answer_id": 121312, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 2, "selected": false, "text": "<p>To add to @hometoasts answer, you can add that command as a comment in the first ten or last ten lines of the file and vim will automatically use it for that file.</p>\n\n<p><PRE>\n /* vim: syn region regionName start=\"regex\" end=\"regex\": */\n</PRE></p>\n" }, { "answer_id": 121390, "author": "skymt", "author_id": 18370, "author_profile": "https://Stackoverflow.com/users/18370", "pm_score": 0, "selected": false, "text": "<p>A quick addition to Denton's addition: to use the new syntax rule with any C or C++ code, add it to a file at <code>$VIMRUNTIME/syntax/c.vim</code> and <code>cpp.vim</code>. (<code>$VIMRUNTIME</code> is where your local Vim code lives: <code>~/.vim</code> on Unix.) Also, the values for <code>start</code> and <code>end</code> in the syntax definition are regular expressions, so you can use <code>^#if</code> and <code>^#endif</code> to ensure they only match those strings at the start of a line.</p>\n" }, { "answer_id": 673965, "author": "Fire Crow", "author_id": 80479, "author_profile": "https://Stackoverflow.com/users/80479", "pm_score": 0, "selected": false, "text": "<p>I've always used forldmethod=marker and defined my own fold tags placed within comments. </p>\n\n<p>this is for defining the characters that define the open and close folds. in this case open is \"&lt;(\" and close is \")>\" replace these with whatever you'd like.</p>\n\n<pre><code>set foldmethod=marker\nset foldmarker=&lt;(,)&gt;\n</code></pre>\n\n<p>This is my custom function to decide what to display of the folded text:</p>\n\n<pre><code>set foldtext=GetCustomFoldText()\nfunction GetCustomFoldText()\n let preline = substitute(getline(v:foldstart),'&lt;(','&lt;(+)','')\n let line = substitute(preline,\"\\t\",' ','g')\n let nextLnNum = v:foldstart + 1\n let nextline = getline(nextLnNum)\n let foldTtl = v:foldend - v:foldstart\n return line . ' | ' . nextline . ' (' . foldTtl . ' lines)&gt;'\nendfunction\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 2377395, "author": "Rajesh", "author_id": 222001, "author_profile": "https://Stackoverflow.com/users/222001", "pm_score": 0, "selected": false, "text": "<p>I have a huge code base and so a large number of #defines. Each file has numerous #ifdef's\nand most of the times they are nested. I tried many of the vim scripts but they always\nused to run into some error with the code I have. So in the end I put all my defines in\na header file and included it in the file that I wanted to work with and did a gcc on it \nlike this</p>\n\n<p>gcc -E -C -P source.cpp > output.cpp</p>\n\n<p>The -E command gets gcc to run only the pre-processor on the file, so all the unwanted\ncode within the undefined #ifdef's are removed. \nThe -C option retains the comments in the file.\nThe -P option inhibits generation of linemarkers in the output from the preprocessor.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21138/" ]
I work with quite a bit of multi-platform C/C++ code, separated by common #defines (#if WIN, #if UNIX, etc). It would be nice if I could have vim automatically fold the sections I'm currently not interested in when I open a file. I've searched through the vim script archives, but I haven't found anything useful. Any suggestions? Places to start?
Just add a folding region to your syntax <http://vim.wikia.com/wiki/Syntax_folding_of_Vim_scripts#Syntax_definitions> ``` :syn region myFold start="\#IF" end="\#ENDIF" transparent fold :syn sync fromstart :set foldmethod=syntax ```
121,237
<p>I would like to convert a string into a node. I have a method that is defined to take a node, but the value I have is a string (it is hard coded). How do I turn that string into a node?</p> <p>So, given an XQuery method:</p> <pre><code>define function foo($bar as node()*) as node() { (: unimportant details :) } </code></pre> <p>I have a string that I want to pass to the foo method. How do I convert the string to a node so that the method will accept the string.</p>
[ { "answer_id": 121249, "author": "Sixty4Bit", "author_id": 1681, "author_profile": "https://Stackoverflow.com/users/1681", "pm_score": 5, "selected": true, "text": "<p><strong>MarkLogic solutions:</strong></p>\n\n<p>The best way to convert a string into a node is to use:</p>\n\n<pre><code>xdmp:unquote($string).\n</code></pre>\n\n<p>Conversely if you want to convert a node into a string you would use: </p>\n\n<pre><code>xdmp:quote($node).\n</code></pre>\n\n<p><strong>Language agnostic solutions:</strong> </p>\n\n<p>Node to string is:</p>\n\n<pre><code>fn:string($node)\n</code></pre>\n" }, { "answer_id": 121467, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 2, "selected": false, "text": "<p>The answer to this question depends on what engine is being used. For instance, users of <strong>Saxon</strong>, use the <code>saxon:parse</code> method.</p>\n\n<p>The fact is the <strong>XQuery</strong> spec doesn't have a built in for this. </p>\n\n<p>Generally speaking you would only really need to use this if you needed to pull some embedded <strong>XML</strong> from a <strong>CDATA</strong> section. Otherwise you can read files in from the filesystem, or declare <strong>XML</strong> directly inline.</p>\n\n<p>For the most you would use the declarative form, instead of a hardcoded string e.g. (using Stylus studio)</p>\n\n<pre><code>declare namespace my = \"http://tempuri.org\";\n\ndeclare function my:foo($bar as node()*) as node() {\n &lt;unimportant&gt;&lt;/unimportant&gt;\n} ;\n\nlet $bar := &lt;node&gt;&lt;child&gt;&lt;/child&gt;&lt;/node&gt;\n\nreturn my:foo(bar)\n</code></pre>\n" }, { "answer_id": 276520, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>If you want to create a <strong>text</strong> node out of the string, just use a <strong>text</strong> node constructor:</p>\n\n<pre><code>text { \"your string goes here\" }\n</code></pre>\n\n<p>or if you prefer to create an <strong>element</strong> with the string content, you can construct an <strong>element</strong> something like this:</p>\n\n<pre><code>element (some-element) { \"your string goes here\" }\n</code></pre>\n" }, { "answer_id": 11784584, "author": "mb21", "author_id": 214446, "author_profile": "https://Stackoverflow.com/users/214446", "pm_score": 3, "selected": false, "text": "<p>If you are talking about strings that contain XML markup, there are standardized solutions (from XPath/XQuery Functions 3.0) as well:</p>\n\n<ul>\n<li>string to node: <a href=\"http://www.w3.org/TR/xpath-functions-30/#func-parse-xml\" rel=\"nofollow noreferrer\">fn:parse-xml()</a></li>\n<li>node to string: <a href=\"http://www.w3.org/TR/xpath-functions-30/#func-serialize\" rel=\"nofollow noreferrer\">fn:serialize()</a></li>\n</ul>\n" }, { "answer_id": 67906474, "author": "the hand of NOD", "author_id": 3564455, "author_profile": "https://Stackoverflow.com/users/3564455", "pm_score": 0, "selected": false, "text": "<p>you also can use <code>fn:parse-xml(xs:string)</code> to convert your current valid XML string into a document.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1681/" ]
I would like to convert a string into a node. I have a method that is defined to take a node, but the value I have is a string (it is hard coded). How do I turn that string into a node? So, given an XQuery method: ``` define function foo($bar as node()*) as node() { (: unimportant details :) } ``` I have a string that I want to pass to the foo method. How do I convert the string to a node so that the method will accept the string.
**MarkLogic solutions:** The best way to convert a string into a node is to use: ``` xdmp:unquote($string). ``` Conversely if you want to convert a node into a string you would use: ``` xdmp:quote($node). ``` **Language agnostic solutions:** Node to string is: ``` fn:string($node) ```
121,240
<p>What is the best (cleanest, most efficient) way to write saturating addition in C?</p> <p>The function or macro should add two unsigned inputs (need both 16- and 32-bit versions) and return all-bits-one (0xFFFF or 0xFFFFFFFF) if the sum overflows.</p> <p>Target is x86 and ARM using gcc (4.1.2) and Visual Studio (for simulation only, so a fallback implementation is OK there).</p>
[ { "answer_id": 121263, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 3, "selected": false, "text": "<pre><code>uint32_t saturate_add32(uint32_t a, uint32_t b)\n{\n uint32_t sum = a + b;\n if ((sum &lt; a) || (sum &lt; b))\n return ~((uint32_t)0);\n else\n return sum;\n} /* saturate_add32 */\n\nuint16_t saturate_add16(uint16_t a, uint16_t b)\n{\n uint16_t sum = a + b;\n if ((sum &lt; a) || (sum &lt; b))\n return ~((uint16_t)0);\n else\n return sum;\n} /* saturate_add16 */\n</code></pre>\n\n<p><B>Edit:</B> Now that you've posted your version, I'm not sure mine is any cleaner/better/more efficient/more studly.</p>\n" }, { "answer_id": 121271, "author": "Frank Szczerba", "author_id": 8964, "author_profile": "https://Stackoverflow.com/users/8964", "pm_score": 2, "selected": false, "text": "<p>The current implementation we are using is:</p>\n\n<pre><code>#define sadd16(a, b) (uint16_t)( ((uint32_t)(a)+(uint32_t)(b)) &gt; 0xffff ? 0xffff : ((a)+(b)))\n#define sadd32(a, b) (uint32_t)( ((uint64_t)(a)+(uint64_t)(b)) &gt; 0xffffffff ? 0xffffffff : ((a)+(b)))\n</code></pre>\n" }, { "answer_id": 121314, "author": "Igor Semenov", "author_id": 11401, "author_profile": "https://Stackoverflow.com/users/11401", "pm_score": 2, "selected": false, "text": "<p>I suppose, the best way for x86 is to use inline assembler to check overflow flag after addition. Something like:</p>\n\n<pre><code>add eax, ebx\njno @@1\nor eax, 0FFFFFFFFh\n@@1:\n.......\n</code></pre>\n\n<p>It's not very portable, but IMHO the most efficient way.</p>\n" }, { "answer_id": 121323, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 4, "selected": false, "text": "<p>In ARM you may already have saturated arithmetic built-in. The ARMv5 DSP-extensions can saturate registers to any bit-length. Also on ARM saturation is usually cheap because you can excute most instructions conditional. </p>\n\n<p>ARMv6 even has saturated addition, subtraction and all the other stuff for 32 bits and packed numbers.</p>\n\n<p>On the x86 you get saturated arithmetic either via MMX or SSE. </p>\n\n<p>All this needs assembler, so it's not what you've asked for.</p>\n\n<p>There are C-tricks to do saturated arithmetic as well. This little code does saturated addition on four bytes of a dword. It's based on the idea to calculate 32 half-adders in parallel, e.g. adding numbers without carry overflow. </p>\n\n<p>This is done first. Then the carries are calculated, added and replaced with a mask if the addition would overflow. </p>\n\n<pre><code>uint32_t SatAddUnsigned8(uint32_t x, uint32_t y) \n{\n uint32_t signmask = 0x80808080;\n uint32_t t0 = (y ^ x) &amp; signmask;\n uint32_t t1 = (y &amp; x) &amp; signmask;\n x &amp;= ~signmask;\n y &amp;= ~signmask;\n x += y;\n t1 |= t0 &amp; x;\n t1 = (t1 &lt;&lt; 1) - (t1 &gt;&gt; 7);\n return (x ^ t0) | t1;\n}\n</code></pre>\n\n<p>You can get the same for 16 bits (or any kind of bit-field) by changing the signmask constant and the shifts at the bottom like this:</p>\n\n<pre><code>uint32_t SatAddUnsigned16(uint32_t x, uint32_t y) \n{\n uint32_t signmask = 0x80008000;\n uint32_t t0 = (y ^ x) &amp; signmask;\n uint32_t t1 = (y &amp; x) &amp; signmask;\n x &amp;= ~signmask;\n y &amp;= ~signmask;\n x += y;\n t1 |= t0 &amp; x;\n t1 = (t1 &lt;&lt; 1) - (t1 &gt;&gt; 15);\n return (x ^ t0) | t1;\n}\n\nuint32_t SatAddUnsigned32 (uint32_t x, uint32_t y)\n{\n uint32_t signmask = 0x80000000;\n uint32_t t0 = (y ^ x) &amp; signmask;\n uint32_t t1 = (y &amp; x) &amp; signmask;\n x &amp;= ~signmask;\n y &amp;= ~signmask;\n x += y;\n t1 |= t0 &amp; x;\n t1 = (t1 &lt;&lt; 1) - (t1 &gt;&gt; 31);\n return (x ^ t0) | t1;\n}\n</code></pre>\n\n<p>Above code does the same for 16 and 32 bit values. </p>\n\n<p>If you don't need the feature that the functions add and saturate multiple values in parallel just mask out the bits you need. On ARM you also want to change the signmask constant because ARM can't load all possible 32 bit constants in a single cycle.</p>\n\n<p><strong>Edit:</strong> The parallel versions are most likely slower than the straight forward methods, but they are faster if you have to saturate more than one value at a time.</p>\n" }, { "answer_id": 121355, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 4, "selected": false, "text": "<p>In IA32 without conditional jumps:</p>\n\n<pre><code>uint32_t sadd32(uint32_t a, uint32_t b)\n{\n#if defined IA32\n __asm\n {\n mov eax,a\n xor edx,edx\n add eax,b\n setnc dl\n dec edx\n or eax,edx\n }\n#elif defined ARM\n // ARM code\n#else\n // non-IA32/ARM way, copy from above\n#endif\n}\n</code></pre>\n" }, { "answer_id": 121801, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p>I'm not sure if this is faster than Skizz's solution (always profile), but here's an alternative no-branch assembly solution. Note that this requires the conditional move (CMOV) instruction, which I'm not sure is available on your target.</p>\n\n<pre><code>\nuint32_t sadd32(uint32_t a, uint32_t b)\n{\n __asm\n {\n movl eax, a\n addl eax, b\n movl edx, 0xffffffff\n cmovc eax, edx\n }\n}\n</code></pre>\n" }, { "answer_id": 122288, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 5, "selected": false, "text": "<p>In plain C:</p>\n<pre class=\"lang-c prettyprint-override\"><code>uint16_t sadd16(uint16_t a, uint16_t b) {\n return (a &gt; 0xFFFF - b) ? 0xFFFF : a + b;\n}\n \nuint32_t sadd32(uint32_t a, uint32_t b) {\n return (a &gt; 0xFFFFFFFF - b) ? 0xFFFFFFFF : a + b;\n}\n</code></pre>\n<p>which is almost macro-ized and directly conveys the meaning.</p>\n" }, { "answer_id": 122346, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 3, "selected": false, "text": "<p>If you care about performance, you <em>really</em> want to do this sort of stuff in SIMD, where x86 has native saturating arithmetic.</p>\n\n<p>Because of this lack of saturating arithmetic in scalar math, one can get cases in which operations done on 4-variable-wide SIMD is <em>more</em> than 4 times faster than the equivalent C (and correspondingly true with 8-variable-wide SIMD):</p>\n\n<pre><code>sub8x8_dct8_c: 1332 clocks\nsub8x8_dct8_mmx: 182 clocks\nsub8x8_dct8_sse2: 127 clocks\n</code></pre>\n" }, { "answer_id": 124709, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 2, "selected": false, "text": "<p>The best performance will usually involve inline assembly (as some have already stated).</p>\n<p>But for portable C, these functions only involve one comparison and no type-casting (and thus I believe optimal):</p>\n<pre><code>unsigned saturate_add_uint(unsigned x, unsigned y)\n{\n if (y &gt; UINT_MAX - x) return UINT_MAX;\n return x + y;\n}\n\nunsigned short saturate_add_ushort(unsigned short x, unsigned short y)\n{\n if (y &gt; USHRT_MAX - x) return USHRT_MAX;\n return x + y;\n}\n</code></pre>\n<p>As macros, they become:</p>\n<pre><code>SATURATE_ADD_UINT(x, y) (((y)&gt;UINT_MAX-(x)) ? UINT_MAX : ((x)+(y)))\nSATURATE_ADD_USHORT(x, y) (((y)&gt;SHRT_MAX-(x)) ? USHRT_MAX : ((x)+(y)))\n</code></pre>\n<p>I leave versions for 'unsigned long' and 'unsigned long long' as an exercise to the reader. ;-)</p>\n" }, { "answer_id": 166393, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 6, "selected": true, "text": "<p>You probably want portable C code here, which your compiler will turn into proper ARM assembly. ARM has conditional moves, and these can be conditional on overflow. The algorithm then becomes: add and conditionally set the destination to unsigned(-1), if overflow was detected.</p>\n<pre class=\"lang-c prettyprint-override\"><code>uint16_t add16(uint16_t a, uint16_t b)\n{\n uint16_t c = a + b;\n if (c &lt; a) /* Can only happen due to overflow */\n c = -1;\n return c;\n}\n</code></pre>\n<p>Note that this differs from the other algorithms in that it corrects overflow, instead of relying on another calculation to detect overflow.</p>\n<p><a href=\"https://gcc.godbolt.org/#%7B%22version%22%3A3%2C%22filterAsm%22%3A%7B%22labels%22%3Atrue%2C%22directives%22%3Atrue%2C%22commentOnly%22%3Atrue%2C%22intel%22%3Atrue%7D%2C%22compilers%22%3A%5B%7B%22sourcez%22%3A%22MQSwdgxgNgrgJgUwAQB4DOAXO4MDoAWAfAFCgBmSAjEjQPS1IgQRICGAbgPYhxpIQBbTuyQB3EBnxJJCNMnBIBaVlAwIATmgDkSdhrQhOYUojLhkUEAGsEUAJ4AKAB4BKGu5oB9TwCMYIVXBPBCcABwQIDAcAQmjnFwAaKhcTBDMwZBgwSxt7eI8kbz8AjCCQ8MiYuNckgAYU4Fs5VPSLa1tHVwKaJxbzJCycjvyPXsawbDJiYnokAGVOdTU4RjAkRcR1dYooBFZMJB9WFaMkJwAOADYk8UkkAHNmAFZp%2FzAMSkvPDDY4Xk%2FPEoVGpNA43h8vj9WElwQCfj43ABvYg0WGQ%2FhIAC8bCQAGpDgBuFGMCgOCAoVhuWgAKiQAGFWGsjPYkPhWKFwms4DBkBhOOs9OoyFBOKIkNTaMSaCxsQBaShEmjqBAYGDqNYQIkAX2I4IAzAAmb6%2FXiGwHKVT6ME4M1QmE2o3wpHE%2FWOjHY1h4wnEkCk8mUpA0%2BmM9bZOys9mcpDc3n84QaYWi8WSjwypDyxVIZWq9X8bXTcjRtLmFYObwgPVXbxuAA%2BNaLrVL3guX0uABZqzMGAAVADyABFewAuJC7H4yficAShAIaJBWMBJySscf4ZCccLqRm8NjK1YgiBssD3PY%2BXbTWY8PZQFmHiJWQqeECXKueJBkRb8ITsJJ%2BVcrrQ%2BGZcNTBLd9PxDVhIhgFRGBfS5pFYdQTwwJJFx%2BBBcHuXAIzQURbCgXUHWNY5TSNFtPFCAArCBAWEa13ltNh7UYt0EWIRE6AYNB8EWEF%2BHUCQmBUWVQhXKQoBXBBIHDHxwyMZAIDsaBeSPaQ1yQNAfB8XR9EMYwPFdY0MGnLF0wVKVuis9xZk4gBBbsADJuw8esAEl3lsJAtRoNA7HeVgnDYS11RXEA9DQHCkG7DTOBkLZBQMIw%2BFuXiYFXEA%2BDEAIoEOZVWAfVL0wEfYBExHBbEs0qkAcAAiUiCk4gBSABtHwAF0Ela1h2vcetus6mhWo67yAB0wFGjBassgpasEYRIBoZqWp6rqWt4DBev69bME6gbvOm6ykBHHbNqQWrcXUWqapM0JEiQFbeouxyrpqykZo8E6Rtq%2B5rocBFAwYGA5HO9QBAQa6Py2T12x8CRdM0fSkgMSB5B%2BTAcoGOQ%2BENOH0ZAe4wFlEI1AmBAVhAARwewKSPpshhF34EVtP0OmaBcTMlRVNU1lu%2FMjKhP40DNCjqNorSfAYjAmOhAZiKdDiuM0kqbznCBOEQWUDAALwQX90tHIwTy2CBBNKCARLEu5JNJpSarbFhTgACX2fCbySPVHbWOyAFl%2BzYCYkAAIXUThjjdqBaDmKw7EkmwUnpzTtMYIDeY002hIt3KrfwGFsnaRRhHMqKJYDlZ5pEJDVOQZRwdHKSZNDYLcrpAAFABVNApVmUva71vvo04WQwC0eF8ofCdEE5RBG9OCdOCgFZ2BUHltmjA5TkZcMYPUQ8kBCCAEFCH5ff7SyBekadObYNABBq%2Bq%2FgKYbBoG8bJsO6zatLjxWo2l%2FTvam%2FKabNzqfifo9JIv9dofysidP%2B51MSvQcLde6j1zq4hen9d6R0vpPV%2BjVdiR0OaWWzDzS%2BoR%2BbyxNMLciVYxZPjAKESSh8pYyxYtLNiKROJKwtmsZUwNq6aVYHXeUWYED3EyiCfWPxeGjyQKEUO3JD7qWQMqNAMBVCrBxBkMUyoJGYA0FVW%2B98GpIGfpAx6QCYHdDmt%2BFgrVlCbQsT1axBQTo9XQZgt6CdrK4POvg%2F6qDHFPSQfKKkDB1YaJWAIgOoMBDXXVmATAW4cBNxasE6RhtjjgHuOZd8oc77gyEOocMmVowwAED4ZG%2FJMAbiZoyXJZACmaV4nFHJjAMByCgBQBQE4PxxRAcQjwpDcysHzOMSYrwkkEwyCsRxaopKeFIp4cEngbDsHAGCaZhNyZnDzgYHZKw7DOg8L6GqdhCDtzcgAOW7GaH2dkAAasougjLWFc259ynnXzeWcXEdhKHvDhEIv4AJlRCClsC2WaJjSEPcJxX5DhPSECQLUJwAAxTF6L0yHDcAAflRRirFx0cT4h8ASbyrwqHKD%2BGacFnBWFumhVQuFS0xE5jWEipAKK0VYr5di2UuKkAEt5fyzFJLPRkoJDqaYRFWLGhpXAOljKSLsKYgDbhswmlTiQAAJVwOfHA7YFVmSlsajALhWC4nJSQ7muZZQODQIQQghpaw1QFi4NA%2BY%2BgZBBXAT4SLfxuHdTgOELgHA1RVRapFLhcRRvDQiNwPKnBkFTRQEVKa00kocDGuNiaUgX0VWaDcUbmJy3lU6JACK7Wco9RGnN4JzXhspHGxtHZo2Ju5YStNPb03dt7am7NubAkuA5pSi8QMwBQ1VGAKSt4pwzl2HwPk0hRD8kSdgUoRhYI%2BC3JANcQETbflkL%2BCIrAYnq2nLOTQg8R4%2FHuKHCe%2BBMpyo4QqlcCy1BLNpUaOAJ53glNLcyitQrkSGWpRUsykrvSnNJI6yDKA2C1nrPBu%2BiHE1s1%2BQAPwbfLFw9Rr5NAQJhmtmkKnakDLSeZW4v2kUNMmV9wLqOLNIgCP90kMCAZhXactEJYUnPcNxsjd8PRehtbByN6i0NIaQHWGqUnUC4p8d0bDuGgWQnw0M9wRGSMcuExRoMzHaOgoQhKWVXZooHuQP%2BjQUlWSLEEmeRSGtkBDgcBZuYAB1OyuqkDnC0YaV9TE5grjsn8du2zZnnE8F5nzngwABDQKWpwaq3THKrS6alMySpoAfNiNF5xaiFeK7UTMF8MC1FNeGAAemcNwjlNLZf2FYMrVCPhVaQA1roDWDlgByy14kQVHLYiw71%2FrmZwzDaQKNpruXMxBVxNiAFxJ2s1mxBVzrZxMztexMg6gKBEOUDcIKvb3KUUAHYtOIqCrVirbqPiArfT8ELGAwtwAi718mZoEtQD4Ml1Lxp0tgd40xMbzWzIFdqFD6HpXMsgY27tmrdXNtg7m3Dp70hqCI8291xrhNxuDc6yN1HA2aCTeJ7N0nZw8RLe29QNb0hKtdbp6a9rB3kg4tO86pAeojuZmu0gW79RZOY%2B9RZz7cyP00f0sQLLhzPCKs8C7MAi44BUQQA4KhssWUuGBzQCDIm2DWuvlQ%2BMQoRRil20i6rUmXCOX%2Bjbipo7nW85%2BaRhwZvEyiAO7zlw1XUPc494KL3jlffEJlakkqmzdc6iAAAA%22%2C%22compiler%22%3A%22g530%22%2C%22options%22%3A%22-xc%20-Wall%20-fverbose-asm%20%20-O3%20-mtune%3Dhaswell%22%7D%5D%7D\" rel=\"noreferrer\">x86-64 clang 3.7 -O3 output for adds32</a>: significantly better than any other answer:</p>\n<pre class=\"lang-asm prettyprint-override\"><code>add edi, esi\nmov eax, -1\ncmovae eax, edi\nret\n</code></pre>\n<p><a href=\"https://gcc.godbolt.org/#%7B%22version%22%3A3%2C%22filterAsm%22%3A%7B%22labels%22%3Atrue%2C%22directives%22%3Atrue%2C%22commentOnly%22%3Atrue%7D%2C%22compilers%22%3A%5B%7B%22sourcez%22%3A%22MQSwdgxgNgrgJgUwAQB4DOAXO4MDoAWAfAFCgBmSAjEjQPS1IgQRICGAbgPYhxpIQBbTuyQB3EBnxJJCNMnBIBaVlAwIATmgDkSdhrQhOYUojLhkUEAGsEUAJ4AKAB4BKGu5oB9TwCMYIVXBPBCcABwQIDAcAQmjnFwAaKhcTBDMwZBgwSxt7eI8kbz8AjCCQ8MiYuNckgAYU4Fs5VPSLa1tHVwKaJxbzJCycjvyPXsawbDJiYnokAGVOdTU4RjAkRcR1dYooBFZMJB9WFaMkJwAOADYk8UkkAHNmAFZp%2FzAMSkvPDDY4Xk%2FPEoVGpNA43h8vj9WElwQCfj43ABvYg0WGQ%2FhIAC8bCQAGpDgBuFGMCgOCAoVhuWgAKiQAGFWGsjPYkPhWKFwms4DBkBhOOs9OoyFBOKIkNTaMSaCxsQBaShEmjqBAYGDqNYQIkAX2I4IAzAAmb6%2FXiGwHKVT6ME4M1QmE2o3wpHE%2FWOjHY1h4wnEkCk8mUpA0%2BmM9bZOys9mcpDc3n84QaYWi8WSjwypDyxVIZWq9X8bXTcjRtLmFYObwgPVXbxuAA%2BNaLrVL3guX0uABZqzMGAAVADyABFewAuJC7H4yficAShAIaJBWMBJySscf4ZCccLqRm8NjK1YgiBssD3PY%2BXbTWY8PZQFmHiJWQqeECXKueJBkRb8ITsJJ%2BVcrrQ%2BGZcNTBLd9PxDVhIhgFRGBfS5pFYdQTwwJJFx%2BBBcHuXAIzQURbCgXUHWNY5TSNFtPFCAArCBAWEa13ltNh7UYt0EWIRE6AYNB8EWEF%2BHUCQmBUWVQhXKQoBXBBIHDHxwyMZAIDsaBeSPaQ1yQNAfB8XR9EMYwPFdY0MGnLF0wVKVuis9xZk4gBBbsADJuw8esAEl3lsJAtRoNA7HeVgnDYS11RXEA9DQHCkG7DTOBkLZBQMIw%2BFuXiYFXEA%2BDEAIoEOZVWAfVL0wEfYBExHBbEs0qkAcAAiUiCk4gBSABtHwAF0Ela1h2vcetus6mhWo67yAB0wFGjBassgpasEYRIBoZqWp6rqWt4DBev69bME6gbvOm6ykBHHbNqQWrcXUWqapM0JEiQFbeouxyrpqykZo8E6Rtq%2B5rocBFAwYGA5HO9QBAQa6Py2T12x8CRdM0fSkgMSB5B%2BTAcoGOQ%2BENOH0ZAe4wFlEI1AmBAVhAARwewKSPpshhF34EVtP0OmaBcTMlRVNU1lu%2FMjKhP40DNCjqNorSfAYjAmOhAZiKdDiuM0kqbznCBOEQWUDAALwQX90tHIwTy2CBBNKCARLEu5JNJpSarbFhTgACX2fCbySPVHbWOyAFl%2BzYCYkAAIXUThjjdqBaDmKw7EkmwUnpzTtMYIDeY002hIt3KrfwGFsnaRRhHMqKJYDlZ5pEJDVOQZRwdHKSZNDYLcrpAAFABVNApVmUva71vvo04WQwC0eF8ofCdEE5RBG9OCdOCgFZ2BUHltmjA5TkZcMYPUQ8kBCCAEFCH5ff7SyBekadObYNABBq%2Bq%2FgKYbBoG8bJsO6zatLjxWo2l%2FTvam%2FKabNzqfifo9JIv9dofysidP%2B51MSvQcLde6j1zq4hen9d6R0vpPV%2BjVdiR0OaWWzDzS%2BoR%2BbyxNMLciVYxZPjAKESSh8pYyxYtLNiKROJKwtmsZUwNq6aVYHXeUWYED3EyiCfWPxeGjyQKEUO3JD7qWQMqNAMBVCrBxBkMUyoJGYA0FVW%2B98GpIGfpAx6QCYHdDmt%2BFgrVlCbQsT1axBQTo9XQZgt6CdrK4POvg%2F6qDHFPSQfKKkDB1YaJWAIgOoMBDXXVmATAW4cBNxasE6RhtjjgHuOZd8oc77gyEOocMmVowwAED4ZG%2FJMAbiZoyXJZACmaV4nFHJjAMByCgBQBQE4PxxRAcQjwpDcysHzOMSYrwkkEwyCsRxaopKeFIp4cEngbDsHAGCaZhNyZnDzgYHZKw7DOg8L6GqdhCDtzcgAOW7GaH2dkAAasougjLWFc259ynnXzeWcXEdhKHvDhEIv4AJlRCClsC2WaJjSEPcJxX5DhPSECQLUJwAAxTF6L0yHDcAAflRRirFx0cT4h8ASbyrwqHKD%2BGacFnBWFumhVQuFS0xE5jWEipAKK0VYr5di2UuKkAEt5fyzFJLPRkoJDqaYRFWLGhpXAOljKSLsKYgDbhswmlTiQAAJVwOfHA7YFVmSlsajALhWC4nJSQ7muZZQODQIQQghpaw1QFi4NA%2BY%2BgZBBXAT4SLfxuHdTgOELgHA1RVRapFLhcRRvDQiNwPKnBkFTRQEVKa00kocDGuNiaUgX0VWaDcUbmJy3lU6JACK7Wco9RGnN4JzXhspHGxtHZo2Ju5YStNPb03dt7am7NubAkuA5pSi8QMwBQ1VGAKSt4pwzl2HwPk0hRD8kSdgUoRhYI%2BC3JANcQETbflkL%2BCIrAYnq2nLOTQg8R4%2FHuKHCe%2BBMpyo4QqlcCy1BLNpUaOAJ53glNLcyitQrkSGWpRUsykrvSnNJI6yDKA2C1nrPBu%2BiHE1s1%2BQAPwbfLFw9Rr5NAQJhmtmkKnakDLSeZW4v2kUNMmV9wLqOLNIgCP90kMCAZhXactEJYUnPcNxsjd8PRehtbByN6i0NIaQHWGqUnUC4p8d0bDuGgWQnw0M9wRGSMcuExRoMzHaOgoQhKWVXZooHuQP%2BjQUlWSLEEmeRSGtkBDgcBZuYAB1OyuqkDnC0YaV9TE5grjsn8du2zZnnE8F5nzngwABDQKWpwaq3THKrS6alMySpoAfNiNF5xaiFeK7UTMF8MC1FNeGAAemcNwjlNLZf2FYMrVCPhVaQA1roDWDlgByy14kQVHLYiw71%2FrmZwzDaQKNpruXMxBVxNiAFxJ2s1mxBVzrZxMztexMg6gKBEOUDcIKvb3KUUAHYtOIqCrVirbqPiArfT8ELGAwtwAi718mZoEtQD4Ml1Lxp0tgd40xMbzWzIFdqFD6HpXMsgY27tmrdXNtg7m3Dp70hqCI8291xrhNxuDc6yN1HA2aCTeJ7N0nZw8RLe29QNb0hKtdbp6a9rB3kg4tO86pAeojuZmu0gW79RZOY%2B9RZz7cyP00f0sQLLhzPCKs8C7MAi44BUQQA4KhssWUuGBzQCDIm2DWuvlQ%2BMQoRRil20i6rUmXCOX%2Bjbipo7nW85%2BaRhwZvEyiAO7zlw1XUPc494KL3jlffEJlakkqmzdc6iAAAA%22%2C%22compiler%22%3A%22armhfg482%22%2C%22options%22%3A%22-xc%20-std%3Dgnu99%20-Wall%20-pedantic%20-Wextra%20-fverbose-asm%20%20-O3%20-march%3Darmv7%22%7D%5D%7D\" rel=\"noreferrer\">ARMv7: <code>gcc 4.8 -O3 -mcpu=cortex-a15 -fverbose-asm</code> output for adds32</a>:</p>\n<pre class=\"lang-asm prettyprint-override\"><code>adds r0, r0, r1 @ c, a, b\nit cs\nmovcs r0, #-1 @ conditional-move\nbx lr\n</code></pre>\n<p>16bit: still doesn't use ARM's unsigned-saturating add instruction (<code>UADD16</code>)</p>\n<pre class=\"lang-asm prettyprint-override\"><code>add r1, r1, r0 @ tmp114, a\nmovw r3, #65535 @ tmp116,\nuxth r1, r1 @ c, tmp114\ncmp r0, r1 @ a, c\nite ls @\nmovls r0, r1 @,, c\nmovhi r0, r3 @,, tmp116\nbx lr @\n</code></pre>\n" }, { "answer_id": 3431717, "author": "R.. GitHub STOP HELPING ICE", "author_id": 379897, "author_profile": "https://Stackoverflow.com/users/379897", "pm_score": 3, "selected": false, "text": "<p>Zero branch solution:</p>\n\n<pre><code>uint32_t sadd32(uint32_t a, uint32_t b)\n{\n uint64_t s = (uint64_t)a+b;\n return -(s&gt;&gt;32) | (uint32_t)s;\n}\n</code></pre>\n\n<p>A good compiler will optimize this to avoid doing any actual 64-bit arithmetic (<code>s&gt;&gt;32</code> will merely be the carry flag, and <code>-(s&gt;&gt;32)</code> is the result of <code>sbb %eax,%eax</code>).</p>\n\n<p>In x86 asm (AT&amp;T syntax, <code>a</code> and <code>b</code> in <code>eax</code> and <code>ebx</code>, result in <code>eax</code>):</p>\n\n<pre><code>add %eax,%ebx\nsbb %eax,%eax\nor %ebx,%eax\n</code></pre>\n\n<p>8- and 16-bit versions should be obvious. Signed version might require a bit more work.</p>\n" }, { "answer_id": 24263421, "author": "0xbadf00d", "author_id": 547231, "author_profile": "https://Stackoverflow.com/users/547231", "pm_score": 0, "selected": false, "text": "<p>Using C++ you could write a more flexible variant of <em>Remo.D</em>'s solution:</p>\n\n<pre><code>template&lt;typename T&gt;\nT sadd(T first, T second)\n{\n static_assert(std::is_integral&lt;T&gt;::value, \"sadd is not defined for non-integral types\");\n return first &gt; std::numeric_limits&lt;T&gt;::max() - second ? std::numeric_limits&lt;T&gt;::max() : first + second;\n}\n</code></pre>\n\n<p>This can be easily translated to C - using the limits defined in <code>limits.h</code>. Please also note that the <a href=\"http://en.cppreference.com/w/cpp/types/integer\" rel=\"nofollow\">Fixed width integer types</a> might not been available on your system.</p>\n" }, { "answer_id": 28074266, "author": "Ian Rogers", "author_id": 4479555, "author_profile": "https://Stackoverflow.com/users/4479555", "pm_score": 1, "selected": false, "text": "<p>An alternative to the branch free x86 asm solution is (AT&amp;T syntax, a and b in eax and ebx, result in eax):</p>\n\n<pre><code>add %eax,%ebx\nsbb $0,%ebx\n</code></pre>\n" }, { "answer_id": 32883349, "author": "Hannodje", "author_id": 5396658, "author_profile": "https://Stackoverflow.com/users/5396658", "pm_score": 2, "selected": false, "text": "<p>Just in case someone wants to know an implementation without branching using 2's complement 32bit integers.</p>\n\n<p>Warning! This code uses the undefined operation: \"shift right by -1\" and therefore exploits the property of the <a href=\"http://eun.github.io/Intel-Pentium-Instruction-Set-Reference/data/shl.html\" rel=\"nofollow\">Intel Pentium SAL instruction</a> to mask the count operand to 5 bits.</p>\n\n<pre><code>int32_t sadd(int32_t a, int32_t b){\n int32_t sum = a+b;\n int32_t overflow = ((a^sum)&amp;(b^sum))&gt;&gt;31;\n return (overflow&lt;&lt;31)^(sum&gt;&gt;overflow);\n }\n</code></pre>\n\n<p>It's the best implementation known to me</p>\n" }, { "answer_id": 35877883, "author": "twostickes", "author_id": 6036406, "author_profile": "https://Stackoverflow.com/users/6036406", "pm_score": 0, "selected": false, "text": "<pre><code>//function-like macro to add signed vals, \n//then test for overlow and clamp to max if required\n#define SATURATE_ADD(a,b,val) ( {\\\nif( (a&gt;=0) &amp;&amp; (b&gt;=0) )\\\n{\\\n val = a + b;\\\n if (val &lt; 0) {val=0x7fffffff;}\\\n}\\\nelse if( (a&lt;=0) &amp;&amp; (b&lt;=0) )\\\n{\\\n val = a + b;\\\n if (val &gt; 0) {val=-1*0x7fffffff;}\\\n}\\\nelse\\\n{\\\n val = a + b;\\\n}\\\n})\n</code></pre>\n\n<p>I did a quick test and seems to work, but not extensively bashed it yet! This works with SIGNED 32 bit.\nop : the editor used on the web page does not let me post a macro ie its not understanding non-indented syntax etc!</p>\n" }, { "answer_id": 46358478, "author": "Shangchih Huang", "author_id": 7537655, "author_profile": "https://Stackoverflow.com/users/7537655", "pm_score": 1, "selected": false, "text": "<pre><code>int saturating_add(int x, int y)\n{\n int w = sizeof(int) &lt;&lt; 3;\n int msb = 1 &lt;&lt; (w-1);\n\n int s = x + y;\n int sign_x = msb &amp; x;\n int sign_y = msb &amp; y;\n int sign_s = msb &amp; s;\n\n int nflow = sign_x &amp;&amp; sign_y &amp;&amp; !sign_s;\n int pflow = !sign_x &amp;&amp; !sign_y &amp;&amp; sign_s;\n\n int nmask = (~!nflow + 1);\n int pmask = (~!pflow + 1);\n\n return (nmask &amp; ((pmask &amp; s) | (~pmask &amp; ~msb))) | (~nmask &amp; msb);\n}\n</code></pre>\n\n<p>This implementation doesn't use control flows, campare operators(<code>==</code>, <code>!=</code>) and the <code>?:</code> operator. It just uses bitwise operators and logical operators.</p>\n" }, { "answer_id": 52411672, "author": "Alexei Shcherbakov", "author_id": 7815105, "author_profile": "https://Stackoverflow.com/users/7815105", "pm_score": 0, "selected": false, "text": "<p>Saturation arithmetic is not standard for C, but it's often implemented via compiler intrinsics, so the most efficient way will not be the cleanest. You must add <code>#ifdef</code> blocks to select the proper way. MSalters's answer is the fastest for x86 architecture. For ARM you need to use <code>__qadd16</code> function (ARM compiler) of <code>_arm_qadd16</code> (Microsoft Visual Studio) for 16 bit version and <code>__qadd</code> for 32-bit version. They'll be automatically translated to one ARM instruction.</p>\n\n<p><em>Links:</em></p>\n\n<ul>\n<li><a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0491c/CJAICDDF.html\" rel=\"nofollow noreferrer\"><code>__qadd16</code></a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/cpp/intrinsics/arm-intrinsics?view=vs-2019\" rel=\"nofollow noreferrer\"><code>_arm_qadd16</code></a></li>\n<li><a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0472m/chr1359125002575.html\" rel=\"nofollow noreferrer\"><code>__qadd</code></a></li>\n</ul>\n" }, { "answer_id": 70403351, "author": "Arty", "author_id": 941531, "author_profile": "https://Stackoverflow.com/users/941531", "pm_score": 0, "selected": false, "text": "<p>I'll add solutions that were not yet mentioned above.</p>\n<p>There exists <a href=\"https://x86.puri.sm/html/file_module_x86_id_4.html\" rel=\"nofollow noreferrer\">ADC</a> instruction in Intel x86. It is represented as <a href=\"https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#ig_expand=196,196,226,196&amp;techs=SSE,SSE2,Other&amp;text=addcarry_u32\" rel=\"nofollow noreferrer\">_addcarry_u32()</a> intrinsic function. For ARM there should be similar intrinsic.</p>\n<p>Which allows us to implement very fast <code>uint32_t</code> saturated addition for Intel x86:</p>\n<p><a href=\"https://godbolt.org/z/8snavvP9G\" rel=\"nofollow noreferrer\">Try it online!</a></p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdint.h&gt;\n#include &lt;immintrin.h&gt;\n\nuint32_t add_sat_u32(uint32_t a, uint32_t b) {\n uint32_t r, carry = _addcarry_u32(0, a, b, &amp;r);\n return r | (-carry);\n}\n</code></pre>\n<p>Intel x86 MMX saturated addition instructions can be used to implement <code>uint16_t</code> variant:</p>\n<p><a href=\"https://godbolt.org/z/o7azhsqz1\" rel=\"nofollow noreferrer\">Try it online!</a></p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdint.h&gt;\n#include &lt;immintrin.h&gt;\n\nuint16_t add_sat_u16(uint16_t a, uint16_t b) {\n return _mm_cvtsi64_si32(_mm_adds_pu16(\n _mm_cvtsi32_si64(a),\n _mm_cvtsi32_si64(b)\n ));\n}\n</code></pre>\n<p>I don't mention ARM solution, as it can be implemented by other generic solutions from other answers.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8964/" ]
What is the best (cleanest, most efficient) way to write saturating addition in C? The function or macro should add two unsigned inputs (need both 16- and 32-bit versions) and return all-bits-one (0xFFFF or 0xFFFFFFFF) if the sum overflows. Target is x86 and ARM using gcc (4.1.2) and Visual Studio (for simulation only, so a fallback implementation is OK there).
You probably want portable C code here, which your compiler will turn into proper ARM assembly. ARM has conditional moves, and these can be conditional on overflow. The algorithm then becomes: add and conditionally set the destination to unsigned(-1), if overflow was detected. ```c uint16_t add16(uint16_t a, uint16_t b) { uint16_t c = a + b; if (c < a) /* Can only happen due to overflow */ c = -1; return c; } ``` Note that this differs from the other algorithms in that it corrects overflow, instead of relying on another calculation to detect overflow. [x86-64 clang 3.7 -O3 output for adds32](https://gcc.godbolt.org/#%7B%22version%22%3A3%2C%22filterAsm%22%3A%7B%22labels%22%3Atrue%2C%22directives%22%3Atrue%2C%22commentOnly%22%3Atrue%2C%22intel%22%3Atrue%7D%2C%22compilers%22%3A%5B%7B%22sourcez%22%3A%22MQSwdgxgNgrgJgUwAQB4DOAXO4MDoAWAfAFCgBmSAjEjQPS1IgQRICGAbgPYhxpIQBbTuyQB3EBnxJJCNMnBIBaVlAwIATmgDkSdhrQhOYUojLhkUEAGsEUAJ4AKAB4BKGu5oB9TwCMYIVXBPBCcABwQIDAcAQmjnFwAaKhcTBDMwZBgwSxt7eI8kbz8AjCCQ8MiYuNckgAYU4Fs5VPSLa1tHVwKaJxbzJCycjvyPXsawbDJiYnokAGVOdTU4RjAkRcR1dYooBFZMJB9WFaMkJwAOADYk8UkkAHNmAFZp%2FzAMSkvPDDY4Xk%2FPEoVGpNA43h8vj9WElwQCfj43ABvYg0WGQ%2FhIAC8bCQAGpDgBuFGMCgOCAoVhuWgAKiQAGFWGsjPYkPhWKFwms4DBkBhOOs9OoyFBOKIkNTaMSaCxsQBaShEmjqBAYGDqNYQIkAX2I4IAzAAmb6%2FXiGwHKVT6ME4M1QmE2o3wpHE%2FWOjHY1h4wnEkCk8mUpA0%2BmM9bZOys9mcpDc3n84QaYWi8WSjwypDyxVIZWq9X8bXTcjRtLmFYObwgPVXbxuAA%2BNaLrVL3guX0uABZqzMGAAVADyABFewAuJC7H4yficAShAIaJBWMBJySscf4ZCccLqRm8NjK1YgiBssD3PY%2BXbTWY8PZQFmHiJWQqeECXKueJBkRb8ITsJJ%2BVcrrQ%2BGZcNTBLd9PxDVhIhgFRGBfS5pFYdQTwwJJFx%2BBBcHuXAIzQURbCgXUHWNY5TSNFtPFCAArCBAWEa13ltNh7UYt0EWIRE6AYNB8EWEF%2BHUCQmBUWVQhXKQoBXBBIHDHxwyMZAIDsaBeSPaQ1yQNAfB8XR9EMYwPFdY0MGnLF0wVKVuis9xZk4gBBbsADJuw8esAEl3lsJAtRoNA7HeVgnDYS11RXEA9DQHCkG7DTOBkLZBQMIw%2BFuXiYFXEA%2BDEAIoEOZVWAfVL0wEfYBExHBbEs0qkAcAAiUiCk4gBSABtHwAF0Ela1h2vcetus6mhWo67yAB0wFGjBassgpasEYRIBoZqWp6rqWt4DBev69bME6gbvOm6ykBHHbNqQWrcXUWqapM0JEiQFbeouxyrpqykZo8E6Rtq%2B5rocBFAwYGA5HO9QBAQa6Py2T12x8CRdM0fSkgMSB5B%2BTAcoGOQ%2BENOH0ZAe4wFlEI1AmBAVhAARwewKSPpshhF34EVtP0OmaBcTMlRVNU1lu%2FMjKhP40DNCjqNorSfAYjAmOhAZiKdDiuM0kqbznCBOEQWUDAALwQX90tHIwTy2CBBNKCARLEu5JNJpSarbFhTgACX2fCbySPVHbWOyAFl%2BzYCYkAAIXUThjjdqBaDmKw7EkmwUnpzTtMYIDeY002hIt3KrfwGFsnaRRhHMqKJYDlZ5pEJDVOQZRwdHKSZNDYLcrpAAFABVNApVmUva71vvo04WQwC0eF8ofCdEE5RBG9OCdOCgFZ2BUHltmjA5TkZcMYPUQ8kBCCAEFCH5ff7SyBekadObYNABBq%2Bq%2FgKYbBoG8bJsO6zatLjxWo2l%2FTvam%2FKabNzqfifo9JIv9dofysidP%2B51MSvQcLde6j1zq4hen9d6R0vpPV%2BjVdiR0OaWWzDzS%2BoR%2BbyxNMLciVYxZPjAKESSh8pYyxYtLNiKROJKwtmsZUwNq6aVYHXeUWYED3EyiCfWPxeGjyQKEUO3JD7qWQMqNAMBVCrBxBkMUyoJGYA0FVW%2B98GpIGfpAx6QCYHdDmt%2BFgrVlCbQsT1axBQTo9XQZgt6CdrK4POvg%2F6qDHFPSQfKKkDB1YaJWAIgOoMBDXXVmATAW4cBNxasE6RhtjjgHuOZd8oc77gyEOocMmVowwAED4ZG%2FJMAbiZoyXJZACmaV4nFHJjAMByCgBQBQE4PxxRAcQjwpDcysHzOMSYrwkkEwyCsRxaopKeFIp4cEngbDsHAGCaZhNyZnDzgYHZKw7DOg8L6GqdhCDtzcgAOW7GaH2dkAAasougjLWFc259ynnXzeWcXEdhKHvDhEIv4AJlRCClsC2WaJjSEPcJxX5DhPSECQLUJwAAxTF6L0yHDcAAflRRirFx0cT4h8ASbyrwqHKD%2BGacFnBWFumhVQuFS0xE5jWEipAKK0VYr5di2UuKkAEt5fyzFJLPRkoJDqaYRFWLGhpXAOljKSLsKYgDbhswmlTiQAAJVwOfHA7YFVmSlsajALhWC4nJSQ7muZZQODQIQQghpaw1QFi4NA%2BY%2BgZBBXAT4SLfxuHdTgOELgHA1RVRapFLhcRRvDQiNwPKnBkFTRQEVKa00kocDGuNiaUgX0VWaDcUbmJy3lU6JACK7Wco9RGnN4JzXhspHGxtHZo2Ju5YStNPb03dt7am7NubAkuA5pSi8QMwBQ1VGAKSt4pwzl2HwPk0hRD8kSdgUoRhYI%2BC3JANcQETbflkL%2BCIrAYnq2nLOTQg8R4%2FHuKHCe%2BBMpyo4QqlcCy1BLNpUaOAJ53glNLcyitQrkSGWpRUsykrvSnNJI6yDKA2C1nrPBu%2BiHE1s1%2BQAPwbfLFw9Rr5NAQJhmtmkKnakDLSeZW4v2kUNMmV9wLqOLNIgCP90kMCAZhXactEJYUnPcNxsjd8PRehtbByN6i0NIaQHWGqUnUC4p8d0bDuGgWQnw0M9wRGSMcuExRoMzHaOgoQhKWVXZooHuQP%2BjQUlWSLEEmeRSGtkBDgcBZuYAB1OyuqkDnC0YaV9TE5grjsn8du2zZnnE8F5nzngwABDQKWpwaq3THKrS6alMySpoAfNiNF5xaiFeK7UTMF8MC1FNeGAAemcNwjlNLZf2FYMrVCPhVaQA1roDWDlgByy14kQVHLYiw71%2FrmZwzDaQKNpruXMxBVxNiAFxJ2s1mxBVzrZxMztexMg6gKBEOUDcIKvb3KUUAHYtOIqCrVirbqPiArfT8ELGAwtwAi718mZoEtQD4Ml1Lxp0tgd40xMbzWzIFdqFD6HpXMsgY27tmrdXNtg7m3Dp70hqCI8291xrhNxuDc6yN1HA2aCTeJ7N0nZw8RLe29QNb0hKtdbp6a9rB3kg4tO86pAeojuZmu0gW79RZOY%2B9RZz7cyP00f0sQLLhzPCKs8C7MAi44BUQQA4KhssWUuGBzQCDIm2DWuvlQ%2BMQoRRil20i6rUmXCOX%2Bjbipo7nW85%2BaRhwZvEyiAO7zlw1XUPc494KL3jlffEJlakkqmzdc6iAAAA%22%2C%22compiler%22%3A%22g530%22%2C%22options%22%3A%22-xc%20-Wall%20-fverbose-asm%20%20-O3%20-mtune%3Dhaswell%22%7D%5D%7D): significantly better than any other answer: ```asm add edi, esi mov eax, -1 cmovae eax, edi ret ``` [ARMv7: `gcc 4.8 -O3 -mcpu=cortex-a15 -fverbose-asm` output for adds32](https://gcc.godbolt.org/#%7B%22version%22%3A3%2C%22filterAsm%22%3A%7B%22labels%22%3Atrue%2C%22directives%22%3Atrue%2C%22commentOnly%22%3Atrue%7D%2C%22compilers%22%3A%5B%7B%22sourcez%22%3A%22MQSwdgxgNgrgJgUwAQB4DOAXO4MDoAWAfAFCgBmSAjEjQPS1IgQRICGAbgPYhxpIQBbTuyQB3EBnxJJCNMnBIBaVlAwIATmgDkSdhrQhOYUojLhkUEAGsEUAJ4AKAB4BKGu5oB9TwCMYIVXBPBCcABwQIDAcAQmjnFwAaKhcTBDMwZBgwSxt7eI8kbz8AjCCQ8MiYuNckgAYU4Fs5VPSLa1tHVwKaJxbzJCycjvyPXsawbDJiYnokAGVOdTU4RjAkRcR1dYooBFZMJB9WFaMkJwAOADYk8UkkAHNmAFZp%2FzAMSkvPDDY4Xk%2FPEoVGpNA43h8vj9WElwQCfj43ABvYg0WGQ%2FhIAC8bCQAGpDgBuFGMCgOCAoVhuWgAKiQAGFWGsjPYkPhWKFwms4DBkBhOOs9OoyFBOKIkNTaMSaCxsQBaShEmjqBAYGDqNYQIkAX2I4IAzAAmb6%2FXiGwHKVT6ME4M1QmE2o3wpHE%2FWOjHY1h4wnEkCk8mUpA0%2BmM9bZOys9mcpDc3n84QaYWi8WSjwypDyxVIZWq9X8bXTcjRtLmFYObwgPVXbxuAA%2BNaLrVL3guX0uABZqzMGAAVADyABFewAuJC7H4yficAShAIaJBWMBJySscf4ZCccLqRm8NjK1YgiBssD3PY%2BXbTWY8PZQFmHiJWQqeECXKueJBkRb8ITsJJ%2BVcrrQ%2BGZcNTBLd9PxDVhIhgFRGBfS5pFYdQTwwJJFx%2BBBcHuXAIzQURbCgXUHWNY5TSNFtPFCAArCBAWEa13ltNh7UYt0EWIRE6AYNB8EWEF%2BHUCQmBUWVQhXKQoBXBBIHDHxwyMZAIDsaBeSPaQ1yQNAfB8XR9EMYwPFdY0MGnLF0wVKVuis9xZk4gBBbsADJuw8esAEl3lsJAtRoNA7HeVgnDYS11RXEA9DQHCkG7DTOBkLZBQMIw%2BFuXiYFXEA%2BDEAIoEOZVWAfVL0wEfYBExHBbEs0qkAcAAiUiCk4gBSABtHwAF0Ela1h2vcetus6mhWo67yAB0wFGjBassgpasEYRIBoZqWp6rqWt4DBev69bME6gbvOm6ykBHHbNqQWrcXUWqapM0JEiQFbeouxyrpqykZo8E6Rtq%2B5rocBFAwYGA5HO9QBAQa6Py2T12x8CRdM0fSkgMSB5B%2BTAcoGOQ%2BENOH0ZAe4wFlEI1AmBAVhAARwewKSPpshhF34EVtP0OmaBcTMlRVNU1lu%2FMjKhP40DNCjqNorSfAYjAmOhAZiKdDiuM0kqbznCBOEQWUDAALwQX90tHIwTy2CBBNKCARLEu5JNJpSarbFhTgACX2fCbySPVHbWOyAFl%2BzYCYkAAIXUThjjdqBaDmKw7EkmwUnpzTtMYIDeY002hIt3KrfwGFsnaRRhHMqKJYDlZ5pEJDVOQZRwdHKSZNDYLcrpAAFABVNApVmUva71vvo04WQwC0eF8ofCdEE5RBG9OCdOCgFZ2BUHltmjA5TkZcMYPUQ8kBCCAEFCH5ff7SyBekadObYNABBq%2Bq%2FgKYbBoG8bJsO6zatLjxWo2l%2FTvam%2FKabNzqfifo9JIv9dofysidP%2B51MSvQcLde6j1zq4hen9d6R0vpPV%2BjVdiR0OaWWzDzS%2BoR%2BbyxNMLciVYxZPjAKESSh8pYyxYtLNiKROJKwtmsZUwNq6aVYHXeUWYED3EyiCfWPxeGjyQKEUO3JD7qWQMqNAMBVCrBxBkMUyoJGYA0FVW%2B98GpIGfpAx6QCYHdDmt%2BFgrVlCbQsT1axBQTo9XQZgt6CdrK4POvg%2F6qDHFPSQfKKkDB1YaJWAIgOoMBDXXVmATAW4cBNxasE6RhtjjgHuOZd8oc77gyEOocMmVowwAED4ZG%2FJMAbiZoyXJZACmaV4nFHJjAMByCgBQBQE4PxxRAcQjwpDcysHzOMSYrwkkEwyCsRxaopKeFIp4cEngbDsHAGCaZhNyZnDzgYHZKw7DOg8L6GqdhCDtzcgAOW7GaH2dkAAasougjLWFc259ynnXzeWcXEdhKHvDhEIv4AJlRCClsC2WaJjSEPcJxX5DhPSECQLUJwAAxTF6L0yHDcAAflRRirFx0cT4h8ASbyrwqHKD%2BGacFnBWFumhVQuFS0xE5jWEipAKK0VYr5di2UuKkAEt5fyzFJLPRkoJDqaYRFWLGhpXAOljKSLsKYgDbhswmlTiQAAJVwOfHA7YFVmSlsajALhWC4nJSQ7muZZQODQIQQghpaw1QFi4NA%2BY%2BgZBBXAT4SLfxuHdTgOELgHA1RVRapFLhcRRvDQiNwPKnBkFTRQEVKa00kocDGuNiaUgX0VWaDcUbmJy3lU6JACK7Wco9RGnN4JzXhspHGxtHZo2Ju5YStNPb03dt7am7NubAkuA5pSi8QMwBQ1VGAKSt4pwzl2HwPk0hRD8kSdgUoRhYI%2BC3JANcQETbflkL%2BCIrAYnq2nLOTQg8R4%2FHuKHCe%2BBMpyo4QqlcCy1BLNpUaOAJ53glNLcyitQrkSGWpRUsykrvSnNJI6yDKA2C1nrPBu%2BiHE1s1%2BQAPwbfLFw9Rr5NAQJhmtmkKnakDLSeZW4v2kUNMmV9wLqOLNIgCP90kMCAZhXactEJYUnPcNxsjd8PRehtbByN6i0NIaQHWGqUnUC4p8d0bDuGgWQnw0M9wRGSMcuExRoMzHaOgoQhKWVXZooHuQP%2BjQUlWSLEEmeRSGtkBDgcBZuYAB1OyuqkDnC0YaV9TE5grjsn8du2zZnnE8F5nzngwABDQKWpwaq3THKrS6alMySpoAfNiNF5xaiFeK7UTMF8MC1FNeGAAemcNwjlNLZf2FYMrVCPhVaQA1roDWDlgByy14kQVHLYiw71%2FrmZwzDaQKNpruXMxBVxNiAFxJ2s1mxBVzrZxMztexMg6gKBEOUDcIKvb3KUUAHYtOIqCrVirbqPiArfT8ELGAwtwAi718mZoEtQD4Ml1Lxp0tgd40xMbzWzIFdqFD6HpXMsgY27tmrdXNtg7m3Dp70hqCI8291xrhNxuDc6yN1HA2aCTeJ7N0nZw8RLe29QNb0hKtdbp6a9rB3kg4tO86pAeojuZmu0gW79RZOY%2B9RZz7cyP00f0sQLLhzPCKs8C7MAi44BUQQA4KhssWUuGBzQCDIm2DWuvlQ%2BMQoRRil20i6rUmXCOX%2Bjbipo7nW85%2BaRhwZvEyiAO7zlw1XUPc494KL3jlffEJlakkqmzdc6iAAAA%22%2C%22compiler%22%3A%22armhfg482%22%2C%22options%22%3A%22-xc%20-std%3Dgnu99%20-Wall%20-pedantic%20-Wextra%20-fverbose-asm%20%20-O3%20-march%3Darmv7%22%7D%5D%7D): ```asm adds r0, r0, r1 @ c, a, b it cs movcs r0, #-1 @ conditional-move bx lr ``` 16bit: still doesn't use ARM's unsigned-saturating add instruction (`UADD16`) ```asm add r1, r1, r0 @ tmp114, a movw r3, #65535 @ tmp116, uxth r1, r1 @ c, tmp114 cmp r0, r1 @ a, c ite ls @ movls r0, r1 @,, c movhi r0, r3 @,, tmp116 bx lr @ ```
121,243
<p>What are some hidden features of <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="nofollow noreferrer">SQL Server</a>?</p> <p>For example, undocumented system stored procedures, tricks to do things which are very useful but not documented enough?</p> <hr> <h2>Answers</h2> <p><em>Thanks to everybody for all the great answers!</em></p> <p><strong>Stored Procedures</strong></p> <ul> <li><strong>sp_msforeachtable:</strong> Runs a command with '?' replaced with each table name (v6.5 and up)</li> <li><strong>sp_msforeachdb:</strong> Runs a command with '?' replaced with each database name (v7 and up)</li> <li><strong>sp_who2:</strong> just like sp_who, but with a lot more info for troubleshooting blocks (v7 and up)</li> <li><strong>sp_helptext:</strong> If you want the code of a stored procedure, view &amp; UDF</li> <li><strong>sp_tables:</strong> return a list of all tables and views of database in scope.</li> <li><strong>sp_stored_procedures:</strong> return a list of all stored procedures</li> <li><strong>xp_sscanf:</strong> Reads data from the string into the argument locations specified by each format argument.</li> <li><strong>xp_fixeddrives:</strong>: Find the fixed drive with largest free space</li> <li><strong>sp_help:</strong> If you want to know the table structure, indexes and constraints of a table. Also views and UDFs. Shortcut is Alt+F1</li> </ul> <p><strong>Snippets</strong></p> <ul> <li>Returning rows in random order</li> <li>All database User Objects by Last Modified Date</li> <li>Return Date Only</li> <li>Find records which date falls somewhere inside the current week.</li> <li>Find records which date occurred last week.</li> <li>Returns the date for the beginning of the current week.</li> <li>Returns the date for the beginning of last week.</li> <li>See the text of a procedure that has been deployed to a server</li> <li>Drop all connections to the database</li> <li>Table Checksum</li> <li>Row Checksum</li> <li>Drop all the procedures in a database</li> <li>Re-map the login Ids correctly after restore</li> <li>Call Stored Procedures from an INSERT statement</li> <li>Find Procedures By Keyword</li> <li>Drop all the procedures in a database</li> <li>Query the transaction log for a database programmatically.</li> </ul> <p><strong>Functions</strong></p> <ul> <li>HashBytes()</li> <li>EncryptByKey</li> <li>PIVOT command</li> </ul> <p><strong>Misc</strong></p> <ul> <li>Connection String extras</li> <li>TableDiff.exe</li> <li>Triggers for Logon Events (New in Service Pack 2)</li> <li>Boosting performance with persisted-computed-columns (pcc).</li> <li>DEFAULT_SCHEMA setting in sys.database_principles</li> <li>Forced Parameterization</li> <li>Vardecimal Storage Format</li> <li>Figuring out the most popular queries in seconds</li> <li>Scalable Shared Databases</li> <li>Table/Stored Procedure Filter feature in SQL Management Studio</li> <li>Trace flags</li> <li>Number after a <code>GO</code> repeats the batch</li> <li>Security using schemas</li> <li>Encryption using built in encryption functions, views and base tables with triggers</li> </ul>
[ { "answer_id": 121275, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 3, "selected": false, "text": "<p>Here are some features I find useful but a lot of people don't seem to know about:</p>\n\n<pre><code>sp_tables\n</code></pre>\n\n<blockquote>\n <p>Returns a list of objects that can be\n queried in the current environment.\n This means any object that can appear\n in a FROM clause, except synonym\n objects.</p>\n</blockquote>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms186250(SQL.90).aspx\" rel=\"nofollow noreferrer\">Link</a></p>\n\n<pre><code>sp_stored_procedures\n</code></pre>\n\n<blockquote>\n <p>Returns a list of stored procedures in\n the current environment.</p>\n</blockquote>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms190504(SQL.90).aspx\" rel=\"nofollow noreferrer\">Link</a></p>\n" }, { "answer_id": 121289, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms174415(SQL.90).aspx\" rel=\"nofollow noreferrer\">HashBytes()</a> to return the MD2, MD4, MD5, SHA, or SHA1 hash of its input.</p>\n" }, { "answer_id": 121391, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 3, "selected": false, "text": "<p>Simple encryption with <a href=\"http://msdn.microsoft.com/en-us/library/ms174361(SQL.90).aspx\" rel=\"nofollow noreferrer\">EncryptByKey</a></p>\n" }, { "answer_id": 121496, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 3, "selected": false, "text": "<p>Useful for parsing stored procedure arguments: <a href=\"http://msdn.microsoft.com/en-us/library/ms181431(SQL.90).aspx\" rel=\"nofollow noreferrer\">xp_sscanf</a></p>\n\n<blockquote>\n <p>Reads data from the string into the argument locations specified by each format argument.</p>\n \n <p>The following example uses xp_sscanf\n to extract two values from a source\n string based on their positions in the\n format of the source string.</p>\n</blockquote>\n\n<pre><code>DECLARE @filename varchar (20), @message varchar (20)\nEXEC xp_sscanf 'sync -b -fproducts10.tmp -rrandom', 'sync -b -f%s -r%s', \n @filename OUTPUT, @message OUTPUT\nSELECT @filename, @message\n</code></pre>\n\n<blockquote>\n <p>Here is the result set.</p>\n</blockquote>\n\n<pre><code>-------------------- -------------------- \nproducts10.tmp random\n</code></pre>\n" }, { "answer_id": 121597, "author": "Booji Boy", "author_id": 1433, "author_profile": "https://Stackoverflow.com/users/1433", "pm_score": 2, "selected": false, "text": "<p>sp_who2, just like sp_who, but with a lot more info for troubleshooting blocks</p>\n" }, { "answer_id": 121613, "author": "ICW", "author_id": 17664, "author_profile": "https://Stackoverflow.com/users/17664", "pm_score": 3, "selected": false, "text": "<p>/* Find the fixed drive with largest free space, you can also copy files to estimate which disk is quickest */</p>\n\n<pre><code>EXEC master..xp_fixeddrives\n</code></pre>\n\n<p>/* Checking assumptions about a file before use or reference */</p>\n\n<pre><code>EXEC master..xp_fileexist 'C:\\file_you_want_to_check'\n</code></pre>\n\n<p><a href=\"http://blogs.msdn.com/sathishcg/archive/2006/11/24/undocumented-sql-server-2000-functions.aspx\" rel=\"nofollow noreferrer\">More details here</a></p>\n" }, { "answer_id": 121618, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 6, "selected": false, "text": "<p><code>sp_msforeachtable</code>: Runs a command with '?' replaced with each table name.\ne.g.</p>\n\n<pre><code>exec sp_msforeachtable \"dbcc dbreindex('?')\"\n</code></pre>\n\n<p>You can issue up to 3 commands for each table </p>\n\n<pre><code>exec sp_msforeachtable\n @Command1 = 'print ''reindexing table ?''',\n @Command2 = 'dbcc dbreindex(''?'')',\n @Command3 = 'select count (*) [?] from ?'\n</code></pre>\n\n<p>Also, <code>sp_MSforeachdb</code></p>\n" }, { "answer_id": 121634, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 5, "selected": false, "text": "<p>A less known TSQL technique for returning rows in random order:</p>\n\n<pre><code>-- Return rows in a random order\nSELECT \n SomeColumn \nFROM \n SomeTable\nORDER BY \n CHECKSUM(NEWID())\n</code></pre>\n" }, { "answer_id": 121684, "author": "Chris Wenham", "author_id": 5548, "author_profile": "https://Stackoverflow.com/users/5548", "pm_score": 6, "selected": false, "text": "<p>Connection String extras:</p>\n\n<p><strong>MultipleActiveResultSets=true;</strong></p>\n\n<p>This makes ADO.Net 2.0 and above read multiple, forward-only, read-only results sets on a single database connection, which can improve performance if you're doing a lot of reading. You can turn it on even if you're doing a mix of query types.</p>\n\n<p><strong>Application Name=MyProgramName</strong></p>\n\n<p>Now when you want to see a list of active connections by querying the sysprocesses table, your program's name will appear in the program_name column instead of \".Net SqlClient Data Provider\" </p>\n" }, { "answer_id": 121791, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 3, "selected": false, "text": "<p>Here is a query I wrote to list All DB User Objects by Last Modified Date:</p>\n\n<pre><code>select name, modify_date, \ncase when type_desc = 'USER_TABLE' then 'Table'\nwhen type_desc = 'SQL_STORED_PROCEDURE' then 'Stored Procedure'\nwhen type_desc in ('SQL_INLINE_TABLE_VALUED_FUNCTION', 'SQL_SCALAR_FUNCTION', 'SQL_TABLE_VALUED_FUNCTION') then 'Function'\nend as type_desc\nfrom sys.objects\nwhere type in ('U', 'P', 'FN', 'IF', 'TF')\nand is_ms_shipped = 0\norder by 2 desc\n</code></pre>\n" }, { "answer_id": 121881, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 1, "selected": false, "text": "<p>A semi-hidden feature, the Table/Stored Procedure Filter feature can be really useful...</p>\n\n<p>In the <strong>SQL Server Management Studio</strong> <em>Object Explorer</em>, right-click the <strong>Tables</strong> or <strong>Stored Procedures</strong> folder, select the <strong>Filter</strong> menu, then <strong>Filter Settings</strong>, and enter a partial name in the <em>Name contains</em> row.</p>\n\n<p>Likewise, use <strong>Remove Filter</strong> to see all Tables/Stored Procedures again.</p>\n" }, { "answer_id": 121915, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 3, "selected": false, "text": "<p>Return Date Only</p>\n\n<pre><code>Select Cast(Floor(Cast(Getdate() As Float))As Datetime)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Select DateAdd(Day, 0, DateDiff(Day, 0, Getdate()))\n</code></pre>\n" }, { "answer_id": 121924, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 3, "selected": false, "text": "<p>Find records which date falls somewhere inside the current week.</p>\n\n<pre><code>where dateadd( week, datediff( week, 0, TransDate ), 0 ) =\ndateadd( week, datediff( week, 0, getdate() ), 0 )\n</code></pre>\n\n<p>Find records which date occurred last week.</p>\n\n<pre><code>where dateadd( week, datediff( week, 0, TransDate ), 0 ) =\ndateadd( week, datediff( week, 0, getdate() ) - 1, 0 )\n</code></pre>\n\n<p>Returns the date for the beginning of the current week.</p>\n\n<pre><code>select dateadd( week, datediff( week, 0, getdate() ), 0 )\n</code></pre>\n\n<p>Returns the date for the beginning of last week.</p>\n\n<pre><code>select dateadd( week, datediff( week, 0, getdate() ) - 1, 0 )\n</code></pre>\n" }, { "answer_id": 121927, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 4, "selected": false, "text": "<p>Drop all connections to the database:</p>\n\n<pre><code>Use Master\nGo\n\nDeclare @dbname sysname\n\nSet @dbname = 'name of database you want to drop connections from'\n\nDeclare @spid int\nSelect @spid = min(spid) from master.dbo.sysprocesses\nwhere dbid = db_id(@dbname)\nWhile @spid Is Not Null\nBegin\n Execute ('Kill ' + @spid)\n Select @spid = min(spid) from master.dbo.sysprocesses\n where dbid = db_id(@dbname) and spid &gt; @spid\nEnd\n</code></pre>\n" }, { "answer_id": 121933, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 4, "selected": false, "text": "<p>Table Checksum</p>\n\n<pre><code>Select CheckSum_Agg(Binary_CheckSum(*)) From Table With (NOLOCK)\n</code></pre>\n\n<p>Row Checksum</p>\n\n<pre><code>Select CheckSum_Agg(Binary_CheckSum(*)) From Table With (NOLOCK) Where Column = Value\n</code></pre>\n" }, { "answer_id": 121995, "author": "Christopher Klein", "author_id": 17632, "author_profile": "https://Stackoverflow.com/users/17632", "pm_score": 0, "selected": false, "text": "<p>For SQL Server 2005:</p>\n\n<pre><code>select * from sys.dm_os_performance_counters\n\nselect * from sys.dm_exec_requests\n</code></pre>\n" }, { "answer_id": 122022, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 5, "selected": false, "text": "<p><strong>TableDiff.exe</strong></p>\n<ul>\n<li>Table Difference tool allows you to discover and reconcile differences between a source and destination table or a view. Tablediff Utility can report differences on schema and data. The most popular feature of tablediff is the fact that it can generate a script that you can run on the destination that will reconcile differences between the tables.</li>\n</ul>\n<p><a href=\"http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/gems-top-10.mspx\" rel=\"nofollow noreferrer\">Link</a></p>\n" }, { "answer_id": 122218, "author": "cheeves", "author_id": 15826, "author_profile": "https://Stackoverflow.com/users/15826", "pm_score": 2, "selected": false, "text": "<p>I find this small script very handy to see the text of a procedure that has been deployed to a server:</p>\n\n<pre><code>DECLARE @procedureName NVARCHAR( MAX ), @procedureText NVARCHAR( MAX )\n\nSET @procedureName = 'myproc_Proc1'\n\nSET @procedureText = (\n SELECT OBJECT_DEFINITION( object_id )\n FROM sys.procedures \n WHERE Name = @procedureName\n )\n\nPRINT @procedureText\n</code></pre>\n" }, { "answer_id": 122233, "author": "cheeves", "author_id": 15826, "author_profile": "https://Stackoverflow.com/users/15826", "pm_score": 1, "selected": false, "text": "<p>If you want to drop all the procedures in a DB - </p>\n\n<pre><code>SELECT IDENTITY ( int, 1, 1 ) id, \n [name] \nINTO #tmp \nFROM sys.procedures \nWHERE [type] = 'P' \n AND is_ms_shipped = 0 \n\nDECLARE @i INT \n\nSELECT @i = COUNT( id ) FROM #tmp \nWHILE @i &gt; 0 \nBEGIN \n DECLARE @name VARCHAR( 100 ) \n SELECT @name = name FROM #tmp WHERE id = @i \n EXEC ( 'DROP PROCEDURE ' + @name ) \n SET @i = @i-1 \nEND\n\nDROP TABLE #tmp\n</code></pre>\n" }, { "answer_id": 122280, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 4, "selected": false, "text": "<p>If you want the code of a stored procedure you can:</p>\n\n<pre><code>sp_helptext 'ProcedureName'\n</code></pre>\n\n<p>(not sure if it is hidden feature, but I use it all the time)</p>\n" }, { "answer_id": 122612, "author": "Kolten", "author_id": 13959, "author_profile": "https://Stackoverflow.com/users/13959", "pm_score": 4, "selected": false, "text": "<p>useful when restoring a database for Testing purposes or whatever. Re-maps the login ID's correctly:</p>\n\n<pre><code>EXEC sp_change_users_login 'Auto_Fix', 'Mary', NULL, 'B3r12-36'\n</code></pre>\n" }, { "answer_id": 124516, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Not so much a hidden feature but setting up key mappings in Management Studio under Tools\\Options\\Keyboard:\nAlt+F1 is defaulted to sp_help \"selected text\" but I cannot live without the adding Ctrl+F1 for sp_helptext \"selected text\"</p>\n" }, { "answer_id": 127030, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms188396.aspx\" rel=\"nofollow noreferrer\">Trace Flags</a>! \"1204\" was invaluable in deadlock debugging on SQL Server 2000 (2005 has better tools for this).</p>\n" }, { "answer_id": 138366, "author": "edomaur", "author_id": 14262, "author_profile": "https://Stackoverflow.com/users/14262", "pm_score": 4, "selected": false, "text": "<p>A stored procedure trick is that you can call them from an INSERT statement. I found this very useful when I was working on an SQL Server database. </p>\n\n<pre><code>CREATE TABLE #toto (v1 int, v2 int, v3 char(4), status char(6))\nINSERT #toto (v1, v2, v3, status) EXEC dbo.sp_fulubulu(sp_param1)\nSELECT * FROM #toto\nDROP TABLE #toto\n</code></pre>\n" }, { "answer_id": 139892, "author": "Jim", "author_id": 681, "author_profile": "https://Stackoverflow.com/users/681", "pm_score": 2, "selected": false, "text": "<p>My favorite is master..xp_cmdshell. It allows you to run commands from a command prompt on the server and see the output. It's extremely useful if you can't login to the server, but you need to get information or control it somehow.</p>\n\n<p>For example, to list the folders on the C: drive of the server where SQL Server is running.</p>\n\n<ul>\n<li>master..xp_cmdshell 'dir c:\\'</li>\n</ul>\n\n<p>You can start and stop services, too.</p>\n\n<ul>\n<li><p>master..xp_cmdshell 'sc query \"My\nService\"'</p></li>\n<li><p>master..xp_cmdshell 'sc stop \"My\nService\"'</p></li>\n<li><p>master..xp_cmdshell 'sc start \"My\nService\"'</p></li>\n</ul>\n\n<p>It's very powerful, but a security risk, also. Many people disable it because it could easily be used do bad things on the server. But, if you have access to it, it can be extremely useful.</p>\n" }, { "answer_id": 140015, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 5, "selected": false, "text": "<p>If you want to know the table structure, indexes and constraints:</p>\n\n<pre><code>sp_help 'TableName'\n</code></pre>\n" }, { "answer_id": 140753, "author": "Ollie", "author_id": 4453, "author_profile": "https://Stackoverflow.com/users/4453", "pm_score": 0, "selected": false, "text": "<p>@Gatekiller - An easier way to get just the Date is surely </p>\n\n<pre><code>CAST(CONVERT(varchar,getdate(),103) as datetime)\n</code></pre>\n\n<p>If you don't use DD/MM/YYYY in your locale, you'd need to use a different value from 103. Lookup CONVERT function in SQL Books Online for the locale codes.</p>\n" }, { "answer_id": 141065, "author": "GilM", "author_id": 10192, "author_profile": "https://Stackoverflow.com/users/10192", "pm_score": 7, "selected": false, "text": "<p>In Management Studio, you can put a number after a GO end-of-batch marker to cause the batch to be repeated that number of times:</p>\n\n<pre><code>PRINT 'X'\nGO 10\n</code></pre>\n\n<p>Will print 'X' 10 times. This can save you from tedious copy/pasting when doing repetitive stuff.</p>\n" }, { "answer_id": 149644, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 2, "selected": false, "text": "<p><strong>Triggers for Logon Events</strong></p>\n<ul>\n<li>Logon triggers can help complement auditing and compliance. For example, logon events can be used for enforcing rules on connections (for example limiting connection through a specific username or limiting connections through a username to a specific time periods) or simply for tracking and recording general connection activity. Just like in any trigger, ROLLBACK cancels the operation that is in execution. In the case of logon event that means canceling the connection establishment. Logon events do not fire when the server is started in the minimal configuration mode or when a connection is established through dedicated admin connection (DAC).</li>\n</ul>\n<p><a href=\"http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/gems-top-10.mspx\" rel=\"nofollow noreferrer\">Link</a></p>\n" }, { "answer_id": 149645, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 3, "selected": false, "text": "<p><strong>Persisted-computed-columns</strong></p>\n<ul>\n<li>Computed columns can help you shift the runtime computation cost to data modification phase. The computed column is stored with the rest of the row and is transparently utilized when the expression on the computed columns and the query matches. You can also build indexes on the PCC’s to speed up filtrations and range scans on the expression.</li>\n</ul>\n<p><a href=\"http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/gems-top-10.mspx\" rel=\"nofollow noreferrer\">Link</a></p>\n" }, { "answer_id": 149653, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 1, "selected": false, "text": "<p><strong>DEFAULT_SCHEMA setting in sys.database_principles</strong></p>\n<ul>\n<li>SQL Server provides great flexibility with name resolution. However name resolution comes at a cost and can get noticeably expensive in adhoc workloads that do not fully qualify object references. SQL Server 2005 allows a new setting of DEFEAULT_SCHEMA for each database principle (also known as “user”) which can eliminate this overhead without changing your TSQL code.</li>\n</ul>\n<p><a href=\"http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/gems-top-10.mspx\" rel=\"nofollow noreferrer\">Link</a></p>\n" }, { "answer_id": 149659, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "<p><strong>Forced Parameterization</strong></p>\n<ul>\n<li>Parameterization allows SQL Server to take advantage of query plan reuse and avoid compilation and optimization overheads on subsequent executions of similar queries. However there are many applications out there that, for one reason or another, still suffer from ad-hoc query compilation overhead. For those cases with high number of query compilation and where lowering CPU utilization and response time is critical for your workload, force parameterization can help.</li>\n</ul>\n<p><a href=\"http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/gems-top-10.mspx\" rel=\"nofollow noreferrer\">Link</a></p>\n" }, { "answer_id": 149661, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 1, "selected": false, "text": "<p><strong>Vardecimal Storage Format</strong></p>\n<ul>\n<li>SQL Server 2005 adds a new storage format for numeric and decimal datatypes called vardecimal. Vardecimal is a variable-length representation for decimal types that can save unused bytes in every instance of the row. The biggest amount of savings come from cases where the decimal definition is large (like decimal(38,6)) but the values stored are small (like a value of 0.0) or there is a large number of repeated values or data is sparsely populated.</li>\n</ul>\n<p><a href=\"http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/gems-top-10.mspx\" rel=\"nofollow noreferrer\">Link</a></p>\n" }, { "answer_id": 149665, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 4, "selected": false, "text": "<p><strong>Figuring out the most popular queries</strong></p>\n\n<ul>\n<li>With sys.dm_exec_query_stats, you can figure out many combinations of query analyses by a single query.</li>\n</ul>\n\n<p><a href=\"http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/gems-top-10.mspx\" rel=\"nofollow noreferrer\">Link</a>\nwith the commnad </p>\n\n<pre><code>select * from sys.dm_exec_query_stats \norder by execution_count desc\n</code></pre>\n" }, { "answer_id": 149667, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 1, "selected": false, "text": "<p><strong>Scalable Shared Databases</strong></p>\n<ul>\n<li>Through Scalable Shared Databases one can mount the same physical drives on commodity machines and allow multiple instances of SQL Server 2005 to work off of the same set of data files. The setup does not require duplicate storage for every instance of SQL Server and allows additional processing power through multiple SQL Server instances that have their own local resources like cpu, memory, tempdb and potentially other local databases.</li>\n</ul>\n<p><a href=\"http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/gems-top-10.mspx\" rel=\"nofollow noreferrer\">Link</a></p>\n" }, { "answer_id": 159835, "author": "Meff", "author_id": 9647, "author_profile": "https://Stackoverflow.com/users/9647", "pm_score": 2, "selected": false, "text": "<p><strong>Find Procedures By Keyword</strong></p>\n\n<p>What procedures contain a certain piece of text (Table name, column name, variable name, TODO, etc)?</p>\n\n<pre><code>SELECT OBJECT_NAME(ID) FROM SysComments \nWHERE Text LIKE '%SearchString%' \nAND OBJECTPROPERTY(id, 'IsProcedure') = 1\n</code></pre>\n" }, { "answer_id": 185368, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 4, "selected": false, "text": "<p>I know it's not exactly hidden, but not too many people know about the <a href=\"http://msdn.microsoft.com/en-us/library/ms177410.aspx\" rel=\"nofollow noreferrer\">PIVOT</a> command. I was able to change a stored procedure that used cursors and took 2 minutes to run into a speedy 6 second piece of code that was one tenth the number of lines!</p>\n" }, { "answer_id": 207184, "author": "Chris Roland", "author_id": 27975, "author_profile": "https://Stackoverflow.com/users/27975", "pm_score": 2, "selected": false, "text": "<p>Here is one I learned today because I needed to search for a transaction.</p>\n\n<p>::fn_dblog<br>\nThis allows you to query the transaction log for a database.</p>\n\n<pre><code>USE mydatabase;\nSELECT *\nFROM ::fn_dblog(NULL, NULL)\n</code></pre>\n\n<p><a href=\"http://killspid.blogspot.com/2006/07/using-fndblog.html\" rel=\"nofollow noreferrer\">http://killspid.blogspot.com/2006/07/using-fndblog.html</a><br></p>\n" }, { "answer_id": 219457, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>A few of my favorite things:</p>\n\n<p>Added in sp2 - Scripting options under tools/options/scripting</p>\n\n<p>New security using schemas - create two schemas: user_access, admin_access. Put your user procs in one and your admin procs in the other like this: user_access.showList , admin_access.deleteUser . Grant EXECUTE on the schema to your app user/role. No more GRANTing EXECUTE all the time.</p>\n\n<p>Encryption using built in encryption functions, views(to decrypt for presentation), and base tables with triggers(to encrypt on insert/update).</p>\n" }, { "answer_id": 232772, "author": "MarlonRibunal", "author_id": 10385, "author_profile": "https://Stackoverflow.com/users/10385", "pm_score": 0, "selected": false, "text": "<p>OK, here's my 2 cents: </p>\n\n<p><a href=\"http://dbalink.wordpress.com/2008/10/24/querying-the-object-catalog-and-information-schema-views/\" rel=\"nofollow noreferrer\">http://dbalink.wordpress.com/2008/10/24/querying-the-object-catalog-and-information-schema-views/</a> </p>\n\n<p>I am too lazy to re-write the whole thing here, so please check my post. That may be trivial to many, but there will be some who will find it a \"hidden gem\".</p>\n\n<p>EDIT:</p>\n\n<p>After a while, I decided to add the code here so you don't have to jump to my blog to see the code.</p>\n\n<pre><code>SELECT T.NAME AS [TABLE NAME], C.NAME AS [COLUMN NAME], P.NAME AS [DATA TYPE], P.MAX_LENGTH AS[SIZE], CAST(P.PRECISION AS VARCHAR) +‘/’+ CAST(P.SCALE AS VARCHAR) AS [PRECISION/SCALE]\nFROM ADVENTUREWORKS.SYS.OBJECTS AS T\nJOIN ADVENTUREWORKS.SYS.COLUMNS AS C\nON T.OBJECT_ID=C.OBJECT_ID\nJOIN ADVENTUREWORKS.SYS.TYPES AS P\nON C.SYSTEM_TYPE_ID=P.SYSTEM_TYPE_ID\nWHERE T.TYPE_DESC=‘USER_TABLE’;\n</code></pre>\n\n<p>Or, if you want to pull all the User Tables altogether, use CURSOR like this:</p>\n\n<pre><code>DECLARE @tablename VARCHAR(60)\n\nDECLARE cursor_tablenames CURSOR FOR\nSELECT name FROM AdventureWorks.sys.tables\n\nOPEN cursor_tablenames\nFETCH NEXT FROM cursor_tablenames INTO @tablename\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n\nSELECT t.name AS [TABLE Name], c.name AS [COLUMN Name], p.name AS [DATA Type], p.max_length AS[SIZE], CAST(p.PRECISION AS VARCHAR) +‘/’+ CAST(p.scale AS VARCHAR) AS [PRECISION/Scale]\nFROM AdventureWorks.sys.objects AS t\nJOIN AdventureWorks.sys.columns AS c\nON t.OBJECT_ID=c.OBJECT_ID\nJOIN AdventureWorks.sys.types AS p\nON c.system_type_id=p.system_type_id\nWHERE t.name = @tablename\nAND t.type_desc=‘USER_TABLE’\nORDER BY t.name ASC\n\nFETCH NEXT FROM cursor_tablenames INTO @tablename\nEND\n\nCLOSE cursor_tablenames\nDEALLOCATE cursor_tablenames\n</code></pre>\n\n<p>ADDITIONAL REFERENCE (my blog): <a href=\"http://dbalink.wordpress.com/2009/01/21/how-to-create-cursor-in-tsql/\" rel=\"nofollow noreferrer\">http://dbalink.wordpress.com/2009/01/21/how-to-create-cursor-in-tsql/</a> </p>\n" }, { "answer_id": 234226, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 2, "selected": false, "text": "<pre><code>sp_executesql \n</code></pre>\n\n<p>For executing a statement in a string. As good as <em>Execute</em> but can return parameters out</p>\n" }, { "answer_id": 234293, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 2, "selected": false, "text": "<p>Since I'm a programmer, not a DBA, my favorite hidden feature is the <a href=\"http://msdn.microsoft.com/en-us/library/ms162169(SQL.90).aspx\" rel=\"nofollow noreferrer\">SMO library</a>. You can automate pretty much anything in SQL Server, from database/table/column creation and deletion to scripting to backup and restore. If you can do it in SQL Server Management Studio, you can automate it in SMO.</p>\n" }, { "answer_id": 234684, "author": "user31269", "author_id": 31269, "author_profile": "https://Stackoverflow.com/users/31269", "pm_score": 0, "selected": false, "text": "<p>Not undocumented</p>\n\n<p>RowNumber courtesy of Itzik Ben-Gan\n<a href=\"http://www.sqlmag.com/article/articleid/97675/sql_server_blog_97675.html\" rel=\"nofollow noreferrer\">http://www.sqlmag.com/article/articleid/97675/sql_server_blog_97675.html</a></p>\n\n<p>SET XACT_ABORT ON\nrollback everything on error for transactions</p>\n\n<p>all the sp_'s are helpful just browse books online</p>\n\n<p>keyboard shortcuts I use all the time in management studio\nF6 - switch between results and query\nAlt+X or F5- run selected text in query if nothing is selected runs the entire window\nAlt+T and Alt+D - results in text or grid respectively</p>\n" }, { "answer_id": 262870, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I find <code>sp_depends</code> useful. It displays the objects which depend on a given object, e.g. </p>\n\n<pre><code>exec sp_depends 'fn_myFunction' \n</code></pre>\n\n<p>returns objects which depend on this function (note, if the objects have not originally been run into the database in the correct order this will give incorrect results.) </p>\n" }, { "answer_id": 318602, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 4, "selected": false, "text": "<p><strong><a href=\"http://msdn.microsoft.com/en-us/library/ms188055(SQL.90).aspx\" rel=\"nofollow noreferrer\">EXCEPT and INTERSECT</a></strong></p>\n\n<p>Instead of writing elaborate joins and subqueries, these two keywords are a much more elegant shorthand and readable way of expressing your query's intent when comparing two query results. New as of SQL Server 2005, they strongly complement UNION which has already existed in the TSQL language for years.</p>\n\n<p>The concepts of EXCEPT, INTERSECT, and UNION are fundamental in set theory which serves as the basis and foundation of relational modeling used by all modern RDBMS. Now, Venn diagram type results can be more intuitively and quite easily generated using TSQL.</p>\n" }, { "answer_id": 318659, "author": "Logicalmind", "author_id": 26977, "author_profile": "https://Stackoverflow.com/users/26977", "pm_score": 0, "selected": false, "text": "<p>In SQL Server 2005 you no longer need to run the <a href=\"http://support.microsoft.com/default.aspx/kb/271509\" rel=\"nofollow noreferrer\">sp-blocker-pss80</a> stored procedure. Instead, you can do:</p>\n\n<pre><code>exec sp_configure 'show advanced options', 1;\nreconfigure;\ngo\nexec sp_configure 'blocked process threshold', 30;\nreconfigure; \n</code></pre>\n\n<p>You can then start a SQL Trace and select the Blocked process report event class in the Errors and Warnings group. Details of that event <a href=\"http://msdn.microsoft.com/en-us/library/ms191168(SQL.90).aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 321159, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 3, "selected": false, "text": "<p>The most surprising thing I learned this week involved using a CASE statement in the ORDER By Clause. For example:</p>\n\n<pre><code>declare @orderby varchar(10)\n\nset @orderby = 'NAME'\n\nselect * \n from Users\n ORDER BY \n CASE @orderby\n WHEN 'NAME' THEN LastName\n WHEN 'EMAIL' THEN EmailAddress\n END\n</code></pre>\n" }, { "answer_id": 421628, "author": "casperOne", "author_id": 50776, "author_profile": "https://Stackoverflow.com/users/50776", "pm_score": 2, "selected": false, "text": "<p>Based on what appears to be a vehement reaction to it by hardened database developers, the CLR integration would rank right up there. =)</p>\n" }, { "answer_id": 422016, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 0, "selected": false, "text": "<p>Some undocumented ones are here: <a href=\"http://wiki.lessthandot.com/index.php/SQL_Server_Programming_Hacks_-_100%2B_List#Undocumented_but_handy\" rel=\"nofollow noreferrer\">Undocumented but handy SQL server Procs and DBCC commands</a></p>\n" }, { "answer_id": 532766, "author": "Binoj Antony", "author_id": 33015, "author_profile": "https://Stackoverflow.com/users/33015", "pm_score": 4, "selected": false, "text": "<p>In SQL Server 2005/2008 to show row numbers in a SELECT query result:</p>\n\n<pre><code>SELECT ( ROW_NUMBER() OVER (ORDER BY OrderId) ) AS RowNumber,\n GrandTotal, CustomerId, PurchaseDate\nFROM Orders\n</code></pre>\n\n<p>ORDER BY is a compulsory clause. The OVER() clause tells the SQL Engine to sort data on the specified column (in this case OrderId) and assign numbers as per the sort results.</p>\n" }, { "answer_id": 542907, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 0, "selected": false, "text": "<pre><code>use db\ngo \nDECLARE @procName varchar(100) \nDECLARE @cursorProcNames CURSOR \nSET @cursorProcNames = CURSOR FOR \nselect name from sys.procedures where modify_date &gt; '2009-02-05 13:12:15.273' order by modify_date desc \n\nOPEN @cursorProcNames \nFETCH NEXT \nFROM @cursorProcNames INTO @procName \nWHILE @@FETCH_STATUS = 0 \nBEGIN \n-- see the text of the last stored procedures modified on \n-- the db , hint Ctrl + T would give you the procedures test \nset nocount off; \nexec sp_HelpText @procName --- or print them \n-- print @procName \n\nFETCH NEXT \nFROM @cursorProcNames INTO @procName \nEND \nCLOSE @cursorProcNames \n\nselect @@error \n</code></pre>\n" }, { "answer_id": 543052, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 0, "selected": false, "text": "<pre><code>use db\ngo \n\nselect o.name \n, (SELECT [definition] AS [text()] \n FROM sys.all_sql_modules \n WHERE sys.all_sql_modules.object_id=a.object_id \n FOR XML PATH(''), TYPE\n ) AS Statement_Text\n , a.object_id\n , o.modify_date \n\n FROM sys.all_sql_modules a \n LEFT JOIN sys.objects o ON a.object_id=o.object_id \n ORDER BY 4 desc\n\n--select * from sys.objects\n</code></pre>\n" }, { "answer_id": 701013, "author": "adolf garlic ", "author_id": 79076, "author_profile": "https://Stackoverflow.com/users/79076", "pm_score": 1, "selected": false, "text": "<p>Get a list of column headers in vertical format:</p>\n\n<p>Copy column names in grid results</p>\n\n<p>Tools - Options - Query Results - SQL Server - Results to Grid\ntick \"Include column headers when copying or saving the results\"</p>\n\n<p>you will need to make a new connection at this point, then run your query</p>\n\n<p>Now when you copy the results from the grid, you get the column headers</p>\n\n<p>Also \nIf you then copy the results to excel</p>\n\n<p>Copy col headers only</p>\n\n<p>Paste Special (must not overlap copy area)</p>\n\n<p>tick \"Transpose\" </p>\n\n<p>OK</p>\n\n<p>[you may wish to add a \",\" and autofill down at this point]</p>\n\n<p>You have an instant list of columns in vertical format</p>\n" }, { "answer_id": 894283, "author": "Sheki", "author_id": 107959, "author_profile": "https://Stackoverflow.com/users/107959", "pm_score": 4, "selected": false, "text": "<p>I'm not sure if this is a hidden feature or not, but I stumbled upon this, and have found it to be useful on many occassions. You can concatonate a set of a field in a single select statement, rather than using a cursor and looping through the select statement.</p>\n\n<p>Example:</p>\n\n<pre><code>DECLARE @nvcConcatonated nvarchar(max)\nSET @nvcConcatonated = ''\n\nSELECT @nvcConcatonated = @nvcConcatonated + C.CompanyName + ', '\nFROM tblCompany C\nWHERE C.CompanyID IN (1,2,3)\n\nSELECT @nvcConcatonated\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>Acme, Microsoft, Apple,\n</code></pre>\n" }, { "answer_id": 894304, "author": "Sheki", "author_id": 107959, "author_profile": "https://Stackoverflow.com/users/107959", "pm_score": 0, "selected": false, "text": "<p>Returing results based on a pipe delimited string of IDs in a single statmeent (alternative to passing xml or first turning the delimited string to a table)</p>\n\n<p>Example:</p>\n\n<pre><code>DECLARE @nvcIDs nvarchar(max)\nSET @nvcIDs = '|1|2|3|'\n\nSELECT C.*\nFROM tblCompany C\nWHERE @nvcIDs LIKE '%|' + CAST(C.CompanyID as nvarchar) + '|%' \n</code></pre>\n" }, { "answer_id": 926216, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 1, "selected": false, "text": "<p>Execute a stored proc and capture the results in a (temp) table for further processing, e.g.:</p>\n\n<pre><code>INSERT INTO someTable EXEC sp_someproc\n</code></pre>\n\n<p>Example: Shows <code>sp_help</code> output, but ordered by database size:</p>\n\n<pre><code>CREATE TABLE #dbs\n(\n name nvarchar(50),\n db_size nvarchar(50),\n owner nvarchar(50),\n dbid int,\n created datetime,\n status nvarchar(255),\n compatiblity_level int\n)\nINSERT INTO #dbs EXEC sp_helpdb\n\nSELECT * FROM #dbs \nORDER BY CONVERT(decimal, LTRIM(LEFT(db_size, LEN(db_size)-3))) DESC\n\nDROP TABLE #dbs\n</code></pre>\n" }, { "answer_id": 1031629, "author": "Dan F", "author_id": 11569, "author_profile": "https://Stackoverflow.com/users/11569", "pm_score": 3, "selected": false, "text": "<h2>SQLCMD</h2>\n\n<p>If you've got scripts that you run over and over, but have to change slight details, running ssms in <a href=\"http://msdn.microsoft.com/en-us/library/ms174187.aspx\" rel=\"nofollow noreferrer\">sqlcmd mode</a> is awesome. The <a href=\"http://msdn.microsoft.com/en-us/library/ms162773.aspx\" rel=\"nofollow noreferrer\">sqlcmd command line</a> is pretty spiffy too.</p>\n\n<p>My favourite features are:</p>\n\n<ul>\n<li>You get to set variables. Proper variables that don't require jumping through sp_exec hoops</li>\n<li>You can run multiple scripts one after the other</li>\n<li>Those scripts can reference the variables in the \"outer\" script</li>\n</ul>\n\n<p>Rather than gushing any more, Simpletalk by Red Gate did an awesome wrap up of sqlcmd - <a href=\"http://www.simple-talk.com/sql/sql-tools/the-sqlcmd-workbench/\" rel=\"nofollow noreferrer\">The SQLCMD Workbench</a>. Donabel Santos has some great <a href=\"http://www.sqlmusings.com/tag/sqlcmd/\" rel=\"nofollow noreferrer\">SQLCMD examples</a> too.</p>\n" }, { "answer_id": 1063685, "author": "Jhonny D. Cano -Leftware-", "author_id": 76832, "author_profile": "https://Stackoverflow.com/users/76832", "pm_score": 0, "selected": false, "text": "<p>I use to add this stored procedure to the master db,</p>\n\n<p>Improvements:</p>\n\n<ul>\n<li>Trim on Host name, so the copy-paste works on VNC.</li>\n<li>Added a LOCK option, for just watching what are the current locked processes.</li>\n</ul>\n\n<p>Usage:</p>\n\n<ul>\n<li>EXEC sp_who3 'ACTIVE'</li>\n<li>EXEC sp_who3 'LOCK'</li>\n<li>EXEC sp_who3 spid_No</li>\n</ul>\n\n<p>That's it.</p>\n\n<pre><code>CREATE procedure sp_who3\n @loginame sysname = NULL --or 'active' or 'lock'\nas\n\ndeclare @spidlow int,\n @spidhigh int,\n @spid int,\n @sid varbinary(85)\n\nselect @spidlow = 0\n ,@spidhigh = 32767\n\n\nif @loginame is not NULL begin\n if upper(@loginame) = 'ACTIVE' begin\n select spid, ecid, status\n , loginame=rtrim(loginame)\n , hostname=rtrim(hostname)\n , blk=convert(char(5),blocked)\n , dbname = case\n when dbid = 0 then null\n when dbid &lt;&gt; 0 then db_name(dbid)\n end\n ,cmd\n from master.dbo.sysprocesses\n where spid &gt;= @spidlow and spid &lt;= @spidhigh AND\n upper(cmd) &lt;&gt; 'AWAITING COMMAND'\n return (0)\n end\n if upper(@loginame) = 'LOCK' begin\n select spid , ecid, status\n , loginame=rtrim(loginame)\n , hostname=rtrim(hostname)\n , blk=convert(char(5),blocked)\n , dbname = case\n when dbid = 0 then null\n when dbid &lt;&gt; 0 then db_name(dbid)\n end\n ,cmd\n from master.dbo.sysprocesses\n where spid &gt;= 0 and spid &lt;= 32767 AND\n upper(cmd) &lt;&gt; 'AWAITING COMMAND'\n AND convert(char(5),blocked) &gt; 0\n return (0)\n end\n\nend\n\nif (@loginame is not NULL\n AND upper(@loginame) &lt;&gt; 'ACTIVE'\n )\nbegin\n if (@loginame like '[0-9]%') -- is a spid.\n begin\n select @spid = convert(int, @loginame)\n select spid, ecid, status\n , loginame=rtrim(loginame)\n , hostname=rtrim(hostname)\n , blk=convert(char(5),blocked)\n , dbname = case\n when dbid = 0 then null\n when dbid &lt;&gt; 0 then db_name(dbid)\n end\n ,cmd\n from master.dbo.sysprocesses\n where spid = @spid\n end\n else\n begin\n select @sid = suser_sid(@loginame)\n if (@sid is null)\n begin\n raiserror(15007,-1,-1,@loginame)\n return (1)\n end\n select spid, ecid, status\n , loginame=rtrim(loginame)\n , hostname=rtrim(hostname)\n , blk=convert(char(5),blocked)\n , dbname = case\n when dbid = 0 then null\n when dbid &lt;&gt; 0 then db_name(dbid)\n end\n ,cmd\n from master.dbo.sysprocesses\n where sid = @sid\n end\n return (0)\nend\n\n\n/* loginame arg is null */\nselect spid,\n ecid,\n status\n , loginame=rtrim(loginame)\n , hostname=rtrim(hostname)\n , blk=convert(char(5),blocked)\n , dbname = case\n when dbid = 0 then null\n when dbid &lt;&gt; 0 then db_name(dbid)\n end\n ,cmd\nfrom master.dbo.sysprocesses\nwhere spid &gt;= @spidlow and spid &lt;= @spidhigh\n\n\nreturn (0) -- sp_who\n</code></pre>\n" }, { "answer_id": 1065869, "author": "penderi", "author_id": 32027, "author_profile": "https://Stackoverflow.com/users/32027", "pm_score": 2, "selected": false, "text": "<p>Ok here's the few I've got left, shame I missed the start, but keep it up there's some top stuff here!</p>\n\n<p><strong>Query Analyzer</strong></p>\n\n<ul>\n<li><code>Alt+F1</code> executes <code>sp_help</code> on the selected text</li>\n<li><code>Alt-D</code> - focus to the database dropdown so you can use select db with cursor keys of letter.</li>\n</ul>\n\n<p><strong>T-Sql</strong></p>\n\n<ul>\n<li><code>if (object_id(\"nameofobject\") IS NOT NULL) begin &lt;do something&gt; end</code> - easiest existence check</li>\n<li><code>sp_locks</code> - more in depth locking informaiton than sp_who2 (which is the first port of call)</li>\n<li><code>dbcc inputbuffer(spid)</code> - list of top line of executing process (kinda useful but v. brief)</li>\n<li><code>dbcc outputbuffer(spid)</code> - list of top line of output of executing process</li>\n</ul>\n\n<p><strong>General T-sql tip</strong></p>\n\n<ul>\n<li>With large volumes use sub queries liberally to process data in sets </li>\n</ul>\n\n<blockquote>\n <p>e.g. to obtain a list of married\n people over fifty you could select a\n set of people who are married in a \n subquery and join with a set of the\n same people over 50 and output the\n joined results - please excuse the\n contrived example</p>\n</blockquote>\n" }, { "answer_id": 1140322, "author": "Chris McCall", "author_id": 86259, "author_profile": "https://Stackoverflow.com/users/86259", "pm_score": 0, "selected": false, "text": "<p>CTRL-E executes the currently selected text in Query Analyzer.</p>\n" }, { "answer_id": 1243721, "author": "marc_s", "author_id": 13302, "author_profile": "https://Stackoverflow.com/users/13302", "pm_score": 6, "selected": false, "text": "<p>A lot of SQL Server developers still don't seem to know about the <strong><a href=\"http://msdn.microsoft.com/en-us/library/ms177564.aspx\" rel=\"nofollow noreferrer\">OUTPUT clause</a></strong> (SQL Server 2005 and newer) on the DELETE, INSERT and UPDATE statement.</p>\n\n<p>It can be extremely useful to know which rows have been INSERTed, UPDATEd, or DELETEd, and the OUTPUT clause allows to do this very easily - it allows access to the \"virtual\" tables called <code>inserted</code> and <code>deleted</code> (like in triggers):</p>\n\n<pre><code>DELETE FROM (table)\nOUTPUT deleted.ID, deleted.Description\nWHERE (condition)\n</code></pre>\n\n<p>If you're inserting values into a table which has an INT IDENTITY primary key field, with the OUTPUT clause, you can get the inserted new ID right away:</p>\n\n<pre><code>INSERT INTO MyTable(Field1, Field2)\nOUTPUT inserted.ID\nVALUES (Value1, Value2)\n</code></pre>\n\n<p>And if you're updating, it can be extremely useful to know what changed - in this case, <code>inserted</code> represents the new values (after the UPDATE), while <code>deleted</code> refers to the old values before the UPDATE:</p>\n\n<pre><code>UPDATE (table)\nSET field1 = value1, field2 = value2\nOUTPUT inserted.ID, deleted.field1, inserted.field1\nWHERE (condition)\n</code></pre>\n\n<p>If a lot of info will be returned, the output of OUTPUT can also be redirected to a temporary table or a table variable (<code>OUTPUT INTO @myInfoTable</code>).</p>\n\n<p>Extremely useful - and very little known!</p>\n\n<p>Marc</p>\n" }, { "answer_id": 1364087, "author": "Kane", "author_id": 113535, "author_profile": "https://Stackoverflow.com/users/113535", "pm_score": 1, "selected": false, "text": "<p>Using the osql utility to run command line queries/scripts/batches</p>\n" }, { "answer_id": 1860923, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 3, "selected": false, "text": "<p>Here's a simple but useful one:</p>\n\n<p>When you're editing table contents manually, you can <strong>insert NULL in a column</strong> by typing <strong>Control-0</strong>.</p>\n" }, { "answer_id": 1928481, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 2, "selected": false, "text": "<p>Sql 2000+\n<code>DBCC DROPCLEANBUFFERS</code> : Clears the buffers. Useful for testing the speed of queries when the buffer is clean.</p>\n" }, { "answer_id": 1930260, "author": "Rob Boek", "author_id": 27179, "author_profile": "https://Stackoverflow.com/users/27179", "pm_score": 2, "selected": false, "text": "<p>In SQL Server Management Studio (SSMS) you can highlight an object name in the Object Explorer and press Ctrl-C to copy the name to the clipboard.</p>\n\n<p>There is no need to press F2 or right-click, rename the object to copy the name.</p>\n\n<p>You can also drag and drop an object from the Object Explorer into your query window.</p>\n" }, { "answer_id": 1930277, "author": "Rob Boek", "author_id": 27179, "author_profile": "https://Stackoverflow.com/users/27179", "pm_score": 5, "selected": false, "text": "<p><strong>Row Constructors</strong></p>\n\n<p>You can insert multiple rows of data with a single insert statement.</p>\n\n<pre><code>INSERT INTO Colors (id, Color)\nVALUES (1, 'Red'),\n (2, 'Blue'),\n (3, 'Green'),\n (4, 'Yellow')\n</code></pre>\n" }, { "answer_id": 1930425, "author": "Rob Boek", "author_id": 27179, "author_profile": "https://Stackoverflow.com/users/27179", "pm_score": 2, "selected": false, "text": "<p><strong>Batch Seperator</strong></p>\n\n<p>Most people don't know it, but \"GO\" is not a SQL command. It is the default batch separator used by the client tools. You can find more info about it in <a href=\"http://msdn.microsoft.com/en-us/library/ms188037.aspx\" rel=\"nofollow noreferrer\">Books Online</a>.</p>\n\n<p>You can change the Batch separator by selecting Tools -> Options in Management Studio, and changing the Batch separator Option in the Query Execution section.</p>\n\n<p>I'm not sure why you would want to do this other than as a prank, but it is a somewhat interesting piece of trivia.</p>\n" }, { "answer_id": 2024797, "author": "Jose Chama", "author_id": 241637, "author_profile": "https://Stackoverflow.com/users/241637", "pm_score": 1, "selected": false, "text": "<p>These are some SQL Management Studio hidden features I like.</p>\n\n<p>Something I love is that if you hold down the ALT key while highlighting information you can select columnar information and not just whole rows.</p>\n\n<p>In SQL Management Studio you have predefined keyboard shortcuts:</p>\n\n<p>Ctrl+1 runs sp_who\nCtrl+2 runs sp_lock\nAlt+F1 runs sp_help\nCtrl+F1 runs sp_helptext</p>\n\n<p>So if you highlight a table name in the editor and press Alt+F1 it will show you the structure of the table.</p>\n" }, { "answer_id": 3164592, "author": "Ramesh", "author_id": 168464, "author_profile": "https://Stackoverflow.com/users/168464", "pm_score": 0, "selected": false, "text": "<p>Use </p>\n\n<blockquote>\n <p>select * from information_schema</p>\n</blockquote>\n\n<p>to list out all the databases,base tables,sps,views etc in sql server.</p>\n" }, { "answer_id": 3278967, "author": "Michhes", "author_id": 119073, "author_profile": "https://Stackoverflow.com/users/119073", "pm_score": 0, "selected": false, "text": "<p>Alternative to Kolten's sp_change_users_login:</p>\n\n<pre><code>ALTER USER wacom_app WITH LOGIN = wacom_app\n</code></pre>\n" }, { "answer_id": 3291170, "author": "Sir Wobin", "author_id": 375187, "author_profile": "https://Stackoverflow.com/users/375187", "pm_score": 2, "selected": false, "text": "<p>Stored proc <strong>sp_MSdependencies</strong> tells you about object dependencies in a more useful fashion than <strong>sp_depends</strong>. For some production releases it's convenient to temporarily disable child table constraints, apply changes then reenable the child table constraints. This is a great way of finding objects that depend on your parent table.</p>\n\n<p>This code disables child table constraints:</p>\n\n<pre><code>create table #deps\n( oType int,\n oObjName sysname,\n oOwner nvarchar(200),\n oSequence int\n)\n\ninsert into #deps \nexec sp_MSdependencies @tableName, null, 1315327\n\nexec sp_MSforeachtable @command1 = 'ALTER TABLE ? NOCHECK CONSTRAINT ALL',\n@whereand = ' and o.name in (select oObjName from #deps where oType = 8)'\n</code></pre>\n\n<p>After the change is applied one can run this code to reenable the constraints:</p>\n\n<pre><code>exec sp_MSforeachtable @command1 = 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL',\n@whereand = ' and o.name in (select oObjName from #deps where oType = 8)'\n</code></pre>\n\n<p>The third parameter is called @flags and it controls what sort of dependencies will be listed. Go read the proc contents to see how you can change @flags for your purposes. The proc uses bit masks to decipher what you want returned.</p>\n" }, { "answer_id": 3291563, "author": "Thomas", "author_id": 198643, "author_profile": "https://Stackoverflow.com/users/198643", "pm_score": 5, "selected": false, "text": "<p>In Management Studio, you can quickly get a comma-delimited list of columns for a table by :</p>\n\n<ol>\n<li>In the Object Explorer, expand the nodes under a given table (so you will see folders for Columns, Keys, Constraints, Triggers etc.)</li>\n<li>Point to the Columns folder and drag into a query. </li>\n</ol>\n\n<p>This is handy when you don't want to use heinous format returned by right-clicking on the table and choosing Script Table As..., then Insert To... This trick does work with the other folders in that it will give you a comma-delimited list of names contained within the folder.</p>\n" }, { "answer_id": 3601926, "author": "Nathan Koop", "author_id": 18821, "author_profile": "https://Stackoverflow.com/users/18821", "pm_score": 3, "selected": false, "text": "<p>dm_db_index_usage_stats</p>\n\n<p>This allows you to know if data in a table has been updated recently even if you don't have a DateUpdated column on the table.</p>\n\n<pre><code>SELECT OBJECT_NAME(OBJECT_ID) AS DatabaseName, last_user_update,*\nFROM sys.dm_db_index_usage_stats\nWHERE database_id = DB_ID( 'MyDatabase')\nAND OBJECT_ID=OBJECT_ID('MyTable')\n</code></pre>\n\n<p>Code from: <a href=\"http://blog.sqlauthority.com/2009/05/09/sql-server-find-last-date-time-updated-for-any-table/\" rel=\"nofollow noreferrer\">http://blog.sqlauthority.com/2009/05/09/sql-server-find-last-date-time-updated-for-any-table/</a></p>\n\n<p>Information referenced from:\n<a href=\"https://stackoverflow.com/questions/837709/sql-server-what-is-the-date-time-of-the-last-inserted-row-of-a-table\">SQL Server - What is the date/time of the last inserted row of a table?</a></p>\n\n<p>Available in SQL 2005 and later</p>\n" }, { "answer_id": 3646602, "author": "Denis Valeev", "author_id": 124681, "author_profile": "https://Stackoverflow.com/users/124681", "pm_score": 3, "selected": false, "text": "<p>There are times when there's no suitable column to sort by, or you just want the default sort order on a table and you want to enumerate each row. In order to do that you can put \"(select 1)\" in the \"order by\" clause and you'd get what you want. Neat, eh?</p>\n\n<pre><code>select row_number() over (order by (select 1)), * from dbo.Table as t\n</code></pre>\n" }, { "answer_id": 3880976, "author": "sourabh", "author_id": 463867, "author_profile": "https://Stackoverflow.com/users/463867", "pm_score": 0, "selected": false, "text": "<p>BCP_IN and BCP_OUT perfect for BULK data import and export</p>\n" }, { "answer_id": 5391295, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://michaeljswart.com/2010/02/more-images-from-the-spatial-results-tab/\">The spatial results tab can be used to create art</a>.</p>\n\n<p><a href=\"http://michaeljswart.com/wp-content/uploads/2010/02/venus.png\">enter link description here http://michaeljswart.com/wp-content/uploads/2010/02/venus.png</a></p>\n" }, { "answer_id": 5416552, "author": "Satya SKJ", "author_id": 378142, "author_profile": "https://Stackoverflow.com/users/378142", "pm_score": 0, "selected": false, "text": "<p>SQL Server Management Studio keyboard shortcuts... that will enable quicker and faster results in day-to-day works. <a href=\"http://sqlserver-qa.net/blogs/tools/archive/2007/04/25/management-studio-shortcut-keys.aspx\" rel=\"nofollow\">http://sqlserver-qa.net/blogs/tools/archive/2007/04/25/management-studio-shortcut-keys.aspx</a></p>\n" }, { "answer_id": 6132609, "author": "waeva", "author_id": 768428, "author_profile": "https://Stackoverflow.com/users/768428", "pm_score": 1, "selected": false, "text": "<p>did you ever accidentally click on Execute button when u actually wanted to click on :<br>\nDebug / Parse / Use Database / Switch between query tabs / etc. ?<br></p>\n\n<p>Here is a way to move that button someplace safe:</p>\n\n<p>Tools -> Customize . and drag button where you want</p>\n\n<p>You can also :<br>\n- add/remove other buttons which are commonly used/unused (applies even to commands within MenuBar like File/Edit)<br>\n- change icon image of button (see the tiny pig under Change Button Image.. lol)</p>\n" }, { "answer_id": 6700081, "author": "MikeM", "author_id": 222714, "author_profile": "https://Stackoverflow.com/users/222714", "pm_score": 2, "selected": false, "text": "<p>use <code>GETDATE()</code> with <code>+</code> or <code>-</code> to calculate a nearby date</p>\n\n<pre><code>SELECT GETDATE() - 1 -- yesterday, 1 day ago, 24 hours ago\nSELECT GETDATE() - .5 -- 12 hours ago\nSELECT GETDATE() - .25 -- 6 hours ago\nSELECT GETDATE() - (1 / 24.0) -- 1 hour ago (implicit decimal result after division)\n</code></pre>\n" }, { "answer_id": 7890222, "author": "StuartLC", "author_id": 314291, "author_profile": "https://Stackoverflow.com/users/314291", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/4273723/what-is-the-purpose-of-system-table-table-master-spt-values-and-what-are-the-me\">master..spt_values</a> (and specifically type='p') has been really useful for <a href=\"https://stackoverflow.com/questions/4273978/why-and-how-to-split-column-using-master-spt-values\">string splitting</a> and doing 'binning' and <a href=\"https://stackoverflow.com/questions/7713532/sql-selecting-rows-at-varying-intervals/7714335#7714335\">time interpolation</a> manipulation.</p>\n" }, { "answer_id": 8070773, "author": "Steve", "author_id": 634027, "author_profile": "https://Stackoverflow.com/users/634027", "pm_score": 0, "selected": false, "text": "<p>You can create a comma separated list with a subquery and not have the last trailing comma. This has been said to be more efficient than the functions that were used before this became available. I think 2005 and later.</p>\n\n<pre><code>SELECT \n Project.ProjectName,\n (SELECT\n SUBSTRING(\n (SELECT ', ' + Site.SiteName\n FROM Site\n WHERE Site.ProjectKey = Project.ProjectKey\n ORDER BY Project.ProjectName\n FOR XML PATH('')),2,200000)) AS CSV \nFROM Project\n</code></pre>\n\n<p>You can also use FOR XML PATH with nested queries to select to XML which I have found useful.</p>\n" }, { "answer_id": 8216370, "author": "viniciushana", "author_id": 333687, "author_profile": "https://Stackoverflow.com/users/333687", "pm_score": 0, "selected": false, "text": "<p><strong>sp_lock</strong>: displays all the current locks. The returned data can be further queried as:</p>\n\n<p><strong>spid</strong> - use it with <code>sp_who</code> to see who owns the lock.</p>\n\n<p><strong>objid</strong> - use it with <code>select object_name(objid)</code> to see which database object is locked.</p>\n" }, { "answer_id": 8457688, "author": "Sundeep Arun", "author_id": 756159, "author_profile": "https://Stackoverflow.com/users/756159", "pm_score": 1, "selected": false, "text": "<p>I would like to recommend a free add-in <a href=\"http://www.ssmstoolspack.com/\" rel=\"nofollow\">SSMS Tools Pack</a> which has got bunch of features such as</p>\n\n<h2>Code Snippets</h2>\n\n<p>You don't need to type SELECT * FROM on your own anymore. Just type SSF and hit enter (which can be customized to any other key. I prefer Tab). Few other useful snippets are</p>\n\n<p>SSC + tab - SELECT COUNT(*) FROM</p>\n\n<p>SST + tab - SELECT TOP 10 * FROM</p>\n\n<p>S + tab - SELECT</p>\n\n<p>I + tab - INSERT </p>\n\n<p>U + tab - UPDATE</p>\n\n<p>W + tab - WHERE </p>\n\n<p>OB + tab - ORDER BY</p>\n\n<p>and the list goes on. You can check and customize the entire list using SSMS Tools Pack Menu</p>\n\n<h2>Execution Log History</h2>\n\n<p>Have you ever realized that you could have saved an ad hoc query which you wrote few days back so that you don't need to reinvent the wheel again? SSMS Tools pack saves all your execution history and you can search based on date or any text in the query.</p>\n\n<h2>Search Database Data</h2>\n\n<p>This feature helps you to search for the occurence of the string in the entire database and displays the table name and column name with total number of occurences. You can use this feature by right clicking the database in object explorer and selecting Search Database Data.</p>\n\n<h2>Format SQL</h2>\n\n<p>Sets all keywords to uppercase or lowercase letters. Right click on query window and select Format Text. You can set the Shortcut key in SSMS Tools Menu. But it lacks alignment feature.</p>\n\n<h2>CRUD SP Generation</h2>\n\n<p>Right click a table, SSMS Tools - > Create CRUD to generate Insert, Update, Delete and Select SP. The content of the SP can be customized using SSMS Tools menu.</p>\n\n<h2>Misc</h2>\n\n<p>Few other features are </p>\n\n<ol>\n<li>Search results in the Grid mode.</li>\n<li>Generate Insert script from resultset, tables &amp; database.</li>\n<li>Execution Plan Analyzer.</li>\n<li>Run one script in multiple databases.</li>\n</ol>\n\n<p>For more information, you can visit their <a href=\"http://www.ssmstoolspack.com/Features\" rel=\"nofollow\">Features</a> page</p>\n" }, { "answer_id": 8721854, "author": "SoftwareCarpenter", "author_id": 1054020, "author_profile": "https://Stackoverflow.com/users/1054020", "pm_score": 0, "selected": false, "text": "<p>I use SSMS to find text in files on the OS harddrive. It makes it super easy to write regex and sift through any directory to replace or find text. I always found this easier then using windows.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7028/" ]
What are some hidden features of [SQL Server](http://en.wikipedia.org/wiki/Microsoft_SQL_Server)? For example, undocumented system stored procedures, tricks to do things which are very useful but not documented enough? --- Answers ------- *Thanks to everybody for all the great answers!* **Stored Procedures** * **sp\_msforeachtable:** Runs a command with '?' replaced with each table name (v6.5 and up) * **sp\_msforeachdb:** Runs a command with '?' replaced with each database name (v7 and up) * **sp\_who2:** just like sp\_who, but with a lot more info for troubleshooting blocks (v7 and up) * **sp\_helptext:** If you want the code of a stored procedure, view & UDF * **sp\_tables:** return a list of all tables and views of database in scope. * **sp\_stored\_procedures:** return a list of all stored procedures * **xp\_sscanf:** Reads data from the string into the argument locations specified by each format argument. * **xp\_fixeddrives:**: Find the fixed drive with largest free space * **sp\_help:** If you want to know the table structure, indexes and constraints of a table. Also views and UDFs. Shortcut is Alt+F1 **Snippets** * Returning rows in random order * All database User Objects by Last Modified Date * Return Date Only * Find records which date falls somewhere inside the current week. * Find records which date occurred last week. * Returns the date for the beginning of the current week. * Returns the date for the beginning of last week. * See the text of a procedure that has been deployed to a server * Drop all connections to the database * Table Checksum * Row Checksum * Drop all the procedures in a database * Re-map the login Ids correctly after restore * Call Stored Procedures from an INSERT statement * Find Procedures By Keyword * Drop all the procedures in a database * Query the transaction log for a database programmatically. **Functions** * HashBytes() * EncryptByKey * PIVOT command **Misc** * Connection String extras * TableDiff.exe * Triggers for Logon Events (New in Service Pack 2) * Boosting performance with persisted-computed-columns (pcc). * DEFAULT\_SCHEMA setting in sys.database\_principles * Forced Parameterization * Vardecimal Storage Format * Figuring out the most popular queries in seconds * Scalable Shared Databases * Table/Stored Procedure Filter feature in SQL Management Studio * Trace flags * Number after a `GO` repeats the batch * Security using schemas * Encryption using built in encryption functions, views and base tables with triggers
In Management Studio, you can put a number after a GO end-of-batch marker to cause the batch to be repeated that number of times: ``` PRINT 'X' GO 10 ``` Will print 'X' 10 times. This can save you from tedious copy/pasting when doing repetitive stuff.
121,253
<p>I'm having a strange problem in Visual Studio 2008 where my "Pending Checkins" window never updates. I open it up, and it says "Updating..." like usual, but I never see the "X remaining" message, and nothing happens. It just sits there doing nothing.</p> <p>Checked-out stuff still shows as checked out in Solution Explorer. SourceSafe 2005 still works like normal.</p> <p>Any ideas?</p>
[ { "answer_id": 122020, "author": "EvilEddie", "author_id": 12986, "author_profile": "https://Stackoverflow.com/users/12986", "pm_score": 0, "selected": false, "text": "<p>Have you tried the Visual SourceSafe 2005 Update patch?</p>\n" }, { "answer_id": 192168, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 4, "selected": true, "text": "<p>Hooray! I found a solution. For anyone else that stumbles across this, here's the deal.</p>\n\n<p>I discovered today that the Pending Checkins window wasn't broken for <em>all</em> solutions, but only for a particular one. Also, though I didn't realize it was related, every time I opened the solution, I was getting:</p>\n\n<p><strong>\"Some of the properties associated with the solution could not be read.\"</strong></p>\n\n<p>The solution I found was <a href=\"http://bloggingabout.net/blogs/rick/archive/2007/12/06/quot-some-of-the-properties-associated-with-the-solution-could-not-be-read-quot.aspx\" rel=\"nofollow noreferrer\">here</a>. It turns out that I had two</p>\n\n<pre><code>GlobalSection(SourceCodeControl) = preSolution\n</code></pre>\n\n<p>sections in the solution (.sln) file. I deleted the second one (which had a long list of projects, but also some gibberish in it), and the message went away, and my Pending Checkins window now works perfectly.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5486/" ]
I'm having a strange problem in Visual Studio 2008 where my "Pending Checkins" window never updates. I open it up, and it says "Updating..." like usual, but I never see the "X remaining" message, and nothing happens. It just sits there doing nothing. Checked-out stuff still shows as checked out in Solution Explorer. SourceSafe 2005 still works like normal. Any ideas?
Hooray! I found a solution. For anyone else that stumbles across this, here's the deal. I discovered today that the Pending Checkins window wasn't broken for *all* solutions, but only for a particular one. Also, though I didn't realize it was related, every time I opened the solution, I was getting: **"Some of the properties associated with the solution could not be read."** The solution I found was [here](http://bloggingabout.net/blogs/rick/archive/2007/12/06/quot-some-of-the-properties-associated-with-the-solution-could-not-be-read-quot.aspx). It turns out that I had two ``` GlobalSection(SourceCodeControl) = preSolution ``` sections in the solution (.sln) file. I deleted the second one (which had a long list of projects, but also some gibberish in it), and the message went away, and my Pending Checkins window now works perfectly.
121,274
<p>How would I go about binding the following object, Car, to a gridview?</p> <pre> public class Car { long Id {get; set;} Manufacturer Maker {get; set;} } public class Manufacturer { long Id {get; set;} String Name {get; set;} } </pre> <p>The primitive types get bound easy but I have found no way of displaying anything for Maker. I would like for it to display the Manufacturer.Name. Is it even possible? </p> <p>What would be a way to do it? Would I have to store ManufacturerId in Car as well and then setup an lookupEditRepository with list of Manufacturers?</p>
[ { "answer_id": 121328, "author": "hollystyles", "author_id": 2083160, "author_profile": "https://Stackoverflow.com/users/2083160", "pm_score": 3, "selected": false, "text": "<pre><code> public class Manufacturer\n {\n long Id {get; set;}\n String Name {get; set;}\n\n public override string ToString()\n {\n return Name;\n }\n }\n</code></pre>\n\n<p>Override the to string method. </p>\n" }, { "answer_id": 121346, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 4, "selected": false, "text": "<p>Yes, you can create a TypeDescriptionProvider to accomplish nested binding. Here is a detailed example from an MSDN blog:</p>\n\n<p><a href=\"http://blogs.msdn.com/msdnts/archive/2007/01/19/how-to-bind-a-datagridview-column-to-a-second-level-property-of-a-data-source.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/msdnts/archive/2007/01/19/how-to-bind-a-datagridview-column-to-a-second-level-property-of-a-data-source.aspx</a></p>\n" }, { "answer_id": 121359, "author": "Seb Nilsson", "author_id": 2429, "author_profile": "https://Stackoverflow.com/users/2429", "pm_score": 2, "selected": false, "text": "<p>Just use a List and set the <strong>DataMember</strong> to the string \"Maker.Name\" and if you want the <strong>DataKeyField</strong> to use car's ID just set that to \"ID\".</p>\n\n<pre><code>dataGrid.DataSource = carList;\ndataGrid.DataMember = \"Maker.Name\";\ndataGrid.DataKeyField = \"ID\";\ndataGrid.DataBind();\n</code></pre>\n\n<p>I know that works in the repeater-control, at least...</p>\n" }, { "answer_id": 128909, "author": "ManiacZX", "author_id": 18148, "author_profile": "https://Stackoverflow.com/users/18148", "pm_score": 3, "selected": false, "text": "<p>The way that I approached this in a recent application was to create my own DataGridViewColumn and DataGridViewCell classes inheriting off of one of the existing ones such as DataGridViewTextBoxColumn and DataGridViewTextBoxCell.</p>\n\n<p>Depending on the type of cell you want, you could use others such as Button, Checkbox, ComboBox, etc. Just take a look at the types available in System.Windows.Forms.</p>\n\n<p>The cells deal with their value's as objects so you will be able to pass your Car class into the cell's value.</p>\n\n<p>Overriding SetValue and GetValue will allow you to have any additional logic you need to handle the value.</p>\n\n<p>For example:</p>\n\n<pre><code>public class CarCell : System.Windows.Forms.DataGridViewTextBoxCell\n{\n protected override object GetValue(int rowIndex)\n {\n Car car = base.GetValue(rowIndex) as Car;\n if (car != null)\n {\n return car.Maker.Name;\n }\n else\n {\n return \"\";\n }\n }\n}\n</code></pre>\n\n<p>On the column class the main thing you need to do is set the CellTemplate to your custom cell class.</p>\n\n<pre><code>public class CarColumn : System.Windows.Forms.DataGridViewTextBoxColumn\n{\n public CarColumn(): base()\n {\n CarCell c = new CarCell();\n base.CellTemplate = c;\n }\n}\n</code></pre>\n\n<p>By using these custom Column/Cells on the DataGridView it allows you to add a lot of extra functionality to your DataGridView.</p>\n\n<p>I used them to alter the displayed formatting by overriding GetFormattedValue to apply custom formatting to the string values.</p>\n\n<p>I also did an override on Paint so that I could do custom cell highlighting depending on value conditions, altering the cells Style.BackColor to what I wanted based on the value.</p>\n" }, { "answer_id": 155861, "author": "Seth Petry-Johnson", "author_id": 23632, "author_profile": "https://Stackoverflow.com/users/23632", "pm_score": 2, "selected": false, "text": "<p>If you want to expose specific, nested properties as binding targets, then Ben Hoffstein's answer (<a href=\"http://blogs.msdn.com/msdnts/archive/2007/01/19/how-to-bind-a-datagridview-column-to-a-second-level-property-of-a-data-source.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/msdnts/archive/2007/01/19/how-to-bind-a-datagridview-column-to-a-second-level-property-of-a-data-source.aspx</a>) is pretty good. The referenced article is a bit obtuse, but it works.</p>\n\n<p>If you just want to bind a column to a complex property (e.g. Manufacturer) and override the rendering logic, then either do what ManiacXZ recommended, or just subclass BoundField and provide a custom implementation of FormatDataValue(). This is similar to overriding ToString(); you get an object reference, and you return the string you want displayed in your grid.</p>\n\n<p>Something like this:</p>\n\n<pre><code>public class ManufacturerField : BoundField\n{\n protected override string FormatDataValue(object dataValue, bool encode)\n {\n var mfr = dataValue as Manufacturer;\n\n if (mfr != null)\n {\n return mfr.Name + \" (ID \" + mfr.Id + \")\";\n }\n else\n {\n return base.FormatDataValue(dataValue, encode);\n }\n }\n}\n</code></pre>\n\n<p>Just add a ManufacturerField to your grid, specifying \"Manufacturer\" as the data field, and you're good to go.</p>\n" }, { "answer_id": 940477, "author": "Ryan Spears", "author_id": 11948, "author_profile": "https://Stackoverflow.com/users/11948", "pm_score": 1, "selected": false, "text": "<p>I would assume you could do the following:</p>\n\n<pre><code>public class Car\n{\n public long Id {get; set;}\n public Manufacturer Maker {private get; set;}\n\n public string ManufacturerName\n {\n get { return Maker != null ? Maker.Name : \"\"; }\n }\n}\n\npublic class Manufacturer\n{\n long Id {get; set;}\n String Name {get; set;}\n}\n</code></pre>\n" }, { "answer_id": 5250423, "author": "n8wrl", "author_id": 37710, "author_profile": "https://Stackoverflow.com/users/37710", "pm_score": 2, "selected": false, "text": "<p>Here's another option I got working:</p>\n\n<pre><code>&lt;asp:TemplateColumn\n HeaderText=\"Maker\"&gt;\n &lt;ItemTemplate&gt;\n &lt;%#Eval(\"Maker.Name\")%&gt;\n &lt;/ItemTemplate&gt;\n&lt;/asp:TemplateColumn&gt;\n</code></pre>\n\n<p>Might be ASP.NET 4.0 specific but it works like a charm!</p>\n" }, { "answer_id": 10567944, "author": "Gad", "author_id": 25152, "author_profile": "https://Stackoverflow.com/users/25152", "pm_score": 5, "selected": false, "text": "<p>Allright guys... This question was posted waaay back but I just found a fairly nice &amp; simple way to do this by using reflection in the cell_formatting event to go retrieve the nested properties.</p>\n\n<p>Goes like this:</p>\n\n<pre><code> private void Grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n {\n\n DataGridView grid = (DataGridView)sender;\n DataGridViewRow row = grid.Rows[e.RowIndex];\n DataGridViewColumn col = grid.Columns[e.ColumnIndex];\n if (row.DataBoundItem != null &amp;&amp; col.DataPropertyName.Contains(\".\"))\n {\n string[] props = col.DataPropertyName.Split('.');\n PropertyInfo propInfo = row.DataBoundItem.GetType().GetProperty(props[0]);\n object val = propInfo.GetValue(row.DataBoundItem, null);\n for (int i = 1; i &lt; props.Length; i++)\n {\n propInfo = val.GetType().GetProperty(props[i]);\n val = propInfo.GetValue(val, null);\n }\n e.Value = val;\n }\n }\n</code></pre>\n\n<p>And that's it! You can now use the familiar syntax \"ParentProp.ChildProp.GrandChildProp\" in the DataPropertyName for your column.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15771/" ]
How would I go about binding the following object, Car, to a gridview? ``` public class Car { long Id {get; set;} Manufacturer Maker {get; set;} } public class Manufacturer { long Id {get; set;} String Name {get; set;} } ``` The primitive types get bound easy but I have found no way of displaying anything for Maker. I would like for it to display the Manufacturer.Name. Is it even possible? What would be a way to do it? Would I have to store ManufacturerId in Car as well and then setup an lookupEditRepository with list of Manufacturers?
Allright guys... This question was posted waaay back but I just found a fairly nice & simple way to do this by using reflection in the cell\_formatting event to go retrieve the nested properties. Goes like this: ``` private void Grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { DataGridView grid = (DataGridView)sender; DataGridViewRow row = grid.Rows[e.RowIndex]; DataGridViewColumn col = grid.Columns[e.ColumnIndex]; if (row.DataBoundItem != null && col.DataPropertyName.Contains(".")) { string[] props = col.DataPropertyName.Split('.'); PropertyInfo propInfo = row.DataBoundItem.GetType().GetProperty(props[0]); object val = propInfo.GetValue(row.DataBoundItem, null); for (int i = 1; i < props.Length; i++) { propInfo = val.GetType().GetProperty(props[i]); val = propInfo.GetValue(val, null); } e.Value = val; } } ``` And that's it! You can now use the familiar syntax "ParentProp.ChildProp.GrandChildProp" in the DataPropertyName for your column.
121,282
<p>If I do something like:</p> <pre><code>$ cat /bin/ls </code></pre> <p>into my terminal, I understand why I see a bunch of binary data, representing the ls executable. But afterwards, when I get my prompt back, my own keystrokes look crazy. I type "a" and I get a weird diagonal line. I type "b" and I get a degree symbol.</p> <p>Why does this happen?</p>
[ { "answer_id": 121297, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": 2, "selected": false, "text": "<p>You're getting some control characters piped into the shell that are telling the shell to alter its behavior and print things differently.</p>\n" }, { "answer_id": 121299, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 5, "selected": false, "text": "<p>Because somewhere in your binary data were some control sequences that your terminal interpreted as requests to, for example, change the character set used to draw. You can restore everything to normal like so:</p>\n\n<pre><code>reset\n</code></pre>\n" }, { "answer_id": 121321, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://local.wasp.uwa.edu.au/~pbourke/dataformats/vt100/\" rel=\"nofollow noreferrer\">VT100</a> is pretty much the standard command set used for terminal windows, but there are a lot of extensions. Some control character set used, keyboard mapping, etc.</p>\n\n<p>When you send a lot of binary characters to such a terminal, a lot of settings change. Some terminals have options to 'clear' the settings back to default, but in general they simply weren't made for binary data.</p>\n\n<p>VT100 and its successors are what allow Linux to print in color text (such as colored ls listings) in a simple terminal program.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 121374, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": -1, "selected": false, "text": "<p>If you really must dump binary data to your terminal, you'd have much better luck if you pipe it to a pager like <code>less</code>, which will display it in a slightly more readable format. (You may also be interested in <code>strings</code> and <code>od</code>, both can be useful if you're fiddling around with binary files.)</p>\n" }, { "answer_id": 121569, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 2, "selected": false, "text": "<p>The terminal will try to interpret the binary data thrown at it as control codes, and garble itself up in the process, so you need to sanitize your tty.</p>\n\n<p>Run:</p>\n\n<pre><code>stty sane\n</code></pre>\n\n<p>And things should be back to normal. Even if the command looks garbled as you type it, the actual characters are being stored correctly, and when you press return the command will be invoked.</p>\n\n<p>You can find more information about the stty command <a href=\"http://www.ncsa.uiuc.edu/UserInfo/Resources/Hardware/IBMp690/IBM/usr/share/man/info/en_US/a_doc_lib/cmds/aixcmds5/stty.htm\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 370227, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 4, "selected": false, "text": "<p>Just do a copy-paste:</p>\n\n<pre><code>echo -e '\\017'\n</code></pre>\n\n<p>to your bash and characters will return to normal. If you don't run bash, try the following keystrokes:</p>\n\n<pre><code>&lt;Ctrl-V&gt;&lt;Ctrl-O&gt;&lt;Enter&gt;\n</code></pre>\n\n<p>and hopefully your terminal's status will return to normal when it complains that it can't find either a &lt;Ctrl-V>&lt;Ctrl-O> or a &lt;Ctrl-O> command to run.</p>\n\n<p>&lt;Ctrl-N>, or character 14 —when sent to your terminal— orders to switch to a special graphics mode, where letters and numbers are replaced with symbols. &lt;Ctrl-O>, or character 15, restores things back to normal.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
If I do something like: ``` $ cat /bin/ls ``` into my terminal, I understand why I see a bunch of binary data, representing the ls executable. But afterwards, when I get my prompt back, my own keystrokes look crazy. I type "a" and I get a weird diagonal line. I type "b" and I get a degree symbol. Why does this happen?
Because somewhere in your binary data were some control sequences that your terminal interpreted as requests to, for example, change the character set used to draw. You can restore everything to normal like so: ``` reset ```
121,309
<p>In an ASP.NET 2.0 website, I have a string representing some well-formed XML. I am currently creating an XmlDocument object with it and running an XSL transformation for display in a Web form. Everything was operating fine until the XML input started to contain namespaces.</p> <p>How can I read in this string and allow namespaces?</p> <p>I've included the current code below. The string source comes from an HTML encoded node in a WordPress RSS feed.</p> <pre><code>XPathNavigator myNav= myPost.CreateNavigator(); XmlNamespaceManager myManager = new XmlNamespaceManager(myNav.NameTable); myManager.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/"); string myPost = HttpUtility.HtmlDecode("&lt;post&gt;" + myNav.SelectSingleNode("//item[1]/content:encoded", myManager).InnerXml + "&lt;/post&gt;"); XmlDocument myDocument = new XmlDocument(); myDocument.LoadXml(myPost.ToString()); </code></pre> <p>The error is on the last line:</p> <p>"System.Xml.XmlException: 'w' is an undeclared namespace. Line 12, position 201. at System.Xml.XmlTextReaderImpl.Throw(Exception e) ..."</p>
[ { "answer_id": 121407, "author": "ckarras", "author_id": 5688, "author_profile": "https://Stackoverflow.com/users/5688", "pm_score": 1, "selected": false, "text": "<p>Your code looks right.</p>\n\n<p>The problem is probably in the xml document you're trying to load.\nIt must have elements with a \"w\" prefix, without having that prefix declared in the XML document</p>\n\n<p>For example, you should have:</p>\n\n<pre><code>&lt;test xmlns:w=\"http://...\"&gt;\n &lt;w:elementInWNamespace /&gt;\n&lt;/test&gt;\n</code></pre>\n\n<p>(your document is probably missing the <code>xmlns:w=\"http://\"</code>)</p>\n" }, { "answer_id": 121414, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 1, "selected": true, "text": "<p>Gut feel - one of the namespaces declared in //content:encoding is being dropped (probably because you're using the literal .InnerXml property)</p>\n\n<p>What's 'w' namespace evaluate to in the myNav DOM? You'll want to add xmlns:w= to your post node. There will probably be others too.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19626/" ]
In an ASP.NET 2.0 website, I have a string representing some well-formed XML. I am currently creating an XmlDocument object with it and running an XSL transformation for display in a Web form. Everything was operating fine until the XML input started to contain namespaces. How can I read in this string and allow namespaces? I've included the current code below. The string source comes from an HTML encoded node in a WordPress RSS feed. ``` XPathNavigator myNav= myPost.CreateNavigator(); XmlNamespaceManager myManager = new XmlNamespaceManager(myNav.NameTable); myManager.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/"); string myPost = HttpUtility.HtmlDecode("<post>" + myNav.SelectSingleNode("//item[1]/content:encoded", myManager).InnerXml + "</post>"); XmlDocument myDocument = new XmlDocument(); myDocument.LoadXml(myPost.ToString()); ``` The error is on the last line: "System.Xml.XmlException: 'w' is an undeclared namespace. Line 12, position 201. at System.Xml.XmlTextReaderImpl.Throw(Exception e) ..."
Gut feel - one of the namespaces declared in //content:encoding is being dropped (probably because you're using the literal .InnerXml property) What's 'w' namespace evaluate to in the myNav DOM? You'll want to add xmlns:w= to your post node. There will probably be others too.
121,318
<p>I need to have a script read the files coming in and check information for verification.</p> <p>On the first line of the files to be read is a date but in numeric form. eg: 20080923 But before the date is other information, I need to read it from position 27. Meaning line 1 position 27, I need to get that number and see if it’s greater then another number.</p> <p>I use the grep command to check other information but I use special characters to search, in this case the information before the date is always different, so I can’t use a character to search on. It has to be done by line 1 position 27.</p>
[ { "answer_id": 121336, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 4, "selected": true, "text": "<pre><code>sed 1q $file | cut -c27-34\n</code></pre>\n\n<p>The <code>sed</code> command reads the first line of the file and the <code>cut</code> command chops out characters 27-34 of the one line, which is where you said the date is.</p>\n\n<p><em>Added later:</em></p>\n\n<p>For the more general case - where you need to read line 24, for example, instead of the first line, you need a slightly more complex <code>sed</code> command:</p>\n\n<pre><code>sed -n -e 24p -e 24q | cut -c27-34\nsed -n '24p;24q' | cut -c27-34\n</code></pre>\n\n<p>The <code>-n</code> option means 'do not print lines by default'; the <code>24p</code> means print line 24; the <code>24q</code> means quit after processing line 24. You could leave that out, in which case <code>sed</code> would continue processing the input, effectively ignoring it.</p>\n\n<p>Finally, especially if you are going to validate the date, you might want to use Perl for the whole job (or Python, or Ruby, or Tcl, or any scripting language of your choice). </p>\n" }, { "answer_id": 121344, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 1, "selected": false, "text": "<p>You can extract the characters starting at position 27 of line 1 like so:</p>\n\n<pre><code>datestring=`head -1 $file | cut -c27-`\n</code></pre>\n\n<p>You'd perform your next processing step on $datestring.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21151/" ]
I need to have a script read the files coming in and check information for verification. On the first line of the files to be read is a date but in numeric form. eg: 20080923 But before the date is other information, I need to read it from position 27. Meaning line 1 position 27, I need to get that number and see if it’s greater then another number. I use the grep command to check other information but I use special characters to search, in this case the information before the date is always different, so I can’t use a character to search on. It has to be done by line 1 position 27.
``` sed 1q $file | cut -c27-34 ``` The `sed` command reads the first line of the file and the `cut` command chops out characters 27-34 of the one line, which is where you said the date is. *Added later:* For the more general case - where you need to read line 24, for example, instead of the first line, you need a slightly more complex `sed` command: ``` sed -n -e 24p -e 24q | cut -c27-34 sed -n '24p;24q' | cut -c27-34 ``` The `-n` option means 'do not print lines by default'; the `24p` means print line 24; the `24q` means quit after processing line 24. You could leave that out, in which case `sed` would continue processing the input, effectively ignoring it. Finally, especially if you are going to validate the date, you might want to use Perl for the whole job (or Python, or Ruby, or Tcl, or any scripting language of your choice).
121,324
<p>I'm looking for a framework to generate Java source files.</p> <p>Something like the following API:</p> <pre><code>X clazz = Something.createClass("package name", "class name"); clazz.addSuperInterface("interface name"); clazz.addMethod("method name", returnType, argumentTypes, ...); File targetDir = ...; clazz.generate(targetDir); </code></pre> <p>Then, a java source file should be found in a sub-directory of the target directory.</p> <p>Does anyone know such a framework?</p> <hr> <p><strong>EDIT</strong>:</p> <ol> <li>I really need the source files.</li> <li>I also would like to fill out the code of the methods.</li> <li>I'm looking for a high-level abstraction, not direct bytecode manipulation/generation.</li> <li>I also need the "structure of the class" in a tree of objects.</li> <li>The problem domain is general: to generate a large amount of very different classes, without a "common structure".</li> </ol> <hr> <p><strong>SOLUTIONS</strong><br> I have posted 2 answers based in your answers... <a href="https://stackoverflow.com/questions/121324/a-java-api-to-generate-java-source-files#136010">with CodeModel</a> and <a href="https://stackoverflow.com/questions/121324/a-java-api-to-generate-java-source-files#136016">with Eclipse JDT</a>.</p> <p>I have used <a href="http://codemodel.java.net/" rel="noreferrer">CodeModel</a> in my solution, :-)</p>
[ { "answer_id": 121367, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": 1, "selected": false, "text": "<p>If you REALLY need the source, I don't know of anything that generates source. You can however use <a href=\"http://asm.objectweb.org/\" rel=\"nofollow noreferrer\">ASM</a> or <a href=\"http://cglib.sourceforge.net/\" rel=\"nofollow noreferrer\">CGLIB</a> to directly create the .class files. </p>\n\n<p>You might be able to generate source from these, but I've only used them to generate bytecode.</p>\n" }, { "answer_id": 121418, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://www.eclipse.org/modeling/m2t/?project=jet\" rel=\"nofollow noreferrer\">Eclipse JET</a> project can be used to do source generation. I don't think it's API is exactly like the one you described, but every time I've heard of a project doing Java source generation they've used JET or a homegrown tool.</p>\n" }, { "answer_id": 121571, "author": "Vladimir Dyuzhev", "author_id": 1163802, "author_profile": "https://Stackoverflow.com/users/1163802", "pm_score": 1, "selected": false, "text": "<p>I was doing it myself for a mock generator tool. It's a very simple task, even if you need to follow Sun formatting guidelines. I bet you'd finish the code that does it faster then you found something that fits your goal on the Internet.</p>\n\n<p>You've basically outlined the API yourself. Just fill it with the actual code now!</p>\n" }, { "answer_id": 121672, "author": "Squirrel", "author_id": 11835, "author_profile": "https://Stackoverflow.com/users/11835", "pm_score": 3, "selected": false, "text": "<p>Another alternative is Eclipse JDT's AST which is good if you need to rewrite arbitrary Java source code rather than just generate source code.\n(and I believe it can be used independently from eclipse).</p>\n" }, { "answer_id": 121710, "author": "ykaganovich", "author_id": 10026, "author_profile": "https://Stackoverflow.com/users/10026", "pm_score": 2, "selected": false, "text": "<p>Don't know of a library, but a generic template engine might be all you need. There are <a href=\"http://java-source.net/open-source/template-engines\" rel=\"nofollow noreferrer\">a bunch of them</a>, I personally have had good experience with <a href=\"http://www.freemarker.org/index.html\" rel=\"nofollow noreferrer\">FreeMarker</a></p>\n" }, { "answer_id": 122209, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 7, "selected": true, "text": "<p>Sun provides an API called CodeModel for generating Java source files using an API. It's not the easiest thing to get information on, but it's there and it works extremely well.</p>\n\n<p>The easiest way to get hold of it is as part of the JAXB 2 RI - the XJC schema-to-java generator uses CodeModel to generate its java source, and it's part of the XJC jars. You can use it just for the CodeModel.</p>\n\n<p>Grab it from <a href=\"http://codemodel.java.net/\" rel=\"noreferrer\">http://codemodel.java.net/</a></p>\n" }, { "answer_id": 136010, "author": "Daniel Fanjul", "author_id": 16135, "author_profile": "https://Stackoverflow.com/users/16135", "pm_score": 6, "selected": false, "text": "<p><strong>Solution found with CodeModel</strong><br>\nThanks, <a href=\"https://stackoverflow.com/users/21234/skaffman\">skaffman</a>.</p>\n\n<p>For example, with this code:</p>\n\n<pre><code>JCodeModel cm = new JCodeModel();\nJDefinedClass dc = cm._class(\"foo.Bar\");\nJMethod m = dc.method(0, int.class, \"foo\");\nm.body()._return(JExpr.lit(5));\n\nFile file = new File(\"./target/classes\");\nfile.mkdirs();\ncm.build(file);\n</code></pre>\n\n<p>I can get this output:</p>\n\n<pre><code>package foo;\npublic class Bar {\n int foo() {\n return 5;\n }\n}\n</code></pre>\n" }, { "answer_id": 136016, "author": "Daniel Fanjul", "author_id": 16135, "author_profile": "https://Stackoverflow.com/users/16135", "pm_score": 5, "selected": false, "text": "<p><strong>Solution found with Eclipse JDT's AST</strong><br>\nThanks, <a href=\"https://stackoverflow.com/users/11835/giles\">Giles</a>.</p>\n\n<p>For example, with this code:</p>\n\n<pre><code>AST ast = AST.newAST(AST.JLS3);\nCompilationUnit cu = ast.newCompilationUnit();\n\nPackageDeclaration p1 = ast.newPackageDeclaration();\np1.setName(ast.newSimpleName(\"foo\"));\ncu.setPackage(p1);\n\nImportDeclaration id = ast.newImportDeclaration();\nid.setName(ast.newName(new String[] { \"java\", \"util\", \"Set\" }));\ncu.imports().add(id);\n\nTypeDeclaration td = ast.newTypeDeclaration();\ntd.setName(ast.newSimpleName(\"Foo\"));\nTypeParameter tp = ast.newTypeParameter();\ntp.setName(ast.newSimpleName(\"X\"));\ntd.typeParameters().add(tp);\ncu.types().add(td);\n\nMethodDeclaration md = ast.newMethodDeclaration();\ntd.bodyDeclarations().add(md);\n\nBlock block = ast.newBlock();\nmd.setBody(block);\n\nMethodInvocation mi = ast.newMethodInvocation();\nmi.setName(ast.newSimpleName(\"x\"));\n\nExpressionStatement e = ast.newExpressionStatement(mi);\nblock.statements().add(e);\n\nSystem.out.println(cu);\n</code></pre>\n\n<p>I can get this output:</p>\n\n<pre><code>package foo;\nimport java.util.Set;\nclass Foo&lt;X&gt; {\n void MISSING(){\n x();\n }\n}\n</code></pre>\n" }, { "answer_id": 1463010, "author": "Bala", "author_id": 42551, "author_profile": "https://Stackoverflow.com/users/42551", "pm_score": 1, "selected": false, "text": "<p>There is also <a href=\"http://www.stringtemplate.org/\" rel=\"nofollow noreferrer\">StringTemplate</a>. It is by the author of ANTLR and is quite powerful.</p>\n" }, { "answer_id": 5287753, "author": "Berlin Brown", "author_id": 10522, "author_profile": "https://Stackoverflow.com/users/10522", "pm_score": 0, "selected": false, "text": "<p>It really depends on what you are trying to do. Code generation is a topic within itself. Without a specific use-case, I suggest looking at velocity code generation/template library. Also, if you are doing the code generation offline, I would suggest using something like ArgoUML to go from UML diagram/Object model to Java code.</p>\n" }, { "answer_id": 19263850, "author": "Stephen Haberman", "author_id": 355031, "author_profile": "https://Stackoverflow.com/users/355031", "pm_score": 2, "selected": false, "text": "<p>I built something that looks very much like your theoretical DSL, called \"sourcegen\", but technically instead of a util project for an ORM I wrote. The DSL looks like:</p>\n\n<pre><code>@Test\npublic void testTwoMethods() {\n GClass gc = new GClass(\"foo.bar.Foo\");\n\n GMethod hello = gc.getMethod(\"hello\");\n hello.arguments(\"String foo\");\n hello.setBody(\"return 'Hi' + foo;\");\n\n GMethod goodbye = gc.getMethod(\"goodbye\");\n goodbye.arguments(\"String foo\");\n goodbye.setBody(\"return 'Bye' + foo;\");\n\n Assert.assertEquals(\n Join.lines(new Object[] {\n \"package foo.bar;\",\n \"\",\n \"public class Foo {\",\n \"\",\n \" public void hello(String foo) {\",\n \" return \\\"Hi\\\" + foo;\",\n \" }\",\n \"\",\n \" public void goodbye(String foo) {\",\n \" return \\\"Bye\\\" + foo;\",\n \" }\",\n \"\",\n \"}\",\n \"\" }),\n gc.toCode());\n}\n</code></pre>\n\n<p><a href=\"https://github.com/stephenh/joist/blob/master/util/src/test/java/joist/sourcegen/GClassTest.java\" rel=\"nofollow\">https://github.com/stephenh/joist/blob/master/util/src/test/java/joist/sourcegen/GClassTest.java</a></p>\n\n<p>It also does some neat things like \"Auto-organize imports\" any FQCNs in parameters/return types, auto-pruning any old files that were not touched in this codegen run, correctly indenting inner classes, etc.</p>\n\n<p>The idea is that generated code should be pretty to look at it, with no warnings (unused imports, etc.), just like the rest of your code. So much generated code is ugly to read...it's horrible.</p>\n\n<p>Anyway, there is not a lot of docs, but I think the API is pretty simple/intuitive. The Maven repo is <a href=\"http://repo.joist.ws/joist/joist-util/\" rel=\"nofollow\">here</a> if anyone is interested.</p>\n" }, { "answer_id": 22719691, "author": "user3207181", "author_id": 3207181, "author_profile": "https://Stackoverflow.com/users/3207181", "pm_score": 0, "selected": false, "text": "<p>Exemple : \n1/ </p>\n\n<pre><code>private JFieldVar generatedField;\n</code></pre>\n\n<p>2/</p>\n\n<pre><code>String className = \"class name\";\n /* package name */\n JPackage jp = jCodeModel._package(\"package name \");\n /* class name */\n JDefinedClass jclass = jp._class(className);\n /* add comment */\n JDocComment jDocComment = jclass.javadoc();\n jDocComment.add(\"By AUTOMAT D.I.T tools : \" + new Date() +\" =&gt; \" + className);\n // génération des getter &amp; setter &amp; attribues\n\n // create attribue \n this.generatedField = jclass.field(JMod.PRIVATE, Integer.class) \n , \"attribue name \");\n // getter\n JMethod getter = jclass.method(JMod.PUBLIC, Integer.class) \n , \"attribue name \");\n getter.body()._return(this.generatedField);\n // setter\n JMethod setter = jclass.method(JMod.PUBLIC, Integer.class) \n ,\"attribue name \");\n // create setter paramétre \n JVar setParam = setter.param(getTypeDetailsForCodeModel(Integer.class,\"param name\");\n // affectation ( this.param = setParam ) \n setter.body().assign(JExpr._this().ref(this.generatedField), setParam);\n\n jCodeModel.build(new File(\"path c://javaSrc//\"));\n</code></pre>\n" }, { "answer_id": 23721770, "author": "Atmega", "author_id": 3649631, "author_profile": "https://Stackoverflow.com/users/3649631", "pm_score": 1, "selected": false, "text": "<p>There is new project <a href=\"https://code.google.com/p/write-it-once/\" rel=\"nofollow\">write-it-once</a>. Template based code generator. You write custom template using <a href=\"http://groovy.codehaus.org/Groovy+Templates\" rel=\"nofollow\">Groovy</a>, and generate file depending on java reflections. It's the simplest way to generate any file. You can make getters/settest/toString by generating AspectJ files, SQL based on JPA annotations, inserts / updates based on enums and so on.</p>\n\n<p>Template example:</p>\n\n<pre><code>package ${cls.package.name};\n\npublic class ${cls.shortName}Builder {\n\n public static ${cls.name}Builder builder() {\n return new ${cls.name}Builder();\n }\n&lt;% for(field in cls.fields) {%&gt;\n private ${field.type.name} ${field.name};\n&lt;% } %&gt;\n&lt;% for(field in cls.fields) {%&gt;\n public ${cls.name}Builder ${field.name}(${field.type.name} ${field.name}) {\n this.${field.name} = ${field.name};\n return this;\n }\n&lt;% } %&gt;\n public ${cls.name} build() {\n final ${cls.name} data = new ${cls.name}();\n&lt;% for(field in cls.fields) {%&gt;\n data.${field.setter.name}(this.${field.name});\n&lt;% } %&gt;\n return data;\n }\n}\n</code></pre>\n" }, { "answer_id": 24681719, "author": "gastaldi", "author_id": 862119, "author_profile": "https://Stackoverflow.com/users/862119", "pm_score": 4, "selected": false, "text": "<p>You can use Roaster (<a href=\"https://github.com/forge/roaster\">https://github.com/forge/roaster</a>) to do code generation.</p>\n\n<p>Here is an example: </p>\n\n<pre><code>JavaClassSource source = Roaster.create(JavaClassSource.class);\nsource.setName(\"MyClass\").setPublic();\nsource.addMethod().setName(\"testMethod\").setPrivate().setBody(\"return null;\")\n .setReturnType(String.class).addAnnotation(MyAnnotation.class);\nSystem.out.println(source);\n</code></pre>\n\n<p>will display the following output:</p>\n\n<pre><code>public class MyClass {\n private String testMethod() {\n return null;\n }\n}\n</code></pre>\n" }, { "answer_id": 35211752, "author": "mtyson", "author_id": 467240, "author_profile": "https://Stackoverflow.com/users/467240", "pm_score": 0, "selected": false, "text": "<p>Here is a JSON-to-POJO project that looks interesting:</p>\n\n<p><a href=\"http://www.jsonschema2pojo.org/\" rel=\"nofollow\">http://www.jsonschema2pojo.org/</a></p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16135/" ]
I'm looking for a framework to generate Java source files. Something like the following API: ``` X clazz = Something.createClass("package name", "class name"); clazz.addSuperInterface("interface name"); clazz.addMethod("method name", returnType, argumentTypes, ...); File targetDir = ...; clazz.generate(targetDir); ``` Then, a java source file should be found in a sub-directory of the target directory. Does anyone know such a framework? --- **EDIT**: 1. I really need the source files. 2. I also would like to fill out the code of the methods. 3. I'm looking for a high-level abstraction, not direct bytecode manipulation/generation. 4. I also need the "structure of the class" in a tree of objects. 5. The problem domain is general: to generate a large amount of very different classes, without a "common structure". --- **SOLUTIONS** I have posted 2 answers based in your answers... [with CodeModel](https://stackoverflow.com/questions/121324/a-java-api-to-generate-java-source-files#136010) and [with Eclipse JDT](https://stackoverflow.com/questions/121324/a-java-api-to-generate-java-source-files#136016). I have used [CodeModel](http://codemodel.java.net/) in my solution, :-)
Sun provides an API called CodeModel for generating Java source files using an API. It's not the easiest thing to get information on, but it's there and it works extremely well. The easiest way to get hold of it is as part of the JAXB 2 RI - the XJC schema-to-java generator uses CodeModel to generate its java source, and it's part of the XJC jars. You can use it just for the CodeModel. Grab it from <http://codemodel.java.net/>
121,326
<p>What does it mean when it gives a backtrace with the following output?</p> <pre><code>#0 0x00000008009c991c in pthread_testcancel () from /lib/libpthread.so.2 #1 0x00000008009b8120 in sigaction () from /lib/libpthread.so.2 #2 0x00000008009c211a in pthread_mutexattr_init () from /lib/libpthread.so.2 #3 0x0000000000000000 in ?? () </code></pre> <p>The program has crashed with a standard signal 11, segmentation fault. My application is a multi-threaded FastCGI C++ program running on FreeBSD 6.3, using pthread as the threading library.</p> <p>It has been compiled with -g and all the symbol tables for my source are loaded, according to info sources.</p> <p>As is clear, none of my actual code appears in the trace but instead the error seems to originate from standard pthread libraries. In particular, what is ?? () ????</p> <p><b>EDIT</b>: eventually tracked the crash down to a standard invalid memory access in my main code. Doesn't explain why the stack trace was corrupted, but that's a question for another day :)</p>
[ { "answer_id": 121361, "author": "Hannes Ovrén", "author_id": 13565, "author_profile": "https://Stackoverflow.com/users/13565", "pm_score": 2, "selected": false, "text": "<p>Make sure you compile with debug symbols. (For gcc I think that is the -g option). Then you should be able to get more interesting information out of GDB. Don't forget to turn it off when you compile the production version.</p>\n" }, { "answer_id": 121370, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 5, "selected": true, "text": "<p>gdb wasn't able to extract the proper return address from pthread_mutexattr_init; it got an address of 0. The \"??\" is the result of looking up address 0 in the symbol table. It cannot find a symbolic name, so it prints a default \"??\"</p>\n\n<p>Unfortunately right offhand I don't know why it could not extract the correct return address.</p>\n" }, { "answer_id": 121457, "author": "oliver", "author_id": 2148773, "author_profile": "https://Stackoverflow.com/users/2148773", "pm_score": 1, "selected": false, "text": "<p>Maybe the bug that caused the crash has broken the stack (overwritten parts of the stack)? In that case, the backtrace might be useless; no idea what to do in that case...</p>\n" }, { "answer_id": 121512, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 3, "selected": false, "text": "<p>Something you did cause the threading library to crash. Since the threading library itself is not compiled with debugging symbols (-g), it cannot display the source code file or line number the crash happened on. In addition, since it's threads, the call stack does not point back to your file. Unfortunately this will be a tough bug to track down, you're gonna need to step through your code and try and narrow down when exactly the crash happens.</p>\n" }, { "answer_id": 327884, "author": "D.Shawley", "author_id": 41747, "author_profile": "https://Stackoverflow.com/users/41747", "pm_score": 2, "selected": false, "text": "<p>I could be missing something, but isn't this indicative of someone using <code>NULL</code> as a function pointer?</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\ntypedef int (*funcptr)(void);\n\nint\nfunc_caller(funcptr f)\n{\n return (*f)();\n}\n\nint\nmain()\n{\n return func_caller(NULL);\n}\n</code></pre>\n\n<p>This produces the same style of a backtrace if you run it in gdb:</p>\n\n<pre><code>rivendell$ gcc -g -O0 foo.c -o foo\nrivendell$ gdb --quiet foo\nReading symbols for shared libraries .. done\n(gdb) r\nStarting program: ...\nReading symbols for shared libraries . done\n\nProgram received signal EXC_BAD_ACCESS, Could not access memory.\nReason: KERN_PROTECTION_FAILURE at address: 0x00000000\n0x00000000 in ?? ()\n(gdb) bt\n#0 0x00000000 in ?? ()\n#1 0x00001f9d in func_caller (f=0) at foo.c:8\n#2 0x00001fb1 in main () at foo.c:14\n</code></pre>\n\n<p>This is a pretty strange crash though... <code>pthread_mutexattr_init</code> rarely does anything more than allocate a data structure and <code>memset</code> it. I'd look for something else going on. Is there a possibility of mismatched threading libraries or something. My BSD knowledge is a little dated, but there used to be issues around this.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10264/" ]
What does it mean when it gives a backtrace with the following output? ``` #0 0x00000008009c991c in pthread_testcancel () from /lib/libpthread.so.2 #1 0x00000008009b8120 in sigaction () from /lib/libpthread.so.2 #2 0x00000008009c211a in pthread_mutexattr_init () from /lib/libpthread.so.2 #3 0x0000000000000000 in ?? () ``` The program has crashed with a standard signal 11, segmentation fault. My application is a multi-threaded FastCGI C++ program running on FreeBSD 6.3, using pthread as the threading library. It has been compiled with -g and all the symbol tables for my source are loaded, according to info sources. As is clear, none of my actual code appears in the trace but instead the error seems to originate from standard pthread libraries. In particular, what is ?? () ???? **EDIT**: eventually tracked the crash down to a standard invalid memory access in my main code. Doesn't explain why the stack trace was corrupted, but that's a question for another day :)
gdb wasn't able to extract the proper return address from pthread\_mutexattr\_init; it got an address of 0. The "??" is the result of looking up address 0 in the symbol table. It cannot find a symbolic name, so it prints a default "??" Unfortunately right offhand I don't know why it could not extract the correct return address.
121,382
<p>Is there a way to comment out markup in an <code>.ASPX</code> page so that it isn't delivered to the client? I have tried the standard comments <code>&lt;!-- --&gt;</code> but this just gets delivered as a comment and doesn't prevent the control from rendering. </p>
[ { "answer_id": 121397, "author": "BigJump", "author_id": 8542, "author_profile": "https://Stackoverflow.com/users/8542", "pm_score": 3, "selected": false, "text": "<p>Another way assuming it's not server side code you want to comment out is...</p>\n\n<pre><code>&lt;asp:panel runat=\"server\" visible=\"false\"&gt;\n html here\n&lt;/asp:panel&gt;\n</code></pre>\n" }, { "answer_id": 121400, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 9, "selected": true, "text": "<pre><code>&lt;%--\n Commented out HTML/CODE/Markup. Anything with\n this block will not be parsed/handled by ASP.NET.\n\n &lt;asp:Calendar runat=\"server\"&gt;&lt;/asp:Calendar&gt; \n\n &lt;%# Eval(“SomeProperty”) %&gt; \n--%&gt;\n</code></pre>\n\n<p><a href=\"http://weblogs.asp.net/scottgu/archive/2006/07/09/Tip_2F00_Trick_3A00_-Using-Server-Side-Comments-with-ASP.NET-2.0-.aspx\" rel=\"noreferrer\">Source</a></p>\n" }, { "answer_id": 121406, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 5, "selected": false, "text": "<pre><code>&lt;%-- not rendered to browser --%&gt;\n</code></pre>\n" }, { "answer_id": 121409, "author": "stefano m", "author_id": 19261, "author_profile": "https://Stackoverflow.com/users/19261", "pm_score": 4, "selected": false, "text": "<p>Yes, there are special server side comments:</p>\n\n\n\n<pre><code>&lt;%-- Text not sent to client --%&gt;\n</code></pre>\n" }, { "answer_id": 121411, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 4, "selected": false, "text": "<p>I believe you're looking for:</p>\n\n<pre><code>&lt;%-- your markup here --%&gt;\n</code></pre>\n\n<p>That is a serverside comment and will not be delivered to the client ... but it's not optional. If you need this to be programmable, then you'll want <a href=\"https://stackoverflow.com/a/121397/2415524\">this answer</a> :-)</p>\n" }, { "answer_id": 122275, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 6, "selected": false, "text": "<p>Bonus answer: The keyboard shortcut in Visual Studio for commenting out anything is <strong>Ctrl-KC</strong> . This works in a number of places, including C#, VB, Javascript, and aspx pages; it also works for SQL in SQL Management Studio. </p>\n\n<p>You can either select the text to be commented out, or you can position your text inside a chunk to be commented out; for example, put your cursor inside the opening tag of a GridView, press Ctrl-KC, and the whole thing is commented out.</p>\n" }, { "answer_id": 125974, "author": "Matthew M. Osborn", "author_id": 5235, "author_profile": "https://Stackoverflow.com/users/5235", "pm_score": 5, "selected": false, "text": "<p>FYI | <kbd>ctrl</kbd> + <kbd>K</kbd>, <kbd>C</kbd> is the comment shortcut in Visual Studio. <kbd>ctrl</kbd> + <kbd>K</kbd>, <kbd>U</kbd> uncomments.</p>\n" }, { "answer_id": 26851082, "author": "ggb667", "author_id": 619895, "author_profile": "https://Stackoverflow.com/users/619895", "pm_score": 3, "selected": false, "text": "<p>While this works:</p>\n\n<pre><code>&lt;%-- &lt;%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\" Inherits=\"ht_tv1.Default\" %&gt; --%&gt;\n&lt;%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\" Inherits=\"Blank._Default\" %&gt;\n</code></pre>\n\n<p>This won't.</p>\n\n<pre><code>&lt;%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\" &lt;%--Inherits=\"ht_tv1.Default\"--%&gt; Inherits=\"Blank._Default\" %&gt;\n</code></pre>\n\n<p>So you can't comment out part of something which is what I want to do 99.9995% of the time.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10676/" ]
Is there a way to comment out markup in an `.ASPX` page so that it isn't delivered to the client? I have tried the standard comments `<!-- -->` but this just gets delivered as a comment and doesn't prevent the control from rendering.
``` <%-- Commented out HTML/CODE/Markup. Anything with this block will not be parsed/handled by ASP.NET. <asp:Calendar runat="server"></asp:Calendar> <%# Eval(“SomeProperty”) %> --%> ``` [Source](http://weblogs.asp.net/scottgu/archive/2006/07/09/Tip_2F00_Trick_3A00_-Using-Server-Side-Comments-with-ASP.NET-2.0-.aspx)
121,387
<p>Table: </p> <pre><code>UserId, Value, Date. </code></pre> <p>I want to get the UserId, Value for the max(Date) for each UserId. That is, the Value for each UserId that has the latest date. Is there a way to do this simply in SQL? (Preferably Oracle)</p> <p><strong>Update:</strong> Apologies for any ambiguity: I need to get ALL the UserIds. But for each UserId, only that row where that user has the latest date.</p>
[ { "answer_id": 121416, "author": "jdmichal", "author_id": 12275, "author_profile": "https://Stackoverflow.com/users/12275", "pm_score": 2, "selected": false, "text": "<p>I think something like this. (Forgive me for any syntax mistakes; I'm used to using HQL at this point!)</p>\n\n<p>EDIT: Also misread the question! Corrected the query...</p>\n\n<pre><code>SELECT UserId, Value\nFROM Users AS user\nWHERE Date = (\n SELECT MAX(Date)\n FROM Users AS maxtest\n WHERE maxtest.UserId = user.UserId\n)\n</code></pre>\n" }, { "answer_id": 121435, "author": "Steve K", "author_id": 739, "author_profile": "https://Stackoverflow.com/users/739", "pm_score": 6, "selected": false, "text": "<p>I don't know your exact columns names, but it would be something like this:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT userid, value\nFROM users u1\nWHERE date = (\n SELECT MAX(date)\n FROM users u2\n WHERE u1.userid = u2.userid\n)\n</code></pre>\n" }, { "answer_id": 121438, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": 1, "selected": false, "text": "<p>(T-SQL) First get all the users and their maxdate. Join with the table to find the corresponding values for the users on the maxdates.</p>\n\n<pre><code>create table users (userid int , value int , date datetime)\ninsert into users values (1, 1, '20010101')\ninsert into users values (1, 2, '20020101')\ninsert into users values (2, 1, '20010101')\ninsert into users values (2, 3, '20030101')\n\nselect T1.userid, T1.value, T1.date \n from users T1,\n (select max(date) as maxdate, userid from users group by userid) T2 \n where T1.userid= T2.userid and T1.date = T2.maxdate\n</code></pre>\n\n<p>results:</p>\n\n<pre><code>userid value date \n----------- ----------- -------------------------- \n2 3 2003-01-01 00:00:00.000\n1 2 2002-01-01 00:00:00.000\n</code></pre>\n" }, { "answer_id": 121450, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 10, "selected": true, "text": "<p>This will retrieve all rows for which the my_date column value is equal to the maximum value of my_date for that userid. This may retrieve multiple rows for the userid where the maximum date is on multiple rows.</p>\n\n<pre><code>select userid,\n my_date,\n ...\nfrom\n(\nselect userid,\n my_date,\n ...\n max(my_date) over (partition by userid) max_my_date\nfrom users\n)\nwhere my_date = max_my_date\n</code></pre>\n\n<p>\"Analytic functions rock\"</p>\n\n<p>Edit: With regard to the first comment ...</p>\n\n<p>\"using analytic queries and a self-join defeats the purpose of analytic queries\"</p>\n\n<p>There is no self-join in this code. There is instead a predicate placed on the result of the inline view that contains the analytic function -- a very different matter, and completely standard practice.</p>\n\n<p>\"The default window in Oracle is from the first row in the partition to the current one\"</p>\n\n<p>The windowing clause is only applicable in the presence of the order by clause. With no order by clause, no windowing clause is applied by default and none can be explicitly specified.</p>\n\n<p>The code works.</p>\n" }, { "answer_id": 121475, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": -1, "selected": false, "text": "<p>If (UserID, Date) is unique, i.e. no date appears twice for the same user then:</p>\n\n<pre><code>select TheTable.UserID, TheTable.Value\nfrom TheTable inner join (select UserID, max([Date]) MaxDate\n from TheTable\n group by UserID) UserMaxDate\n on TheTable.UserID = UserMaxDate.UserID\n TheTable.[Date] = UserMaxDate.MaxDate;\n</code></pre>\n" }, { "answer_id": 121492, "author": "stefano m", "author_id": 19261, "author_profile": "https://Stackoverflow.com/users/19261", "pm_score": 2, "selected": false, "text": "<p>i thing you shuold make this variant to previous query:</p>\n\n<pre><code>SELECT UserId, Value FROM Users U1 WHERE \nDate = ( SELECT MAX(Date) FROM Users where UserId = U1.UserId)\n</code></pre>\n" }, { "answer_id": 121506, "author": "marc", "author_id": 12260, "author_profile": "https://Stackoverflow.com/users/12260", "pm_score": 1, "selected": false, "text": "<p>Assuming Date is unique for a given UserID, here's some TSQL:</p>\n\n<pre><code>SELECT \n UserTest.UserID, UserTest.Value\nFROM UserTest\nINNER JOIN\n(\n SELECT UserID, MAX(Date) MaxDate\n FROM UserTest\n GROUP BY UserID\n) Dates\nON UserTest.UserID = Dates.UserID\nAND UserTest.Date = Dates.MaxDate \n</code></pre>\n" }, { "answer_id": 121519, "author": "Aheho", "author_id": 21155, "author_profile": "https://Stackoverflow.com/users/21155", "pm_score": 2, "selected": false, "text": "<pre><code>Select \n UserID, \n Value, \n Date \nFrom \n Table, \n ( \n Select \n UserID, \n Max(Date) as MDate \n From \n Table \n Group by \n UserID \n ) as subQuery \nWhere \n Table.UserID = subQuery.UserID and \n Table.Date = subQuery.mDate \n</code></pre>\n" }, { "answer_id": 121556, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 0, "selected": false, "text": "<pre><code>select userid, value, date\n from thetable t1 ,\n ( select t2.userid, max(t2.date) date2 \n from thetable t2 \n group by t2.userid ) t3\n where t3.userid t1.userid and\n t3.date2 = t1.date\n</code></pre>\n\n<p>IMHO this works. HTH </p>\n" }, { "answer_id": 121589, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 0, "selected": false, "text": "<p>I think this should work?</p>\n\n<pre><code>Select\nT1.UserId,\n(Select Top 1 T2.Value From Table T2 Where T2.UserId = T1.UserId Order By Date Desc) As 'Value'\nFrom\nTable T1\nGroup By\nT1.UserId\nOrder By\nT1.UserId\n</code></pre>\n" }, { "answer_id": 121622, "author": "Valerion", "author_id": 16156, "author_profile": "https://Stackoverflow.com/users/16156", "pm_score": 0, "selected": false, "text": "<p>This should be as simple as:</p>\n\n<pre><code>SELECT UserId, Value\nFROM Users u\nWHERE Date = (SELECT MAX(Date) FROM Users WHERE UserID = u.UserID)\n</code></pre>\n" }, { "answer_id": 121659, "author": "KyleLanser", "author_id": 12923, "author_profile": "https://Stackoverflow.com/users/12923", "pm_score": 0, "selected": false, "text": "<p>First try I misread the question, following the top answer, here is a complete example with correct results:</p>\n\n<pre><code>CREATE TABLE table_name (id int, the_value varchar(2), the_date datetime);\n\nINSERT INTO table_name (id,the_value,the_date) VALUES(1 ,'a','1/1/2000');\nINSERT INTO table_name (id,the_value,the_date) VALUES(1 ,'b','2/2/2002');\nINSERT INTO table_name (id,the_value,the_date) VALUES(2 ,'c','1/1/2000');\nINSERT INTO table_name (id,the_value,the_date) VALUES(2 ,'d','3/3/2003');\nINSERT INTO table_name (id,the_value,the_date) VALUES(2 ,'e','3/3/2003');\n</code></pre>\n\n<p>--</p>\n\n<pre><code> select id, the_value\n from table_name u1\n where the_date = (select max(the_date)\n from table_name u2\n where u1.id = u2.id)\n</code></pre>\n\n<p>--</p>\n\n<pre><code>id the_value\n----------- ---------\n2 d\n2 e\n1 b\n\n(3 row(s) affected)\n</code></pre>\n" }, { "answer_id": 121661, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 7, "selected": false, "text": "<pre><code>SELECT userid, MAX(value) KEEP (DENSE_RANK FIRST ORDER BY date DESC)\n FROM table\n GROUP BY userid\n</code></pre>\n" }, { "answer_id": 121693, "author": "mancaus", "author_id": 13797, "author_profile": "https://Stackoverflow.com/users/13797", "pm_score": 4, "selected": false, "text": "<p>I know you asked for Oracle, but in SQL 2005 we now use this:</p>\n\n<pre><code>\n-- Single Value\n;WITH ByDate\nAS (\nSELECT UserId, Value, ROW_NUMBER() OVER (PARTITION BY UserId ORDER BY Date DESC) RowNum\nFROM UserDates\n)\nSELECT UserId, Value\nFROM ByDate\nWHERE RowNum = 1\n\n-- Multiple values where dates match\n;WITH ByDate\nAS (\nSELECT UserId, Value, RANK() OVER (PARTITION BY UserId ORDER BY Date DESC) Rnk\nFROM UserDates\n)\nSELECT UserId, Value\nFROM ByDate\nWHERE Rnk = 1\n</code></pre>\n" }, { "answer_id": 121873, "author": "user11318", "author_id": 11318, "author_profile": "https://Stackoverflow.com/users/11318", "pm_score": 3, "selected": false, "text": "<p>I don't have Oracle to test it, but the most efficient solution is to use analytic queries. It should look something like this:</p>\n\n<pre><code>SELECT DISTINCT\n UserId\n , MaxValue\nFROM (\n SELECT UserId\n , FIRST (Value) Over (\n PARTITION BY UserId\n ORDER BY Date DESC\n ) MaxValue\n FROM SomeTable\n )\n</code></pre>\n\n<p>I suspect that you can get rid of the outer query and put distinct on the inner, but I'm not sure. In the meantime I know this one works.</p>\n\n<p>If you want to learn about analytic queries, I'd suggest reading <a href=\"http://www.orafaq.com/node/55\" rel=\"nofollow noreferrer\">http://www.orafaq.com/node/55</a> and <strike><a href=\"http://www.akadia.com/services/ora_analytic_functions.html\" rel=\"nofollow noreferrer\">http://www.akadia.com/services/ora_analytic_functions.html</a></strike>. Here is the short summary.</p>\n\n<p>Under the hood analytic queries sort the whole dataset, then process it sequentially. As you process it you partition the dataset according to certain criteria, and then for each row looks at some window (defaults to the first value in the partition to the current row - that default is also the most efficient) and can compute values using a number of analytic functions (the list of which is very similar to the aggregate functions).</p>\n\n<p>In this case here is what the inner query does. The whole dataset is sorted by UserId then Date DESC. Then it processes it in one pass. For each row you return the UserId and the first Date seen for that UserId (since dates are sorted DESC, that's the max date). This gives you your answer with duplicated rows. Then the outer DISTINCT squashes duplicates.</p>\n\n<p>This is not a particularly spectacular example of analytic queries. For a much bigger win consider taking a table of financial receipts and calculating for each user and receipt, a running total of what they paid. Analytic queries solve that efficiently. Other solutions are less efficient. Which is why they are part of the 2003 SQL standard. (Unfortunately Postgres doesn't have them yet. Grrr...)</p>\n" }, { "answer_id": 123481, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 9, "selected": false, "text": "<p>I see many people use subqueries or else window functions to do this, but I often do this kind of query without subqueries in the following way. It uses plain, standard SQL so it should work in any brand of RDBMS.</p>\n<pre><code>SELECT t1.*\nFROM mytable t1\n LEFT OUTER JOIN mytable t2\n ON (t1.UserId = t2.UserId AND t1.&quot;Date&quot; &lt; t2.&quot;Date&quot;)\nWHERE t2.UserId IS NULL;\n</code></pre>\n<p>In other words: fetch the row from <code>t1</code> where no other row exists with the same <code>UserId</code> and a greater Date.</p>\n<p>(I put the identifier &quot;Date&quot; in delimiters because it's an SQL reserved word.)</p>\n<p>In case if <code>t1.&quot;Date&quot; = t2.&quot;Date&quot;</code>, doubling appears. Usually tables has <code>auto_inc(seq)</code> key, e.g. <code>id</code>.\nTo avoid doubling can be used follows:</p>\n<pre><code>SELECT t1.*\nFROM mytable t1\n LEFT OUTER JOIN mytable t2\n ON t1.UserId = t2.UserId AND ((t1.&quot;Date&quot; &lt; t2.&quot;Date&quot;) \n OR (t1.&quot;Date&quot; = t2.&quot;Date&quot; AND t1.id &lt; t2.id))\nWHERE t2.UserId IS NULL;\n</code></pre>\n<hr />\n<p>Re comment from @Farhan:</p>\n<p>Here's a more detailed explanation:</p>\n<p>An outer join attempts to join <code>t1</code> with <code>t2</code>. By default, all results of <code>t1</code> are returned, and <em>if</em> there is a match in <code>t2</code>, it is also returned. If there is no match in <code>t2</code> for a given row of <code>t1</code>, then the query still returns the row of <code>t1</code>, and uses <code>NULL</code> as a placeholder for all of <code>t2</code>'s columns. That's just how outer joins work in general.</p>\n<p>The trick in this query is to design the join's matching condition such that <code>t2</code> must match the <em>same</em> <code>userid</code>, and a <em>greater</em> <code>date</code>. The idea being if a row exists in <code>t2</code> that has a greater <code>date</code>, then the row in <code>t1</code> it's compared against <em>can't</em> be the greatest <code>date</code> for that <code>userid</code>. But if there is no match -- i.e. if no row exists in <code>t2</code> with a greater <code>date</code> than the row in <code>t1</code> -- we know that the row in <code>t1</code> was the row with the greatest <code>date</code> for the given <code>userid</code>.</p>\n<p>In those cases (when there's no match), the columns of <code>t2</code> will be <code>NULL</code> -- even the columns specified in the join condition. So that's why we use <code>WHERE t2.UserId IS NULL</code>, because we're searching for the cases where no row was found with a greater <code>date</code> for the given <code>userid</code>.</p>\n" }, { "answer_id": 123511, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 6, "selected": false, "text": "<p>Not being at work, I don't have Oracle to hand, but I seem to recall that Oracle allows multiple columns to be matched in an IN clause, which should at least avoid the options that use a correlated subquery, which is seldom a good idea.</p>\n\n<p>Something like this, perhaps (can't remember if the column list should be parenthesised or not):</p>\n\n<pre><code>SELECT * \nFROM MyTable\nWHERE (User, Date) IN\n ( SELECT User, MAX(Date) FROM MyTable GROUP BY User)\n</code></pre>\n\n<p>EDIT: Just tried it for real:</p>\n\n<pre><code>SQL&gt; create table MyTable (usr char(1), dt date);\nSQL&gt; insert into mytable values ('A','01-JAN-2009');\nSQL&gt; insert into mytable values ('B','01-JAN-2009');\nSQL&gt; insert into mytable values ('A', '31-DEC-2008');\nSQL&gt; insert into mytable values ('B', '31-DEC-2008');\nSQL&gt; select usr, dt from mytable\n 2 where (usr, dt) in \n 3 ( select usr, max(dt) from mytable group by usr)\n 4 /\n\nU DT\n- ---------\nA 01-JAN-09\nB 01-JAN-09\n</code></pre>\n\n<p>So it works, although some of the new-fangly stuff mentioned elsewhere may be more performant.</p>\n" }, { "answer_id": 2327894, "author": "na43251", "author_id": 210716, "author_profile": "https://Stackoverflow.com/users/210716", "pm_score": 0, "selected": false, "text": "<p>This will also take care of duplicates (return one row for each user_id):</p>\n\n<pre><code>SELECT *\nFROM (\n SELECT u.*, FIRST_VALUE(u.rowid) OVER(PARTITION BY u.user_id ORDER BY u.date DESC) AS last_rowid\n FROM users u\n) u2\nWHERE u2.rowid = u2.last_rowid\n</code></pre>\n" }, { "answer_id": 2731582, "author": "Guus", "author_id": 328126, "author_profile": "https://Stackoverflow.com/users/328126", "pm_score": 1, "selected": false, "text": "<p>The answer here is Oracle only. Here's a bit more sophisticated answer in all SQL:</p>\n\n<p>Who has the best overall homework result (maximum sum of homework points)?</p>\n\n<pre><code>SELECT FIRST, LAST, SUM(POINTS) AS TOTAL\nFROM STUDENTS S, RESULTS R\nWHERE S.SID = R.SID AND R.CAT = 'H'\nGROUP BY S.SID, FIRST, LAST\nHAVING SUM(POINTS) &gt;= ALL (SELECT SUM (POINTS)\nFROM RESULTS\nWHERE CAT = 'H'\nGROUP BY SID)\n</code></pre>\n\n<p>And a more difficult example, which need some explanation, for which I don't have time atm:</p>\n\n<p>Give the book (ISBN and title) that is most popular in 2008, i.e., which is borrowed most often in 2008.</p>\n\n<pre><code>SELECT X.ISBN, X.title, X.loans\nFROM (SELECT Book.ISBN, Book.title, count(Loan.dateTimeOut) AS loans\nFROM CatalogEntry Book\nLEFT JOIN BookOnShelf Copy\nON Book.bookId = Copy.bookId\nLEFT JOIN (SELECT * FROM Loan WHERE YEAR(Loan.dateTimeOut) = 2008) Loan \nON Copy.copyId = Loan.copyId\nGROUP BY Book.title) X\nHAVING loans &gt;= ALL (SELECT count(Loan.dateTimeOut) AS loans\nFROM CatalogEntry Book\nLEFT JOIN BookOnShelf Copy\nON Book.bookId = Copy.bookId\nLEFT JOIN (SELECT * FROM Loan WHERE YEAR(Loan.dateTimeOut) = 2008) Loan \nON Copy.copyId = Loan.copyId\nGROUP BY Book.title);\n</code></pre>\n\n<p>Hope this helps (anyone).. :)</p>\n\n<p>Regards,\nGuus</p>\n" }, { "answer_id": 2753881, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 0, "selected": false, "text": "<p>Just tested this and it seems to work on a logging table</p>\n\n<pre><code>select ColumnNames, max(DateColumn) from log group by ColumnNames order by 1 desc\n</code></pre>\n" }, { "answer_id": 3141266, "author": "Truper", "author_id": 379052, "author_profile": "https://Stackoverflow.com/users/379052", "pm_score": 2, "selected": false, "text": "<p>Just had to write a \"live\" example at work :)</p>\n\n<p>This one supports multiple values for UserId on the <strong>same</strong> date.</p>\n\n<p>Columns:\nUserId, Value, Date</p>\n\n<pre><code>SELECT\n DISTINCT UserId,\n MAX(Date) OVER (PARTITION BY UserId ORDER BY Date DESC),\n MAX(Values) OVER (PARTITION BY UserId ORDER BY Date DESC)\nFROM\n(\n SELECT UserId, Date, SUM(Value) As Values\n FROM &lt;&lt;table_name&gt;&gt;\n GROUP BY UserId, Date\n)\n</code></pre>\n\n<p>You can use FIRST_VALUE instead of MAX and look it up in the explain plan. I didn't have the time to play with it.</p>\n\n<p>Of course, if searching through huge tables, it's probably better if you use FULL hints in your query.</p>\n" }, { "answer_id": 7824518, "author": "wcw", "author_id": 1003601, "author_profile": "https://Stackoverflow.com/users/1003601", "pm_score": 3, "selected": false, "text": "<p>Wouldn't a QUALIFY clause be both simplest and best?</p>\n\n<pre><code>select userid, my_date, ...\nfrom users\nqualify rank() over (partition by userid order by my_date desc) = 1\n</code></pre>\n\n<p>For context, on Teradata here a decent size test of this runs in 17s with this QUALIFY version and in 23s with the 'inline view'/Aldridge solution #1.</p>\n" }, { "answer_id": 7967101, "author": "Cito", "author_id": 1008762, "author_profile": "https://Stackoverflow.com/users/1008762", "pm_score": 3, "selected": false, "text": "<p>With PostgreSQL 8.4 or later, you can use this:</p>\n\n<pre><code>select user_id, user_value_1, user_value_2\n from (select user_id, user_value_1, user_value_2, row_number()\n over (partition by user_id order by user_date desc) \n from users) as r\n where r.row_number=1\n</code></pre>\n" }, { "answer_id": 8243260, "author": "nouky", "author_id": 623703, "author_profile": "https://Stackoverflow.com/users/623703", "pm_score": 2, "selected": false, "text": "<pre><code>select VALUE from TABLE1 where TIME = \n (select max(TIME) from TABLE1 where DATE= \n (select max(DATE) from TABLE1 where CRITERIA=CRITERIA))\n</code></pre>\n" }, { "answer_id": 16127407, "author": "王奕然", "author_id": 2245634, "author_profile": "https://Stackoverflow.com/users/2245634", "pm_score": -1, "selected": false, "text": "<pre><code>select UserId,max(Date) over (partition by UserId) value from users;\n</code></pre>\n" }, { "answer_id": 18539442, "author": "Ben Lin", "author_id": 1960137, "author_profile": "https://Stackoverflow.com/users/1960137", "pm_score": 1, "selected": false, "text": "<p>Solution for MySQL which doesn't have concepts of partition KEEP, DENSE_RANK. </p>\n\n<pre><code>select userid,\n my_date,\n ...\nfrom\n(\nselect @sno:= case when @pid&lt;&gt;userid then 0\n else @sno+1\n end as serialnumber, \n @pid:=userid,\n my_Date,\n ...\nfrom users order by userid, my_date\n) a\nwhere a.serialnumber=0\n</code></pre>\n\n<p>Reference: <a href=\"http://benincampus.blogspot.com/2013/08/select-rows-which-have-maxmin-value-in.html\" rel=\"nofollow\">http://benincampus.blogspot.com/2013/08/select-rows-which-have-maxmin-value-in.html</a> </p>\n" }, { "answer_id": 24860655, "author": "aLevelOfIndirection", "author_id": 913665, "author_profile": "https://Stackoverflow.com/users/913665", "pm_score": 2, "selected": false, "text": "<p>I'm quite late to the party but the following hack will outperform both correlated subqueries and any analytics function but has one restriction: values must convert to strings. So it works for dates, numbers and other strings. The code does not look good but the execution profile is great. </p>\n\n<pre><code>select\n userid,\n to_number(substr(max(to_char(date,'yyyymmdd') || to_char(value)), 9)) as value,\n max(date) as date\nfrom \n users\ngroup by\n userid\n</code></pre>\n\n<p>The reason why this code works so well is that it only needs to scan the table once. It does not require any indexes and most importantly it does not need to sort the table, which most analytics functions do. Indexes will help though if you need to filter the result for a single userid.</p>\n" }, { "answer_id": 26872328, "author": "Bruno Calza", "author_id": 822023, "author_profile": "https://Stackoverflow.com/users/822023", "pm_score": 2, "selected": false, "text": "<p>If you're using Postgres, you can use <code>array_agg</code> like</p>\n\n<pre><code>SELECT userid,MAX(adate),(array_agg(value ORDER BY adate DESC))[1] as value\nFROM YOURTABLE\nGROUP BY userid\n</code></pre>\n\n<p>I'm not familiar with Oracle. This is what I came up with</p>\n\n<pre><code>SELECT \n userid,\n MAX(adate),\n SUBSTR(\n (LISTAGG(value, ',') WITHIN GROUP (ORDER BY adate DESC)),\n 0,\n INSTR((LISTAGG(value, ',') WITHIN GROUP (ORDER BY adate DESC)), ',')-1\n ) as value \nFROM YOURTABLE\nGROUP BY userid \n</code></pre>\n\n<p>Both queries return the same results as the accepted answer. See SQLFiddles:</p>\n\n<ol>\n<li><a href=\"http://sqlfiddle.com/#!4/2749b5/42\" rel=\"nofollow\">Accepted answer</a></li>\n<li><a href=\"http://sqlfiddle.com/#!12/24a7a/18\" rel=\"nofollow\">My solution with Postgres</a></li>\n<li><a href=\"http://sqlfiddle.com/#!4/2749b5/41\" rel=\"nofollow\">My solution with Oracle</a></li>\n</ol>\n" }, { "answer_id": 30888495, "author": "Smart003", "author_id": 3835573, "author_profile": "https://Stackoverflow.com/users/3835573", "pm_score": -1, "selected": false, "text": "<p>check <a href=\"https://stackoverflow.com/questions/30393321/how-to-select-a-unique-record-in-a-table-which-has-no-key-constraints#comment49816289_30393321\">this link</a> if your questions seems similar to that page then i would suggest you the following query which will give the solution for that link</p>\n\n<p><code>select distinct sno,item_name,max(start_date) over(partition by sno),max(end_date) over(partition by sno),max(creation_date) over(partition by sno),\nmax(last_modified_date) over(partition by sno) \nfrom uniq_select_records\norder by sno,item_name asc;</code></p>\n\n<p>will given accurate results related to that link</p>\n" }, { "answer_id": 43028479, "author": "Gurwinder Singh", "author_id": 6348498, "author_profile": "https://Stackoverflow.com/users/6348498", "pm_score": 3, "selected": false, "text": "<p>In <strong><code>Oracle 12c+</code></strong>, you can use <em>Top n</em> queries along with analytic function <code>rank</code> to achieve this very concisely <em>without</em> subqueries:</p>\n\n<pre><code>select *\nfrom your_table\norder by rank() over (partition by user_id order by my_date desc)\nfetch first 1 row with ties;\n</code></pre>\n\n<p>The above returns all the rows with max my_date per user. </p>\n\n<p>If you want only one row with max date, then replace the <code>rank</code> with <code>row_number</code>:</p>\n\n<pre><code>select *\nfrom your_table\norder by row_number() over (partition by user_id order by my_date desc)\nfetch first 1 row with ties; \n</code></pre>\n" }, { "answer_id": 43913890, "author": "Natty ", "author_id": 7116494, "author_profile": "https://Stackoverflow.com/users/7116494", "pm_score": -1, "selected": false, "text": "<p>Use the code:</p>\n\n<pre><code>select T.UserId,T.dt from (select UserId,max(dt) \nover (partition by UserId) as dt from t_users)T where T.dt=dt;\n</code></pre>\n\n<p>This will retrieve the results, irrespective of duplicate values for UserId. \nIf your UserId is unique, well it becomes more simple:</p>\n\n<pre><code>select UserId,max(dt) from t_users group by UserId;\n</code></pre>\n" }, { "answer_id": 46113606, "author": "praveen", "author_id": 7856544, "author_profile": "https://Stackoverflow.com/users/7856544", "pm_score": -1, "selected": false, "text": "<pre><code>SELECT a.* \nFROM user a INNER JOIN (SELECT userid,Max(date) AS date12 FROM user1 GROUP BY userid) b \nON a.date=b.date12 AND a.userid=b.userid ORDER BY a.userid;\n</code></pre>\n" }, { "answer_id": 47036253, "author": "markusk", "author_id": 108326, "author_profile": "https://Stackoverflow.com/users/108326", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"https://docs.oracle.com/database/121/SQLRF/functions170.htm\" rel=\"nofollow noreferrer\"><code>ROW_NUMBER()</code></a> to assign a unique ranking on descending <code>Date</code> for each <code>UserId</code>, then filter to the first row for each <code>UserId</code> (i.e., <code>ROW_NUMBER</code> = 1).</p>\n\n<pre><code>SELECT UserId, Value, Date\nFROM (SELECT UserId, Value, Date,\n ROW_NUMBER() OVER (PARTITION BY UserId ORDER BY Date DESC) rn\n FROM users) u\nWHERE rn = 1;\n</code></pre>\n" }, { "answer_id": 52829751, "author": "praveen", "author_id": 7856544, "author_profile": "https://Stackoverflow.com/users/7856544", "pm_score": -1, "selected": false, "text": "<pre><code>SELECT a.userid,a.values1,b.mm \nFROM table_name a,(SELECT userid,Max(date1)AS mm FROM table_name GROUP BY userid) b\nWHERE a.userid=b.userid AND a.DATE1=b.mm;\n</code></pre>\n" }, { "answer_id": 61795657, "author": "kiruba", "author_id": 11781901, "author_profile": "https://Stackoverflow.com/users/11781901", "pm_score": -1, "selected": false, "text": "<p>Below query can work :</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT user_id, value, date , row_number() OVER (PARTITION BY user_id ORDER BY date desc) AS rn\nFROM table_name\nWHERE rn= 1\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21154/" ]
Table: ``` UserId, Value, Date. ``` I want to get the UserId, Value for the max(Date) for each UserId. That is, the Value for each UserId that has the latest date. Is there a way to do this simply in SQL? (Preferably Oracle) **Update:** Apologies for any ambiguity: I need to get ALL the UserIds. But for each UserId, only that row where that user has the latest date.
This will retrieve all rows for which the my\_date column value is equal to the maximum value of my\_date for that userid. This may retrieve multiple rows for the userid where the maximum date is on multiple rows. ``` select userid, my_date, ... from ( select userid, my_date, ... max(my_date) over (partition by userid) max_my_date from users ) where my_date = max_my_date ``` "Analytic functions rock" Edit: With regard to the first comment ... "using analytic queries and a self-join defeats the purpose of analytic queries" There is no self-join in this code. There is instead a predicate placed on the result of the inline view that contains the analytic function -- a very different matter, and completely standard practice. "The default window in Oracle is from the first row in the partition to the current one" The windowing clause is only applicable in the presence of the order by clause. With no order by clause, no windowing clause is applied by default and none can be explicitly specified. The code works.
121,392
<p>I have a bunch (hundreds) of files that are supposed to have Unix line endings. I strongly suspect that some of them have Windows line endings, and I want to programmatically figure out which ones do.</p> <p>I know I can just run <pre>flip -u</pre> or something similar in a script to convert everything, but I want to be able to identify those files that need changing first.</p>
[ { "answer_id": 121415, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 0, "selected": false, "text": "<p>Windows use char 13 &amp; 10 for line ending, unix only one of them ( i don't rememeber which one ). So you can replace char 13 &amp; 10 for char 13 or 10 ( the one, which use unix ).</p>\n" }, { "answer_id": 121447, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 6, "selected": false, "text": "<p>You can use the <a href=\"http://en.wikipedia.org/wiki/File_(Unix)\" rel=\"noreferrer\"><code>file</code></a> tool, which will tell you the type of line ending. Or, you could just use <code>dos2unix -U</code> which will convert everything to Unix line endings, regardless of what it started with.</p>\n" }, { "answer_id": 121459, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 2, "selected": false, "text": "<p>Unix uses one byte, 0x0A (LineFeed), while windows uses two bytes, 0x0D 0x0A (Carriage Return, Line feed).</p>\n\n<p>If you never see a 0x0D, then it's very likely Unix. If you see 0x0D 0x0A pairs then it's very likely MSDOS.</p>\n" }, { "answer_id": 121464, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 6, "selected": true, "text": "<p>You could use grep</p>\n\n<pre><code>egrep -l $'\\r'\\$ *\n</code></pre>\n" }, { "answer_id": 2065154, "author": "joachim", "author_id": 187581, "author_profile": "https://Stackoverflow.com/users/187581", "pm_score": 4, "selected": false, "text": "<p>Something along the lines of:</p>\n\n<pre><code>perl -p -e 's[\\r\\n][WIN\\n]; s[(?&lt;!WIN)\\n][UNIX\\n]; s[\\r][MAC\\n];' FILENAME\n</code></pre>\n\n<p>though some of that regexp may need refining and tidying up.</p>\n\n<p>That'll output your file with WIN, MAC, or UNIX at the end of each line. Good if your file is somehow a dreadful mess (or a diff) and has mixed endings.</p>\n" }, { "answer_id": 30138038, "author": "1ac0", "author_id": 1196670, "author_profile": "https://Stackoverflow.com/users/1196670", "pm_score": 0, "selected": false, "text": "<p>When you know which files has Windows line endings (<code>0x0D 0x0A</code> or <code>\\r \\n</code>), what you will do with that files? I supose, you will convert them into Unix line ends (<code>0x0A</code> or <code>\\n</code>). You can convert file with Windows line endings into Unix line endings with <code>sed</code> utility, just use command:</p>\n\n<pre><code>$&gt; sed -i 's/\\r//' my_file_with_win_line_endings.txt\n</code></pre>\n\n<p>You can put it into script like this:</p>\n\n<pre><code>#!/bin/bash\n\nfunction travers()\n{\n for file in $(ls); do\n if [ -f \"${file}\" ]; then\n sed -i 's/\\r//' \"${file}\"\n elif [ -d \"${file}\" ]; then\n cd \"${file}\"\n travers\n cd ..\n fi\n done\n}\n\ntravers\n</code></pre>\n\n<p>If you run it from your root dir with files, at end you will be sure all files are with Unix line endings.</p>\n" }, { "answer_id": 37846265, "author": "Bryce Guinta", "author_id": 487464, "author_profile": "https://Stackoverflow.com/users/487464", "pm_score": 3, "selected": false, "text": "<p>Here's the most failsafe answer. Stimms answer doesn account for subdirectories and binary files</p>\n\n<pre><code>find . -type f -exec file {} \\; | grep \"CRLF\" | awk -F ':' '{ print $1 }'\n</code></pre>\n\n<ul>\n<li>Use <code>file</code> to find file type. Those with CRLF have windows return characters. The output of <code>file</code> is delimited by a <code>:</code>, and the first field is the path of the file.</li>\n</ul>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18177/" ]
I have a bunch (hundreds) of files that are supposed to have Unix line endings. I strongly suspect that some of them have Windows line endings, and I want to programmatically figure out which ones do. I know I can just run ``` flip -u ``` or something similar in a script to convert everything, but I want to be able to identify those files that need changing first.
You could use grep ``` egrep -l $'\r'\$ * ```
121,396
<p>When you call the <code>object.__repr__()</code> method in Python you get something like this back: </p> <blockquote> <pre><code>&lt;__main__.Test object at 0x2aba1c0cf890&gt; </code></pre> </blockquote> <p>Is there any way to get a hold of the memory address if you overload <code>__repr__()</code>, other then calling <code>super(Class, obj).__repr__()</code> and regexing it out? </p>
[ { "answer_id": 121422, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 6, "selected": false, "text": "<p>Just use </p>\n\n<pre><code>id(object)\n</code></pre>\n" }, { "answer_id": 121426, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 2, "selected": false, "text": "<p>You can get something suitable for that purpose with:</p>\n\n<pre><code>id(self)\n</code></pre>\n" }, { "answer_id": 121452, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 9, "selected": true, "text": "<p>The <a href=\"https://docs.python.org/2/library/functions.html#id\" rel=\"noreferrer\">Python manual</a> has this to say about <code>id()</code>:</p>\n\n<blockquote>\n <p>Return the \"identity'' of an object.\n This is an integer (or long integer)\n which is guaranteed to be unique and\n constant for this object during its\n lifetime. Two objects with\n non-overlapping lifetimes may have the\n same id() value. (Implementation note:\n this is the address of the object.)</p>\n</blockquote>\n\n<p>So in CPython, this will be the address of the object. No such guarantee for any other Python interpreter, though.</p>\n\n<p>Note that if you're writing a C extension, you have full access to the internals of the Python interpreter, including access to the addresses of objects directly.</p>\n" }, { "answer_id": 121508, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 6, "selected": false, "text": "<p>You could reimplement the default repr this way:</p>\n\n<pre><code>def __repr__(self):\n return '&lt;%s.%s object at %s&gt;' % (\n self.__class__.__module__,\n self.__class__.__name__,\n hex(id(self))\n )\n</code></pre>\n" }, { "answer_id": 121572, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 2, "selected": false, "text": "<p>With <a href=\"http://docs.python.org/lib/module-ctypes.html\" rel=\"nofollow noreferrer\">ctypes</a>, you can achieve the same thing with</p>\n\n<pre><code>&gt;&gt;&gt; import ctypes\n&gt;&gt;&gt; a = (1,2,3)\n&gt;&gt;&gt; ctypes.addressof(a)\n3077760748L\n</code></pre>\n\n<p>Documentation:</p>\n\n<blockquote>\n <p><code>addressof(C instance) -&gt; integer</code><br>\n Return the address of the C instance internal buffer</p>\n</blockquote>\n\n<p>Note that in CPython, currently <code>id(a) == ctypes.addressof(a)</code>, but <code>ctypes.addressof</code> should return the real address for each Python implementation, if</p>\n\n<ul>\n<li>ctypes is supported</li>\n<li>memory pointers are a valid notion.</li>\n</ul>\n\n<p><strong>Edit</strong>: added information about interpreter-independence of ctypes</p>\n" }, { "answer_id": 122032, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 0, "selected": false, "text": "<p>While it's true that <code>id(object)</code> gets the object's address in the default CPython implementation, this is generally useless... you can't <i>do</i> anything with the address from pure Python code.</p>\n\n<p>The only time you would actually be able to use the address is from a C extension library... in which case it is trivial to get the object's address since Python objects are always passed around as C pointers.</p>\n" }, { "answer_id": 4628230, "author": "Peter Le Bek", "author_id": 509631, "author_profile": "https://Stackoverflow.com/users/509631", "pm_score": 4, "selected": false, "text": "<p>Just in response to Torsten, I wasn't able to call <code>addressof()</code> on a regular python object. Furthermore, <code>id(a) != addressof(a)</code>. This is in CPython, don't know about anything else.</p>\n\n<pre><code>&gt;&gt;&gt; from ctypes import c_int, addressof\n&gt;&gt;&gt; a = 69\n&gt;&gt;&gt; addressof(a)\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\nTypeError: invalid type\n&gt;&gt;&gt; b = c_int(69)\n&gt;&gt;&gt; addressof(b)\n4300673472\n&gt;&gt;&gt; id(b)\n4300673392\n</code></pre>\n" }, { "answer_id": 26285749, "author": "abarnert", "author_id": 908494, "author_profile": "https://Stackoverflow.com/users/908494", "pm_score": 5, "selected": false, "text": "<p>There are a few issues here that aren't covered by any of the other answers.</p>\n\n<p>First, <a href=\"https://docs.python.org/3/library/functions.html#id\" rel=\"noreferrer\"><code>id</code></a> only returns:</p>\n\n<blockquote>\n <p>the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same <code>id()</code> value.</p>\n</blockquote>\n\n<hr>\n\n<p>In CPython, this happens to be the pointer to the <a href=\"https://docs.python.org/3/c-api/object.html\" rel=\"noreferrer\"><code>PyObject</code></a> that represents the object in the interpreter, which is the same thing that <code>object.__repr__</code> displays. But this is just an implementation detail of CPython, not something that's true of Python in general. Jython doesn't deal in pointers, it deals in Java references (which the JVM of course probably represents as pointers, but you can't see those—and wouldn't want to, because the GC is allowed to move them around). PyPy lets different types have different kinds of <code>id</code>, but the most general is just an index into a table of objects you've called <code>id</code> on, which is obviously not going to be a pointer. I'm not sure about IronPython, but I'd suspect it's more like Jython than like CPython in this regard. So, in most Python implementations, there's no way to get whatever showed up in that <code>repr</code>, and no use if you did.</p>\n\n<hr>\n\n<p>But what if you only care about CPython? That's a pretty common case, after all.</p>\n\n<p>Well, first, you may notice that <code>id</code> is an integer;* if you want that <code>0x2aba1c0cf890</code> string instead of the number <code>46978822895760</code>, you're going to have to format it yourself. Under the covers, I believe <code>object.__repr__</code> is ultimately using <code>printf</code>'s <code>%p</code> format, which you don't have from Python… but you can always do this:</p>\n\n<pre><code>format(id(spam), '#010x' if sys.maxsize.bit_length() &lt;= 32 else '#18x')\n</code></pre>\n\n<p><sub>* In 3.x, it's an <code>int</code>. In 2.x, it's an <code>int</code> if that's big enough to hold a pointer—which is may not be because of signed number issues on some platforms—and a <code>long</code> otherwise.</sub></p>\n\n<p>Is there anything you can do with these pointers besides print them out? Sure (again, assuming you only care about CPython).</p>\n\n<p>All of the <a href=\"https://docs.python.org/3/c-api/index.html\" rel=\"noreferrer\">C API</a> functions take a pointer to a <code>PyObject</code> or a related type. For those related types, you can just call <code>PyFoo_Check</code> to make sure it really is a <code>Foo</code> object, then cast with <code>(PyFoo *)p</code>. So, if you're writing a C extension, the <code>id</code> is exactly what you need.</p>\n\n<p>What if you're writing pure Python code? You can call the exact same functions with <a href=\"https://docs.python.org/3/library/ctypes.html#accessing-values-exported-from-dlls\" rel=\"noreferrer\"><code>pythonapi</code></a> from <code>ctypes</code>.</p>\n\n<hr>\n\n<p>Finally, a few of the other answers have brought up <a href=\"https://docs.python.org/3/library/ctypes.html#ctypes.addressof\" rel=\"noreferrer\"><code>ctypes.addressof</code></a>. That isn't relevant here. This only works for <code>ctypes</code> objects like <code>c_int32</code> (and maybe a few memory-buffer-like objects, like those provided by <code>numpy</code>). And, even there, it isn't giving you the address of the <code>c_int32</code> value, it's giving you the address of the C-level <code>int32</code> that the <code>c_int32</code> wraps up.</p>\n\n<p>That being said, more often than not, if you really think you need the address of something, you didn't want a native Python object in the first place, you wanted a <code>ctypes</code> object.</p>\n" }, { "answer_id": 58107525, "author": "commanderbasher", "author_id": 12087395, "author_profile": "https://Stackoverflow.com/users/12087395", "pm_score": 2, "selected": false, "text": "<p>I know this is an old question but if you're still programming, in python 3 these days... I have actually found that if it is a string, then there is a really easy way to do this:</p>\n\n<pre><code>&gt;&gt;&gt; spam.upper\n&lt;built-in method upper of str object at 0x1042e4830&gt;\n&gt;&gt;&gt; spam.upper()\n'YO I NEED HELP!'\n&gt;&gt;&gt; id(spam)\n4365109296\n</code></pre>\n\n<p>string conversion does not affect location in memory either:</p>\n\n<pre><code>&gt;&gt;&gt; spam = {437 : 'passphrase'}\n&gt;&gt;&gt; object.__repr__(spam)\n'&lt;dict object at 0x1043313f0&gt;'\n&gt;&gt;&gt; str(spam)\n\"{437: 'passphrase'}\"\n&gt;&gt;&gt; object.__repr__(spam)\n'&lt;dict object at 0x1043313f0&gt;'\n</code></pre>\n" }, { "answer_id": 68684928, "author": "Marco El-Korashy", "author_id": 15592529, "author_profile": "https://Stackoverflow.com/users/15592529", "pm_score": 1, "selected": false, "text": "<p>You can get the memory address/location of any object by using the '<strong>partition</strong>' method of the <strong>built-in</strong> '<strong><code>str</code></strong>' type.</p>\n<p>Here is an example of using it to get the memory address of an object:</p>\n<pre><code>Python 3.8.3 (default, May 27 2020, 02:08:17)\n[GCC 9.3.0] on linux\nType &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.\n&gt;&gt;&gt; object.__repr__(1)\n'&lt;int object at 0x7ca70923f0&gt;'\n&gt;&gt;&gt; hex(int(object.__repr__(1).partition('object at ')[2].strip('&gt;'), 16))\n0x7ca70923f0\n&gt;&gt;&gt;\n</code></pre>\n<p><em>Here</em>, I am using the built-in '<code>object</code>' class' '<code>__repr__</code>' method with an object/item such as <code>1</code> as an argument to return the string and then I am partitioning that string which will return a tuple of the string before the string that I provided, the string that I provided and then the string after the string that I provided, and as the memory location is positioned after '<code>object at</code>', I can get the memory address as it has partitioned it from that part.</p>\n<p>And then as the memory address was returned as the third item in the returned tuple, I can access it with index <code>2</code> from the tuple. But then, it has a right angled bracket as a suffix in the string that I obtained, so I use the '<code>strip</code>' function to remove it, which will return it without the angled bracket. I then transformed the resulted string into an integer with base 16 and then turn it into a hex number.</p>\n" }, { "answer_id": 69441298, "author": "Cloud Cho", "author_id": 5595995, "author_profile": "https://Stackoverflow.com/users/5595995", "pm_score": 0, "selected": false, "text": "<p>If the <code>__repr__</code> is overloaded, you may consider <code>__str__</code> to see the memory address of the variable.</p>\n<p>Here is the details of <a href=\"https://stackoverflow.com/questions/1436703/what-is-the-difference-between-str-and-repr\"><code>__repr__</code> versus <code>__str__</code></a> by <a href=\"https://stackoverflow.com/users/122683/moshez\">Moshe Zadka</a> in StackOverflow.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/452521/" ]
When you call the `object.__repr__()` method in Python you get something like this back: > > > ``` > <__main__.Test object at 0x2aba1c0cf890> > > ``` > > Is there any way to get a hold of the memory address if you overload `__repr__()`, other then calling `super(Class, obj).__repr__()` and regexing it out?
The [Python manual](https://docs.python.org/2/library/functions.html#id) has this to say about `id()`: > > Return the "identity'' of an object. > This is an integer (or long integer) > which is guaranteed to be unique and > constant for this object during its > lifetime. Two objects with > non-overlapping lifetimes may have the > same id() value. (Implementation note: > this is the address of the object.) > > > So in CPython, this will be the address of the object. No such guarantee for any other Python interpreter, though. Note that if you're writing a C extension, you have full access to the internals of the Python interpreter, including access to the addresses of objects directly.
121,439
<p>I'm running <code>Django 1.0</code> and I'm close to deploying my app. As such, I'll be changing the DEBUG setting to False.</p> <p>With that being said, I'd still like to include the stacktrace on my 500.html page when errors occur. By doing so, users can copy-and-paste the errors and easily email them to the developers.</p> <p>Any thoughts on how best to approach this issue?</p>
[ { "answer_id": 121474, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 5, "selected": true, "text": "<p>Automatically log your 500s, that way:</p>\n\n<ul>\n<li>You know when they occur.</li>\n<li>You don't need to rely on users sending you stacktraces.</li>\n</ul>\n\n<p>Joel recommends even going so far as automatically creating tickets in your bug tracker when your application experiences a failure. Personally, I create a (private) RSS feed with the stacktraces, urls, etc. that the developers can subscribe to.</p>\n\n<p>Showing stack traces to your users on the other hand could possibly leak information that malicious users could use to attack your site. Overly detailed error messages are one of the classic stepping stones to SQL injection attacks.</p>\n\n<p><em>Edit</em> (added code sample to capture traceback):</p>\n\n<p>You can get the exception information from the sys.exc_info call. While formatting the traceback for display comes from the traceback module:</p>\n\n<pre><code>import traceback\nimport sys\n\ntry:\n raise Exception(\"Message\")\nexcept:\n type, value, tb = sys.exc_info()\n print &gt;&gt; sys.stderr, type.__name__, \":\", value\n print &gt;&gt; sys.stderr, '\\n'.join(traceback.format_tb(tb))\n</code></pre>\n\n<p>Prints:</p>\n\n<pre><code>Exception : Message\n File \"exception.py\", line 5, in &lt;module&gt;\n raise Exception(\"Message\")\n</code></pre>\n" }, { "answer_id": 121487, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 1, "selected": false, "text": "<p>You could call <code>sys.exc_info()</code> in a custom exception handler. But I don't recommend that. Django can send you emails for exceptions.</p>\n" }, { "answer_id": 122482, "author": "Carl Meyer", "author_id": 3207, "author_profile": "https://Stackoverflow.com/users/3207", "pm_score": 4, "selected": false, "text": "<p>As @zacherates says, you really don't want to display a stacktrace to your users. The easiest approach to this problem is what Django does by default if you have yourself and your developers listed in the ADMINS setting with email addresses; it sends an email to everyone in that list with the full stack trace (and more) everytime there is a 500 error with DEBUG = False.</p>\n" }, { "answer_id": 17483769, "author": "Avinash Garg", "author_id": 1900027, "author_profile": "https://Stackoverflow.com/users/1900027", "pm_score": 2, "selected": false, "text": "<p>If we want to show exceptions which are generated , on ur template(500.html) then we could write your own 500 view, grabbing the exception and passing it to your 500 template.</p>\n\n<h2>Steps:</h2>\n\n<h2># In views.py:</h2>\n\n<pre><code>import sys,traceback\n\ndef custom_500(request):\n t = loader.get_template('500.html')\n\n print sys.exc_info()\n type, value, tb = sys.exc_info()\n return HttpResponseServerError(t.render(Context({\n 'exception_value': value,\n 'value':type,\n 'tb':traceback.format_exception(type, value, tb)\n },RequestContext(request))))\n</code></pre>\n\n<h2># In Main urls.py:</h2>\n\n<pre><code>from django.conf.urls.defaults import *\nhandler500 = 'project.web.services.views.custom_500'\n</code></pre>\n\n<h2># In Template(500.html):</h2>\n\n<pre><code>{{ exception_value }}{{value}}{{tb}}\n</code></pre>\n\n<p>more about it here: <a href=\"https://docs.djangoproject.com/en/dev/topics/http/views/#the-500-server-error-view\" rel=\"nofollow noreferrer\">https://docs.djangoproject.com/en/dev/topics/http/views/#the-500-server-error-view</a></p>\n" }, { "answer_id": 35889521, "author": "Joel Cross", "author_id": 1039538, "author_profile": "https://Stackoverflow.com/users/1039538", "pm_score": 0, "selected": false, "text": "<p>I know this is an old question, but these days I would recommend using a service such as <a href=\"https://getsentry.com/welcome/\" rel=\"nofollow\">Sentry</a> to capture your errors.</p>\n\n<p>On Django, the steps to set this up are incredibly simple. From <a href=\"https://docs.getsentry.com/hosted/clients/python/integrations/django/\" rel=\"nofollow\">the docs</a>:</p>\n\n<ul>\n<li>Install Raven using <code>pip install raven</code></li>\n<li>Add <code>'raven.contrib.django.raven_compat'</code> to your <code>settings.INSTALLED_APPS</code>.</li>\n<li>Add <code>RAVEN_CONFIG = {\"dsn\": YOUR_SENTRY_DSN}</code> to your settings.</li>\n</ul>\n\n<p>Then, on your 500 page (defined in <code>handler500</code>), pass the <code>request.sentry.id</code> to the template and your users can reference the specific error without any of your internals being exposed.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10040/" ]
I'm running `Django 1.0` and I'm close to deploying my app. As such, I'll be changing the DEBUG setting to False. With that being said, I'd still like to include the stacktrace on my 500.html page when errors occur. By doing so, users can copy-and-paste the errors and easily email them to the developers. Any thoughts on how best to approach this issue?
Automatically log your 500s, that way: * You know when they occur. * You don't need to rely on users sending you stacktraces. Joel recommends even going so far as automatically creating tickets in your bug tracker when your application experiences a failure. Personally, I create a (private) RSS feed with the stacktraces, urls, etc. that the developers can subscribe to. Showing stack traces to your users on the other hand could possibly leak information that malicious users could use to attack your site. Overly detailed error messages are one of the classic stepping stones to SQL injection attacks. *Edit* (added code sample to capture traceback): You can get the exception information from the sys.exc\_info call. While formatting the traceback for display comes from the traceback module: ``` import traceback import sys try: raise Exception("Message") except: type, value, tb = sys.exc_info() print >> sys.stderr, type.__name__, ":", value print >> sys.stderr, '\n'.join(traceback.format_tb(tb)) ``` Prints: ``` Exception : Message File "exception.py", line 5, in <module> raise Exception("Message") ```
121,453
<p>There is a way to know the flash player version installed on the computer that runs our SWF file with Action Script 3.0?</p>
[ { "answer_id": 121486, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 2, "selected": false, "text": "<p>It's in <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/system/Capabilities.html#version\" rel=\"nofollow noreferrer\">flash.system.Capabilities.version</a></p>\n" }, { "answer_id": 125823, "author": "Brian Hodge", "author_id": 20628, "author_profile": "https://Stackoverflow.com/users/20628", "pm_score": 4, "selected": true, "text": "<p>If you are programming from within the IDE the following will get you the version</p>\n\n<pre>\ntrace(Capabilities.version);\n</pre>\n\n<p>If you are building a custom class the following should help.\nMake sure that this following code goes into a file named VersionCheck.as</p>\n\n<blockquote>\n<pre>\npackage\n{\n import flash.system.Capabilities;\n\n public class VersionCheck\n {\n public function VersionCheck():void\n {\n trace(Capabilities.version);\n }\n }\n}\n</pre>\n</blockquote>\n\n<p>Hope this helps, always remember that all of the AS3 language can be studied online here <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/</a>.</p>\n" }, { "answer_id": 149292, "author": "Martin", "author_id": 15840, "author_profile": "https://Stackoverflow.com/users/15840", "pm_score": 2, "selected": false, "text": "<p>This example might help figuring out the details you receive so that you can act on specifics within the somewhat awkward data you get.</p>\n\n<pre><code>import flash.system.Capabilities;\n\n\nvar versionNumber:String = Capabilities.version;\ntrace(\"versionNumber: \"+versionNumber);\ntrace(\"-----\");\n\n// The version number is a list of items divided by \",\"\nvar versionArray:Array = versionNumber.split(\",\");\nvar length:Number = versionArray.length;\nfor(var i:Number = 0; i &lt; length; i++) trace(\"versionArray[\"+i+\"]: \"+versionArray[i]);\ntrace(\"-----\");\n\n// The main version contains the OS type too so we split it in two\n// and we'll have the OS type and the major version number separately.\nvar platformAndVersion:Array = versionArray[0].split(\" \");\nfor(var j:Number = 0; j &lt; 2; j++) trace(\"platformAndVersion[\"+j+\"]: \"+platformAndVersion[j]);\ntrace(\"-----\");\n\nvar majorVersion:Number = parseInt(platformAndVersion[1]);\nvar minorVersion:Number = parseInt(versionArray[1]);\nvar buildNumber:Number = parseInt(versionArray[2]);\n\ntrace(\"Platform: \"+platformAndVersion[0]);\ntrace(\"Major version: \"+majorVersion);\ntrace(\"Minor version: \"+minorVersion);\ntrace(\"Build number: \"+buildNumber);\ntrace(\"-----\");\n\nif (majorVersion &lt; 9) trace(\"Your Flash Player version is older than the current version 9, please update.\");\nelse trace(\"You are using Flash Player 9 or later.\");\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20601/" ]
There is a way to know the flash player version installed on the computer that runs our SWF file with Action Script 3.0?
If you are programming from within the IDE the following will get you the version ``` trace(Capabilities.version); ``` If you are building a custom class the following should help. Make sure that this following code goes into a file named VersionCheck.as > > > ``` > > package > { > import flash.system.Capabilities; > > public class VersionCheck > { > public function VersionCheck():void > { > trace(Capabilities.version); > } > } > } > > ``` > > Hope this helps, always remember that all of the AS3 language can be studied online here <http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/>.
121,493
<p>I'm no crypto expert, but as I understand it, 3DES is a symmetric encryption algorithm, which means it doesnt use public/private keys.</p> <p>Nevertheless, I have been tasked with encrypting data using a public key, (specifically, a .CER file). If you ignore the whole symmetric/asymmetric thang, I should just be able to use the key data from the public key as the TripleDES key. However, I'm having difficulty extracting the key bytes from the .CER file. This is the code as it stands..</p> <pre><code>TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider(); X509Certificate2 cert = new X509Certificate2(@"c:\temp\whatever.cer"); cryptoProvider.Key = cert.PublicKey.Key. </code></pre> <p>The simplest method I can find to extract the raw key bytes from the certificate is ToXmlString(bool), and then doing some hacky substringing upon the returned string. However, this seems so hackish I feel I must be missing a simpler, more obvious way to do it.</p> <p>Am I missing a simpler way to use a .cer file to provide the key data to the C# 3DES crypto class, or is hacking it out of the certificate xml string really the best way to go about this?</p>
[ { "answer_id": 121526, "author": "jlew", "author_id": 7450, "author_profile": "https://Stackoverflow.com/users/7450", "pm_score": 3, "selected": true, "text": "<p>cryptoProvider.Key = cert.GetPublicKey()?</p>\n" }, { "answer_id": 121527, "author": "Seb Nilsson", "author_id": 2429, "author_profile": "https://Stackoverflow.com/users/2429", "pm_score": 0, "selected": false, "text": "<p>I think what you are missing is converting the bytes from the string containing the key-bytes.</p>\n\n<p>Hope the method <strong><a href=\"http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx\" rel=\"nofollow noreferrer\">FromBase64String</a></strong> will help you:</p>\n\n<pre><code>byte[] keyBytes = Convert.FromBase64String(sourceString);\n</code></pre>\n" }, { "answer_id": 121532, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 1, "selected": false, "text": "<p>Encrypting large amounts of data with asymmetric cryptography is not the way to go. Instead, encrypt the data with a symmetric algorithm and encrypt the symmetric key (and IV) with your public key.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx\" rel=\"nofollow noreferrer\">This page</a> from MSDN really helped me get going with .Net symmetric cryptography.</p>\n" }, { "answer_id": 121559, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 2, "selected": false, "text": "<p>It's not a good idea to use keys generated for asymmetric cryptography for symmetric cryptography. There's nothing preventing you from coming up with a way of using a public key as an encryption key for 3DES, but the end result will be that anyone having access to the public key (and this means everyone!) will be able to decrypt your ciphertext.</p>\n" }, { "answer_id": 121630, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 1, "selected": false, "text": "<p>The real problem here is that the public key is, well, <strong>public</strong>. Meaning freely available, meaning it's providing zero security of encryption.</p>\n\n<p>Heck, anyone on this thread has all the information they need to decrypt everything. So do googlers.</p>\n\n<p>Please try to encourage your users not to use public key data like that. At the very least, get them to give a password or some other slightly-more-secure chunk you can use to generate a consistent key.</p>\n\n<p>One more thing. Certificate keys vary in size. It can probably handle throwing away extra bytes in the key, but you'll probably get an Array Index / Out Of Bounds exception if the key happens to be shorter than the 3DES key needs. I doubt that'll happen, 3DES only needs 56bits, and cert keys are almost always 256bits or larger.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21002/" ]
I'm no crypto expert, but as I understand it, 3DES is a symmetric encryption algorithm, which means it doesnt use public/private keys. Nevertheless, I have been tasked with encrypting data using a public key, (specifically, a .CER file). If you ignore the whole symmetric/asymmetric thang, I should just be able to use the key data from the public key as the TripleDES key. However, I'm having difficulty extracting the key bytes from the .CER file. This is the code as it stands.. ``` TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider(); X509Certificate2 cert = new X509Certificate2(@"c:\temp\whatever.cer"); cryptoProvider.Key = cert.PublicKey.Key. ``` The simplest method I can find to extract the raw key bytes from the certificate is ToXmlString(bool), and then doing some hacky substringing upon the returned string. However, this seems so hackish I feel I must be missing a simpler, more obvious way to do it. Am I missing a simpler way to use a .cer file to provide the key data to the C# 3DES crypto class, or is hacking it out of the certificate xml string really the best way to go about this?
cryptoProvider.Key = cert.GetPublicKey()?
121,499
<p>Suppose I attach an <code>blur</code> function to an HTML input box like this:</p> <pre><code>&lt;input id="myInput" onblur="function() { ... }"&gt;&lt;/input&gt; </code></pre> <p>Is there a way to get the ID of the element which caused the <code>blur</code> event to fire (the element which was clicked) inside the function? How?</p> <p>For example, suppose I have a span like this:</p> <pre><code>&lt;span id="mySpan"&gt;Hello World&lt;/span&gt; </code></pre> <p>If I click the span right after the input element has focus, the input element will lose its focus. How does the function know that it was <code>mySpan</code> that was clicked?</p> <p>PS: If the onclick event of the span would occur before the onblur event of the input element my problem would be solved, because I could set some status value indicating a specific element had been clicked.</p> <p>PPS: The background of this problem is that I want to trigger an AJAX autocompleter control externally (from a clickable element) to show its suggestions, without the suggestions disappearing immediately because of the <code>blur</code> event on the input element. So I want to check in the <code>blur</code> function if one specific element has been clicked, and if so, ignore the blur event. </p>
[ { "answer_id": 121517, "author": "brock.holum", "author_id": 15860, "author_profile": "https://Stackoverflow.com/users/15860", "pm_score": 0, "selected": false, "text": "<p><strong>Edit:</strong>\nA hacky way to do it would be to create a variable that keeps track of focus for every element you care about. So, if you care that 'myInput' lost focus, set a variable to it on focus.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n var lastFocusedElement;\n&lt;/script&gt;\n&lt;input id=\"myInput\" onFocus=\"lastFocusedElement=this;\" /&gt;\n</code></pre>\n\n<p>Original Answer:\nYou can pass 'this' to the function.</p>\n\n<pre><code>&lt;input id=\"myInput\" onblur=\"function(this){\n var theId = this.id; // will be 'myInput'\n}\" /&gt;\n</code></pre>\n" }, { "answer_id": 121522, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": -1, "selected": false, "text": "<p>This way:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n function yourFunction(element) {\n alert(element);\n }\n&lt;/script&gt;\n&lt;input id=\"myinput\" onblur=\"yourFunction(this)\"&gt;\n</code></pre>\n\n<p>Or if you attach the listener via JavaScript (jQuery in this example):</p>\n\n<pre><code>var input = $('#myinput').blur(function() {\n alert(this);\n});\n</code></pre>\n\n<p><strong>Edit</strong>: sorry. I misread the question.</p>\n" }, { "answer_id": 121576, "author": "stefano m", "author_id": 19261, "author_profile": "https://Stackoverflow.com/users/19261", "pm_score": 1, "selected": false, "text": "<p>i think it's not possibe,\nwith IE you can try to use <code>window.event.toElement</code>, but it dosn't work with firefox!</p>\n" }, { "answer_id": 121708, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 8, "selected": true, "text": "<p>Hmm... In Firefox, you can use <code>explicitOriginalTarget</code> to pull the element that was clicked on. I expected <code>toElement</code> to do the same for IE, but it does not appear to work... However, you can pull the newly-focused element from the document:</p>\n\n<pre><code>function showBlur(ev)\n{\n var target = ev.explicitOriginalTarget||document.activeElement;\n document.getElementById(\"focused\").value = \n target ? target.id||target.tagName||target : '';\n}\n\n...\n\n&lt;button id=\"btn1\" onblur=\"showBlur(event)\"&gt;Button 1&lt;/button&gt;\n&lt;button id=\"btn2\" onblur=\"showBlur(event)\"&gt;Button 2&lt;/button&gt;\n&lt;button id=\"btn3\" onblur=\"showBlur(event)\"&gt;Button 3&lt;/button&gt;\n&lt;input id=\"focused\" type=\"text\" disabled=\"disabled\" /&gt;\n</code></pre>\n\n<hr>\n\n<p><strong>Caveat:</strong> This technique does <em>not</em> work for focus changes caused by <em>tabbing</em> through fields with the keyboard, and does not work at all in Chrome or Safari. The big problem with using <code>activeElement</code> (except in IE) is that it is not consistently updated until <em>after</em> the <code>blur</code> event has been processed, and may have no valid value at all during processing! This can be mitigated with a variation on <a href=\"https://stackoverflow.com/questions/121499/when-onblur-occurs-how-can-i-find-out-which-element-focus-went-to/128452#128452\">the technique Michiel ended up using</a>:</p>\n\n<pre><code>function showBlur(ev)\n{\n // Use timeout to delay examination of activeElement until after blur/focus \n // events have been processed.\n setTimeout(function()\n {\n var target = document.activeElement;\n document.getElementById(\"focused\").value = \n target ? target.id||target.tagName||target : '';\n }, 1);\n}\n</code></pre>\n\n<p>This should work in most modern browsers (tested in Chrome, IE, and Firefox), with the caveat that Chrome does not set focus on buttons that are <em>clicked</em> (vs. tabbed to). </p>\n" }, { "answer_id": 124560, "author": "bmb", "author_id": 5298, "author_profile": "https://Stackoverflow.com/users/5298", "pm_score": 2, "selected": false, "text": "<p>Can you reverse what you're checking and when? That is if you remeber what was blurred last:</p>\n\n<pre><code>&lt;input id=\"myInput\" onblur=\"lastBlurred=this;\"&gt;&lt;/input&gt;\n</code></pre>\n\n<p>and then in the onClick for your span, call function() with both objects:</p>\n\n<pre><code>&lt;span id=\"mySpan\" onClick=\"function(lastBlurred, this);\"&gt;Hello World&lt;/span&gt;\n</code></pre>\n\n<p>Your function could then decide whether or not to trigger the Ajax.AutoCompleter control. The function has the clicked object <em>and</em> the blurred object. The onBlur has already happened so it won't make the suggestions disappear.</p>\n" }, { "answer_id": 124578, "author": "stalepretzel", "author_id": 1615, "author_profile": "https://Stackoverflow.com/users/1615", "pm_score": 0, "selected": false, "text": "<p>I suggest using global variables blurfrom and blurto. Then, configure all elements you care about to assign their position in the DOM to the variable blurfrom when they lose focus. Additionally, configure them so that gaining focus sets the variable blurto to <em>their</em> position in the DOM. Then, you could use another function altogether to analyze the blurfrom and blurto data.</p>\n" }, { "answer_id": 128452, "author": "Michiel Borkent", "author_id": 6264, "author_profile": "https://Stackoverflow.com/users/6264", "pm_score": 4, "selected": false, "text": "<p>I solved it eventually with a timeout on the onblur event (thanks to the advice of a friend who is not StackOverflow):</p>\n\n<pre><code>&lt;input id=\"myInput\" onblur=\"setTimeout(function() {alert(clickSrc);},200);\"&gt;&lt;/input&gt;\n&lt;span onclick=\"clickSrc='mySpan';\" id=\"mySpan\"&gt;Hello World&lt;/span&gt;\n</code></pre>\n\n<p>Works both in FF and IE. </p>\n" }, { "answer_id": 177936, "author": "matte", "author_id": 25768, "author_profile": "https://Stackoverflow.com/users/25768", "pm_score": 2, "selected": false, "text": "<p>I am also trying to make Autocompleter ignore blurring if a specific element clicked and have a working solution, but for only Firefox due to explicitOriginalTarget</p>\n\n<pre><code>Autocompleter.Base.prototype.onBlur = Autocompleter.Base.prototype.onBlur.wrap( \n function(origfunc, ev) {\n if ($(this.options.ignoreBlurEventElement)) {\n var newTargetElement = (ev.explicitOriginalTarget.nodeType == 3 ? ev.explicitOriginalTarget.parentNode : ev.explicitOriginalTarget);\n if (!newTargetElement.descendantOf($(this.options.ignoreBlurEventElement))) {\n return origfunc(ev);\n }\n }\n }\n );\n</code></pre>\n\n<p>This code wraps default onBlur method of Autocompleter and checks if ignoreBlurEventElement parameters is set. if it is set, it checks everytime to see if clicked element is ignoreBlurEventElement or not. If it is, Autocompleter does not cal onBlur, else it calls onBlur. The only problem with this is that it only works in Firefox because explicitOriginalTarget property is Mozilla specific . Now I am trying to find a different way than using explicitOriginalTarget. The solution you have mentioned requires you to add onclick behaviour manually to the element. If I can't manage to solve explicitOriginalTarget issue, I guess I will follow your solution.</p>\n" }, { "answer_id": 947529, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>keep in mind, that the solution with explicitOriginalTarget does not work for text-input-to-text-input jumps.</p>\n\n<p>try to replace buttons with the following text-inputs and you will see the difference:</p>\n\n<pre><code>&lt;input id=\"btn1\" onblur=\"showBlur(event)\" value=\"text1\"&gt;\n&lt;input id=\"btn2\" onblur=\"showBlur(event)\" value=\"text2\"&gt;\n&lt;input id=\"btn3\" onblur=\"showBlur(event)\" value=\"text3\"&gt;\n</code></pre>\n" }, { "answer_id": 2572467, "author": "Evgeny Shmanev", "author_id": 308436, "author_profile": "https://Stackoverflow.com/users/308436", "pm_score": 4, "selected": false, "text": "<p>It's possible to use mousedown event of document instead of blur:</p>\n\n<pre><code>$(document).mousedown(function(){\n if ($(event.target).attr(\"id\") == \"mySpan\") {\n // some process\n }\n});\n</code></pre>\n" }, { "answer_id": 6202863, "author": "EricDuWeb", "author_id": 779573, "author_profile": "https://Stackoverflow.com/users/779573", "pm_score": 0, "selected": false, "text": "<p>I've been playing with this same feature and found out that FF, IE, Chrome and Opera have the ability to provide the source element of an event. I haven't tested Safari but my guess is it might have something similar.</p>\n\n<pre><code>$('#Form').keyup(function (e) {\n var ctrl = null;\n if (e.originalEvent.explicitOriginalTarget) { // FF\n ctrl = e.originalEvent.explicitOriginalTarget;\n }\n else if (e.originalEvent.srcElement) { // IE, Chrome and Opera\n ctrl = e.originalEvent.srcElement;\n }\n //...\n});\n</code></pre>\n" }, { "answer_id": 8853179, "author": "Vikas", "author_id": 1147999, "author_profile": "https://Stackoverflow.com/users/1147999", "pm_score": 1, "selected": false, "text": "<p>Use something like this:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var myVar = null;\n</code></pre>\n\n<p>And then inside your function:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>myVar = fldID;\n</code></pre>\n\n<p>And then:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>setTimeout(setFocus,1000)\n</code></pre>\n\n<p>And then:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function setFocus(){ document.getElementById(fldID).focus(); }\n</code></pre>\n\n<p>Final code:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;html&gt;\n&lt;head&gt;\n &lt;script type=\"text/javascript\"&gt;\n function somefunction(){\n var myVar = null;\n\n myVar = document.getElementById('myInput');\n\n if(myVar.value=='')\n setTimeout(setFocusOnJobTitle,1000);\n else\n myVar.value='Success';\n }\n function setFocusOnJobTitle(){\n document.getElementById('myInput').focus();\n }\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;label id=\"jobTitleId\" for=\"myInput\"&gt;Job Title&lt;/label&gt;\n&lt;input id=\"myInput\" onblur=\"somefunction();\"&gt;&lt;/input&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 9928738, "author": "Ronan Quillevere", "author_id": 1301197, "author_profile": "https://Stackoverflow.com/users/1301197", "pm_score": 0, "selected": false, "text": "<p>I do not like using timeout when coding javascript so I would do it the opposite way of Michiel Borkent. (Did not try the code behind but you should get the idea).</p>\n\n<pre><code>&lt;input id=\"myInput\" onblur=\"blured = this.id;\"&gt;&lt;/input&gt;\n&lt;span onfocus = \"sortOfCallback(this.id)\" id=\"mySpan\"&gt;Hello World&lt;/span&gt;\n</code></pre>\n\n<p>In the head something like that</p>\n\n<pre><code>&lt;head&gt;\n &lt;script type=\"text/javascript\"&gt;\n function sortOfCallback(id){\n bluredElement = document.getElementById(blured);\n // Do whatever you want on the blured element with the id of the focus element\n\n\n }\n\n &lt;/script&gt;\n&lt;/head&gt;\n</code></pre>\n" }, { "answer_id": 12004741, "author": "Monika Sharma", "author_id": 1606730, "author_profile": "https://Stackoverflow.com/users/1606730", "pm_score": -1, "selected": false, "text": "<p><br>\nI think its easily possible via jquery by passing the reference of the field causing the onblur event in \"this\".<br>\nFor e.g.</p>\n\n<pre><code>&lt;input type=\"text\" id=\"text1\" onblur=\"showMessageOnOnblur(this)\"&gt;\n\nfunction showMessageOnOnblur(field){\n alert($(field).attr(\"id\"));\n}\n</code></pre>\n\n<p>Thanks<br>\nMonika</p>\n" }, { "answer_id": 29704319, "author": "Shikekaka Yamiryuukido", "author_id": 4801908, "author_profile": "https://Stackoverflow.com/users/4801908", "pm_score": -1, "selected": false, "text": "<p>You could make it like this:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nfunction myFunction(thisElement) \n{\n document.getElementByName(thisElement)[0];\n}\n&lt;/script&gt;\n&lt;input type=\"text\" name=\"txtInput1\" onBlur=\"myFunction(this.name)\"/&gt;\n</code></pre>\n" }, { "answer_id": 33325953, "author": "Oriol", "author_id": 1529630, "author_profile": "https://Stackoverflow.com/users/1529630", "pm_score": 7, "selected": false, "text": "<p><strong>2015 answer</strong>: according to <a href=\"http://www.w3.org/TR/uievents\" rel=\"noreferrer\">UI Events</a>, you can use the <a href=\"http://www.w3.org/TR/uievents/#widl-FocusEvent-relatedTarget\" rel=\"noreferrer\"><code>relatedTarget</code></a> property of the event:</p>\n\n<blockquote>\n <p>Used to identify a secondary <a href=\"http://www.w3.org/TR/uievents/#interface-EventTarget\" rel=\"noreferrer\"><code>EventTarget</code></a> related to a Focus\n event, depending on the type of event.</p>\n</blockquote>\n\n<p>For <a href=\"http://www.w3.org/TR/uievents/#event-type-blur\" rel=\"noreferrer\"><code>blur</code></a> events,</p>\n\n<blockquote>\n <p><a href=\"http://www.w3.org/TR/uievents/#widl-FocusEvent-relatedTarget\" rel=\"noreferrer\"><code>relatedTarget</code></a>: <a href=\"http://www.w3.org/TR/uievents/#glossary-event-target\" rel=\"noreferrer\">event target</a> receiving focus.</p>\n</blockquote>\n\n<p>Example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function blurListener(event) {\r\n event.target.className = 'blurred';\r\n if(event.relatedTarget)\r\n event.relatedTarget.className = 'focused';\r\n}\r\n[].forEach.call(document.querySelectorAll('input'), function(el) {\r\n el.addEventListener('blur', blurListener, false);\r\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.blurred { background: orange }\r\n.focused { background: lime }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;p&gt;Blurred elements will become orange.&lt;/p&gt;\r\n&lt;p&gt;Focused elements should become lime.&lt;/p&gt;\r\n&lt;input /&gt;&lt;input /&gt;&lt;input /&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Note Firefox won't support <code>relatedTarget</code> until version 48 (<a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=962251\" rel=\"noreferrer\">bug 962251</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/relatedTarget\" rel=\"noreferrer\">MDN</a>).</p>\n" }, { "answer_id": 38101004, "author": "Madbean", "author_id": 6528671, "author_profile": "https://Stackoverflow.com/users/6528671", "pm_score": 1, "selected": false, "text": "<p>You can fix IE with :</p>\n\n<pre><code> event.currentTarget.firstChild.ownerDocument.activeElement\n</code></pre>\n\n<p>It looks like \"explicitOriginalTarget\" for FF.</p>\n\n<p>Antoine And J</p>\n" }, { "answer_id": 40899101, "author": "Kevin", "author_id": 473792, "author_profile": "https://Stackoverflow.com/users/473792", "pm_score": 1, "selected": false, "text": "<p>As noted in <a href=\"https://stackoverflow.com/a/7096271/473792\">this answer</a>, you can check the value of <code>document.activeElement</code>. <code>document</code> is a global variable, so you don't have to do any magic to use it in your onBlur handler:</p>\n\n<pre><code>function myOnBlur(e) {\n if(document.activeElement ===\n document.getElementById('elementToCheckForFocus')) {\n // Focus went where we expected!\n // ...\n }\n}\n</code></pre>\n" }, { "answer_id": 40925160, "author": "rplaurindo", "author_id": 2730593, "author_profile": "https://Stackoverflow.com/users/2730593", "pm_score": 3, "selected": false, "text": "<p>The instance of type <code>FocusEvent</code> has the <code>relatedTarget</code> property, however, up to version 47 of the FF, specifically, this attribute returns <code>null</code>, from 48 it already works.</p>\n<p>You can see more <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 43010274, "author": "Serhii Matrunchyk", "author_id": 1323496, "author_profile": "https://Stackoverflow.com/users/1323496", "pm_score": 0, "selected": false, "text": "<p>I wrote an <a href=\"https://jsfiddle.net/matrunchyk/h612wb9t/\" rel=\"nofollow noreferrer\">alternative solution</a> how to make any element focusable and \"blurable\".</p>\n\n<p>It's based on making an element as <code>contentEditable</code> and hiding visually it and disabling edit mode itself:</p>\n\n<pre><code>el.addEventListener(\"keydown\", function(e) {\n e.preventDefault();\n e.stopPropagation();\n});\n\nel.addEventListener(\"blur\", cbBlur);\nel.contentEditable = true;\n</code></pre>\n\n<p><a href=\"https://jsfiddle.net/matrunchyk/h612wb9t/\" rel=\"nofollow noreferrer\">DEMO</a></p>\n\n<p>Note: Tested in Chrome, Firefox, and Safari (OS X). Not sure about IE.</p>\n\n<hr>\n\n<p>Related: I was searching for a solution for VueJs, so for those who interested/curious how to implement such functionality using Vue Focusable directive, please <a href=\"https://jsfiddle.net/matrunchyk/pv10fLxL/\" rel=\"nofollow noreferrer\">take a look</a>.</p>\n" }, { "answer_id": 43824817, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<ul>\n<li>document.activeElement could be a parent node (for example body node because it is in a temporary phase switching from a target to another), so it is not usable for your scope</li>\n<li>ev.explicitOriginalTarget is not always valued</li>\n</ul>\n\n<p>So the best way is to use onclick on body event for understanding indirectly your node(event.target) is on blur </p>\n" }, { "answer_id": 45921048, "author": "Thomas J.", "author_id": 5470560, "author_profile": "https://Stackoverflow.com/users/5470560", "pm_score": -1, "selected": false, "text": "<p>I see only hacks in the answers, but there's actually a builtin solution very easy to use :\nBasically you can capture the focus element like this:</p>\n\n<pre><code>const focusedElement = document.activeElement\n</code></pre>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement</a></p>\n" }, { "answer_id": 50340689, "author": "LuisEduardox", "author_id": 7452226, "author_profile": "https://Stackoverflow.com/users/7452226", "pm_score": 2, "selected": false, "text": "<p>Works in Google Chrome v66.x, Mozilla v59.x and Microsoft Edge... Solution with jQuery.</p>\n\n<blockquote>\n <p>I test in Internet Explorer 9 and not supported. </p>\n</blockquote>\n\n<pre><code>$(\"#YourElement\").blur(function(e){\n var InputTarget = $(e.relatedTarget).attr(\"id\"); // GET ID Element\n console.log(InputTarget);\n if(target == \"YourId\") { // If you want validate or make a action to specfic element\n ... // your code\n }\n});\n</code></pre>\n\n<p>Comment your test in others internet explorer versions.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6264/" ]
Suppose I attach an `blur` function to an HTML input box like this: ``` <input id="myInput" onblur="function() { ... }"></input> ``` Is there a way to get the ID of the element which caused the `blur` event to fire (the element which was clicked) inside the function? How? For example, suppose I have a span like this: ``` <span id="mySpan">Hello World</span> ``` If I click the span right after the input element has focus, the input element will lose its focus. How does the function know that it was `mySpan` that was clicked? PS: If the onclick event of the span would occur before the onblur event of the input element my problem would be solved, because I could set some status value indicating a specific element had been clicked. PPS: The background of this problem is that I want to trigger an AJAX autocompleter control externally (from a clickable element) to show its suggestions, without the suggestions disappearing immediately because of the `blur` event on the input element. So I want to check in the `blur` function if one specific element has been clicked, and if so, ignore the blur event.
Hmm... In Firefox, you can use `explicitOriginalTarget` to pull the element that was clicked on. I expected `toElement` to do the same for IE, but it does not appear to work... However, you can pull the newly-focused element from the document: ``` function showBlur(ev) { var target = ev.explicitOriginalTarget||document.activeElement; document.getElementById("focused").value = target ? target.id||target.tagName||target : ''; } ... <button id="btn1" onblur="showBlur(event)">Button 1</button> <button id="btn2" onblur="showBlur(event)">Button 2</button> <button id="btn3" onblur="showBlur(event)">Button 3</button> <input id="focused" type="text" disabled="disabled" /> ``` --- **Caveat:** This technique does *not* work for focus changes caused by *tabbing* through fields with the keyboard, and does not work at all in Chrome or Safari. The big problem with using `activeElement` (except in IE) is that it is not consistently updated until *after* the `blur` event has been processed, and may have no valid value at all during processing! This can be mitigated with a variation on [the technique Michiel ended up using](https://stackoverflow.com/questions/121499/when-onblur-occurs-how-can-i-find-out-which-element-focus-went-to/128452#128452): ``` function showBlur(ev) { // Use timeout to delay examination of activeElement until after blur/focus // events have been processed. setTimeout(function() { var target = document.activeElement; document.getElementById("focused").value = target ? target.id||target.tagName||target : ''; }, 1); } ``` This should work in most modern browsers (tested in Chrome, IE, and Firefox), with the caveat that Chrome does not set focus on buttons that are *clicked* (vs. tabbed to).
121,511
<p>I have inherited a poorly written web application that seems to have errors when it tries to read in an xml document stored in the database that has an "&amp;" in it. For example there will be a tag with the contents: "Prepaid &amp; Charge". Is there some secret simple thing to do to have it not get an error parsing that character, or am I missing something obvious? </p> <p>EDIT: Are there any other characters that will cause this same type of parser error for not being well formed?</p>
[ { "answer_id": 121529, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": 2, "selected": false, "text": "<p>You can replace &amp; with <code>&amp;amp;</code></p>\n\n<p>Or you might also be able to use <a href=\"http://en.wikipedia.org/wiki/CDATA\" rel=\"nofollow noreferrer\">CDATA</a> sections.</p>\n" }, { "answer_id": 121537, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 6, "selected": true, "text": "<p>The problem is the xml is not well-formed. Properly generated xml would list the data like this:</p>\n<blockquote>\n<p><code>Prepaid &amp;amp; Charge</code></p>\n</blockquote>\n<p>I've fixed the same problem before, and I did it with this regex:</p>\n<pre><code>Regex badAmpersand = new Regex(&quot;&amp;(?![a-zA-Z]{2,6};|#[0-9]{2,4};)&quot;);\n</code></pre>\n<p>Combine that with a string constant defined like this:</p>\n<pre><code>const string goodAmpersand = &quot;&amp;amp;&quot;;\n</code></pre>\n<p>Now you can say <code>badAmpersand.Replace(&lt;your input&gt;, goodAmpersand);</code></p>\n<p>Note a simple <code>String.Replace(&quot;&amp;&quot;, &quot;&amp;amp;&quot;)</code> isn't good enough, since you can't know in advance for a given document whether any &amp; characters will be coded correctly, incorrectly, or even both in the same document.</p>\n<p>The catches here are you have to do this to your xml document <em>before</em> loading it into your parser, which likely means an extra pass through the document. Also, it does not account for ampersands inside of a CDATA section. Finally, it <em>only</em> catches ampersands, not other illegal characters like &lt;. <strong>Update:</strong> based on the comment, I need to update the expression for hex-coded (&amp;#x...;) entities as well.</p>\n<p>Regarding which characters can cause problems, the actual rules are a little complex. For example, certain characters are allowed in data, but not as the first letter of an element name. And there's no simple list of illegal characters. Instead, large (non-contiguous) swaths of UNICODE are <a href=\"http://www.w3.org/TR/REC-xml#charsets\" rel=\"nofollow noreferrer\">defined as legal</a>, and anything outside that is illegal.</p>\n<p>When it comes down to it, you have to trust your document source to have at least a certain amount of compliance and consistency. For example, I've found people are often smart enough to make sure the tags work properly and escape &lt;, even if they don't know that &amp; isn't allowed, hence your problem today. However, <strong>the best thing would be to get this fixed at the source.</strong></p>\n<p>Oh, and a note about the CDATA suggestion: I use that to make sure xml <em>I'm creating</em> is well-formed, but when dealing with existing xml from outside, I find the regex method easier.</p>\n" }, { "answer_id": 121544, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 2, "selected": false, "text": "<p>The web application isn't at fault, the XML document is. Ampersands in XML should be encoded as <code>&amp;amp;</code>. Failure to do so is a syntax error.</p>\n\n<p><strong>Edit:</strong> in answer to the followup question, yes there are all kinds of similar errors. For example, unbalanced tags, unencoded less-than signs, unquoted attribute values, octets outside of the character encoding and various Unicode oddities, unrecognised entity references, and so on. In order to get any decent XML parser to consume a document, that document must be well-formed. The XML specification requires that a parser encountering a malformed document throw a fatal error.</p>\n" }, { "answer_id": 121555, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 2, "selected": false, "text": "<p>There are several characters which will cause XML data to be reported as badly-formed.</p>\n\n<p>From <a href=\"http://www.w3schools.com/XML/xml_cdata.asp\" rel=\"nofollow noreferrer\">w3schools</a>:</p>\n\n<blockquote>\n <p>Characters like \"&lt;\" and \"&amp;\" are illegal in XML elements.</p>\n</blockquote>\n\n<p>The best solution for input you can't trust to be XML-compliant is to wrap it in CDATA tags, e.g.</p>\n\n<pre><code>&lt;![CDATA[This is my wonderful &amp; great user text]]&gt;\n</code></pre>\n\n<p>Everything within the <code>&lt;![CDATA[</code> and <code>]]></code> tags is ignored by the parser.</p>\n" }, { "answer_id": 121667, "author": "Chris Ingrassia", "author_id": 6991, "author_profile": "https://Stackoverflow.com/users/6991", "pm_score": 2, "selected": false, "text": "<p>The other answers are all correct, and I concur with their advice, but let me just add one thing:</p>\n\n<p>PLEASE do not make applications that work with non well-formed XML, it just makes the rest of our lives more difficult :).</p>\n\n<p>Granted, there are times when you really just don't have a choice if you have no control over the other end, but you should really have it throwing a fatal error and complaining very loudly and explicitly about what is broken when such an event occurs.</p>\n\n<p>You could probably take it one step further and say \"Ack! This XML is broken in these places and for these reasons, here's how I tried to fix it to make it well-formed: ...\".</p>\n\n<p>I'm not overly familiar with the MSXML APIs, but most good XML parsers will allow you to install error handlers so that you can trap the exact line/column number where errors are appearing along with getting the error code and message.</p>\n" }, { "answer_id": 123795, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 2, "selected": false, "text": "<p>Your database doesn't contain XML documents. It contains some well-formed XML documents and some strings that look like XML to a human. </p>\n\n<p>If it's at all possible, you should fix this - in particular, you should fix whatever process is generating the malformed XML documents. Fixing the program that reads data out of this database is just putting wallpaper over a crack in the wall.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13593/" ]
I have inherited a poorly written web application that seems to have errors when it tries to read in an xml document stored in the database that has an "&" in it. For example there will be a tag with the contents: "Prepaid & Charge". Is there some secret simple thing to do to have it not get an error parsing that character, or am I missing something obvious? EDIT: Are there any other characters that will cause this same type of parser error for not being well formed?
The problem is the xml is not well-formed. Properly generated xml would list the data like this: > > `Prepaid &amp; Charge` > > > I've fixed the same problem before, and I did it with this regex: ``` Regex badAmpersand = new Regex("&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)"); ``` Combine that with a string constant defined like this: ``` const string goodAmpersand = "&amp;"; ``` Now you can say `badAmpersand.Replace(<your input>, goodAmpersand);` Note a simple `String.Replace("&", "&amp;")` isn't good enough, since you can't know in advance for a given document whether any & characters will be coded correctly, incorrectly, or even both in the same document. The catches here are you have to do this to your xml document *before* loading it into your parser, which likely means an extra pass through the document. Also, it does not account for ampersands inside of a CDATA section. Finally, it *only* catches ampersands, not other illegal characters like <. **Update:** based on the comment, I need to update the expression for hex-coded (&#x...;) entities as well. Regarding which characters can cause problems, the actual rules are a little complex. For example, certain characters are allowed in data, but not as the first letter of an element name. And there's no simple list of illegal characters. Instead, large (non-contiguous) swaths of UNICODE are [defined as legal](http://www.w3.org/TR/REC-xml#charsets), and anything outside that is illegal. When it comes down to it, you have to trust your document source to have at least a certain amount of compliance and consistency. For example, I've found people are often smart enough to make sure the tags work properly and escape <, even if they don't know that & isn't allowed, hence your problem today. However, **the best thing would be to get this fixed at the source.** Oh, and a note about the CDATA suggestion: I use that to make sure xml *I'm creating* is well-formed, but when dealing with existing xml from outside, I find the regex method easier.
121,521
<p>I use the on-demand (hosted) version of FogBugz. I would like to start using Mercurial for source control. I would like to integrate FogBugz and a BitBucket repository. I gave it a bit of a try but things weren't going very well. </p> <p>FogBugz requires that you hook up your Mercurial client to a fogbugz.py python script. TortoiseHg doesn't seem to have the hgext directory that they refer to in instructions.</p> <p>So has anyone successfully done something similar?</p>
[ { "answer_id": 123314, "author": "Stefan Rusek", "author_id": 19704, "author_profile": "https://Stackoverflow.com/users/19704", "pm_score": 4, "selected": true, "text": "<p>From the sounds of it you are wanting to run the hook on your local machine. The hook and directions are intended for use on the central server.</p>\n\n<p>If you are the only one working in your repository or don't mind commit not showing up in FB until after you do a pull, then you can add the hook locally to your primary clone, If you are using your primary clone then you need to do something slightly different from what they say here:\n<a href=\"http://bugs.movabletype.org/help/topics/sourcecontrol/setup/Mercurial.html\" rel=\"nofollow noreferrer\">http://bugs.movabletype.org/help/topics/sourcecontrol/setup/Mercurial.html</a></p>\n\n<p>You can put your fogbugz.py anywhere you want, just add a path line to your [fogbugz] section of that repositories hgrc file:</p>\n\n<pre><code>[fogbugz]\npath=C:\\Program Files\\TortoiseHg\\scripts\\fogbugz.py\n</code></pre>\n\n<p>Just make sure you have python installed. you may also wish to add a commit hook so that local commits to the repository also get into FB.</p>\n\n<pre><code>[hooks]\ncommit=python:hgext.fogbugz.hook\nincoming=python:hgext.fogbugz.hook\n</code></pre>\n\n<p>On the Fogbugz install you will want change put the following in your for your logs url:</p>\n\n<pre><code>^REPO/log/^R2/^FILE\n</code></pre>\n\n<p>and the following for your diff url:</p>\n\n<pre><code>^REPO/diff/^R2/^FILE\n</code></pre>\n\n<p>When the hook script runs it connects to your FB install and sends it a few parameters. These parameters are stored in the DB and used to generate urls for diffs and log informaiton. The script sends the url of repo, this is in your baseurl setting in the [web] section. You want this url to be the url to your bitbucket repository. This will be used to replace <b>^REPO</b> from the url templates above. The hook script also passes the revision id and the file name to FB. These will replace ^R2 and ^FILE. So in summary this is the stuff you want to add to the hgrc file in your .hg directory:</p>\n\n<pre><code>[extensions]\nhgext.fogbugz=\n\n[fogbugz]\npath=C:\\Program Files\\TortoiseHg\\scripts\\fogbugz.py\nhost=https://&lt;YOURACCOUNT&gt;.fogbugz.com/\nscript=cvsSubmit.asp\n\n[hooks]\ncommit=python:hgext.fogbugz.hook\nincoming=python:hgext.fogbugz.hook\n\n[web]\nbaseurl=http://www.bitbucket.org/&lt;YOURBITBUCKETACCOUNT&gt;/&lt;YOURPROJECT&gt;/\n</code></pre>\n\n<p>One thing to remember is that FB may get notified of a checkin before you actually push those changes to bitbucket. If this is the cause do a push and things will work.</p>\n\n<p>EDIT: added section about the FB server and the summary.</p>\n" }, { "answer_id": 262051, "author": "jespern", "author_id": 112415, "author_profile": "https://Stackoverflow.com/users/112415", "pm_score": 4, "selected": false, "text": "<p>Post-mortem:</p>\n\n<p>Bitbucket now has native fogbugz support, as well as other post-back services.</p>\n\n<p><a href=\"http://www.bitbucket.org/help/service-integration/\" rel=\"noreferrer\">http://www.bitbucket.org/help/service-integration/</a></p>\n" }, { "answer_id": 2495896, "author": "kamens", "author_id": 1335, "author_profile": "https://Stackoverflow.com/users/1335", "pm_score": 1, "selected": false, "text": "<p>Just a heads-up: Fog Creek has released <a href=\"http://kilnhg.com\" rel=\"nofollow noreferrer\">Kiln</a> which provides Mercurial hosting that's tightly integrated with FogBugz and doesn't require any configuration.</p>\n\n<p>I normally wouldn't \"advertise\" on Stack Overflow (disclaimer: I'm one of the Kiln devs), but I feel that this directly answers the original question.</p>\n" }, { "answer_id": 13556272, "author": "dr.scre", "author_id": 1851915, "author_profile": "https://Stackoverflow.com/users/1851915", "pm_score": 1, "selected": false, "text": "<p>It is possible to integrate your GIT BitBucket repository with FogBugz issue tracker, but unfortunately it is not properly documented.</p>\n\n<p>You have to follow steps described at <a href=\"https://confluence.atlassian.com/display/BITBUCKET/FogBugz+Service+Management\" rel=\"nofollow\">https://confluence.atlassian.com/display/BITBUCKET/FogBugz+Service+Management</a>, but beware that </p>\n\n<ol>\n<li><p>In CVSSubmit URL you need to put url WITHOUT \"?ixBug=bugID&amp;sFile=file&amp;sPrev=x&amp;sNew=y&amp;ixRepository=\" parameters.</p>\n\n<p>It should just be \"https://your_repo.fogbugz.com/cvsSubmit.asp\"</p></li>\n<li><p>You will need to mention your FogBugz case ID in the git commit message\nby putting \"BugzID: ID\" string in it (this is not documented\nanywhere :-( ) similar to this:</p>\n\n<p>git commit -m \"This is a superb commit which solves case BugzID: 42\"</p></li>\n</ol>\n\n<p>Of course, commit info will be sent to FogBugz after you push your commit to BitBucket server, not after your do a local commit.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20498/" ]
I use the on-demand (hosted) version of FogBugz. I would like to start using Mercurial for source control. I would like to integrate FogBugz and a BitBucket repository. I gave it a bit of a try but things weren't going very well. FogBugz requires that you hook up your Mercurial client to a fogbugz.py python script. TortoiseHg doesn't seem to have the hgext directory that they refer to in instructions. So has anyone successfully done something similar?
From the sounds of it you are wanting to run the hook on your local machine. The hook and directions are intended for use on the central server. If you are the only one working in your repository or don't mind commit not showing up in FB until after you do a pull, then you can add the hook locally to your primary clone, If you are using your primary clone then you need to do something slightly different from what they say here: <http://bugs.movabletype.org/help/topics/sourcecontrol/setup/Mercurial.html> You can put your fogbugz.py anywhere you want, just add a path line to your [fogbugz] section of that repositories hgrc file: ``` [fogbugz] path=C:\Program Files\TortoiseHg\scripts\fogbugz.py ``` Just make sure you have python installed. you may also wish to add a commit hook so that local commits to the repository also get into FB. ``` [hooks] commit=python:hgext.fogbugz.hook incoming=python:hgext.fogbugz.hook ``` On the Fogbugz install you will want change put the following in your for your logs url: ``` ^REPO/log/^R2/^FILE ``` and the following for your diff url: ``` ^REPO/diff/^R2/^FILE ``` When the hook script runs it connects to your FB install and sends it a few parameters. These parameters are stored in the DB and used to generate urls for diffs and log informaiton. The script sends the url of repo, this is in your baseurl setting in the [web] section. You want this url to be the url to your bitbucket repository. This will be used to replace **^REPO** from the url templates above. The hook script also passes the revision id and the file name to FB. These will replace ^R2 and ^FILE. So in summary this is the stuff you want to add to the hgrc file in your .hg directory: ``` [extensions] hgext.fogbugz= [fogbugz] path=C:\Program Files\TortoiseHg\scripts\fogbugz.py host=https://<YOURACCOUNT>.fogbugz.com/ script=cvsSubmit.asp [hooks] commit=python:hgext.fogbugz.hook incoming=python:hgext.fogbugz.hook [web] baseurl=http://www.bitbucket.org/<YOURBITBUCKETACCOUNT>/<YOURPROJECT>/ ``` One thing to remember is that FB may get notified of a checkin before you actually push those changes to bitbucket. If this is the cause do a push and things will work. EDIT: added section about the FB server and the summary.
121,579
<p>I don't know if anyone has seen this issue before but I'm just stumped. Here's the unhandled exception message that my error page is capturing. </p> <blockquote> <p>Error Message: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.</p> <p>Stack Trace: at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) at System.Web.UI.HiddenFieldPageStatePersister.Load() at System.Web.UI.Page.LoadPageStateFromPersistenceMedium() at System.Web.UI.Page.LoadAllState() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.generic_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously)</p> <p>Source: System.Web</p> </blockquote> <p>Anybody have any ideas on how I could resolve this? Thanks.</p>
[ { "answer_id": 121583, "author": "Chris Driver", "author_id": 5217, "author_profile": "https://Stackoverflow.com/users/5217", "pm_score": 5, "selected": true, "text": "<p>I seem to recall that this error can occur if you click a button/link etc before the page has fully loaded.</p>\n\n<p>If this is the case, the error is caused by an ASP.net 2.0 feature called Event Validation. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered \nform tag, you'll see something like this:</p>\n\n<pre><code>&lt;input type=\"hidden\" name=\"__EVENTVALIDATION\" id=\"__EVENTVALIDATION\" value=\"AEBnx7v.........tS\" /&gt;\n</code></pre>\n\n<p>When a postback occurs, ASP.net uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception that you've been seeing.</p>\n\n<p>The problem you're seeing happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.net cannot validate your click.</p>\n\n<p>One work around is of course to just disable event validation, but you have to be aware of the security implications. Alternatively, just never post back before the form has finished rendering. Of course, that's hard to tell your users, but perhaps you could disable the UI until the form has rendered?</p>\n\n<p>from <a href=\"http://forums.asp.net/p/955145/1173230.aspx\" rel=\"noreferrer\">http://forums.asp.net/p/955145/1173230.aspx</a></p>\n" }, { "answer_id": 121593, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "<p>do you have multiple servers running this application and/or have a web garden? If yes, you are going to have to set the <a href=\"http://msdn.microsoft.com/en-us/library/ms998288.aspx\" rel=\"nofollow noreferrer\">machine key</a> in the web.config</p>\n" }, { "answer_id": 121640, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 0, "selected": false, "text": "<p>I know you can disable the Validation of viewstate MAC, but I think if the page is not loaded you can get into more trouble. When I ran into this problem I had to disable all buttons until the page was fully loaded.</p>\n" }, { "answer_id": 121775, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/121579/im-getting-a-strange-unhandled-exception-from-my-aspnet-application-validation#121583\">@Chris</a></p>\n\n<p>if the problem is clicking an item before the page has completely rendered, asp.net 3.5 SP1 added a web.config entry on the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.renderallhiddenfieldsattopofform.aspx\" rel=\"nofollow noreferrer\">page element called renderAllHiddenFieldsAtTopOfForm</a>.</p>\n" }, { "answer_id": 122084, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 1, "selected": false, "text": "<p>By default, ASP.NET includes a digital signature of the ViewState value in the page. It does so with an automatically-generated key that is held in memory. This is done to prevent a malicious user from altering the ViewState from the browser and, for example, grant him/herself access to stuff they wouldn't normally have access to.</p>\n\n<p>ASP.NET can also, optionally, encrypt the ViewState, but it's turned off by default for performance reasons. In many web sites, it is a lot more important to make sure that the content of the ViewState is not 'mucked with', than it is to keep it confidential.</p>\n\n<p>The error message says that the signature verification failed. The page was posted with a ViewState, but the ViewState signature didn't match the signature calculated with the keys held by the server.</p>\n\n<p>The most common reason for this error is that you are using two or more web servers in a farm-like environment: one server sends the original page, signed with the key in memory on that server, but the page is posted back to the second (or third...) server. Because the two or more servers don't share the signature key, the signatures don't match.</p>\n\n<blockquote>\n <p>...If this application is hosted by a Web Farm or cluster, \n ensure that configuration specifies the same <strong>validationKey</strong> and validation algorithm. AutoGenerate cannot be used in a cluster.</p>\n</blockquote>\n\n<p>What the error message is telling you is to use the <strong>validationKey</strong> attribute (<a href=\"http://msdn.microsoft.com/en-us/library/w8h3skw9(VS.71).aspx\" rel=\"nofollow noreferrer\">see details in MSDN</a>) in your web.config to hardcode the signature key to a value shared by all your servers, instead of using a dynamically-generated one. That way, the signature validation can succeed independently of which server receives the postback.</p>\n\n<p>You <em>could</em> turn off the verification, but it's very dangerous to do so. It means any hacker with a bit of free time can fake values in your application. For example, if you keep the price of the item in a ViewState value, the hacker could change the value from the browser to $0.01 right before putting the order.</p>\n" }, { "answer_id": 141056, "author": "orlando calresian", "author_id": 21165, "author_profile": "https://Stackoverflow.com/users/21165", "pm_score": 1, "selected": false, "text": "<p>For anyone else ending up struggling with this issue here is a helpful link to some work arounds:</p>\n\n<p><a href=\"http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx</a></p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21165/" ]
I don't know if anyone has seen this issue before but I'm just stumped. Here's the unhandled exception message that my error page is capturing. > > Error Message: Validation of > viewstate MAC failed. If this > application is hosted by a Web Farm or > cluster, ensure that configuration > specifies the same validationKey and > validation algorithm. AutoGenerate > cannot be used in a cluster. > > > Stack Trace: at > System.Web.UI.ViewStateException.ThrowError(Exception > inner, String persistedState, String > errorPageMessage, Boolean > macValidationError) at > System.Web.UI.ObjectStateFormatter.Deserialize(String > inputString) at > System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String > serializedState) at > System.Web.UI.Util.DeserializeWithAssert(IStateFormatter > formatter, String serializedState) at > System.Web.UI.HiddenFieldPageStatePersister.Load() > at > System.Web.UI.Page.LoadPageStateFromPersistenceMedium() > at System.Web.UI.Page.LoadAllState() > at > System.Web.UI.Page.ProcessRequestMain(Boolean > includeStagesBeforeAsyncPoint, Boolean > includeStagesAfterAsyncPoint) at > System.Web.UI.Page.ProcessRequest(Boolean > includeStagesBeforeAsyncPoint, Boolean > includeStagesAfterAsyncPoint) at > System.Web.UI.Page.ProcessRequest() > at > System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext > context) at > System.Web.UI.Page.ProcessRequest(HttpContext > context) at > ASP.generic\_aspx.ProcessRequest(HttpContext > context) at > System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() > at > System.Web.HttpApplication.ExecuteStep(IExecutionStep > step, Boolean& completedSynchronously) > > > Source: System.Web > > > Anybody have any ideas on how I could resolve this? Thanks.
I seem to recall that this error can occur if you click a button/link etc before the page has fully loaded. If this is the case, the error is caused by an ASP.net 2.0 feature called Event Validation. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered form tag, you'll see something like this: ``` <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="AEBnx7v.........tS" /> ``` When a postback occurs, ASP.net uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception that you've been seeing. The problem you're seeing happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.net cannot validate your click. One work around is of course to just disable event validation, but you have to be aware of the security implications. Alternatively, just never post back before the form has finished rendering. Of course, that's hard to tell your users, but perhaps you could disable the UI until the form has rendered? from <http://forums.asp.net/p/955145/1173230.aspx>
121,581
<p>In SQL Server what is the simplest/cleanest way to make a datetime representing the first of the month based on another datetime? eg I have a variable or column with 3-Mar-2005 14:23 and I want to get 1-Mar-2005 00:00 (as a datetime, not as varchar)</p>
[ { "answer_id": 121596, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT DATEADD(mm, DATEDIFF(mm, 0, @date), 0)\n</code></pre>\n" }, { "answer_id": 121602, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 6, "selected": true, "text": "<pre><code>Select DateAdd(Month, DateDiff(Month, 0, GetDate()), 0)\n</code></pre>\n\n<p>To run this on a column, replace GetDate() with your column name.</p>\n\n<p>The trick to this code is with DateDiff. DateDiff returns an integer. The second parameter (the 0) represents the 0 date in SQL Server, which is Jan 1, 1900. So, the datediff calculates the integer number of months since Jan 1, 1900, then adds that number of months to Jan 1, 1900. The net effect is removing the day (and time) portion of a datetime value.</p>\n" }, { "answer_id": 121614, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 2, "selected": false, "text": "<p>Something like this would work....</p>\n\n<pre><code>UPDATE YOUR_TABLE\nSET NewColumn = DATEADD(day, (DATEPART(day, OldColumn) -1)*-1, OldColumn)\n</code></pre>\n" }, { "answer_id": 27782399, "author": "sinan.petrus", "author_id": 4323416, "author_profile": "https://Stackoverflow.com/users/4323416", "pm_score": 0, "selected": false, "text": "<p>Just use</p>\n\n<pre><code>DATEADD(DAY, 1-DAY(@date), @date)\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8479/" ]
In SQL Server what is the simplest/cleanest way to make a datetime representing the first of the month based on another datetime? eg I have a variable or column with 3-Mar-2005 14:23 and I want to get 1-Mar-2005 00:00 (as a datetime, not as varchar)
``` Select DateAdd(Month, DateDiff(Month, 0, GetDate()), 0) ``` To run this on a column, replace GetDate() with your column name. The trick to this code is with DateDiff. DateDiff returns an integer. The second parameter (the 0) represents the 0 date in SQL Server, which is Jan 1, 1900. So, the datediff calculates the integer number of months since Jan 1, 1900, then adds that number of months to Jan 1, 1900. The net effect is removing the day (and time) portion of a datetime value.
121,605
<p>What is the best way to reduce the size of the viewstate hidden field in JSF? I have noticed that my view state is approximately 40k this goes down to the client and back to the server on every request and response espically coming to the server this is a significant slowdown for the user. </p> <p>My Environment JSF 1.2, MyFaces, Tomcat, Tomahawk, RichFaces</p>
[ { "answer_id": 121624, "author": "David Waters", "author_id": 12148, "author_profile": "https://Stackoverflow.com/users/12148", "pm_score": 4, "selected": false, "text": "<p>If you are using MyFaces you can try this setting to compress the viewstate before sending to the client.</p>\n\n<pre><code>&lt;context-param&gt;\n &lt;param-name&gt;org.apache.myfaces.COMPRESS_STATE_IN_CLIENT&lt;/param-name&gt;\n &lt;param-value&gt;true&lt;/param-value&gt;\n&lt;/context-param&gt; `\n</code></pre>\n" }, { "answer_id": 124605, "author": "royalghost", "author_id": 3627, "author_profile": "https://Stackoverflow.com/users/3627", "pm_score": 0, "selected": false, "text": "<p>One option is to completely save the view state on client side but you may face some problem such as not being able to Serialize the object. You may want to try using different compression algorithm/utility based on your requirement but since the browser will already use the GZip by default I am not sure how much you can gain. </p>\n" }, { "answer_id": 170877, "author": "Cristian Vat", "author_id": 20109, "author_profile": "https://Stackoverflow.com/users/20109", "pm_score": 5, "selected": true, "text": "<p>Have you tried setting the state saving to server? This should only send an id to the client, and keep the full state on the server. Simply add the following to the file <em>web.xml</em> :</p>\n\n<pre><code> &lt;context-param&gt;\n &lt;param-name&gt;javax.faces.STATE_SAVING_METHOD&lt;/param-name&gt;\n &lt;param-value&gt;server&lt;/param-value&gt;\n &lt;/context-param&gt;\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12148/" ]
What is the best way to reduce the size of the viewstate hidden field in JSF? I have noticed that my view state is approximately 40k this goes down to the client and back to the server on every request and response espically coming to the server this is a significant slowdown for the user. My Environment JSF 1.2, MyFaces, Tomcat, Tomahawk, RichFaces
Have you tried setting the state saving to server? This should only send an id to the client, and keep the full state on the server. Simply add the following to the file *web.xml* : ``` <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>server</param-value> </context-param> ```
121,631
<p>Is there a difference in performance (in oracle) between</p> <pre><code>Select * from Table1 T1 Inner Join Table2 T2 On T1.ID = T2.ID </code></pre> <p>And</p> <pre><code>Select * from Table1 T1, Table2 T2 Where T1.ID = T2.ID </code></pre> <p>?</p>
[ { "answer_id": 121648, "author": "Craig Trader", "author_id": 12895, "author_profile": "https://Stackoverflow.com/users/12895", "pm_score": 6, "selected": false, "text": "<p>If the query optimizer is doing its job right, there should be no difference between those queries. They are just two ways to specify the same desired result.</p>\n" }, { "answer_id": 121696, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 2, "selected": false, "text": "<p>In PostgreSQL, there's definitely no difference - they both equate to the same query plan. I'm 99% sure that's also the case for Oracle.</p>\n" }, { "answer_id": 121701, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 6, "selected": false, "text": "<p>They should be exactly the same. However, as a coding practice, I would rather see the Join. It clearly articulates your intent, </p>\n" }, { "answer_id": 121719, "author": "Bob Gettys", "author_id": 7567, "author_profile": "https://Stackoverflow.com/users/7567", "pm_score": 2, "selected": false, "text": "<p>They're both inner joins that do the same thing, one simply uses the newer ANSI syntax.</p>\n" }, { "answer_id": 121747, "author": "MattC", "author_id": 21126, "author_profile": "https://Stackoverflow.com/users/21126", "pm_score": 2, "selected": false, "text": "<p>Functionally they are the same as has been said. I agree though that doing the join is better for describing exactly what you want to do. Plenty of times I've thought I knew how I wanted to query something until I started doing the joins and realized I wanted to do a different query than the original one in my head.</p>\n" }, { "answer_id": 121820, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 4, "selected": false, "text": "<p>They're logically identical, but in the earlier versions of Oracle that adopted ANSI syntax there were often bugs with it in more complex cases, so you'll sometimes encounter resistance from Oracle developers when using it.</p>\n" }, { "answer_id": 122391, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 4, "selected": false, "text": "<p>I don't know about Oracle but I know that the old syntax is being deprecated in SQL Server and will disappear eventually. Before I used that old syntax in a new query I would check what Oracle plans to do with it.</p>\n\n<p>I prefer the newer syntax rather than the mixing of the join criteria with other needed where conditions. In the newer syntax it is much clearer what creates the join and what other conditions are being applied. Not really a big problem in a short query like this, but it gets much more confusing when you have a more complex query. Since people learn on the basic queries, I would tend to prefer people learn to use the join syntax before they need it in a complex query. </p>\n\n<p>And again I don't know Oracle specifically, but I know the SQL Server version of the old style left join is flawed even in SQL Server 2000 and gives inconsistent results (sometimes a left join sometimes a cross join), so it should never be used. Hopefully Oracle doesn't suffer the same issue, but certainly left and right joins can be mcuh harder to properly express in the old syntax. </p>\n\n<p>Plus it has been my experience (and of course this is strictly a personal opinion, you may have differnt experience) that developers who use the ANSII standard joins tend to have a better understanding of what a join is and what it means in terms of getting data out of the database. I belive that is becasue most of the people with good database understanding tend to write more complex queries and those seem to me to be far easier to maintain using the ANSII Standard than the old style.</p>\n" }, { "answer_id": 122403, "author": "user21241", "author_id": 21241, "author_profile": "https://Stackoverflow.com/users/21241", "pm_score": 5, "selected": false, "text": "<p>Using <code>JOIN</code> makes the code easier to read, since it's self-explanatory.</p>\n\n<p>There's no difference in speed(<em>I have just tested it</em>) and the execution plan is the same.</p>\n" }, { "answer_id": 142761, "author": "JoshL", "author_id": 20625, "author_profile": "https://Stackoverflow.com/users/20625", "pm_score": 1, "selected": false, "text": "<p>It is true that, functionally, both queries should be processed the same way. However, experience has shown that if you are selecting from views that use the new join syntax, it is important to structure your queries using it as well. Oracle's optimizer can get confused if a view uses a \"join\" statement, but a query accessing the view uses the traditional method of joining in the \"where\" clause.</p>\n" }, { "answer_id": 341864, "author": "stili", "author_id": 20763, "author_profile": "https://Stackoverflow.com/users/20763", "pm_score": 3, "selected": false, "text": "<p>The performance should be identical, but I would suggest using the join-version due to improved clarity when it comes to outer joins.</p>\n\n<p>Also unintentional cartesian products can be avoided using the join-version.</p>\n\n<p>A third effect is an easier to read SQL with a simpler WHERE-condition.</p>\n" }, { "answer_id": 354834, "author": "kiewic", "author_id": 27211, "author_profile": "https://Stackoverflow.com/users/27211", "pm_score": 9, "selected": true, "text": "<p>No! The same execution plan, look at these two tables:</p>\n\n<pre><code>CREATE TABLE table1 (\n id INT,\n name VARCHAR(20)\n);\n\nCREATE TABLE table2 (\n id INT,\n name VARCHAR(20)\n);\n</code></pre>\n\n<p>The execution plan for the query using the inner join:</p>\n\n<pre><code>-- with inner join\n\nEXPLAIN PLAN FOR\nSELECT * FROM table1 t1\nINNER JOIN table2 t2 ON t1.id = t2.id;\n\nSELECT *\nFROM TABLE (DBMS_XPLAN.DISPLAY);\n\n-- 0 select statement\n-- 1 hash join (access(\"T1\".\"ID\"=\"T2\".\"ID\"))\n-- 2 table access full table1\n-- 3 table access full table2\n</code></pre>\n\n<p>And the execution plan for the query using a WHERE clause.</p>\n\n<pre><code>-- with where clause\n\nEXPLAIN PLAN FOR\nSELECT * FROM table1 t1, table2 t2\nWHERE t1.id = t2.id;\n\nSELECT *\nFROM TABLE (DBMS_XPLAN.DISPLAY);\n\n-- 0 select statement\n-- 1 hash join (access(\"T1\".\"ID\"=\"T2\".\"ID\"))\n-- 2 table access full table1\n-- 3 table access full table2\n</code></pre>\n" }, { "answer_id": 947481, "author": "cheduardo", "author_id": 113082, "author_profile": "https://Stackoverflow.com/users/113082", "pm_score": 3, "selected": false, "text": "<p>Don&rsquo;t forget that in Oracle, provided the join key attributes are named the same in both tables, you can also write this as:</p>\n\n<pre><code>select *\nfrom Table1 inner join Table2 using (ID);\n</code></pre>\n\n<p>This also has the same query plan, of course.</p>\n" }, { "answer_id": 1340625, "author": "Chris Gill", "author_id": 159226, "author_profile": "https://Stackoverflow.com/users/159226", "pm_score": 4, "selected": false, "text": "<p>[For a bonus point...]</p>\n\n<p>Using the JOIN syntax allows you to more easily comment out the join as its all included on one line. This <em>can</em> be useful if you are debugging a complex query</p>\n\n<p>As everyone else says, they are functionally the same, however the JOIN is more clear of a statement of intent. It therefore <em>may</em> help the query optimiser either in current oracle versions in certain cases (I have no idea if it does), it <em>may</em> help the query optimiser in future versions of Oracle (no-one has any idea), or it <em>may</em> help if you change database supplier.</p>\n" }, { "answer_id": 24447857, "author": "greatvovan", "author_id": 947012, "author_profile": "https://Stackoverflow.com/users/947012", "pm_score": 0, "selected": false, "text": "<p>Although the identity of two queries seems obvious sometimes some strange things happens. I have come accros the query wich has different execution plans when moving join predicate from JOIN to WHERE in Oracle 10g (for WHERE plan is better), but I can't reproduce this issue in simplified tables and data. I think it depends on my data and statistics. Optimizer is quite complex module and sometimes it behaves magically.</p>\n\n<p>Thats why we can't answer to this question in general because it depends on DB internals. But we should know that answer has to be '<em>no differences</em>'.</p>\n" }, { "answer_id": 26610614, "author": "trbullet81", "author_id": 4190263, "author_profile": "https://Stackoverflow.com/users/4190263", "pm_score": 0, "selected": false, "text": "<p>i had this conundrum today when inspecting one of our sp's timing out in production, changed an inner join on a table built from an xml feed to a 'where' clause instead....average exec time is now 80ms over 1000 executions, whereas before average exec was 2.2 seconds...major difference in the execution plan is the dissapearance of a key lookup... The message being you wont know until youve tested using both methods.</p>\n\n<p>cheers. </p>\n" }, { "answer_id": 38135956, "author": "abrittaf", "author_id": 3207231, "author_profile": "https://Stackoverflow.com/users/3207231", "pm_score": 3, "selected": false, "text": "<p>In a scenario where tables are in 3rd normal form, joins between tables shouldn't change. I.e. join CUSTOMERS and PAYMENTS should always remain the same. </p>\n\n<p>However, we should distinguish <strong>joins</strong> from <strong>filters</strong>. Joins are about relationships and filters are about partitioning a whole.</p>\n\n<p>Some authors, referring to the standard (i.e. Jim Melton; Alan R. Simon (1993). Understanding The New SQL: A Complete Guide. Morgan Kaufmann. pp. 11–12. ISBN 978-1-55860-245-8.), wrote about benefits to adopt JOIN syntax over comma-separated tables in FROM clause. </p>\n\n<p>I totally agree with this point of view.</p>\n\n<p>There are several ways to write SQL and achieve the same results but for many of those who do teamwork, source code legibility is an important aspect, and certainly separate how tables relate to each other from specific filters was a big leap in sense of clarifying source code.</p>\n" }, { "answer_id": 42571646, "author": "rxpande", "author_id": 2772095, "author_profile": "https://Stackoverflow.com/users/2772095", "pm_score": 0, "selected": false, "text": "<p>They're both joins and where that do the same thing.</p>\n\n<p>Give a look at <a href=\"https://stackoverflow.com/questions/2241991/in-mysql-queries-why-use-join-instead-of-where\">In MySQL queries, why use join instead of where?</a> </p>\n" }, { "answer_id": 45568773, "author": "ROQUEFORT François", "author_id": 7436563, "author_profile": "https://Stackoverflow.com/users/7436563", "pm_score": 0, "selected": false, "text": "<p>As kiewik said, the execution plan is the same. </p>\n\n<p>The JOIN statement is only more easy to read, making it easier not to forget the ON condition and getting a cartesian product. These errors can be quite hard to detect in long queries using multiple joins of type : SELECT * FROM t1, t2 WHERE t1.id=t2.some_field. </p>\n\n<p>If you forget only one join condition, you get a very long to execute query returning too many records... really too many. Some poeple use a DISTINCT to patch the query, but it's still very long to execute.</p>\n\n<p>That's accurately why, using JOIN statement is surely the best practice : a better maintainability, and a better readability.</p>\n\n<p>Further more, if I well remember, JOIN is optimized concerning memory usage.</p>\n" }, { "answer_id": 59412549, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I have an addition to that <a href=\"https://stackoverflow.com/a/38135956/2188550\">good answer</a>:</p>\n\n<p>That's what is defined as SQL92 and SQL89 respectively, there is no performance difference between them although you can omit the word INNER (using just JOIN is clear enough and in the simplest query you save 5 keyboard strokes now imagine how many strokes there are in big ones).</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
Is there a difference in performance (in oracle) between ``` Select * from Table1 T1 Inner Join Table2 T2 On T1.ID = T2.ID ``` And ``` Select * from Table1 T1, Table2 T2 Where T1.ID = T2.ID ``` ?
No! The same execution plan, look at these two tables: ``` CREATE TABLE table1 ( id INT, name VARCHAR(20) ); CREATE TABLE table2 ( id INT, name VARCHAR(20) ); ``` The execution plan for the query using the inner join: ``` -- with inner join EXPLAIN PLAN FOR SELECT * FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.id; SELECT * FROM TABLE (DBMS_XPLAN.DISPLAY); -- 0 select statement -- 1 hash join (access("T1"."ID"="T2"."ID")) -- 2 table access full table1 -- 3 table access full table2 ``` And the execution plan for the query using a WHERE clause. ``` -- with where clause EXPLAIN PLAN FOR SELECT * FROM table1 t1, table2 t2 WHERE t1.id = t2.id; SELECT * FROM TABLE (DBMS_XPLAN.DISPLAY); -- 0 select statement -- 1 hash join (access("T1"."ID"="T2"."ID")) -- 2 table access full table1 -- 3 table access full table2 ```
121,656
<p>I have the following string and I would like to remove <code>&lt;bpt *&gt;*&lt;/bpt&gt;</code> and <code>&lt;ept *&gt;*&lt;/ept&gt;</code> (notice the additional tag content inside them that also needs to be removed) without using a XML parser (overhead too large for tiny strings).</p> <pre><code>The big &lt;bpt i="1" x="1" type="bold"&gt;&lt;b&gt;&lt;/bpt&gt;black&lt;ept i="1"&gt;&lt;/b&gt;&lt;/ept&gt; &lt;bpt i="2" x="2" type="ulined"&gt;&lt;u&gt;&lt;/bpt&gt;cat&lt;ept i="2"&gt;&lt;/u&gt;&lt;/ept&gt; sleeps. </code></pre> <p>Any regex in VB.NET or C# will do.</p>
[ { "answer_id": 121727, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 1, "selected": false, "text": "<p>I presume you want to drop the tag entirely?</p>\n\n<pre><code>(&lt;bpt .*?&gt;.*?&lt;/bpt&gt;)|(&lt;ept .*?&gt;.*?&lt;/ept&gt;)\n</code></pre>\n\n<p>The ? after the * makes it non-greedy, so it will try to match as few characters as possible.</p>\n\n<p>One problem you'll have is nested tags. stuff would not see the second because the first matched.</p>\n" }, { "answer_id": 121833, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 0, "selected": false, "text": "<p>Does the .NET regex engine support negative lookaheads? If yes, then you can use</p>\n\n<pre><code>(&lt;([eb])pt[^&gt;]+&gt;((?!&lt;/\\2pt&gt;).)+&lt;/\\2pt&gt;)\n</code></pre>\n\n<p>Which makes <em>The big black cat sleeps.</em> out of the string above if you remove all matches. However keep in mind that it will not work if you have nested <code>bpt</code>/<code>ept</code> elements.\nYou might also want to add <code>\\s</code> in some places to allow for extra whitespace in closing elements etc.</p>\n" }, { "answer_id": 121973, "author": "tyshock", "author_id": 16448, "author_profile": "https://Stackoverflow.com/users/16448", "pm_score": 4, "selected": true, "text": "<p>If you just want to remove all the tags from the string, use this (C#):</p>\n\n<pre><code>try {\n yourstring = Regex.Replace(yourstring, \"(&lt;[be]pt[^&gt;]+&gt;.+?&lt;/[be]pt&gt;)\", \"\");\n} catch (ArgumentException ex) {\n // Syntax error in the regular expression\n}\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>I decided to add on to my solution with a better option. The previous option would not work if there were embedded tags. This new solution should strip all &lt;**pt*> tags, embedded or not. In addition, this solution uses a back reference to the original [be] match so that the exact matching end tag is found. This solution also creates a reusable Regex object for improved performance so that each iteration does not have to recompile the Regex:</p>\n\n<pre><code>bool FoundMatch = false;\n\ntry {\n Regex regex = new Regex(@\"&lt;([be])pt[^&gt;]+&gt;.+?&lt;/\\1pt&gt;\");\n while(regex.IsMatch(yourstring) ) {\n yourstring = regex.Replace(yourstring, \"\");\n }\n} catch (ArgumentException ex) {\n // Syntax error in the regular expression\n}\n</code></pre>\n\n<p>ADDITIONAL NOTES:</p>\n\n<p>In the comments a user expressed worry that the '.' pattern matcher would be cpu intensive. While this is true in the case of a standalone greedy '.', the use of the non-greedy character '?' causes the regex engine to only look ahead until it finds the first match of the next character in the pattern versus a greedy '.' which requires the engine to look ahead all the way to the end of the string. I use <a href=\"http://www.regexbuddy.com/\" rel=\"noreferrer\">RegexBuddy</a> as a regex development tool, and it includes a debugger which lets you see the relative performance of different regex patterns. It also auto comments your regexes if desired, so I decided to include those comments here to explain the regex used above:</p>\n\n<pre><code> // &lt;([be])pt[^&gt;]+&gt;.+?&lt;/\\1pt&gt;\n// \n// Match the character \"&lt;\" literally «&lt;»\n// Match the regular expression below and capture its match into backreference number 1 «([be])»\n// Match a single character present in the list \"be\" «[be]»\n// Match the characters \"pt\" literally «pt»\n// Match any character that is not a \"&gt;\" «[^&gt;]+»\n// Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»\n// Match the character \"&gt;\" literally «&gt;»\n// Match any single character that is not a line break character «.+?»\n// Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»\n// Match the characters \"&lt;/\" literally «&lt;/»\n// Match the same text as most recently matched by backreference number 1 «\\1»\n// Match the characters \"pt&gt;\" literally «pt&gt;»\n</code></pre>\n" }, { "answer_id": 122070, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 1, "selected": false, "text": "<p>Why do you say the overhead is too large? Did you measure it? Or are you guessing?</p>\n\n<p>Using a regex instead of a proper parser is a shortcut that you may run afoul of when someone comes along with something like &lt;bpt foo=\"bar&gt;\"&gt;</p>\n" }, { "answer_id": 123770, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 0, "selected": false, "text": "<p>If you're going to use a regex to remove XML elements, you'd better be sure that your input XML doesn't use elements from different namespaces, or contain CDATA sections whose content you don't want to modify.</p>\n\n<p>The proper (i.e. both performant and correct) way to do this is with XSLT. An XSLT transform that copies everything except a specific element to the output is a trivial extension of the identity transform. Once the transform is compiled it will execute extremely quickly. And it won't contain any hidden defects.</p>\n" }, { "answer_id": 396338, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>is there any possible way to get a global solution of the regex.pattern for xml type of text? \nthat way i\"ll get rid of the replace function and shell use the regex. \nThe trouble is to analyze the &lt; > coming in order or not.. \nAlso replacing reserved chars as ' &amp; and so on.\nhere is the code\n 'handling special chars functions \n Friend Function ReplaceSpecChars(ByVal str As String) As String\n Dim arrLessThan As New Collection\n Dim arrGreaterThan As New Collection\n If Not IsDBNull(str) Then</p>\n\n<pre><code> str = CStr(str)\n If Len(str) &gt; 0 Then\n str = Replace(str, \"&amp;\", \"&amp;amp;\")\n str = Replace(str, \"'\", \"&amp;apos;\")\n str = Replace(str, \"\"\"\", \"&amp;quot;\")\n arrLessThan = FindLocationOfChar(\"&lt;\", str)\n arrGreaterThan = FindLocationOfChar(\"&gt;\", str)\n str = ChangeGreaterLess(arrLessThan, arrGreaterThan, str)\n str = Replace(str, Chr(13), \"chr(13)\")\n str = Replace(str, Chr(10), \"chr(10)\")\n End If\n Return str\nElse\n Return \"\"\nEnd If\n</code></pre>\n\n<p>End Function\n Friend Function ChangeGreaterLess(ByVal lh As Collection, ByVal gr As Collection, ByVal str As String) As String\n For i As Integer = 0 To lh.Count\n If CInt(lh.Item(i)) > CInt(gr.Item(i)) Then\n str = Replace(str, \"&lt;\", \"&lt;\") /////////problems////\n End If</p>\n\n<pre><code> Next\n\n\n str = Replace(str, \"&gt;\", \"&amp;gt;\")\n</code></pre>\n\n<p>End Function\n Friend Function FindLocationOfChar(ByVal chr As Char, ByVal str As String) As Collection\n Dim arr As New Collection\n For i As Integer = 1 To str.Length() - 1\n If str.ToCharArray(i, 1) = chr Then\n arr.Add(i)\n End If\n Next\n Return arr\n End Function</p>\n\n<p>got trouble at problem mark</p>\n\n<p>that's a standart xml with different tags i want to analyse..</p>\n" }, { "answer_id": 3834084, "author": "Eamon Nerbonne", "author_id": 42921, "author_profile": "https://Stackoverflow.com/users/42921", "pm_score": 0, "selected": false, "text": "<p>Have you measured this? I <em>have</em> run into performance issues using .NET's regex engine, but by contrast have parsed xml files of around 40GB <em>without</em> issue using the Xml parser (you will need to use XmlReader for larger strings, however).</p>\n\n<p>Please post a an actual code sample and mention your performance requirements: I doubt the <code>Regex</code> class is the best solution here if performance matters.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508/" ]
I have the following string and I would like to remove `<bpt *>*</bpt>` and `<ept *>*</ept>` (notice the additional tag content inside them that also needs to be removed) without using a XML parser (overhead too large for tiny strings). ``` The big <bpt i="1" x="1" type="bold"><b></bpt>black<ept i="1"></b></ept> <bpt i="2" x="2" type="ulined"><u></bpt>cat<ept i="2"></u></ept> sleeps. ``` Any regex in VB.NET or C# will do.
If you just want to remove all the tags from the string, use this (C#): ``` try { yourstring = Regex.Replace(yourstring, "(<[be]pt[^>]+>.+?</[be]pt>)", ""); } catch (ArgumentException ex) { // Syntax error in the regular expression } ``` EDIT: I decided to add on to my solution with a better option. The previous option would not work if there were embedded tags. This new solution should strip all <\*\*pt\*> tags, embedded or not. In addition, this solution uses a back reference to the original [be] match so that the exact matching end tag is found. This solution also creates a reusable Regex object for improved performance so that each iteration does not have to recompile the Regex: ``` bool FoundMatch = false; try { Regex regex = new Regex(@"<([be])pt[^>]+>.+?</\1pt>"); while(regex.IsMatch(yourstring) ) { yourstring = regex.Replace(yourstring, ""); } } catch (ArgumentException ex) { // Syntax error in the regular expression } ``` ADDITIONAL NOTES: In the comments a user expressed worry that the '.' pattern matcher would be cpu intensive. While this is true in the case of a standalone greedy '.', the use of the non-greedy character '?' causes the regex engine to only look ahead until it finds the first match of the next character in the pattern versus a greedy '.' which requires the engine to look ahead all the way to the end of the string. I use [RegexBuddy](http://www.regexbuddy.com/) as a regex development tool, and it includes a debugger which lets you see the relative performance of different regex patterns. It also auto comments your regexes if desired, so I decided to include those comments here to explain the regex used above: ``` // <([be])pt[^>]+>.+?</\1pt> // // Match the character "<" literally «<» // Match the regular expression below and capture its match into backreference number 1 «([be])» // Match a single character present in the list "be" «[be]» // Match the characters "pt" literally «pt» // Match any character that is not a ">" «[^>]+» // Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» // Match the character ">" literally «>» // Match any single character that is not a line break character «.+?» // Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?» // Match the characters "</" literally «</» // Match the same text as most recently matched by backreference number 1 «\1» // Match the characters "pt>" literally «pt>» ```
121,662
<p>Ok, so we have clients and those clients get to customize their web facing page. One option we are giving them is to be able to change the color of a graphic (it's like a framish-looking bar) using one of those hex wheels or whatever. </p> <p>So, I've thought about it, and I don't know where to start. I am sending comps out this week to my xhtml guy and I want to have the implementation done at least in my mind before I send things out. </p> <p>Something about System.Drawing sounds about right, but I've never worked with that before and it sounds hella complicated. Does anyone have an idea? </p> <p><strong>UPDATE:</strong> The color of an image will be changing. So if I want image 1 to be green, and image 2 to be blue, I go into my admin screen and enter those hex values (probably will give them an interface for it) and then when someone else looks at their page they will see the changes they made. Kind of like customizing a facebook or myspace page (OMFGz soooo Werb 2.0)</p>
[ { "answer_id": 121692, "author": "Aaron Jensen", "author_id": 11229, "author_profile": "https://Stackoverflow.com/users/11229", "pm_score": 1, "selected": false, "text": "<p>What exactly will be changing? Depending on what's changing you may be able to overlay a transparent png on top of an html background color. Just change the background color and the logo color will change. Of course this limits what you can change, but you'd be surprised how much you can get away with.</p>\n\n<p>And yes, the alternative is to paint the image on the web server. <a href=\"http://www.hanselman.com/blog/ASPNETFuturesGeneratingDynamicImagesWithHttpHandlersGetsEasier.aspx\" rel=\"nofollow noreferrer\">Here's a post on it from hanselman</a>.</p>\n" }, { "answer_id": 121698, "author": "Max Cantor", "author_id": 16034, "author_profile": "https://Stackoverflow.com/users/16034", "pm_score": 0, "selected": false, "text": "<p>I've done stuff like this in PHP before, and I used ImageMagick and GD libraries. I'm not sure if ASP and C# can plug into that using the .NET framework, but it's a start.</p>\n" }, { "answer_id": 121704, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 0, "selected": false, "text": "<p>System.Drawing is GDI+ based. Only useful if you're drawing bitmaps in teh worlda web.</p>\n" }, { "answer_id": 121711, "author": "Matt", "author_id": 17759, "author_profile": "https://Stackoverflow.com/users/17759", "pm_score": 1, "selected": false, "text": "<p><strong>EDIT (since you changed the title):</strong></p>\n\n<p><strong>If you have a small number of colours on the hex-wheel thing then you could simply use JavaScript to change the image source from some pre-made graphics.</strong></p>\n\n<p><strong>If you have a large or changeable set of colours for the user to choose from then I'd use an AJAX call to generate the graphic using the relevant ASP functions you'll find online or in a book.</strong></p>\n\n<hr>\n\n<p>We'd need to see the frame or graphic that you're talking about.</p>\n\n<p>Might be doable <strong>client-side</strong> with <strong>CSS</strong> and <strong>JavaScript</strong>, or might need to be a <strong>server-side</strong> graphic generation using <strong>PHP</strong> or <strong>ASP</strong> etc.</p>\n" }, { "answer_id": 121736, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 0, "selected": false, "text": "<p>Your solution will depend on how complex the graphics are. If you have simple graphics (you can make with MS Paint), then you can use the System.Drawing namespace to re-create the image fairly reliably.</p>\n<p>If you have complex graphics, like ones made in photoshop or Paint.NET with multiple layers, you may be better off by allowing the client a choice of only a few colors (4-8-16) and pre-make the graphics to match the selections.</p>\n" }, { "answer_id": 121753, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 1, "selected": false, "text": "<p>You maybe search for <a href=\"http://www.allscoop.com/tools/Web-Colors/web-colors.php\" rel=\"nofollow noreferrer\">this example</a>. But I'm not sure.</p>\n" }, { "answer_id": 121789, "author": "JohnIdol", "author_id": 1311500, "author_profile": "https://Stackoverflow.com/users/1311500", "pm_score": 1, "selected": false, "text": "<p>Standard way to obtain something like this is linking to different CSS files (or classes) depending on the user choice (You probably want to store the user choice and retrieve whenever the same user logs in, but that's out of scope here).</p>\n\n<p>If you're using ASP.NET you could use Themes as an optimized and centralized way to control presentation for your web application. You can have stylesheets in your themes and easily programmatically switch between themes, automatically applying associated stylesheets.</p>\n\n<p>To see how to define ASP.NET page themes have a look at this link:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms247256.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms247256.aspx</a> </p>\n\n<p>To see how to programmatically switch between themes follow this other link:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/0yy5hxdk(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/0yy5hxdk(VS.80).aspx</a></p>\n" }, { "answer_id": 122354, "author": "clweeks", "author_id": 13748, "author_profile": "https://Stackoverflow.com/users/13748", "pm_score": 2, "selected": true, "text": "<p>I'm sort of intuiting that you'll have a black on white bitmap that you use as the base image. The client can then select any other color combination. This may not be exactly your situation, but it should get us started. (The code below is VB -- it's what I know, but converting to C# should be trivial for you.)</p>\n\n<pre><code>Imports System.Drawing\n\nPrivate Function createImage(ByVal srcPath As String, ByVal fg As Color, ByVal bg As Color) As Bitmap\n Dim img As New Bitmap(srcPath)\n For x As Int16 = 0 To img.Width\n For y As Int16 = 0 To img.Height\n If img.GetPixel(x, y) = Color.Black Then\n img.SetPixel(x, y, fg)\n Else\n img.SetPixel(x, y, bg)\n End If\n Next\n Next\n Return img\nEnd Function\n</code></pre>\n\n<p>And then you can do whatever with the image...</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140/" ]
Ok, so we have clients and those clients get to customize their web facing page. One option we are giving them is to be able to change the color of a graphic (it's like a framish-looking bar) using one of those hex wheels or whatever. So, I've thought about it, and I don't know where to start. I am sending comps out this week to my xhtml guy and I want to have the implementation done at least in my mind before I send things out. Something about System.Drawing sounds about right, but I've never worked with that before and it sounds hella complicated. Does anyone have an idea? **UPDATE:** The color of an image will be changing. So if I want image 1 to be green, and image 2 to be blue, I go into my admin screen and enter those hex values (probably will give them an interface for it) and then when someone else looks at their page they will see the changes they made. Kind of like customizing a facebook or myspace page (OMFGz soooo Werb 2.0)
I'm sort of intuiting that you'll have a black on white bitmap that you use as the base image. The client can then select any other color combination. This may not be exactly your situation, but it should get us started. (The code below is VB -- it's what I know, but converting to C# should be trivial for you.) ``` Imports System.Drawing Private Function createImage(ByVal srcPath As String, ByVal fg As Color, ByVal bg As Color) As Bitmap Dim img As New Bitmap(srcPath) For x As Int16 = 0 To img.Width For y As Int16 = 0 To img.Height If img.GetPixel(x, y) = Color.Black Then img.SetPixel(x, y, fg) Else img.SetPixel(x, y, bg) End If Next Next Return img End Function ``` And then you can do whatever with the image...
121,665
<p>How does one invoke a groovy method that prints to stdout, appending the output to a string?</p>
[ { "answer_id": 121776, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 5, "selected": true, "text": "<p>This demonstrates how you can do this. Paste this into a Groovy script file and run it. You will see the first call functions as normal. The second call produces no results. Finally, the last step in the main prints the results of the second call that were redirected to a ByteArrayOutputStream.</p>\n\n<p>Have fun!</p>\n\n<pre><code>void doSomething() {\n println \"i did something\"\n}\n\nprintln \"normal call\\n---------------\"\ndoSomething()\nprintln \"\"\n\ndef buf = new ByteArrayOutputStream()\ndef newOut = new PrintStream(buf)\ndef saveOut = System.out\n\nprintln \"redirected call\\n---------------\"\nSystem.out = newOut\ndoSomething()\nSystem.out = saveOut\nprintln \"\"\n\nprintln \"results of call\\n---------------\"\nprintln buf.toString()\n</code></pre>\n" }, { "answer_id": 198786, "author": "Robert Fischer", "author_id": 27561, "author_profile": "https://Stackoverflow.com/users/27561", "pm_score": 1, "selected": false, "text": "<p>I'm not sure what you mean by \"appending the output to a string\", but you can print to standard out using \"print\" or \"println\".</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How does one invoke a groovy method that prints to stdout, appending the output to a string?
This demonstrates how you can do this. Paste this into a Groovy script file and run it. You will see the first call functions as normal. The second call produces no results. Finally, the last step in the main prints the results of the second call that were redirected to a ByteArrayOutputStream. Have fun! ``` void doSomething() { println "i did something" } println "normal call\n---------------" doSomething() println "" def buf = new ByteArrayOutputStream() def newOut = new PrintStream(buf) def saveOut = System.out println "redirected call\n---------------" System.out = newOut doSomething() System.out = saveOut println "" println "results of call\n---------------" println buf.toString() ```
121,676
<p>Inside a .NET 3.5 web app running impersonation I am trying to execute a process via:</p> <pre><code>var process = new Process { StartInfo = { CreateNoWindow = true, FileName = "someFileName", Domain = "someDomain", Username = "someUserName", Password = securePassword, UseShellExecute = false } }; process.Start(); </code></pre> <p>-Changing the trust mode to full in web.config did not fix.</p> <p>-Note the var securePassword is a secureString set up earlier in the code.</p> <p>This throws an exception with 'Access is Denied' as its message. If I remove the username and password information, the exception goes away, but the process starts as aspnet_wp instead of the user I need it to.</p> <p>I've seen this issue in multiple forums and never seen a solution provided. Any ideas?</p>
[ { "answer_id": 121721, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 0, "selected": false, "text": "<p>I ran into the same problem that you did on a project. There <em>should</em> be a way to spawn a process out of your web app with given credentials, but in practice, it's a kludge at best. What I wound up finally doing was just having the app push information to an MSMQ and having a windows service that popped items of the Queue an serviced the requests.</p>\n\n<p>Even when you appliation is impersonating, it still wants to run under theaspnet user account.</p>\n" }, { "answer_id": 121763, "author": "Mike L", "author_id": 12085, "author_profile": "https://Stackoverflow.com/users/12085", "pm_score": 2, "selected": false, "text": "<p>You can use ProcessStartInfo which allows you to specify credentials. The trick is that the password is a secure string, so you have to pass it as a byte array.</p>\n\n<p>The code might look something like:</p>\n\n<pre><code>Dim startInfo As New ProcessStartInfo(programName)\n With startInfo\n .Domain = \"test.local\"\n .WorkingDirectory = My.Application.Info.DirectoryPath\n .UserName = \"testuser\"\n Dim pwd As New Security.SecureString\n For Each c As Char In \"password\"\n pwd.AppendChar(c)\n Next\n .Password = pwd\n\n 'If you provide a value for the Password property, the UseShellExecute property must be false, or an InvalidOperationException will be thrown when the Process..::.Start(ProcessStartInfo) method is called. \n .UseShellExecute = False\n\n .WindowStyle = ProcessWindowStyle.Hidden\n End With\n</code></pre>\n" }, { "answer_id": 121846, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 0, "selected": false, "text": "<p>Check the <a href=\"http://msdn.microsoft.com/en-us/library/87x8e4d1.aspx\" rel=\"nofollow noreferrer\" title=\"MSDN - ASP.NET Code Access Security\">Code Access Security</a> level as <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx\" rel=\"nofollow noreferrer\" title=\"MSDN - System.Diagnostics.Process\">Process</a> requires <code>Full Trust</code>. Your web application may be running in a partial trust setting.</p>\n\n<p>From the Process MSDN page:</p>\n\n<blockquote>\n <p><b>Permissions</b><br /><br />\n * <b>LinkDemand</b><br />\n for full trust for the immediate caller. This class cannot be used by partially trusted code.<br /><br />\n * <b>InheritanceDemand</b><br />\n for full trust for inheritors. This class cannot be inherited by partially trusted code. </p>\n</blockquote>\n" }, { "answer_id": 122080, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I wanted to mention that I have tried the code at\n<a href=\"http://odetocode.com/Blogs/scott/archive/2004/10/28/602.aspx\" rel=\"nofollow noreferrer\">this site</a>\nincluding the updated code mentioned in the comments. This code runs the process as the impersonated identity (which is really all I need), but the redirecting of the standard error fails -- so this link could be useful to those not concerned with dealing with the stderr.</p>\n" }, { "answer_id": 125593, "author": "Brian ONeil", "author_id": 21371, "author_profile": "https://Stackoverflow.com/users/21371", "pm_score": 1, "selected": false, "text": "<p>Not sure if this is it, but I had a related problem and the answer was that the account didn't have permission to impersonate on the machine. This can be changed by adding the account to the Policy \"Impersonate a client after authentication\" using the local policy manager on the machine.</p>\n" }, { "answer_id": 148855, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I went a different way and put the whole application in its own app-pool running as the user we were originally impersonating. Now, when asp.net spawns a new process, it spawns under the context of the user instead of aspnet_wp. Not the exact solution to the problem I posted, but it worked for our situation.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Inside a .NET 3.5 web app running impersonation I am trying to execute a process via: ``` var process = new Process { StartInfo = { CreateNoWindow = true, FileName = "someFileName", Domain = "someDomain", Username = "someUserName", Password = securePassword, UseShellExecute = false } }; process.Start(); ``` -Changing the trust mode to full in web.config did not fix. -Note the var securePassword is a secureString set up earlier in the code. This throws an exception with 'Access is Denied' as its message. If I remove the username and password information, the exception goes away, but the process starts as aspnet\_wp instead of the user I need it to. I've seen this issue in multiple forums and never seen a solution provided. Any ideas?
You can use ProcessStartInfo which allows you to specify credentials. The trick is that the password is a secure string, so you have to pass it as a byte array. The code might look something like: ``` Dim startInfo As New ProcessStartInfo(programName) With startInfo .Domain = "test.local" .WorkingDirectory = My.Application.Info.DirectoryPath .UserName = "testuser" Dim pwd As New Security.SecureString For Each c As Char In "password" pwd.AppendChar(c) Next .Password = pwd 'If you provide a value for the Password property, the UseShellExecute property must be false, or an InvalidOperationException will be thrown when the Process..::.Start(ProcessStartInfo) method is called. .UseShellExecute = False .WindowStyle = ProcessWindowStyle.Hidden End With ```
121,700
<p>In an attempt to add some parameter validation and correct usage semantics to our application, we are trying to add correct exception handling to our .NET applications.</p> <p>My question is this: When throwing exceptions in ADO.NET if a particular query returns no data or the data could not be found, what type of exception should I use?</p> <p>Psuedocode: (read, don't scrutinize the semantics of the code, I know it won't compile)</p> <pre><code>public DataSet GetData(int identifier) { dataAdapter.Command.Text = "Select * from table1 Where ident = " + identifier.toString(); DataSet ds = dataAdapter.Fill(ds); if (ds.table1.Rows.Count == 0) throw new Exception("Data not found"); return ds; } </code></pre>
[ { "answer_id": 121746, "author": "Richard Yorkshire", "author_id": 21001, "author_profile": "https://Stackoverflow.com/users/21001", "pm_score": 2, "selected": false, "text": "<p>As far as ADO.net is concerned, a query that returns zero rows is not an error. If your application wishes to treat such a query as an error, you should create your own exception class by inheriting from Exception.</p>\n\n<pre><code>public class myException : Exception\n{\n public myException(string s) : base() \n {\n this.MyReasonMessage = s;\n }\n}\n\npublic void GetData(int identifier)\n{\n dataAdapter.Command.Text = \"Select * from table1 Where ident = \" + identifier.toString();\n DataSet ds = dataAdapter.Fill(ds);\n if (ds.table1.Rows.Count == 0)\n throw new myException(\"Data not found\");\n}\n</code></pre>\n" }, { "answer_id": 121809, "author": "Johan Buret", "author_id": 15366, "author_profile": "https://Stackoverflow.com/users/15366", "pm_score": 2, "selected": false, "text": "<p>You really should define your own exception : DataNotFoundException.</p>\n\n<p>You should not use the basic class Exception, since when you will catch it in calling code, you will write something like</p>\n\n<pre><code>try\n{\n int i;\n GetData(i);\n\n}\ncatch(Exception e) //will catch many many exceptions\n{\n //Handle gracefully the \"Data not Found\" case;\n //Whatever else happens will get caught and ignored\n}\n</code></pre>\n\n<p>Where as catching only your DataNotFoundEXception will get only the case you really want to handle.</p>\n\n<pre><code>try\n{\n int i;\n GetData(i);\n\n}\ncatch(DataNotFoundException e) \n{\n //Handle gracefully the \"Data not Found\" case;\n} //Any other exception will bubble up\n</code></pre>\n\n<p>There is a class aptly named SqlException, when there are troubles with the SQL engine but it's better not overload it with your business logic </p>\n" }, { "answer_id": 122021, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 4, "selected": true, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/ms229021(VS.80).aspx\" rel=\"nofollow noreferrer\">MSDN guidelines</a> state:</p>\n\n<ul>\n<li><p>Consider throwing existing exceptions residing in the System namespaces instead of creating custom exception types.</p></li>\n<li><p>Do create and throw custom exceptions if you have an error condition that can be programmatically handled in a different way than any other existing exceptions. Otherwise, throw one of the existing exceptions.</p></li>\n<li><p>Do not create and throw new exceptions just to have your team's exception.</p></li>\n</ul>\n\n<p>There is no hard and fast rule: but if you have a scenario for treating this exception differently, consider creating a custom exception type, such as DataNotFoundException <a href=\"https://stackoverflow.com/questions/121700/what-exception-should-be-thrown-when-an-adonet-query-cannot-retrieve-the-reques#121809\">as suggested by Johan Buret</a>.</p>\n\n<p>Otherwise you might consider throwing one of the existing exception types, such as System.Data.DataException or possibly even System.Collections.Generic.KeyNotFoundException.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15766/" ]
In an attempt to add some parameter validation and correct usage semantics to our application, we are trying to add correct exception handling to our .NET applications. My question is this: When throwing exceptions in ADO.NET if a particular query returns no data or the data could not be found, what type of exception should I use? Psuedocode: (read, don't scrutinize the semantics of the code, I know it won't compile) ``` public DataSet GetData(int identifier) { dataAdapter.Command.Text = "Select * from table1 Where ident = " + identifier.toString(); DataSet ds = dataAdapter.Fill(ds); if (ds.table1.Rows.Count == 0) throw new Exception("Data not found"); return ds; } ```
The [MSDN guidelines](http://msdn.microsoft.com/en-us/library/ms229021(VS.80).aspx) state: * Consider throwing existing exceptions residing in the System namespaces instead of creating custom exception types. * Do create and throw custom exceptions if you have an error condition that can be programmatically handled in a different way than any other existing exceptions. Otherwise, throw one of the existing exceptions. * Do not create and throw new exceptions just to have your team's exception. There is no hard and fast rule: but if you have a scenario for treating this exception differently, consider creating a custom exception type, such as DataNotFoundException [as suggested by Johan Buret](https://stackoverflow.com/questions/121700/what-exception-should-be-thrown-when-an-adonet-query-cannot-retrieve-the-reques#121809). Otherwise you might consider throwing one of the existing exception types, such as System.Data.DataException or possibly even System.Collections.Generic.KeyNotFoundException.
121,715
<p>Java Newbie here. I have a JFrame that I added to my netbeans project, and I've added the following method to it, which creates a JTable. Problem is, for some reason when I call this method, the JTable isn't displayed. Any suggestions?</p> <pre><code>public void showFromVectors(Vector colNames, Vector data) { jt = new javax.swing.JTable(data, colNames); sp = new javax.swing.JScrollPane(jt); //NB: "this" refers to my class DBGridForm, which extends JFrame this.add(sp,java.awt.BorderLayout.CENTER); this.setSize(640,480); } </code></pre> <p>The method is called in the following context:</p> <pre><code>DBGridForm gf = new DBGridForm(); //DBGridForm extends JFrame DBReader.outMatchesTable(gf); gf.setVisible(true); </code></pre> <p>... where DBReader.outMatchesTable() is defined as</p> <pre><code>static public void outMatchesTable(DBGridForm gf) { DBReader ddb = new DBReader(); ddb.readMatchesTable(null); gf.showFromVectors(ddb.lastRsltColNames, ddb.lastRsltData); } </code></pre> <p>My guess is I'm overlooking something, either about the swing classes I'm using, or about Java. Any ideas?</p>
[ { "answer_id": 121777, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 2, "selected": true, "text": "<p>\"this\" in your context is unclear. Is it inside an applet? a JFrame?</p>\n\n<p>You may be having a layout issue, make sure you've called setLayout on your class with a new borderlayout.</p>\n\n<p>In a swing application, you'd want to use getRootContentPane().add() instead of a raw add(), depending on the version.</p>\n\n<p>Java tutorial on adding top-level content: <a href=\"http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html\" rel=\"nofollow noreferrer\">http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html</a></p>\n" }, { "answer_id": 123549, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 0, "selected": false, "text": "<p>If you are not running on the event thread, it could be a problem--I've seen that cause stuff not to display.</p>\n\n<p>If this code is called in response to an AWT event (mouse click, button press, ...) then that's not the problem, but if it's still the same thread that started your app, or this code is running off a timer, could very well be.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11820/" ]
Java Newbie here. I have a JFrame that I added to my netbeans project, and I've added the following method to it, which creates a JTable. Problem is, for some reason when I call this method, the JTable isn't displayed. Any suggestions? ``` public void showFromVectors(Vector colNames, Vector data) { jt = new javax.swing.JTable(data, colNames); sp = new javax.swing.JScrollPane(jt); //NB: "this" refers to my class DBGridForm, which extends JFrame this.add(sp,java.awt.BorderLayout.CENTER); this.setSize(640,480); } ``` The method is called in the following context: ``` DBGridForm gf = new DBGridForm(); //DBGridForm extends JFrame DBReader.outMatchesTable(gf); gf.setVisible(true); ``` ... where DBReader.outMatchesTable() is defined as ``` static public void outMatchesTable(DBGridForm gf) { DBReader ddb = new DBReader(); ddb.readMatchesTable(null); gf.showFromVectors(ddb.lastRsltColNames, ddb.lastRsltData); } ``` My guess is I'm overlooking something, either about the swing classes I'm using, or about Java. Any ideas?
"this" in your context is unclear. Is it inside an applet? a JFrame? You may be having a layout issue, make sure you've called setLayout on your class with a new borderlayout. In a swing application, you'd want to use getRootContentPane().add() instead of a raw add(), depending on the version. Java tutorial on adding top-level content: <http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html>