qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
336,909 | <p>I'm looking for a method to grep for multiple atoms e.g. "foo" and "bar".
I'm aware i can use <br />
<code>grep 'foo' file | grep 'bar'</code><br />
to get both of them but i was wondering if there was a more efficient way. Any googleing seems to only throw results for an 'or' based search rather than 'and'. </p>
| [
{
"answer_id": 336920,
"author": "activout.se",
"author_id": 20444,
"author_profile": "https://Stackoverflow.com/users/20444",
"pm_score": 2,
"selected": false,
"text": "egrep '(foo.*bar|bar.*foo)'\n# or\ngrep -E '(foo.*bar|bar.*foo)'\n"
},
{
"answer_id": 336926,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 1,
"selected": false,
"text": "grep grep"
},
{
"answer_id": 336947,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "egrep 'foo.*bar|bar.*foo' allan@allan-desktop:~$ time egrep 'foo.*bar|bar.*foo' foobar | wc -l\n2000\nreal 0m0.006s\nuser 0m0.004s\nsys 0m0.004s\n\nallan@allan-desktop:~$ time fgrep 'foo' foobar | fgrep 'bar' | wc -l\n2000\nreal 0m0.039s\nuser 0m0.000s\nsys 0m0.000s\n\nallan@allan-desktop:~$ time egrep 'foo.*bar|bar.*foo' foobar | wc -l\n2000\nreal 0m0.006s\nuser 0m0.004s\nsys 0m0.008s\n\nallan@allan-desktop:~$ time fgrep 'foo' foobar | fgrep 'bar' | wc -l\n2000\nreal 0m0.005s\nuser 0m0.004s\nsys 0m0.004s\n foo-bar\nbar-dgfjhdgjhdgdfgdjghdjghdfg-foo\n allan@allan-desktop:~$ time egrep 'foo.*bar|bar.*foo' foobar | wc -l\n 100000\n real 0m0.135s\n user 0m0.136s\n sys 0m0.012s\nallan@allan-desktop:~$ time fgrep 'foo' foobar | fgrep 'bar' | wc -l\n 100000\n real 0m0.034s\n user 0m0.048s\n sys 0m0.012s\nallan@allan-desktop:~$ time egrep 'foo.*bar|bar.*foo' foobar | wc -l\n 100000\n real 0m0.151s\n user 0m0.144s\n sys 0m0.000s\nallan@allan-desktop:~$ time fgrep 'foo' foobar | fgrep 'bar' | wc -l\n 100000\n real 0m0.046s\n user 0m0.044s\n sys 0m0.012s\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42789/"
] |
336,919 | <p>The code I have pasted below is meant to display images on the middle 2 links without text and go back to text on the reset and fourth link. I have set display:none for the span tag only, but it does nothing. Is there anyway to do what I am after simply, without using a framework?</p>
<p>edit: example</p>
<pre><code><html>
<head>
<style type="text/css">
.class1{color:#000; background-image:url('1.jpg');}
.class1 span { display: none;}
.class2{color:#00f; background-image:url('2.jpg');}
.class2 span { display: none;}
.class3{color:#0f0; background-image:url('1.jpg');}
.class3 span { display: none;}
.class4{color:#f00;}
</style>
</head>
<body>
<script type="text/javascript">
function sbox(divid, classname)
{
document.getElementById(divid).className=classname;
}
</script>
<div>
<a href="#" onclick="sbox('div1','class1');return false;">Reset</a><br/>
<a href="#" onclick="sbox('div1','class2');return false;">try here</a><br/>
<a href="#" onclick="sbox('div1','class3'); return false;">or here</a><br/>
<a href="#" onclick="sbox('div1','class4');return false;">or maybe here</a>
</div>
<div id="div1" class="class4"><span id="div1_text">Blah blah blah</span></div>
</body>
</html>
</code></pre>
| [
{
"answer_id": 336939,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": true,
"text": "rel /* in case color needs to apply to other elements */\n .class1 { color: #000; }\n\n div .class1 {\n background-image:url('1.jpg');\n width: 60px;\n height: 30px;\n }\n\n div .class1 span { display: none;}\n"
},
{
"answer_id": 336943,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 0,
"selected": false,
"text": "<link>"
},
{
"answer_id": 336952,
"author": "meleyal",
"author_id": 4196,
"author_profile": "https://Stackoverflow.com/users/4196",
"pm_score": 0,
"selected": false,
"text": "rel"
},
{
"answer_id": 337022,
"author": "DisgruntledGoat",
"author_id": 37947,
"author_profile": "https://Stackoverflow.com/users/37947",
"pm_score": 0,
"selected": false,
"text": "<a href=\"...\" rel=\"next\">Next</a> <a href=\"...\" rev=\"prev\">Prev</a> em strong code"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
336,922 | <p>Is this still the recommended library in use? ThickBox 3.1</p>
| [
{
"answer_id": 336939,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": true,
"text": "rel /* in case color needs to apply to other elements */\n .class1 { color: #000; }\n\n div .class1 {\n background-image:url('1.jpg');\n width: 60px;\n height: 30px;\n }\n\n div .class1 span { display: none;}\n"
},
{
"answer_id": 336943,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 0,
"selected": false,
"text": "<link>"
},
{
"answer_id": 336952,
"author": "meleyal",
"author_id": 4196,
"author_profile": "https://Stackoverflow.com/users/4196",
"pm_score": 0,
"selected": false,
"text": "rel"
},
{
"answer_id": 337022,
"author": "DisgruntledGoat",
"author_id": 37947,
"author_profile": "https://Stackoverflow.com/users/37947",
"pm_score": 0,
"selected": false,
"text": "<a href=\"...\" rel=\"next\">Next</a> <a href=\"...\" rev=\"prev\">Prev</a> em strong code"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41291/"
] |
336,925 | <p>I have a number of heroshot images, that have a modal popup when clicked.
I'm trying to get my cursor to turn into magnifying glass whenever it is moved over the image. The following CSS does not appear to work even though my <code>magnify.cur</code> is present in the right location.</p>
<pre><code>a.heroshot img {
cursor:url(/img/magnify.cur), pointer;
}
</code></pre>
<p>Has anyone ever done anything similar? I don't mind a JavaScript solution if one exists.</p>
<p><strong>EDIT</strong>: It works in Safari, but not in Firefox.</p>
| [
{
"answer_id": 336931,
"author": "activout.se",
"author_id": 20444,
"author_profile": "https://Stackoverflow.com/users/20444",
"pm_score": 2,
"selected": false,
"text": "a.heroshot img {\ncursor:url('/img/magnify.cur'), pointer;\n}\n"
},
{
"answer_id": 337266,
"author": "isani",
"author_id": 12154,
"author_profile": "https://Stackoverflow.com/users/12154",
"pm_score": 6,
"selected": true,
"text": "-moz-zoom-in cursor:url(/img/magnify.cur), -moz-zoom-in, auto;\n"
},
{
"answer_id": 350198,
"author": "Chris J Allen",
"author_id": 26107,
"author_profile": "https://Stackoverflow.com/users/26107",
"pm_score": 3,
"selected": false,
"text": "a.heroshot img {\ncursor:url(/img/layout/backgrounds/moz-zoom.gif), -moz-zoom-in;\n}\n"
},
{
"answer_id": 16841039,
"author": "Kevin Borders",
"author_id": 1676044,
"author_profile": "https://Stackoverflow.com/users/1676044",
"pm_score": 3,
"selected": false,
"text": "cursor: -webkit-zoom-in;\ncursor: -moz-zoom-in;\ncursor: zoom-in;\n"
},
{
"answer_id": 22090970,
"author": "user3335780",
"author_id": 3335780,
"author_profile": "https://Stackoverflow.com/users/3335780",
"pm_score": 0,
"selected": false,
"text": " #myid{cursor:url('myimage.png') , auto}\n #myid{cursor:url('myimage.png') , auto}\n #myid{cursor:url('myimage.png') ,url('myimage2.gif') , auto} etc\n #myid{cursor:url('myimage.png')}\n"
},
{
"answer_id": 37932053,
"author": "SandroMarques",
"author_id": 3691530,
"author_profile": "https://Stackoverflow.com/users/3691530",
"pm_score": 2,
"selected": false,
"text": "a.heroshot img {\n cursor: url(/img/zoom_in.png), url(/img/zoom_in.cur), pointer; \n cursor: url(/img/zoom_in.png), -moz-zoom-in; \n cursor: url(/img/zoom_in.png), -webkit-zoom-in;\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
336,942 | <p>I hava an ajax application that will not display an image, or make a popup window from html stored in a file.</p>
<p>This is the code I am usiong for the popup:</p>
<pre><code>echo '<script>
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write(' . json_encode($row2["ARTICLE_DESC"]) . ');
child1.document.close();
}
</script>';
</code></pre>
<p>And the resulting html</p>
<pre><code><script>
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write("<!-- +++++++++++++++++++++++++ Bitte \u00e4ndern Sie im eigenen Interesse nichts an diesem Code! ++++++++++++++++++++++++ -->\n<!-- +++++++++++++++++++++++++ Das kann massive Fehldarstellungen ihrer Auktion zur Folge haben! +++++++++++++++++++ -->\n<!-- +++++++++++++++++++++++++ ++++++++++++++++++++++++++ Ihr Supreme Team +++++++++++++++++++++++++++++++++++++++++ -->\n");
child1.document.close();
}
</script><br />
<b>Notice</b>: Undefined index: CATEGORY in <b>C:\Programme\EasyPHP 2.0b1\www\get_auction.php</b> on line <b>39</b><br />
<div id='leftlayer'>
<strong>Article Number</strong> 220288560247
<p><strong>Article Name</strong></p> Ed Hardy Herren Shirt Rock & Roll Weiss XXL Neu & OVP
<p><strong>Subtitle</strong></p>
<p><strong>Username</strong></p> fashionticker1
<p><strong>Total Selling</strong></p> 1
<p><strong>Total Sold</strong></p> 0
<p><strong>Category</strong></p>
<p><strong>Highest Bidder</strong></p> 0
</div>
<div class='leftlayer2'>
<strong>Current Bid</strong> 0.00
<p><strong>Start Price</strong></p> 49.00
<p><strong>Buyitnow Price</strong></p> 59.00
<p><strong>Bid Count</strong></p> 0
<p><strong>Start Date</strong></p> 1.10.2008 16:22:09
<p><strong>End Date</strong></p> 6.10.2008 16:22:09
<p><strong>Original End</strong></p> 6.10.2008 16:22:09
<p><strong>Auction Type</strong></p> 1
</div>
<div class='leftlayer2'>
<strong>Private Auction</strong></p> 0
<p><strong>Paypal Accepted</strong></p> 0
<p><strong>Auction Watched</strong></p> 0
<p><strong>Finished</strong></p> 1
<p><strong>Country</strong></p>
<br>
<br>
<style ty
<p><strong>Location</strong></p> float: right;
<p><strong>Conditions</strong></p> margin: 0px;
</div>
<div class='leftlayer2'>
<strong>Auction Revised</strong></p> 0
<p><strong>Cancelled</strong></p> 0
<p><strong>Shipping to</strong></p> padding:5px;
<p><strong>Fee Insertion</strong></p> 0.00
<p><strong>Fee Final</strong></p> 0.00
<p><strong>Fee Listing</strong></p> 0.00
<p><a href='#' onclick='makewindows(); return false;'>Click for full description </a></p>
</div><div id='rightlayer'>Picture Picture
<img src=http://storage.supremeauction.com/flash/ebay2/10/49/76/10497654/13895964e.jpg>
</div>
</code></pre>
<p>The img src is a valid location and opens in a browser fine, but will not display in the page. I get a script error which does not state any details.</p>
<p>edit: When calling the file alone, not as part of the application, the resulting html file generates a link that creates a popup window, but the source shows that nothing is being assigned to the window:</p>
<pre><code>child1.document.write("");
</code></pre>
<p>I made changes to the img src line:</p>
<pre><code><img src='".$lastImg."'>
</code></pre>
<p>Which results in the html returning:</p>
<pre><code><img src=''>
</code></pre>
| [
{
"answer_id": 337221,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 0,
"selected": false,
"text": "<script>...</script> eval()"
},
{
"answer_id": 337294,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 2,
"selected": true,
"text": "<style ty\n <p><strong>Location</strong></p> float: right;\n\n <p><strong>Conditions</strong></p> margin: 0px;\n <style> float: right;"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
336,946 | <p>Does the MySQL command :</p>
<pre><code>FLUSH TABLES;
</code></pre>
<p>flush every table in the current database, or every table on the server ?</p>
<p>I'm using MySQL 5.0 - the <a href="http://dev.mysql.com/doc/refman/5.0/en/flush.html" rel="noreferrer">documentation</a> is unclear, although it does mention that :</p>
<pre><code>FLUSH TABLES WITH READ LOCK;
</code></pre>
<p>will do so for ALL databases.</p>
<p>Thanks.</p>
| [
{
"answer_id": 341414,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": false,
"text": "FLUSH TABLES mysql_server/sql/sql_base.cc FLUSH TABLES FLUSH TABLES"
},
{
"answer_id": 65326082,
"author": "Jihad Mehdi",
"author_id": 3120117,
"author_profile": "https://Stackoverflow.com/users/3120117",
"pm_score": 0,
"selected": false,
"text": "FLUSH TABLES FLUSH TABLES tbl_name [, tbl_name] ...\n READ LOCK FLUSH TABLES tbl_name [, tbl_name] ... WITH READ LOCK\n SHOW TABLES FLUSH TABLES db_name.table_1, \n db_name.table_2,\n db_name.table_3,\n ...\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36214/"
] |
336,948 | <p>When does script added to the page with <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx" rel="nofollow noreferrer">Page.ClientScript.RegisterStartupScript()</a> actually run? MSDN states "when the page finishes loading but before the page's <code>OnLoad</code> event is raised" but this isn't much detail.</p>
<p>For example, can a script added with <code>RegisterStartupScript</code> assume the DOM tree has been built? Does the behaviour differ between different browser implementations and how?</p>
| [
{
"answer_id": 341414,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": false,
"text": "FLUSH TABLES mysql_server/sql/sql_base.cc FLUSH TABLES FLUSH TABLES"
},
{
"answer_id": 65326082,
"author": "Jihad Mehdi",
"author_id": 3120117,
"author_profile": "https://Stackoverflow.com/users/3120117",
"pm_score": 0,
"selected": false,
"text": "FLUSH TABLES FLUSH TABLES tbl_name [, tbl_name] ...\n READ LOCK FLUSH TABLES tbl_name [, tbl_name] ... WITH READ LOCK\n SHOW TABLES FLUSH TABLES db_name.table_1, \n db_name.table_2,\n db_name.table_3,\n ...\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6651/"
] |
336,960 | <p>Can you tell me if there anybody has implemented a <strong>custom validator for checking that one of two (or N)</strong> input fields are filled?</p>
<pre><code> "Insert phone number or email address"
</code></pre>
<p>I'm using ASP.NET (Ajax) 3.5, the ajaxToolkit:ValidatorCalloutExtender (and jQuery if it's necessary).</p>
| [
{
"answer_id": 3785900,
"author": "Ian Grainger",
"author_id": 48348,
"author_profile": "https://Stackoverflow.com/users/48348",
"pm_score": 3,
"selected": false,
"text": "function validatePhoneOrEmail(source, args) {\n if ($(\"[id$='txtEmail']\").val() == \"\" && $(\"[id$='txtTel']\").val() == \"\") \n args.IsValid = false;\n else\n args.IsValid = true;\n}\n <asp:CustomValidator runat=\"server\" \n ClientValidationFunction=\"validatePhoneOrEmail\" \n ErrorMessage=\"Please enter a telephone number or email address\">\n</asp:CustomValidator>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6461/"
] |
336,961 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/72264/how-can-a-c-windows-dll-be-merged-into-a-c-sharp-application-exe">How can a C++ windows dll be merged into a C# application exe?</a> </p>
</blockquote>
<p>Is anybody aware of a program that can pack several DLL and a .EXE into one executable. I am not talking about .NET case here, I am talking about general DLLs, some of which I generate in C++, some of others are external DLL I have no control over.</p>
<p>My specific case is a python program packaged with py2exe, where I would like to "hide" the other DLL by packing them. The question is general enough though.</p>
<p>The things that had a look at:</p>
<ul>
<li>ILMerge: specific to .NET</li>
<li><a href="http://madebits.com/netz/" rel="noreferrer">NETZ</a>: specific to .NET</li>
<li><a href="http://upx.sourceforge.net/" rel="noreferrer">UPX</a>: does DLL compression but not multiple DLL + EXE packing</li>
<li><a href="http://www.file-joiner.com/" rel="noreferrer">FileJoiner</a>: </li>
</ul>
<blockquote>
Almost got it. It can pack executable + anything into one exe but when opened, it will launch the default opener for every file that was packed. So, if the user user dlldepend installed, it will launch it (becaues that's the default dll opener).
</blockquote>
<p>Maybe that's not possible ?</p>
<hr>
<p>Summary of the answers:</p>
<p>DLL opening is managed by the OS, so packing DLL into executable means that at some point, they need to be extracted to a place where the OS can find them. No magic bullet.</p>
<p>So, what I want is not possible.</p>
<p>Unless...</p>
<p>We change something in the OS. Thanks Conrad for pointing me to <a href="http://www.vmware.com/products/thinapp/overview.html" rel="noreferrer">ThinInstall</a>, which virtualise the application and the OS loading mechanism. With ThinInstall, it is possible to pack everything in one exe (DLL, registry settings, ...).</p>
| [
{
"answer_id": 337163,
"author": "Arnout",
"author_id": 3496,
"author_profile": "https://Stackoverflow.com/users/3496",
"pm_score": 2,
"selected": false,
"text": "LoadLibrary()"
},
{
"answer_id": 337218,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 2,
"selected": false,
"text": "LoadLibrary LoadLibrary/Ex LoadLibrary/Ex LoadLibrary"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13618/"
] |
336,963 | <p>I am not sure what <code>optparse</code>'s <code>metavar</code> parameter is used for. I see it is used all around, but I can't see its use.</p>
<p>Can someone make it clear to me? Thanks.</p>
| [
{
"answer_id": 336992,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 6,
"selected": true,
"text": "metavar add_option usage = \"usage: %prog [options] arg1 arg2\"\nparser = OptionParser(usage=usage)\nparser.add_option(\"-f\", \"--filename\",\n metavar=\"FILE\", help=\"write output to FILE\"),\n usage: <yourscript> [options] arg1 arg2\n\noptions:\n -f FILE, --filename=FILE\n"
},
{
"answer_id": 3882232,
"author": "Yuda Prawira",
"author_id": 454229,
"author_profile": "https://Stackoverflow.com/users/454229",
"pm_score": 0,
"selected": false,
"text": "metavar FILE INT STRING metavar optparse dest"
},
{
"answer_id": 11416894,
"author": "count0",
"author_id": 163231,
"author_profile": "https://Stackoverflow.com/users/163231",
"pm_score": 0,
"selected": false,
"text": "parser.add_argument(\n 'my_fancy_tag',\n help='Specify destination',\n metavar='helpful_message'\n )\n parser.add_argument(\n dest='my_fancy_tag',\n help='Specify destination',\n metavar='helpful_message'\n )\n ./parse.py -h usage: parser [-h] destination\n\npositional arguments: \n helpful_message Specify destination\n ./parse.py test \nNamespace(my_fancy_tag='test')\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,965 | <p>Today one of my friends said: </p>
<pre><code>if (typeof isoft == "undefined") var isoft = new Object();
</code></pre>
<p>is such kind of code is writted by a freshman and writes</p>
<pre><code>if(!isoft) var isoft = new Object();
</code></pre>
<p>I originally consider there must be some difference. But I can't find the difference. Is
there any? Or are the two examples the same?</p>
<p>Thanks.</p>
| [
{
"answer_id": 336982,
"author": "stesch",
"author_id": 41860,
"author_profile": "https://Stackoverflow.com/users/41860",
"pm_score": 1,
"selected": false,
"text": "isoft !isoft"
},
{
"answer_id": 337906,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 1,
"selected": false,
"text": "var radioButtons = document.forms['formName'].elements['radioButtonName'];\nif ('undefined' === typeof radioButtons.length) {\n radioButtons = [ radioButtons ];\n}\nfor (var i = 0; i < radioButtons.length; i++) {\n // ...\n}\n if (!radioButtons.length) if ('undefined' === typeof radioButtons.length) {\n // there is only one\n} else {\n // there are many or none\n}\n if (!variable)"
},
{
"answer_id": 5167606,
"author": "luklatlug",
"author_id": 485577,
"author_profile": "https://Stackoverflow.com/users/485577",
"pm_score": 1,
"selected": false,
"text": "function alertSomething(something) {\n //say you wanna show alert only if something is defined.\n //but you do not know if something is going to be an object or\n //a string or a number, so you cannot just do\n //if (!something) return;\n //you have to check if something is defined\n if (typeof something=='undefined') return;\n alert(something);\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,988 | <p>I use XML serialization for the reading of my Config-POCOs. </p>
<p>To get intellisense support in Visual Studio for XML files I need a schema file. I can create the schema with xsd.exe mylibrary.dll and this works fine.</p>
<p>But I want that the schema is always created if I serialize an object to the file system. Is there any way without using xsd.exe?</p>
| [
{
"answer_id": 337008,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 3,
"selected": true,
"text": "System.Xml.Serialization.XmlSchemaExporter"
},
{
"answer_id": 338100,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "XmlReflectionImporter importer = new XmlReflectionImporter();\nXmlSchemas schemas = new XmlSchemas();\nXmlSchemaExporter exporter = new XmlSchemaExporter(schemas);\nType type = toSerialize.GetType();\nXmlTypeMapping map = importer.ImportTypeMapping(type);\nexporter.ExportTypeMapping(map);\n\nTextWriter tw = new StreamWriter(fileName + \".xsd\");\nschemas[0].Write(tw);\ntw.Close();\n"
},
{
"answer_id": 1615023,
"author": "Matt Murrell",
"author_id": 73801,
"author_profile": "https://Stackoverflow.com/users/73801",
"pm_score": 4,
"selected": false,
"text": " public class Test\n {\n [XmlAttribute()]\n public string Attribute { get; set; }\n public string Description { get; set; }\n\n [XmlArray(ElementName = \"Customers\")]\n [XmlArrayItem(ElementName = \"Customer\")]\n public List<CustomerClass> blah { get; set; }\n\n }\n public static void AttachXmlAttributes(XmlAttributeOverrides xao, Type t)\n {\n List<Type> types = new List<Type>();\n AttachXmlAttributes(xao, types, t);\n }\n\n public static void AttachXmlAttributes(XmlAttributeOverrides xao, List<Type> all, Type t)\n {\n if(all.Contains(t))\n return;\n else\n all.Add(t);\n\n XmlAttributes list1 = GetAttributeList(t.GetCustomAttributes(false));\n xao.Add(t, list1);\n\n foreach (var prop in t.GetProperties())\n {\n XmlAttributes list2 = GetAttributeList(prop.GetCustomAttributes(false));\n xao.Add(t, prop.Name, list2);\n AttachXmlAttributes(xao, all, prop.PropertyType);\n }\n }\n\n private static XmlAttributes GetAttributeList(object[] attributes)\n {\n XmlAttributes list = new XmlAttributes();\n foreach (var attribute in attributes)\n {\n Type type = attribute.GetType();\n if (type.Name == \"XmlAttributeAttribute\") list.XmlAttribute = (XmlAttributeAttribute)attribute;\n else if (type.Name == \"XmlArrayAttribute\") list.XmlArray = (XmlArrayAttribute)attribute;\n else if (type.Name == \"XmlArrayItemAttribute\") list.XmlArrayItems.Add((XmlArrayItemAttribute)attribute);\n\n }\n return list;\n }\n public static string GetSchema<T>()\n {\n XmlAttributeOverrides xao = new XmlAttributeOverrides();\n AttachXmlAttributes(xao, typeof(T));\n\n XmlReflectionImporter importer = new XmlReflectionImporter(xao);\n XmlSchemas schemas = new XmlSchemas();\n XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);\n XmlTypeMapping map = importer.ImportTypeMapping(typeof(T));\n exporter.ExportTypeMapping(map);\n\n using (MemoryStream ms = new MemoryStream())\n {\n schemas[0].Write(ms);\n ms.Position = 0;\n return new StreamReader(ms).ReadToEnd();\n }\n }\n"
},
{
"answer_id": 45568276,
"author": "Janeks Malinovskis",
"author_id": 111253,
"author_profile": "https://Stackoverflow.com/users/111253",
"pm_score": 0,
"selected": false,
"text": "private static void AttachXmlAttributes(XmlAttributeOverrides xao, List<Type> all, Type t)\n{\n if (all.Contains(t))\n {\n return;\n }\n else\n {\n all.Add(t);\n }\n\n var list1 = GetAttributeList(t.GetCustomAttributes(false));\n xao.Add(t, list1);\n\n foreach (var prop in t.GetProperties())\n {\n var propType = prop.PropertyType;\n if (propType.IsGenericType) // is list?\n {\n var args = propType.GetGenericArguments();\n if (args != null && args.Length == 1)\n { \n var genType = args[0];\n if (genType.Name.ToLower() != \"object\")\n {\n var list2 = GetAttributeList(prop.GetCustomAttributes(false));\n xao.Add(t, prop.Name, list2);\n AttachXmlAttributes(xao, all, genType);\n } \n }\n }\n else\n {\n var list2 = GetAttributeList(prop.GetCustomAttributes(false));\n xao.Add(t, prop.Name, list2);\n AttachXmlAttributes(xao, all, prop.PropertyType);\n }\n }\n} \n\nprivate static XmlAttributes GetAttributeList(object[] attributes)\n{\n var list = new XmlAttributes();\n foreach (var attr in attributes)\n {\n Type type = attr.GetType();\n switch (type.Name)\n {\n case \"XmlAttributeAttribute\":\n list.XmlAttribute = (XmlAttributeAttribute)attr;\n break; \n case \"XmlRootAttribute\":\n list.XmlRoot = (XmlRootAttribute)attr;\n break;\n case \"XmlElementAttribute\":\n list.XmlElements.Add((XmlElementAttribute)attr);\n break;\n case \"XmlArrayAttribute\":\n list.XmlArray = (XmlArrayAttribute)attr;\n break;\n case \"XmlArrayItemAttribute\":\n list.XmlArrayItems.Add((XmlArrayItemAttribute)attr);\n break;\n }\n }\n return list;\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,997 | <p>Following up this question: "<a href="https://stackoverflow.com/questions/336846/database-enums-pros-and-cons">Database enums - pros and cons</a>", I'd like to know which database systems support enumeration data types, and a bit of detail on how they do it (e.g. what is stored internally, what are the limits, query syntax implications, indexing implications, ...).</p>
<p>Discussion of use cases or the pros and cons should take place in the other questions.</p>
| [
{
"answer_id": 337120,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "SELECT enum_col+0 ENUM('0','1','2') '0' 1"
},
{
"answer_id": 337131,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 3,
"selected": false,
"text": "CREATE TABLE persons (\n person_id int not null primary key,\n favourite_colour varchar(255) NOT NULL,\n CHECK (favourite_colour IN ('red', 'blue', 'yellow', 'purple'))\n);\n CREATE TABLE colours (\n colour_id int not null primary key,\n colour varchar(255) not null\n)\nCREATE TABLE persons (\n person_id int not null primary key,\n favourite_colour_id integer NOT NULL references colours(colour_id),\n);\n CHECK"
},
{
"answer_id": 349547,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 2,
"selected": false,
"text": "essais=> CREATE TYPE rcount AS ENUM (\nessais(> 'one',\nessais(> 'two',\nessais(> 'three'\nessais(> );\nCREATE TYPE\nessais=> \nessais=> CREATE TABLE dummy (id SERIAL, num rcount);\nNOTICE: CREATE TABLE will create implicit sequence \"dummy_id_seq\" for serial column \"dummy.id\"\nCREATE TABLE\nessais=> INSERT INTO dummy (num) VALUES ('one');\nINSERT 0 1\nessais=> INSERT INTO dummy (num) VALUES ('three');\nINSERT 0 1\nessais=> INSERT INTO dummy (num) VALUES ('four');\nERROR: invalid input value for enum rcount: \"four\"\nessais=> \nessais=> SELECT * FROM dummy WHERE num='three';\n id | num \n----+-------\n 2 | three\n 4 | three\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18771/"
] |
337,019 | <p>In the below program:</p>
<pre><code>class Main
{
static string staticVariable = "Static Variable";
string instanceVariable = "Instance Variable";
public Main(){}
}
</code></pre>
<p>The <code>instanceVariable</code> will be stored inside the memory allocated for object instance. Where will the <code>staticVariable</code> be stored, is it stored in the object instance itself or somewhere else? If its stored somewhere else, how are the memory locations connected?</p>
| [
{
"answer_id": 337032,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 5,
"selected": true,
"text": "object[]"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26036/"
] |
337,023 | <p>While trying to answer a question in the vicinity '<a href="https://stackoverflow.com/questions/331215/unit-test-wpf-bindings">Unit Testing WPF Bindings</a>' I had the following niggling question..<br>
<strong>What's the best way to find if you have WPF Data Binding wiring setup incorrectly (or you just broke something that was wired up correctly) ?</strong></p>
<p>Although the unit-testing approach seems to be like Joel's 'ripping off your arm to remove a splinter'.. I am looking around for easier less Overhead ways to detect this.</p>
<p>Everyone seems to have committed themselves to data binding in a big way with WPF.. and it does have its merits.</p>
| [
{
"answer_id": 337026,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 6,
"selected": true,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <system.diagnostics>\n <sources>\n <source name=\"System.Windows.Data\" switchName=\"SourceSwitch\" >\n <listeners>\n <add name=\"textListener\" />\n </listeners>\n </source>\n\n </sources>\n <switches>\n <add name=\"SourceSwitch\" value=\"All\" />\n </switches>\n\n <sharedListeners>\n <add name=\"textListener\"\n type=\"System.Diagnostics.TextWriterTraceListener\"\n initializeData=\"GraveOfBindErrors.txt\" />\n </sharedListeners>\n\n <trace autoflush=\"true\" indentsize=\"4\"></trace>\n\n </system.diagnostics>\n</configuration>\n System.Windows.Data Error: 35 : BindingExpression path error: 'MyProperty' property not found on 'object' ''MyWindow' (Name='')'. BindingExpression:Path=MyProperty; DataItem='MyWindow' (Name=''); target element is 'TextBox' (Name='txtValue2'); target property is 'Text' (type 'String')\n"
},
{
"answer_id": 343206,
"author": "Enrico Campidoglio",
"author_id": 26396,
"author_profile": "https://Stackoverflow.com/users/26396",
"pm_score": 6,
"selected": false,
"text": "<Window x:Class=\"WpfApplication1.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:diag=\"clr-namespace:System.Diagnostics;assembly=WindowsBase\"\n Title=\"Debug Binding Sample\"\n Height=\"300\"\n Width=\"300\">\n <StackPanel>\n <TextBox Name=\"txtInput\" />\n <Label>\n <Label.Content>\n <Binding ElementName=\"txtInput\"\n Path=\"Text\"\n diag:PresentationTraceSources.TraceLevel=\"High\" />\n </Label.Content>\n </Label>\n </StackPanel>\n</Window>\n"
},
{
"answer_id": 11632148,
"author": "Jeroen de Bekker",
"author_id": 581255,
"author_profile": "https://Stackoverflow.com/users/581255",
"pm_score": 3,
"selected": false,
"text": "BindingListener private static readonly IList<string> m_MessagesToIgnore =\n new List<String>()\n {\n //Windows.Data.Error 7\n //Binding transfer from target to source failed because of an exception\n //Normal WPF Scenario, requires ValidatesOnExceptions / ExceptionValidationRule\n //To cope with these kind of errors\n \"ConvertBack cannot convert value\",\n\n //Windows.Data.Error 8\n //Binding transfer from target to source failed because of an exception\n //Normal WPF Scenario, requires ValidatesOnExceptions / ExceptionValidationRule\n //To cope with these kind of errors\n \"Cannot save value from target back to source\" \n };\n ....\n if (this.InformationPropertyCount == 0)\n {\n //Only treat message as an exception if it is not to be ignored\n if (!m_MessagesToIgnore.Any(\n x => this.Message.StartsWith(x, StringComparison.InvariantCultureIgnoreCase)))\n {\n PresentationTraceSources.DataBindingSource.Listeners.Remove(this);\n\n throw new BindingException(this.Message,\n new BindingExceptionInformation(this.Callstack,\n System.DateTime.Parse(this.DateTime),\n this.LogicalOperationStack, int.Parse(this.ProcessId),\n int.Parse(this.ThreadId), long.Parse(this.Timestamp)));\n }\n else\n {\n //Ignore message, reset values\n this.IsFirstWrite = true;\n this.DetermineInformationPropertyCount();\n }\n }\n }\n"
},
{
"answer_id": 23674534,
"author": "Simon Mourier",
"author_id": 403671,
"author_profile": "https://Stackoverflow.com/users/403671",
"pm_score": 1,
"selected": false,
"text": "....\n#if DEBUG\n WpfUtilities.SetTracing();\n#endif\n....\n public static void SetTracing()\n{\n SetTracing(SourceLevels.Warning, null);\n}\n\npublic static void SetTracing(SourceLevels levels, TraceListener listener)\n{\n if (listener == null)\n {\n listener = new DefaultTraceListener();\n }\n\n // enable WPF tracing\n PresentationTraceSources.Refresh();\n\n // enable all WPF Trace sources (change this if you only want DataBindingSource)\n foreach (PropertyInfo pi in typeof(PresentationTraceSources).GetProperties(BindingFlags.Static | BindingFlags.Public))\n {\n if (typeof(TraceSource).IsAssignableFrom(pi.PropertyType))\n {\n TraceSource ts = (TraceSource)pi.GetValue(null, null);\n ts.Listeners.Add(listener);\n ts.Switch.Level = levels;\n }\n }\n}\n"
},
{
"answer_id": 66690125,
"author": "MRK",
"author_id": 6296708,
"author_profile": "https://Stackoverflow.com/users/6296708",
"pm_score": 0,
"selected": false,
"text": "Benoit Blanchon"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695/"
] |
337,024 | <p>I am working with an SVN repository with many projects. I need to move a few of the projects out of that repository into individual repositories, one for each project, keeping the history.</p>
<p>I've been able to use <code>svnadmin dump</code> to dump the entire repository and <code>svnadmin load</code> it into another repository, but I can't find a way of dumping only one project from the original repository so I can load it into the new one. Is this possible? If so how?</p>
| [
{
"answer_id": 337110,
"author": "Avi",
"author_id": 1605,
"author_profile": "https://Stackoverflow.com/users/1605",
"pm_score": 7,
"selected": true,
"text": "\n$ svnadmin dump /path/to/repo \n | svndumpfilter include /proj > dump-file\n$ svnadmin create /new/proj/repo\n$ svnadmin load --ignore-uuid /new/proj/repo < dump-file\n$ svn rm file:///path/to/repo/proj\n"
},
{
"answer_id": 26468520,
"author": "Leos Literak",
"author_id": 1639556,
"author_profile": "https://Stackoverflow.com/users/1639556",
"pm_score": 0,
"selected": false,
"text": "svndumpfilter cat dump | svndumpfilter --drop-empty-revs --renumber-revs include trunk/project > project.dump \nsvnadmin load --ignore-uuid /opt/svn/newlocation < project.dump\n<<< Started new transaction, based on original revision 1 \nsvnadmin: File not found: transaction '0-0', path 'trunk/project'\n trunk"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1142/"
] |
337,029 | <p>How do I implement this equality comparison is a sane java way? </p>
<pre><code>boolean x = (a == b) || (a.equals(b))
</code></pre>
<p>I want to make sure the content of both objects is equal but null is also ok, i.e. both can be null and are thus equal.</p>
<p>Update: just to be clear, I have to implement this comparison several times and don't want to copy&paste this stuff every time, especially with lenghty object names. With 'a' and 'b' it looks small and simple, but tends to grow... I'd like to know if I'm missing some existing Java feature for this.</p>
| [
{
"answer_id": 337039,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": "boolean x = (a == null && b == null) || (a != null && a.equals(b))\n public class MyClass {\n\n public static boolean NullEquals( MyClass a, MyClass b )\n {\n return (a == null && b == null) || (a != null && a.equals(b));\n }\n}\n\n\nif (MyClass.NullEquals(a,b))\n{\n ...\n}\n"
},
{
"answer_id": 337056,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "if (a == b)\n{\n return true;\n}\nif (a == null || b == null)\n{\n return false;\n}\n// Now deal with a and b, knowing that they are non-identical, non-null references\n"
},
{
"answer_id": 337082,
"author": "Dennis C",
"author_id": 40214,
"author_profile": "https://Stackoverflow.com/users/40214",
"pm_score": 3,
"selected": false,
"text": "boolean x = null==a ? null==b : a.equals(b);\n"
},
{
"answer_id": 337384,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 0,
"selected": false,
"text": "a==null ? b==null : a.equals(b)\n a==b || (a!=null && a.equals(b))\n public static boolean eq(Object a, Object b) {\n return a==b || (a!=null && a.equals(b));\n}\n"
},
{
"answer_id": 339323,
"author": "ykaganovich",
"author_id": 10026,
"author_profile": "https://Stackoverflow.com/users/10026",
"pm_score": 0,
"selected": false,
"text": "equals public boolean equals(Object obj) {\n if(this == obj) return true;\n ...\n}\n a == null ? b == null : a.equals(b);\n a == null ? b == null : (a == b || a.equals(b));\n"
},
{
"answer_id": 339358,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 1,
"selected": false,
"text": "boolean x = equals( a, b );\n\npublic static boolean equals( Object a, Object b ) {\n if ( a == null && a == b ) {\n return true;\n } else {\n return a == b || a.equals( b );\n }\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6460/"
] |
337,037 | <p>This is related to a chapter from <a href="https://rads.stackoverflow.com/amzn/click/com/0596510047" rel="noreferrer" rel="nofollow noreferrer">beautiful code</a>.
And in that chapter I read about the nested <code>if</code>s.</p>
<p>The author was talking about deeply nested <code>if</code>s as originator of bugs and less readable.
And he was talking about replacing nested <code>if</code>s with <code>case</code> statements and <a href="https://en.wikipedia.org/wiki/Decision_table" rel="noreferrer">decision tables</a>. </p>
<p>Can anybody illustrate how to remove nested <code>if</code>s with <code>case</code> (<code>select case</code>) and decision tables ? </p>
| [
{
"answer_id": 337105,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 4,
"selected": false,
"text": "if (i == 1) {\n // action 1\n} else {\n if (i == 2) {\n // action 2\n } else {\n if (i == 3) {\n // action 3\n } else {\n // action 4\n }\n }\n}\n switch (i) {\n case 1:\n // action 1\n break;\n case 2:\n // action 2\n break;\n case 3:\n // action 3\n break;\n default:\n // action 4\n break;\n}\n switch (i) {\n case 1:\n outmsg = \"no paper\";\n genmsg = true;\n mailmsg = true;\n phonemsg = false;\n break;\n case 2:\n outmsg = \"no ink\";\n genmsg = true;\n mailmsg = true;\n phonemsg = false;\n break;\n default:\n outmsg = \"unknown problem\";\n genmsg = true;\n mailmsg = true;\n phonemsg = true;\n break;\n}\n\nif (genmsg)\n // Send message to screen.\nif (mailmsg)\n // Send message to operators email address.\nif (phonemsg)\n // Hassle operators mobile phone.\n"
},
{
"answer_id": 337119,
"author": "khivi",
"author_id": 42669,
"author_profile": "https://Stackoverflow.com/users/42669",
"pm_score": 3,
"selected": false,
"text": "if (condition1)\n{\n do1\n} \nelse\n{\n if (condition2)\n {\n do2\n }\n else (condition3)\n {\n do3;\n\n }\n}\n bool cond1=condition1;\nbool cond2=condition2;\nbool cond3=condition3;\n\nif (cond1) {do1;}\nif (!cond1 and cond2) {do2;}\nif (!cond1 and cond3) {do2;}\n"
},
{
"answer_id": 337125,
"author": "Jim C",
"author_id": 21706,
"author_profile": "https://Stackoverflow.com/users/21706",
"pm_score": -1,
"selected": false,
"text": " switch true{\n case i==0\n //action\n break\n\n case j==2\n //action\n break\n\n case i>j\n //action\n break\n }\n"
},
{
"answer_id": 337138,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "if (condition1)\n{\n do1\n} \nelse\n{\n if (condition2)\n {\n do2\n }\n else (condition3)\n {\n do3;\n\n }\n}\n if (condition1) {\n do1;\n} else if (condition2) {\n do2;\n} else if (condition3) {\n do3;\n}\n"
},
{
"answer_id": 337245,
"author": "Paul Stephenson",
"author_id": 5536,
"author_profile": "https://Stackoverflow.com/users/5536",
"pm_score": 1,
"selected": false,
"text": "if (i == 1) {\n // action 1\n} else {\n if (i == 2) {\n // action 2\n } else {\n if (i == 3) {\n // action 3\n } else {\n // action 4\n }\n }\n}\n void action1()\n{\n // action 1\n}\n\nvoid action2()\n{\n // action 2\n}\n\nvoid action3()\n{\n // action 3\n}\n\nvoid action4()\n{\n // action 4\n}\n\n#define NUM_ACTIONS 4\n\n// Create array of function pointers for each allowed value of i\nvoid (*actions[NUM_ACTIONS])() = { NULL, action1, action2, action3 }\n\n// And now in the body of a function somewhere...\nif ((i < NUM_ACTIONS) && actions[i])\n actions[i]();\nelse\n action4();\n i i actions if switch"
},
{
"answer_id": 19157118,
"author": "Demis Palma ツ",
"author_id": 2841837,
"author_profile": "https://Stackoverflow.com/users/2841837",
"pm_score": 0,
"selected": false,
"text": "if (condition1)\n{\n if (function(2))\n {\n if (condition3)\n {\n // do something\n }\n }\n}\n if (condition1 && function(2) && condition3)\n{\n // do something\n}\n"
},
{
"answer_id": 30275131,
"author": "Alexis Paques",
"author_id": 3540247,
"author_profile": "https://Stackoverflow.com/users/3540247",
"pm_score": 2,
"selected": false,
"text": "function validate(){\n if(b==\"\" || b==null){\n alert(\"Please enter your city\");\n return false;\n }\n\n if(a==\"\" || a==null){\n alert(\"Please enter your address\");\n return false;\n }\n return true;\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41968/"
] |
337,038 | <p>I have an interface called Dictionary which has a method <code>insert()</code>. This interface is implemented by class <code>BSTree</code>, but I also have a class <code>AVLTree</code> which is a child class of <code>BSTree</code>. <code>AVLTree</code> redefines the <code>insert()</code> so it suits it's needs. Now if I type the following code:</p>
<pre><code>Dictionary data=new AVLTree();
data.insert();
</code></pre>
<p>There is a problem, because the <code>insert()</code> method that is called is of <code>BSTree</code> instead of <code>AVLTree</code>. Why doesn't the polymorphism kick in here? What is the appropriate solution, one that retains the principle of polymorphism?</p>
| [
{
"answer_id": 337093,
"author": "huo73",
"author_id": 15657,
"author_profile": "https://Stackoverflow.com/users/15657",
"pm_score": 2,
"selected": false,
"text": "public Interface Dictionary {\n ...\n public void insert();\n ...\n}\n\npublic Class BSTree implements Dictionary {\n ...\n public void insert() {\n // some implementation here\n }\n ...\n}\n\npublic Class AVLTree extends BSTree {\n ...\n public void insert() {\n // another implementation of insert\n }\n ...\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42803/"
] |
337,058 | <p>How do I integrate AJAX toolkit into MVC applications in .net?</p>
| [
{
"answer_id": 337093,
"author": "huo73",
"author_id": 15657,
"author_profile": "https://Stackoverflow.com/users/15657",
"pm_score": 2,
"selected": false,
"text": "public Interface Dictionary {\n ...\n public void insert();\n ...\n}\n\npublic Class BSTree implements Dictionary {\n ...\n public void insert() {\n // some implementation here\n }\n ...\n}\n\npublic Class AVLTree extends BSTree {\n ...\n public void insert() {\n // another implementation of insert\n }\n ...\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42791/"
] |
337,060 | <p>We recently had a project where we released beta of a big web app on our client's server. Our client requested us to do bug fixes as they come, and we tried to do it same way. Normally while building an app on our prototype server is way easier, as I just have to issue simple 'svn up' command which takes a second. </p>
<p>But on production environment, we do not have any version control tool available. Is it possible to automate the patching work, so that we need not to login to ftp and upload each a every file one by one? </p>
<p>Its very difficult to work this way. As I'm having this problem, its for sure that some of you have already solved the problem. Please share your solutions.</p>
<p>Looking forward to your replies... Thanks a lot for reading guys.</p>
| [
{
"answer_id": 337092,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 2,
"selected": false,
"text": "svn diff -r x:y patch rsync"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
337,066 | <p>I am developing a wrapper for a third party function library that is interfacing with some special hardware. So basically, I want to encapsulate the dll functions (<code>bool Connect()</code>, <code>void Disconnect()</code> etc) in a MyHardwareObject with connect- and disconnect methods.</p>
<p>The Connect function from the dll can throw some specific exceptions, for example when the hardware is not present. For the application, the information on why the connect method failed is considered unimportant, so the additional information contained in the exception is not needed. </p>
<p>What is the best way of handling those exceptions, returning <code>false</code>, or leaving the exception unhandled here and catch it on the level that would otherwise handle the fact that the connect method returnded <code>false</code>?</p>
<pre><code> bool MyHardwareObject.Connect()
{
try
{
ThirdPartyLibrary.Connect();
}
catch (SomeException)
{
return false;
}
return true;
}
</code></pre>
<p>As opposed to </p>
<pre><code> bool MyHardwareObject.Connect()
{
ThirdPartyLibrary.Connect();
return true;
}
</code></pre>
<p>(or in the second case better <code>void MyHardwareObject.Connect()</code>, since we either return true, or throw an exception?)</p>
<p>Or what else would you do? And most important: Why?</p>
| [
{
"answer_id": 337127,
"author": "Petar Petrov",
"author_id": 42377,
"author_profile": "https://Stackoverflow.com/users/42377",
"pm_score": 2,
"selected": false,
"text": " bool MyHardwareObject.Connect()\n{\n try\n {\n ThirdPartyLibrary.Connect();\n }\n catch (SomeException)\n {\n return false;\n }\n return true;\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22114/"
] |
337,072 | <p>Can anyone explain in simple words what First and Second Level caching in Hibernate/NHibernate are?</p>
| [
{
"answer_id": 25072915,
"author": "Thadeuse",
"author_id": 1733575,
"author_profile": "https://Stackoverflow.com/users/1733575",
"pm_score": 7,
"selected": false,
"text": "evict() evict() clear() load()"
},
{
"answer_id": 51306851,
"author": "Vlad Mihalcea",
"author_id": 1025118,
"author_profile": "https://Stackoverflow.com/users/1025118",
"pm_score": 5,
"selected": false,
"text": "SessionFactory"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38807/"
] |
337,087 | <p>Say I have some code like</p>
<pre><code>namespace Portal
{
public class Author
{
public Author() { }
private void SomeMethod(){
string myMethodName = "";
// myMethodName = "Portal.Author.SomeMethod()";
}
}
}
</code></pre>
<p>Can I find out the name of the method I am using? In my example I'ld like to programmatically set <code>myMethodName</code> to the name of the current method (ie in this case <code>"Portal.Author.SomeMethod"</code>). </p>
<p>Thanks</p>
| [
{
"answer_id": 337091,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 5,
"selected": true,
"text": "MethodInfo.GetCurrentMethod().Name\n"
},
{
"answer_id": 337109,
"author": "mookid8000",
"author_id": 6560,
"author_profile": "https://Stackoverflow.com/users/6560",
"pm_score": 2,
"selected": false,
"text": "System.Diagnostics StackFrame StackTrace StackFrame stackFrame = new StackFrame(1, true); //< skip first frame and capture src info\nStackTrace stackTrace = new StackTrace(stackFrame);\nMethodBase method = stackTrace.GetMethod();\nstring name = method.Name;\n"
},
{
"answer_id": 341353,
"author": "Ian G",
"author_id": 31765,
"author_profile": "https://Stackoverflow.com/users/31765",
"pm_score": 1,
"selected": false,
"text": "myMethodName = System.Reflection.MethodBase.GetCurrentMethod().ReflectedType + \n \".\" + System.Reflection.MethodBase.GetCurrentMethod().Name;\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31765/"
] |
337,090 | <p>I have created a TCP client that connects to a listening server.
We implemeted TCP keep alive also.
Some times the client crashes and core dumped.
Below are the core dump traces.</p>
<p>Problem is in linux kernel version Update 4, kernel 2.6.9-42.0.10.</p>
<p>we had two core dumps.</p>
<pre><code>(gdb) where
#0 0x005e77a2 in _dl_sysinfo_int80 () from /ddisk/d303/dumps/mhx239131/ld-
linux.so.2
#1 0x006c8bd1 in connect () from /ddisk/d303/dumps/mhx239131/libc.so.6
#2 0x08057863 in connect_to_host ()
#3 0x08052f38 in open_ldap_connection ()
#4 0x0805690a in new_connection ()
#5 0x08052cc9 in ldap_open ()
#6 0x080522cf in checkHosts ()
#7 0x08049b36 in pollLDEs ()
#8 0x0804d1cd in doOnChange ()
#9 0x0804a642 in main ()
(gdb) where
#0 0x005e77a2 in _dl_sysinfo_int80 () from /ddisk/d303/dumps/mhx239131/ld-
linux.so.2
#1 0x0068ab60 in __nanosleep_nocancel (
from /ddisk/d303/dumps/mhx239131/libc.so.6
#2 0x080520a2 in Sleep ()
#3 0x08049ac1 in pollLDEs ()
#4 0x0804d1cd in doOnChange ()
#5 0x0804a642 in main ()
</code></pre>
<p>We have tried to reproduce the problem in our environment, but we could not.</p>
<p>What would cause the core file?</p>
<p>Please help me to avoid such situation.</p>
<p>Thanks,
Naga</p>
| [
{
"answer_id": 337748,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 1,
"selected": false,
"text": "_dl_sysinfo_int80 connect nanosleep #2 valgrind"
},
{
"answer_id": 346046,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "'kill -SIGABRT <pid>' 'info threads' 'thread apply all where'"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
337,103 | <p>I have a form with a few buttons which execute code when pressed like running validations on the database.</p>
<p>Some code can run for a few minutes so is there any way to show the time remaining or a message to display the % of process completed?</p>
<p>Or pop out a message when code evaluation starts and the message should disappear once code running is completed?</p>
| [
{
"answer_id": 337129,
"author": "Mike Powell",
"author_id": 205,
"author_profile": "https://Stackoverflow.com/users/205",
"pm_score": 0,
"selected": false,
"text": "DoEvents Application_OnTime"
},
{
"answer_id": 337506,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 2,
"selected": true,
"text": "'foo, being the ProgressBar\nme.foo = 70 '70%\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31132/"
] |
337,112 | <p>I need to round decimal numbers to six places using JavaScript, but I need to consider legacy browsers so I <a href="http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference" rel="noreferrer">can't rely on Number.toFixed</a> </p>
<blockquote>
<p>The big catch with toExponential, toFixed, and toPrecision is that they are fairly modern constructs not supported in Mozilla until Firefox version 1.5 (although IE supported the methods since version 5.5). While it's mostly safe to use these methods, older browsers WILL break so if you are writing a public program it's recommended you provide your own prototypes to provide functionality for these methods for older browser.</p>
</blockquote>
<p>I'm considering using something like</p>
<pre><code>Math.round(N*1000000)/1000000
</code></pre>
<p>What is the best method for providing this a prototype to older browsers?</p>
| [
{
"answer_id": 337139,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "javascript: var num = 3.1415926535897932384; alert(num.toFixed(7));\n"
},
{
"answer_id": 337146,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 5,
"selected": true,
"text": "if (!Number.prototype.toFixed)\n\n Number.prototype.toFixed = function(precision) {\n var power = Math.pow(10, precision || 0);\n return String(Math.round(this * power)/power);\n }\n"
},
{
"answer_id": 337154,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "if (!num.toFixed) \n{\n Number.prototype.toFixed = function(precision) \n {\n var num = (Math.round(this*Math.pow(10,precision))).toString();\n return num.substring(0,num.length-precision) + \".\" + \n num.substring(num.length-precision, num.length);\n }\n}\n"
},
{
"answer_id": 395838,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Number.prototype._toFixed=Number.prototype.toFixed; //Preserves the current function\nNumber.prototype.toFixed=function(precision){\n/* step 1 */ var a=this, pre=Math.pow(10,precision||0);\n/* step 2 */ a*=pre; //currently number is 162295.499999\n/* step 3 */ a = a._toFixed(2); //sets 2 more digits of precision creating 16230.00\n/* step 4 */ a = Math.round(a);\n/* step 5 */ a/=pre;\n/* step 6 */ return a._toFixed(precision);\n}\n/*This last step corrects the number of digits from 162.3 ( which is what we get in step 5 to the corrected 162.30. Without it we would get 162.3 */\n this*=Math.pow(10, precision||0) a"
},
{
"answer_id": 1380030,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " Number.prototype.toFixed = function(precision) {\n var power = Math.pow(10, precision || 0);\n return String(Math.round(this * power)/power);\n }\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20074/"
] |
337,115 | <p>We're trying to tune an application that accepts messages via TCP and also uses TCP for some of its internal messaging. While load testing, we noticed that response time degrades significantly (and then stops altogether) as more simultaneous requests are made to the system. During this time, we see a lot of TCP connections in <code>TIME_WAIT</code> status and someone suggested lowering the <code>TIME_WAIT</code> environment variable from it's default 60 seconds to 30.</p>
<p>From <a href="http://www.developerweb.net/forum/showthread.php?t=2941" rel="noreferrer">what I understand</a>, the <code>TIME_WAIT</code> setting essentially sets the time a TCP resource is made available to the system again after the connection is closed.</p>
<p>I'm not a "network guy" and know very little about these things. I need a lot of what's in that linked post, but "dumbed down" a little.</p>
<ul>
<li>I think I understand why the <code>TIME_WAIT</code> value can't be set to 0, but can it safely be set to 5? What about 10? What determines a "safe" setting for this value?</li>
<li>Why is the default for this value 60? I'm guessing that people a lot smarter than me had good reason for selecting this as a reasonable default.</li>
<li>What else should I know about the potential risks and benefits of overriding this value?</li>
</ul>
| [
{
"answer_id": 338132,
"author": "yogman",
"author_id": 24349,
"author_profile": "https://Stackoverflow.com/users/24349",
"pm_score": -1,
"selected": false,
"text": "int listen(int sockfd, int backlog);\n"
},
{
"answer_id": 15593859,
"author": "Synetech",
"author_id": 119540,
"author_profile": "https://Stackoverflow.com/users/119540",
"pm_score": 2,
"selected": false,
"text": "; Set the TIME_WAIT delay to 30 seconds (0x1E)\n\n[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\TCPIP\\Parameters]\n\"TcpTimedWaitDelay\"=dword:0000001E\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2890/"
] |
337,121 | <p>Suppose I have a class 'Application'. In order to be initialised it takes certain settings in the constructor. Let's also assume that the number of settings is so many that it's compelling to place them in a class of their own.</p>
<p>Compare the following two implementations of this scenario.</p>
<p>Implementation 1:</p>
<pre><code>class Application
{
Application(ApplicationSettings settings)
{
//Do initialisation here
}
}
class ApplicationSettings
{
//Settings related methods and properties here
}
</code></pre>
<p>Implementation 2:</p>
<pre><code>class Application
{
Application(Application.Settings settings)
{
//Do initialisation here
}
class Settings
{
//Settings related methods and properties here
}
}
</code></pre>
<p>To me, the second approach is very much preferable. It is more readable because it strongly emphasises the relation between the two classes. When I write code to instantiate Application class anywhere, the second approach is going to look prettier. </p>
<p>Now just imagine the Settings class itself in turn had some similarly "related" class and that class in turn did so too. Go only three such levels and the class naming gets out out of hand in the 'non-nested' case. If you nest, however, things still stay elegant.</p>
<p>Despite the above, I've read people saying on StackOverflow that nested classes are justified only if they're not visible to the outside world; that is if they are used only for the internal implementation of the containing class. The commonly cited objection is bloating the size of containing class's source file, but partial classes is the perfect solution for that problem.</p>
<p>My question is, why are we wary of the "publicly exposed" use of nested classes? Are there any other arguments against such use?</p>
| [
{
"answer_id": 337132,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 0,
"selected": false,
"text": "public abstract class Outer\n{\n protected class Inner\n {\n }\n}\n"
},
{
"answer_id": 337143,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "public class Outer\n{\n private Outer(Builder builder)\n {\n // Copy stuff\n }\n\n public class Builder\n {\n public Outer Build()\n {\n return new Outer(this);\n }\n }\n}\n"
},
{
"answer_id": 337185,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 3,
"selected": false,
"text": "namespace Diner\n{\n public class Sandwich\n {\n public Sandwich(Filling filling) { }\n }\n\n public class Filling { }\n}\n using using Diner;\n\n...\n\nvar sandwich = new Sandwich(new Filling());\n Sandwich Filling Sandwich.Filling Filling"
},
{
"answer_id": 34399059,
"author": "BornToCode",
"author_id": 1057791,
"author_profile": "https://Stackoverflow.com/users/1057791",
"pm_score": 0,
"selected": false,
"text": "public class OrderViewModel\n{\npublic int OrderId{ get; set; }\npublic IEnumerable<Product> Products{ get; set; }\n\npublic class Product {\npublic string ProductName{ get; set; }\npublic decimal ProductPrice{ get; set; }\n}\n\n}\n Product"
},
{
"answer_id": 59295573,
"author": "cbast",
"author_id": 2532856,
"author_profile": "https://Stackoverflow.com/users/2532856",
"pm_score": -1,
"selected": false,
"text": "public class PersonSearch\n{\n public PersonSearchCriteria\n {\n string FirstName {get; set;}\n string LastName {get; set;}\n }\n\n public PersonSearchResult\n {\n string FirstName {get;}\n string MiddleName {get;}\n string LastName {get;}\n string Quest {get;}\n string FavoriteColor {get;}\n }\n\n public static List<PersonSearchResult> Run(PersonSearchCriteria criteria)\n {\n // create a query using the given criteria\n\n // run the query\n\n // return the results \n }\n}\n\n\npublic class PersonSearchTester\n{\n public void Test()\n {\n PersonSearch.PersonSearchCriteria criteria = new PersonSearch.PersonSearchCriteria();\n criteria.FirstName = \"George\";\n criteria.LastName = \"Washington\";\n\n List<PersonSearch.PersonSearchResults> results = \n PersonSearch.Run(criteria);\n }\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32688/"
] |
337,141 | <p>I am working with an order system that has two tables Order and OrderLine pretty standard stuff. I want to work out an order line number for the order lines with respect to the order e.g.</p>
<p>Orderid Orderlineid linenumber<br>
1 1 1<br>
2 2 1<br>
2 3 2<br>
3 4 1<br>
4 5 1<br>
4 6 2</p>
<p>The OrderLineId is an identity column. I don't want to store the line number as data in the database for two reasons. First there are already a great many existing orders and lines in the system and retrospectively adding the data is a headache I wish to avoid. Second if the user deletes a line then I would need to recalculate the line numbers for the whole order.</p>
<p>In SQL 2005 I can do this easy peasy using the ROW_NUMBER function.</p>
<pre><code>Select Orderid, OrderLineid, ROW_NUMBER()
OVER(PARTITION BY Orderid ORDER BY Orderlineid) as LineNumber
FROM OrderLine
</code></pre>
<p>Is there anyway I can do this in SQL 2000?</p>
<p>The closest I found was a ranking function (see below) but this counts orders not lines.</p>
<pre><code>SELECT x.Ranking, x.OrderId
FROM (SELECT (SELECT COUNT( DISTINCT t1.Orderid) FROM orderline t1 WHERE z.Orderid >= t1.Orderid)AS Ranking, z.orderid
FROM orderline z ) x
ORDER BY x.Ranking
</code></pre>
| [
{
"answer_id": 337214,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 3,
"selected": true,
"text": "select \n ol1.orderId,\n ol1.orderLineId,\n count(*) as lineNumber\nfrom \n orderLine ol1\n inner join orderLine ol2 \n on ol1.orderId = ol2.orderId\n and ol1.orderLineId >= ol2.orderLineId\ngroup by \n ol1.orderId, \n ol1.orderLineId\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2253/"
] |
337,158 | <p>I have researched and haven't found a way to run INTERSECT and MINUS operations in MS Access. Does any way exist</p>
| [
{
"answer_id": 337203,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": 6,
"selected": true,
"text": "select distinct\n a.*\nfrom\n a\n inner join b on a.id = b.id\n select distinct\n a.*\nfrom\n a\n left outer join b on a.id = b.id\nwhere\n b.id is null\n"
},
{
"answer_id": 337580,
"author": "Dave Markle",
"author_id": 24995,
"author_profile": "https://Stackoverflow.com/users/24995",
"pm_score": 4,
"selected": false,
"text": "SELECT DISTINCT a.*\nFROM a\nINNER JOIN b\n on a.PK = b.PK\n SELECT DISTINCT a.*\nFROM a\nINNER JOIN b\n ON a.Col1 = b.Col1\n AND a.Col2 = b.Col2\n AND a.Col3 = b.Col3 ...\n SELECT DISTINCT a.*\nFROM a\nLEFT JOIN b\n on a.PK = b.PK\nWHERE b.PK IS NULL\n"
},
{
"answer_id": 57519327,
"author": "Porebo",
"author_id": 11934512,
"author_profile": "https://Stackoverflow.com/users/11934512",
"pm_score": -1,
"selected": false,
"text": "SELECT DISTINCT\n a.CustomerID, \n b.CustomerID\nFROM \n tblCustomers a\nLEFT JOIN \n [Copy Of tblCustomers] b\nON\n a.CustomerID = b.CustomerID\nWHERE\n b.CustomerID IS NULL\n"
},
{
"answer_id": 69465132,
"author": "Paul Verschoor",
"author_id": 343475,
"author_profile": "https://Stackoverflow.com/users/343475",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT a.*\nFROM a\nWHERE a.PK NOT IN (SELECT DISTINCT b.pk FROM b)\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6613/"
] |
337,159 | <p>In an application I need to execute other programs with another user's credentials. Currently I use <strong><a href="http://msdn.microsoft.com/en-us/library/ed04yy3t.aspx" rel="nofollow noreferrer">System.Diagnostics.Process.Start</a></strong> to execute the program:</p>
<pre><code>public static Process Start(
string fileName,
string arguments,
string userName,
SecureString password,
string domain
)
</code></pre>
<p>However this function does not load the roaming profile from the net - which is required.</p>
<p>I could use "runas /profile ..." to load the profile and execute the command, but that would ask for a password. There must be an more elegant way...</p>
<p>But where?</p>
| [
{
"answer_id": 337396,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 3,
"selected": false,
"text": " Process p = new Process();\n\n p.StartInfo.FileName = textFilename.Text;\n p.StartInfo.Arguments = textArgument.Text;\n p.StartInfo.UserName = textUsername.Text;\n p.StartInfo.Domain = textDomain.Text;\n p.StartInfo.Password = securePassword.SecureText;\n\n p.StartInfo.LoadUserProfile = true;\n p.StartInfo.UseShellExecute = false;\n\n try {\n p.Start();\n } catch (Win32Exception ex) {\n MessageBox.Show(\"Error:\\r\\n\" + ex.Message);\n }\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/999/"
] |
337,165 | <p>This code is executed by many way. When it's executed by the form button it works (the button start a thread and in the loop it call this method = it works). BUT it doesn't work when I have a call to that method from my BackgroundWorker in the form. </p>
<p>With the following code:</p>
<pre><code>private void resizeThreadSafe(int width, int height)
{
if (this.form.InvokeRequired)
{
this.form.Invoke(new DelegateSize(resizeThreadSafe),
new object[] { width, height });
}
this.form.Size = new Size(width, height); // problem occurs on this line
this.form.Location = new Point(0, 0); // dummy coordinate
}
</code></pre>
<p>Then on the line containing <code>this.form.Size = ...</code> I get the following exception:</p>
<pre><code>InvalidOperationException was unhandled
Cross-thread operation not valid: Control 'Form1' accessed from a thread other
than the thread it was created on.
</code></pre>
<p>Why?</p>
| [
{
"answer_id": 337171,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "private void resizeThreadSafe(int width, int height)\n{\n if (this.form.InvokeRequired)\n {\n this.form.Invoke(new DelegateSize(resizeThreadSafe,\n new object[] { width, height });\n return;\n }\n this.form.Size = new Size(width, height);\n this.form.Location = new Point(0, SystemInformation.MonitorSize // whatever comes next\n}\n"
},
{
"answer_id": 337182,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 1,
"selected": false,
"text": "if ( this.form.InvokeRequired ) {\n this.form.Invoke( ...... );\n return;\n}\nthis.form.Size = new Sizte( ... );\n if ( this.form.InvokeRequired ) {\n this.form.Invoke( ...... );\n}\nelse {\n this.form.Size = new Sizte( ... );\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21386/"
] |
337,175 | <p>I was once given this task to do in an RDBMS:</p>
<p>Given tables customer, order, orderlines and product. Everything done with the usual fields and relationships, with a comment memo field on the orderline table.</p>
<p>For one customer retrieve a list of all products that customer has ever ordered with product name, year of first purchase, dates of three last purchases, comment of the latest order, sum of total income for that product-customer combination last 12 months.</p>
<p>After a couple of days I gave up doing it as a Query and opted to just fetch every orderline for a customer, and every product and run through the data procedurally to build the required table clientside.</p>
<p>I regard this a symptom of one or more of the following:</p>
<ul>
<li>I'm a lazy idiot and should have seen how to do it in SQL</li>
<li>Set operations are not as expressive as procedural operations</li>
<li>SQL is not as expressive as it should be</li>
</ul>
<p>Did I do the right thing? Did I have other options?</p>
| [
{
"answer_id": 338183,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": true,
"text": "JOIN JOIN SELECT o.*, l.*, p.*\nFROM Orders o\n JOIN OrderLines l USING (order_id)\n JOIN Products p USING (product_id)\nWHERE o.customer_id = ?\nORDER BY o.order_date;\n order_date SELECT YEAR(MIN(o.order_date)) FROM Orders o WHERE o.customer_id = ?;\n SELECT SUM(l.quantity * p.price)\nFROM Orders o\n JOIN OrderLines l USING (order_id)\n JOIN Products p USING (product_id)\nWHERE o.customer_id = ?\n AND o.order_date > CURDATE() - INTERVAL 1 YEAR;\n SELECT o1.order_date\nFROM Orders o1\n LEFT OUTER JOIN Orders o2 \n ON (o1.customer_id = o2.customer_id AND (o1.order_date < o2.order_date \n OR (o1.order_date = o2.order_date AND o1.order_id < o2.order_id)))\nWHERE o1.customer_id = ?\nGROUP BY o1.order_id\nHAVING COUNT(*) <= 3;\n TOP LIMIT SELECT TOP 3 order_date\nFROM Orders\nWHERE customer_id = ?\nORDER BY order_date DESC;\n\nSELECT order_date\nFROM Orders\nWHERE customer_id = ?\nORDER BY order_date DESC\nLIMIT 3;\n"
},
{
"answer_id": 338769,
"author": "GalacticCowboy",
"author_id": 29638,
"author_profile": "https://Stackoverflow.com/users/29638",
"pm_score": 2,
"selected": false,
"text": "-- This could be a parameter to a stored procedure\n-- I picked this one because he has products that he ordered 4 or more times\ndeclare @customerId nchar(5)\nset @customerId = 'ERNSH'\n\nselect c.CustomerID, p.ProductName, products_ordered_by_cust.FirstOrderYear,\n latest_order_dates_pivot.LatestOrder1 as LatestOrderDate,\n latest_order_dates_pivot.LatestOrder2 as SecondLatestOrderDate,\n latest_order_dates_pivot.LatestOrder3 as ThirdLatestOrderDate,\n 'If I had a comment field it would go here' as LatestOrderComment,\n isnull(last_year_revenue_sum.ItemGrandTotal, 0) as LastYearIncome\nfrom\n -- Find all products ordered by customer, along with first year product was ordered\n (\n select c.CustomerID, od.ProductID,\n datepart(year, min(o.OrderDate)) as FirstOrderYear\n from Customers c\n join Orders o on o.CustomerID = c.CustomerID\n join [Order Details] od on od.OrderID = o.OrderID\n group by c.CustomerID, od.ProductID\n ) products_ordered_by_cust\n -- Find the grand total for product purchased within last year - note fudged date below (Northwind)\n join (\n select o.CustomerID, od.ProductID, \n sum(cast(round((od.UnitPrice * od.Quantity) - ((od.UnitPrice * od.Quantity) * od.Discount), 2) as money)) as ItemGrandTotal\n from\n Orders o\n join [Order Details] od on od.OrderID = o.OrderID\n -- The Northwind database only contains orders from 1998 and earlier, otherwise I would just use getdate()\n where datediff(yy, o.OrderDate, dateadd(year, -10, getdate())) = 0\n group by o.CustomerID, od.ProductID\n ) last_year_revenue_sum on last_year_revenue_sum.CustomerID = products_ordered_by_cust.CustomerID\n and last_year_revenue_sum.ProductID = products_ordered_by_cust.ProductID\n -- THIS is where the magic happens. I will walk through the individual pieces for you\n join (\n select CustomerID, ProductID,\n max([1]) as LatestOrder1,\n max([2]) as LatestOrder2,\n max([3]) as LatestOrder3\n from\n (\n -- For all orders matching the customer and product, assign them a row number based on the order date, descending\n -- So, the most recent is row # 1, next is row # 2, etc.\n select o.CustomerID, od.ProductID, o.OrderID, o.OrderDate,\n row_number() over (partition by o.CustomerID, od.ProductID order by o.OrderDate desc) as RowNumber\n from Orders o join [Order Details] od on o.OrderID = od.OrderID\n ) src\n -- Now, produce a pivot table that contains the first three row #s from our result table,\n -- pivoted into columns by customer and product\n pivot\n (\n max(OrderDate)\n for RowNumber in ([1], [2], [3])\n ) as pvt\n group by CustomerID, ProductID\n ) latest_order_dates_pivot on products_ordered_by_cust.CustomerID = latest_order_dates_pivot.CustomerID\n and products_ordered_by_cust.ProductID = latest_order_dates_pivot.ProductID\n -- Finally, join back to our other tables to get more details\n join Customers c on c.CustomerID = products_ordered_by_cust.CustomerID\n join Orders o on o.CustomerID = products_ordered_by_cust.CustomerID and o.OrderDate = latest_order_dates_pivot.LatestOrder1\n join [Order Details] od on od.OrderID = o.OrderID and od.ProductID = products_ordered_by_cust.ProductID\n join Products p on p.ProductID = products_ordered_by_cust.ProductID\nwhere c.CustomerID = @customerId\norder by CustomerID, p.ProductID\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37771/"
] |
337,179 | <p>I'm running tomcat and have some jsp pages that display a subset of a table. I show 20 rows at a time on a single page. When the table has large amounts of data, the jsp page doesn't render. I'm guessing that the ResultSet is using a client side cursor. I've worked with ASP in the past, and we always used server side forward only cursors, and never had any problems with large amounts of data. Our database is oracle 10g.</p>
<p>How can I specify a server-side forward-only cursor in JDBC?</p>
| [
{
"answer_id": 337206,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 2,
"selected": false,
"text": "Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY);\nResultSet rs = stmt.executeQuery(sql);\n rs.setFetchDirection(ResultSet.TYPE_FORWARD_ONLY);\n"
},
{
"answer_id": 338396,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 0,
"selected": false,
"text": "SELECT * \n FROM MyDataObjects\n WHERE rownum > 20 AND rownum < 41\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15852/"
] |
337,181 | <p>I need to create a rectangle bubble with rounded corners with text inside, like a cartoon speech bubble. I need the bubble to expand horizontally and vertically depending on the size of the text it contain. I would like the speech arrow and the radius of the rounded corners to remain constant.</p>
<p>I could simply use a path to create my bubble, but I can't resize the bubble and keep the corners radius and arrow constant... it's the whole path that will be resized.</p>
<p>I'd appreciate that some one could point me in the right direction.</p>
<p><em>removed dead ImageShack link</em></p>
<p>Here is the final version of the cartoon bubble user-control. I've added a rectangle without a stroke to Jobi Joy's version to hide the end of path lines, instead of trying to make then appear flush with the rectangle.</p>
<pre><code><Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<Rectangle Fill="#FF686868" Stroke="#FF000000" RadiusX="10" RadiusY="10"/>
<Path Fill="#FF686868" Stretch="Fill" Stroke="#FF000000" HorizontalAlignment="Left" Margin="30,-5.597,0,-0.003" Width="25" Grid.Row="1" Data="M22.166642,154.45381 L29.999666,187.66699 40.791059,154.54395"/>
<Rectangle Fill="#FF686868" RadiusX="10" RadiusY="10" Margin="1"/>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="25" Text="Hello World" TextWrapping="Wrap"/>
</Grid>
</code></pre>
| [
{
"answer_id": 337644,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 6,
"selected": true,
"text": "<Grid x:Name=\"grid\">\n <Grid.RowDefinitions>\n <RowDefinition Height=\"*\"/>\n <RowDefinition Height=\"40\"/>\n </Grid.RowDefinitions>\n <Rectangle Fill=\"#FF686868\" Stroke=\"#FF000000\" RadiusX=\"10\" RadiusY=\"10\"/>\n <Path Fill=\"#FF686868\" Stretch=\"Fill\" Stroke=\"#FF000000\" HorizontalAlignment=\"Left\" Margin=\"30,-1.6,0,0\" Width=\"25\" Grid.Row=\"1\" \n Data=\"M22.166642,154.45381 L29.999666,187.66699 40.791059,154.54395\"/> \n <TextBlock HorizontalAlignment=\"Center\" VerticalAlignment=\"Center\" FontSize=\"25\" Text=\"Hello World\" TextWrapping=\"Wrap\"/> \n</Grid>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42826/"
] |
337,183 | <p>I'd like to output html controls using xslt, but I need to be able to name the controls so that I can get at them when the form posts back.</p>
<p>I'd like to be able to name the radio button <code>"action_" + _case_id</code>.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="data.xsl"?>
<NewDataSet>
<Cases>
<Case>
<case_id>30</case_id>
</Case>
<Cases>
</NewDataSet>
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<div class="your_action">
Your action:<br />
<input type="radio" name="?" value="No" checked ="true"/> nothing to report<br />
<input type="radio" name="?" value="Yes" /> memo to follow
</div>
</xsl:template>
</xsl:stylesheet>
</code></pre>
| [
{
"answer_id": 337227,
"author": "Artur...",
"author_id": 41465,
"author_profile": "https://Stackoverflow.com/users/41465",
"pm_score": 0,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"data.xsl\"?>\n<NewDataSet>\n <Cases>\n <Case>\n <case_id>30</case_id>\n </Case>\n <Cases>\n</NewDataSet>\n\n<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:template match=\"/\">\n <xsl:variable name=\"actionid\">action_<xsl:value-of select=\"Cases/Case/case_id\"/></xsl:variable>\n <div class=\"your_action\">\n Your action:<br />\n <input type=\"radio\" name=\"{actionid}\" value=\"No\" checked =\"true\"/> nothing to report<br />\n <input type=\"radio\" name=\"{actionid}\" value=\"Yes\" /> memo to follow\n </div>\n </xsl:template>\n</xsl:stylesheet>\n"
},
{
"answer_id": 337430,
"author": "Johan L",
"author_id": 40282,
"author_profile": "https://Stackoverflow.com/users/40282",
"pm_score": 0,
"selected": false,
"text": "<input type=\"radio\" name=\"{$actionid}\" value=\"No\" checked =\"true\"/> nothing to report<br />\n"
},
{
"answer_id": 337625,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": 0,
"selected": false,
"text": "<xsl:variable name=\"parent1Name\"\n select=\"name(parent::*)\" />\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42697/"
] |
337,186 | <p>My if statement is always evaluating to false and not entering the <code><span></code> block. Because of which, I'm not able to get the value of "index" in the if condition, I've tried every thing appending index with # and %. Can anybody suggest the solution?</p>
<pre><code><c:forEach var="index" begin="1" end="<%=a%>" step="1">
<s:if test="index == 1">
<span class="currentpage"><b>${page_id}</b></span>
</s:if>
<s:else>
<a href="searchAction.html?page_id=${index}&searchString=${searchString}" class="paginglinks">${index}</a>
</s:else>
</c:forEach>
</code></pre>
| [
{
"answer_id": 337212,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "<s:if test=\"%{index == 1}\">\n"
},
{
"answer_id": 337228,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 0,
"selected": false,
"text": " test=\"${index == 1}\"\n <c:forEach var=\"index\" varStatus=\"status\" begin=\"1\" end=\"<%=a%>\" step=\"1\">\n\n <s:if test=\"${status.count == 1}\">\n <span class=\"currentpage\"><b>${page_id}</b></span>\n </s:if>\n <s:else>\n <a href=\"searchAction.html?page_id=${index}&searchString=${searchString}\" class=\"paginglinks\">${index}</a>\n </s:else>\n</c:forEach>\n"
},
{
"answer_id": 340279,
"author": "Vinayak Bevinakatti",
"author_id": 28557,
"author_profile": "https://Stackoverflow.com/users/28557",
"pm_score": 2,
"selected": true,
"text": "<c:forEach var=\"index\" begin=\"1\" end=\"<%=a%>\" step=\"1\" varStatus=\"status\">\n <c:choose>\n <c:when test=\"${page_id==index}\"> \n <span class=\"currentpage\"><b>${page_id}</b></span>\n </c:when>\n <c:otherwise>\n <a href=\"searchAction.html?page_id=${index}&searchString=${searchString}\" class=\"paginglinks\">${index}</a>\n </c:otherwise>\n </c:choose>\n </c:forEach>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28557/"
] |
337,208 | <p>MS Access appears to support nulls in code, but I can't for the life of me figure out how to enter a null directly in a table. This is maddening because once a field has had a figure entered in it, it can never be deleted/set to null. Normally, allowing zero length strings would take care of this, but Access treats the XML export of a null and a zero length string differently. A null eliminates the associated XML tag and a zero length string sends an empty tag.</p>
| [
{
"answer_id": 337235,
"author": "Patrick Harrington",
"author_id": 41165,
"author_profile": "https://Stackoverflow.com/users/41165",
"pm_score": 2,
"selected": false,
"text": "UPDATE test SET test.test = Null;\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1537/"
] |
337,223 | <p>Disclaimer: I'm fairly new to python!</p>
<p>If I want all the lines of a file until (edit: and including) the line containing some string <code>stopterm</code>, is there a way of using the list syntax for it? I was hoping there would be something like:</p>
<pre><code>usefullines = [line for line in file until stopterm in line]
</code></pre>
<p>For now, I've got</p>
<pre><code>usefullines = []
for line in file:
usefullines.append(line)
if stopterm in line:
break
</code></pre>
<p>It's not the end of the world, but since there rest of Python syntax is so straightforward, I was hoping for a 1 thought->1 Python line mapping.</p>
| [
{
"answer_id": 337247,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 1,
"selected": false,
"text": "def enum_until(source, until_criteria):\n for k in source:\n if until_criteria(k):\n break;\n yield k;\n\ndef enum_while(source, while_criteria):\n for k in source:\n if not while_criteria(k):\n break;\n yield k;\n \nl1 = [k for k in enum_until(xrange(1, 100000), lambda y: y == 100)];\nl2 = [k for k in enum_while(xrange(1, 100000), lambda y: y < 100)];\nprint l1;\nprint l2;\n"
},
{
"answer_id": 337279,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": "def usefulLines( aFile ):\n for line in aFile:\n yield line\n if line == stopterm:\n break\n for line in usefulLines( aFile ):\n # process a line, knowing it occurs BEFORE stopterm.\n lassevk enum_while enum_until"
},
{
"answer_id": 337285,
"author": "Steven Huwig",
"author_id": 28604,
"author_profile": "https://Stackoverflow.com/users/28604",
"pm_score": 4,
"selected": true,
"text": "from itertools import takewhile\nusefullines = takewhile(lambda x: not re.search(stopterm, x), lines)\n\nfrom itertools import takewhile\nusefullines = takewhile(lambda x: stopterm not in x, lines)\n def useful_lines(lines, stopterm):\n for line in lines:\n if stopterm in line:\n yield line\n break\n yield line\n\nusefullines = useful_lines(lines, stopterm)\n# or...\nfor line in useful_lines(lines, stopterm):\n # ... do stuff\n pass\n"
},
{
"answer_id": 337586,
"author": "JV.",
"author_id": 33612,
"author_profile": "https://Stackoverflow.com/users/33612",
"pm_score": 2,
"selected": false,
"text": "hello\nworld\nhappy\nday\nbye\n lines=open('./try').readlines()\n print [each for each in lines if lines.index(each)<=[lines.index(line) for line in lines if 'happy' in line][0]]\n ['hello\\n', 'world\\n', 'happy\\n']\n print [each for each in lines if lines.index(each)<=[lines.index(line) for line in lines if 'day' in line][0]]\n ['hello\\n', 'world\\n', 'happy\\n', 'day\\n']\n"
},
{
"answer_id": 337886,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 0,
"selected": false,
"text": "def stop(): raise StopIteration()\n\nusefullines = list(stop() if stopterm in line else line for line in file)\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36537/"
] |
337,237 | <p>I need the current user and the domain. I am using a VB 6 application. </p>
<p>Thanks</p>
| [
{
"answer_id": 337262,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": true,
"text": "Dim UserName As String\nDim UserDomain As String\nUserName = Environ(\"USERNAME\")\nUserDomain = Environ(\"USERDOMAIN\")\n"
},
{
"answer_id": 337269,
"author": "Saiyine",
"author_id": 38238,
"author_profile": "https://Stackoverflow.com/users/38238",
"pm_score": 0,
"selected": false,
"text": "Private Function IsAdmin() As Boolean\nDim groups As Object\nDim user As Object\n\nSet groups = GetObject(\"WinNT://./administrators\")\n\nFor Each user In groups.members\n\nIf UCase(Environ(\"USERNAME\")) = UCase(user.Name) Then\nIsAdmin = True\nEnd If\n\nNext user\n\nEnd Function\n"
},
{
"answer_id": 337374,
"author": "Stefan",
"author_id": 19307,
"author_profile": "https://Stackoverflow.com/users/19307",
"pm_score": 3,
"selected": false,
"text": "Private Declare Function GetUserName Lib \"advapi32.dll\" Alias \"GetUserNameA\" (ByVal lpBuffer As String, nSize As Long) As Long \n\nDeclare Function LookupAccountName Lib \"advapi32.dll\" Alias \"LookupAccountNameA\" (lpSystemName As String, ByVal lpAccountName As String, sid As Any, cbSid As Long, ByVal ReferencedDomainName As String, cbReferencedDomainName As Long, peUse As Long) As Long\n\nPrivate Sub Form_Load() \n Dim sDomainName As String * 255 \n Dim lDomainNameLength As Long \n Dim sUserName as String\n Dim bUserSid(255) As Byte \n Dim lSIDType As Long \n\n Rem Create a buffer\n sUserName = String(100, Chr$(0)) \n\n Rem Get the username\n GetUserName sUserName, 100 \n\n Rem strip the rest of the buffer\n sUserName = Left$(sUserName, InStr(sUserName, Chr$(0)) - 1)\n\n rem Show the temppath and the username\n MsgBox \"Hello \" + strUserName \n\n lResult = LookupAccountName(vbNullString, sUserName, bUserSid(0), 255, sDomainName, lDomainNameLength, _\n lSIDType)\n if lResult <>0 then\n msgbox sDomainName\n end if\nend sub\n"
},
{
"answer_id": 337375,
"author": "JeffK",
"author_id": 5420,
"author_profile": "https://Stackoverflow.com/users/5420",
"pm_score": 2,
"selected": false,
"text": "Dim Network As WshNetwork\nSet Network = New WshNetwork\n\nDebug.Print \"ComputerName: \" & Network.ComputerName\nDebug.Print \"UserDomain: \" & Network.UserDomain\nDebug.Print \"UserName: \" & Network.UserName\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154/"
] |
337,239 | <p>In C#, if I declare an auto-implemented property, why do I have to declare BOTH the get and set part? </p>
<p>i.e.</p>
<pre><code>public string ThisWorks { get; set; }
public string ThisDoesnt { get; }
</code></pre>
<p>Isn't this just syntactic sugar - i.e. the compiler inserts a private field for the property? So why the problem?</p>
<p>Curious.</p>
| [
{
"answer_id": 337246,
"author": "stusmith",
"author_id": 6604,
"author_profile": "https://Stackoverflow.com/users/6604",
"pm_score": 6,
"selected": true,
"text": "public string Foo\n{\n get;\n private set;\n}\n"
},
{
"answer_id": 337252,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "public string ReadonlyProperty { get; readonly set; }\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] |
337,254 | <p>I wonder if there is something like a standalone Version of Visual Studios "Immediate Window"? Sometimes I just want to test some simple stuff, like "DateTime.Parse("blah")" to see if that works. But everytime i have to create a new console application, put in my code and test it.</p>
<p>The Immediate Window sadly only works when I am debugging something. Could PowerShell do that? Just open a CLI similar to what cmd.exe does, allowing me to execute some C# code?</p>
| [
{
"answer_id": 337286,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "public static void Foo()\n{ \n Console.WriteLine(\"Hello\");\n}\n...\nFoo();\n"
},
{
"answer_id": 4269853,
"author": "Cameron",
"author_id": 21475,
"author_profile": "https://Stackoverflow.com/users/21475",
"pm_score": 0,
"selected": false,
"text": "DateTime.Parse(\"Blah\")"
},
{
"answer_id": 34032413,
"author": "Athari",
"author_id": 293099,
"author_profile": "https://Stackoverflow.com/users/293099",
"pm_score": 4,
"selected": false,
"text": "csi /path/myScript.csx csi csi foo.csx csi"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
337,268 | <p>What is the 'correct' way to store a native pointer inside a Java object?</p>
<p>I could treat the pointer as a Java <code>int</code>, if I happen to know that native pointers are <= 32 bits in size, or a Java <code>long</code> if I happen to know that native pointers are <= 64 bits in size. But is there a better or cleaner way to do this?</p>
<p><strong>Edit</strong>: Returning a native pointer from a JNI function is exactly what I <em>don't</em> want to do. I would rather return a Java object that represents the native resource. However, the Java object that I return must presumably have a field containing a pointer, which brings me back to the original question.</p>
<p>Or, alternatively, is there some better way for a JNI function to return a reference to a native resource?</p>
| [
{
"answer_id": 337303,
"author": "Avi",
"author_id": 1605,
"author_profile": "https://Stackoverflow.com/users/1605",
"pm_score": 2,
"selected": false,
"text": "int long"
},
{
"answer_id": 337359,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 6,
"selected": true,
"text": "java.util.zip java.nio long"
},
{
"answer_id": 337367,
"author": "Aaron Digulla",
"author_id": 34088,
"author_profile": "https://Stackoverflow.com/users/34088",
"pm_score": 2,
"selected": false,
"text": "int /*long*/ hModule = OS.GetLibraryHandle ();\n"
},
{
"answer_id": 36122140,
"author": "Alex Byrth",
"author_id": 4304439,
"author_profile": "https://Stackoverflow.com/users/4304439",
"pm_score": 3,
"selected": false,
"text": "java.nio.DirectByteBuffer private long address env->NewDirectByteBuffer((void*) data, sizeof(MyNativeStruct)) ByteBuffer directBuff = ByteBuffer.allocateDirect(sizeInBytes);\n malloc(sizeInBytes) env->GetDirectBufferAddress(buffer) void* env->NewDirectByteBuffer()"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31662/"
] |
337,272 | <p>How do I trigger a delay, let's say I want to call a method (once) in 3 seconds from now, and how do I cancel that call if I need to?</p>
| [
{
"answer_id": 337302,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 1,
"selected": false,
"text": "NSTimer *timer;\n timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(yourMethod:) userInfo:nil repeats:NO];\n [timer invalidate];\n"
},
{
"answer_id": 337310,
"author": "Stephen Darlington",
"author_id": 2998,
"author_profile": "https://Stackoverflow.com/users/2998",
"pm_score": 2,
"selected": false,
"text": " [NSTimer scheduledTimerWithTimeInterval: 3\n target: self\n selector: @selector(method:)\n userInfo: nil\n repeats: NO];\n - (void) method: (NSTimer*) theTimer;\n"
},
{
"answer_id": 337504,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 4,
"selected": true,
"text": "-[NSObject performSelector:awithObject:afterDelay:] +[NSObject cancelPreviousPerformRequestsWithTarget:selector:object]"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36182/"
] |
337,293 | <p>I need to edit (using javascript) an SVG document embedded in an html page.</p>
<p>When the SVG is loaded, I can access the dom of the SVG and its elements. But I am not able to know if the SVG dom is ready or not, so I cant' perform default actions on the SVG when the html page is loaded.</p>
<p>To access the SVG dom, I use this code:</p>
<pre><code>var svg = document.getElementById("chart").getSVGDocument();
</code></pre>
<p>where "chart" is the id of the embed element.</p>
<p>If I try to access the SVG when the html document is ready, in this way:</p>
<pre><code>jQuery(document).ready( function() {
var svg = document.getElementById("chart").getSVGDocument();
...
</code></pre>
<p>svg is always null. I just need to know when it is not null, so I can start manipulate it.
Do you know if there is a way to do it?</p>
| [
{
"answer_id": 337383,
"author": "Mocky",
"author_id": 3211,
"author_profile": "https://Stackoverflow.com/users/3211",
"pm_score": -1,
"selected": true,
"text": "function checkReady() {\n var svg = document.getElementById(\"chart\").getSVGDocument();\n if (svg == null) {\n setTimeout(\"checkReady()\", 300);\n } else {\n ...\n }\n}\n"
},
{
"answer_id": 3510578,
"author": "Erik Dahlström",
"author_id": 109374,
"author_profile": "https://Stackoverflow.com/users/109374",
"pm_score": 5,
"selected": false,
"text": "onload embeddingElm.addEventListener('load', callbackFunction, false) DOMContentLoaded jQuery(document).ready jQuery(document).ready embeddingElm.contentDocument embeddingElm.getSVGDocument()"
},
{
"answer_id": 4171518,
"author": "Boermans",
"author_id": 506555,
"author_profile": "https://Stackoverflow.com/users/506555",
"pm_score": 2,
"selected": false,
"text": "$(window).load(function(){\n var svg = document.getElementById(\"chart\").getSVGDocument();\n});\n"
},
{
"answer_id": 19141141,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 3,
"selected": false,
"text": "<embed> <embed id=\"embedded-image\" src=\"image.svg\" type=\"image/svg+xml\" />\n load document var embed = document.getElementById(\"embedded-image\");\nembed.addEventListener('load', function()\n{\n var svg = embed.getSVGDocument();\n // Operate upon the SVG DOM here\n});\n"
},
{
"answer_id": 20855567,
"author": "Terence Bandoian",
"author_id": 2367957,
"author_profile": "https://Stackoverflow.com/users/2367957",
"pm_score": 3,
"selected": false,
"text": "var element = document.getElementById( 'elementId' );\nvar svgDoc = element.contentDocument;\nvar svgRoot = svgDoc ? svgDoc.rootElement : null;\n\nif ( svgRoot\n && svgRoot.getCurrentTime\n && ( svgRoot.getCurrentTime() > 0 ))\n{\n /* SVG DOM ready */\n}\n"
},
{
"answer_id": 33934944,
"author": "Roshan Poudyal",
"author_id": 4139910,
"author_profile": "https://Stackoverflow.com/users/4139910",
"pm_score": 4,
"selected": false,
"text": "<body> \n<object id=\"svgholder\" data=\"some.svg\" type=\"image/svg+xml\"></object>\n</body>\n var svgholder = $('body').find(\"object#svgholder\");\n\nsvgholder.load(\"image/svg+xml\", function() {\n alert(\"some svg loaded\");\n});\n var svgholder = document.getElementById(\"svgholder\");\n\nsvgholder.onload = function() {\n alert(\"some svg loaded\");\n}\n"
},
{
"answer_id": 60735075,
"author": "LosManos",
"author_id": 521554,
"author_profile": "https://Stackoverflow.com/users/521554",
"pm_score": 0,
"selected": false,
"text": " @ViewChild('startimage', {static:false})\n private startimage: ElementRef;\n...\n this.startimage.nativeElement.addEventListener('load', () => {\n alert('loaded');\n });\n const svg = this.startimage.nativeElement.getSVGDocument();"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36587/"
] |
337,300 | <p>We need to validate an user on Microsoft's Active Directory using Delphi 7, what is the best way to do that?</p>
<p>We can have two scenarios: the user inputs its network username and password, where the username may include the domain, and we check on active directory if it is a valid, active user. Or we get the current logged user from Windows, and check on AD if it is still valid.</p>
<p>The first scenario requires user validation, while the second one just a simple AD search and locate.</p>
<p>Does anyone know of components or code that do one or both of the scenarios described above?</p>
| [
{
"answer_id": 337804,
"author": "Mick",
"author_id": 12458,
"author_profile": "https://Stackoverflow.com/users/12458",
"pm_score": 3,
"selected": false,
"text": " try\n ADSISearch1.Filter := WideString('samaccountname=' + GetUserFromWindows());\n\n try\n ADSISearch1.Search;\n slTemp := ADSISearch1.GetFirstRow();\n except\n //uh-oh, this is a problem, get out of here\n // --- must not have been able to talk to AD\n // --- could be the user recently changed pwd and is logged in with\n // their cached credentials\n // just suppress this exception\n bHomeDriveMappingFailed := True;\n Result := bSuccess;\n Exit;\n end;\n\n while (slTemp <> nil) do\n begin\n for ix := 0 to slTemp.Count - 1 do\n begin\n curLine := AnsiUpperCase(slTemp[ix]);\n if AnsiStartsStr('HOMEDIRECTORY', curLine) then\n begin\n sADHomeDriveUncPath := AnsiReplaceStr(curLine, 'HOMEDIRECTORY=', '');\n //sADHomeDriveUncPath := slTemp[ix];\n end\n else if AnsiStartsStr('HOMEDRIVE', curLine) then\n begin\n sADHomeDriveLetter := AnsiReplaceStr(curLine, 'HOMEDRIVE=', '');\n //sADHomeDriveLetter := slTemp[ix];\n end;\n end;\n\n FreeAndNil(slTemp);\n slTemp := ADSISearch1.GetNextRow();\n end;\n except\n //suppress this exception\n bHomeDriveMappingFailed := True;\n Exit;\n end;\n (* ----------------------------------------------------------------------------\n Module: ADSI Searching in Delphi\n Author: Marc Scheuner\n Date: July 17, 2000\n\n Changes:\n\n Description:\n\n constructor Create(aOwner : TComponent); override;\n Creates a new instance of component\n\n destructor Destroy; override;\n Frees instance of component\n\n function CheckIfExists() : Boolean;\n Checks to see if the object described in the properties exists or not\n TRUE: Object exists, FALSE: object does not exist\n\n procedure Search;\n Launches the ADSI search - use GetFirstRow and GetNextRow to retrieve information\n\n function GetFirstRow() : TWideStringList;\n function GetNextRow() : TWideStringList;\n Returns the first row / next row of the result set, as a WideStringList.\n The values are stored in the string list as a <name>=<value> pair, so you\n can access the values via the FWideStringList.Values['name'] construct.\n\n Multivalued attributes are returned as one per line, in an array index\n manner:\n objectClass[0]=top\n objectClass[1]=Person\n objectClass[2]=organizationalPerson\n objectClass[3]=user\n and so forth. The index is zero-based.\n\n If there are no (more) rows, the return value will be NIL.\n\n It's up to the receiver to free the string list when no longer needed.\n\n property Attributes : WideString\n Defines the attributes you want to retrieve from the object. If you leave\n this empty, all available attributes will be returned.\n You can specify multiple attributes separated by comma:\n cn,distinguishedName,name,ADsPath\n will therefore retrieve these four attributes for all the objects returned\n in the search (if the attributes exist).\n\n property BaseIADs : IADs\n If you already have an interface to an IADs object, you can reuse it here\n by setting it to the BaseIADs property - in this case, ADSISearch can skip\n the step of binding to the ADSI object and will be executing faster.\n\n property BasePath : WideString\n LDAP base path for the search - the further down in the LDAP tree you start\n searching, the smaller the namespace to search and the quicker the search\n will return what you're looking for.\n\n LDAP://cn=Users,dc=stmaarten,dc=qc,dc=rnd\n is the well-known LDAP path for the Users container in the stmaarten.qc.rnd\n domain.\n\n property ChaseReferrals : Boolean\n If set to TRUE, the search might need to connect to other domain controllers\n and naming contexts, which is very time consuming.\n Set this property to FALSE to limit it to the current naming context, thus\n speeding up searches significantly.\n\n property DirSrchIntf : IDirectorySearch\n Provides access to the basic Directory Search interface, in case you need\n to do some low-level tweaking\n\n property Filter : WideString\n LDAP filter expression to search for. It will be ANDed together with a\n (objectClass=<ObjectClass>) filter to form the full search filter.\n It can be anything that is a valid LDAP search filter - see the appropriate\n books or online help files for details.\n\n It can be (among many other things):\n cn=Marc*\n badPwdCount>=0\n countryCode=49\n givenName=Steve\n and multiple conditions can be ANDed or ORed together using the LDAP syntax.\n\n property MaxRows : Integer\n Maximum rows of the result set you want to retrieve.\n Default is 0 which means all rows.\n\n property PageSize : Integer\n Maximum number of elements to be returned in a paged search. If you set this to 0,\n the search will *not* be \"paged\", e.g. IDirectorySearch will return all elements\n found in one big gulp, but there's a limit at 1'000 elements.\n With paged searching, you can search and find any number of AD objects. Default is\n set to 100 elements. No special need on the side of the developer / user to use\n paged searches - just set the PageSize to something non-zero.\n\n property ObjectClass: WideString\n ObjectClass of the ADSI object you are searching for. This allows you to\n specify e.g. just users, only computers etc.\n Be aware that ObjectClass is a multivalued attribute in LDAP, and sometimes\n has unexpected hierarchies (e.g.\"computer\" descends from \"user\" and will therefore\n show up if you search for object class \"user\").\n This property will be included in the LDAP search filter passed to the\n search engine. If you don't want to limit the objects returned, just leave\n it at the default value of *\n\n property SearchScope\n Limits the scope of the search.\n scBase: search only the base object (as specified by the LDAP path) - not very\n useful.....\n scOneLevel: search only object immediately contained by the specified base\n object (does not include baes object) - limits the depth of\n the search\n scSubtree: no limit on how \"deep\" the search goes, below the specified\n base object - this is the default.\n\n---------------------------------------------------------------------------- *)\n\nunit ADSISearch;\n\ninterface\n\nuses\n ActiveX,\n ActiveDs_TLB,\n Classes,\n SysUtils\n{$IFDEF UNICODE}\n ,Unicode\n{$ENDIF}\n ;\n\ntype\n EADSISearchException = class(Exception);\n\n TSearchScope = (scBase, scOneLevel, scSubtree);\n\n TADSISearch = class(TComponent)\n private\n FBaseIADs : IADs;\n FDirSrchIntf : IDirectorySearch;\n FSearchHandle : ADS_SEARCH_HANDLE;\n FAttributes,\n FFilter,\n FBasePath,\n FObjectClass : Widestring;\n FResult : HRESULT;\n FChaseReferrals,\n FSearchExecuted : Boolean;\n FMaxRows,\n FPageSize : Integer;\n FSearchScope : TSearchScope;\n FUsername: Widestring;\n FPassword: Widestring;\n\n{$IFDEF UNICODE}\n procedure EnumerateColumns(aStrList : TWideStringList);\n{$ELSE}\n procedure EnumerateColumns(aStrList : TStringList);\n{$ENDIF}\n\n function GetStringValue(oSrchColumn : ads_search_column; Index : Integer) : WideString;\n\n procedure SetBaseIADs(const Value: IADs);\n procedure SetBasePath(const Value: WideString);\n procedure SetFilter(const Value: WideString);\n procedure SetObjectClass(const Value: Widestring);\n procedure SetMaxRows(const Value: Integer);\n procedure SetPageSize(const Value: Integer);\n procedure SetAttributes(const Value: WideString);\n procedure SetChaseReferrals(const Value: Boolean);\n procedure SetUsername(const Value: WideString);\n procedure SetPassword(const Value: WideString);\n\n public\n constructor Create(aOwner : TComponent); override;\n destructor Destroy; override;\n\n function CheckIfExists() : Boolean;\n procedure Search;\n\n{$IFDEF UNICODE}\n function GetFirstRow() : TWideStringList;\n function GetNextRow() : TWideStringList;\n{$ELSE}\n function GetFirstRow() : TStringList;\n function GetNextRow() : TStringList;\n{$ENDIF}\n\n published\n // list of attributes to return - empty string equals all attributes\n property Attributes : WideString read FAttributes write SetAttributes;\n\n // search base - both as an IADs interface, as well as a LDAP path\n property BaseIADs : IADs read FBaseIADs write SetBaseIADs stored False;\n property BasePath : WideString read FBasePath write SetBasePath;\n\n // chase possible referrals to other domain controllers?\n property ChaseReferrals : Boolean read FChaseReferrals write SetChaseReferrals default False;\n\n // \"raw\" search interface - for any low-level tweaking necessary\n property DirSrchIntf : IDirectorySearch read FDirSrchIntf;\n\n // LDAP filter to limit the search\n property Filter : WideString read FFilter write SetFilter;\n\n // maximum number of rows to return - 0 = all rows (no limit)\n property MaxRows : Integer read FMaxRows write SetMaxRows default 0;\n property ObjectClass : Widestring read FObjectClass write SetObjectClass;\n property PageSize : Integer read FPageSize write SetPageSize default 100;\n property SearchScope : TSearchScope read FSearchScope write FSearchScope default scSubtree;\n property Username : Widestring read FUsername write SetUsername;\n property Password : Widestring read FPassword write SetPassword;\n end;\n\nconst\n // ADSI success codes\n S_ADS_ERRORSOCCURRED = $00005011;\n S_ADS_NOMORE_ROWS = $00005012;\n S_ADS_NOMORE_COLUMNS = $00005013;\n\n // ADSI error codes\n E_ADS_BAD_PATHNAME = $80005000;\n E_ADS_INVALID_DOMAIN_OBJECT = $80005001;\n E_ADS_INVALID_USER_OBJECT = $80005002;\n E_ADS_INVALID_COMPUTER_OBJECT = $80005003;\n E_ADS_UNKNOWN_OBJECT = $80005004;\n E_ADS_PROPERTY_NOT_SET = $80005005;\n E_ADS_PROPERTY_NOT_SUPPORTED = $80005006;\n E_ADS_PROPERTY_INVALID = $80005007;\n E_ADS_BAD_PARAMETER = $80005008;\n E_ADS_OBJECT_UNBOUND = $80005009;\n E_ADS_PROPERTY_NOT_MODIFIED = $8000500A;\n E_ADS_PROPERTY_MODIFIED = $8000500B;\n E_ADS_CANT_CONVERT_DATATYPE = $8000500C;\n E_ADS_PROPERTY_NOT_FOUND = $8000500D;\n E_ADS_OBJECT_EXISTS = $8000500E;\n E_ADS_SCHEMA_VIOLATION = $8000500F;\n E_ADS_COLUMN_NOT_SET = $80005010;\n E_ADS_INVALID_FILTER = $80005014;\n\nprocedure Register;\n\n\n(*============================================================================*)\n(* IMPLEMENTATION *)\n(*============================================================================*)\n\nimplementation\n\nuses\n Windows;\n\nvar\n ActiveDSHandle : THandle;\n gADsGetObject: function(pwcPathName: PWideChar; const xRIID: TGUID; out pVoid): HResult; stdcall;\n gFreeADsMem : function(aPtr : Pointer) : BOOL; stdcall;\n\n\n// Active Directory API helper functions - implemented in ActiveDs.DLL and\n// dynamically loaded at time of initialization of this module\n\nfunction ADsGetObject(pwcPathName: PWideChar; const xRIID: TGUID; var pVoid): HResult;\nbegin\n Result := gADsGetObject(pwcPathName, xRIID, pVoid);\nend;\n\nfunction FreeADsMem(aPtr : Pointer) : BOOL;\nbegin\n Result := gFreeADsMem(aPtr);\nend;\n\n\n// resource strings for all messages - makes localization so much easier!\n\nresourcestring\n rc_CannotLoadActiveDS = 'Cannot load ActiveDS.DLL';\n rc_CannotGetProcAddress = 'Cannot GetProcAddress of ';\n\n rc_CouldNotBind = 'Could not bind to object %s (%x)';\n rc_CouldNotFreeSH = 'Could not free search handle (%x)';\n rc_CouldNotGetIDS = 'Could not obtain IDirectorySearch interface for %s (%x)';\n rc_GetFirstFailed = 'GetFirstRow failed (%x)';\n rc_GetNextFailed = 'GetNextRow failed (%x)';\n rc_SearchFailed = 'Search in ADSI failed (result code %x)';\n rc_SearchNotExec = 'Search has not been executed yet';\n rc_SetSrchPrefFailed = 'Setting the max row limit failed (%x)';\n rc_UnknownDataType = '(unknown data type %d)';\n\n// ---------------------------------------------------------------------------\n// Constructor and destructor\n// ---------------------------------------------------------------------------\n\nconstructor TADSISearch.Create(aOwner : TComponent);\nbegin\n inherited Create(aOwner);\n\n FBaseIADs := nil;\n FDirSrchIntf := nil;\n\n FAttributes := '';\n FBasePath := '';\n FFilter := '';\n FObjectClass := '*';\n\n FMaxRows := 0;\n FPageSize := 100;\n\n FChaseReferrals := False;\n FSearchScope := scSubtree;\n\n FSearchExecuted := False;\nend;\n\ndestructor TADSISearch.Destroy;\nbegin\n if (FSearchHandle <> 0) then\n FResult := FDirSrchIntf.CloseSearchHandle(FSearchHandle);\n\n FBaseIADs := nil;\n FDirSrchIntf := nil;\n\n inherited;\nend;\n\n// ---------------------------------------------------------------------------\n// Set and Get methods\n// ---------------------------------------------------------------------------\n\nprocedure TADSISearch.SetPassword(const Value: WideString);\nbegin\n if (FPassword <> Value) then\n begin\n FPassword := Value;\n end;\nend;\n\nprocedure TADSISearch.SetUsername(const Value: WideString);\nbegin\n if (FUsername <> Value) then\n begin\n FUsername := Value;\n end;\nend;\n\nprocedure TADSISearch.SetAttributes(const Value: WideString);\nbegin\n if (FAttributes <> Value) then begin\n FAttributes := Value;\n end;\nend;\n\n// the methods to set the search base always need to update the other property\n// as well, in order to make sure the base IADs interface and the BasePath\n// property stay in sync\n// setting the search base will require a new search\n// therefore set internal flag FSearchExecuted to false\nprocedure TADSISearch.SetBaseIADs(const Value: IADs);\nbegin\n if (FBaseIADs <> Value) then begin\n FBaseIADs := Value;\n FBasePath := FBaseIADs.ADsPath;\n FSearchExecuted := False;\n end;\nend;\n\nprocedure TADSISearch.SetBasePath(const Value: WideString);\nbegin\n if (FBasePath <> Value) then begin\n FBasePath := Value;\n FBaseIADs := nil;\n FSearchExecuted := False;\n end;\nend;\n\nprocedure TADSISearch.SetChaseReferrals(const Value: Boolean);\nbegin\n if (FChaseReferrals <> Value) then begin\n FChaseReferrals := Value;\n end;\nend;\n\n// setting the filter will require a new search\n// therefore set internal flag FSearchExecuted to false\nprocedure TADSISearch.SetFilter(const Value: WideString);\nbegin\n if (FFilter <> Value) then begin\n FFilter := Value;\n FSearchExecuted := False;\n end;\nend;\n\nprocedure TADSISearch.SetMaxRows(const Value: Integer);\nbegin\n if (Value >= 0) and (Value <> FMaxRows) then begin\n FMaxRows := Value;\n end;\nend;\n\nprocedure TADSISearch.SetPageSize(const Value: Integer);\nbegin\n if (Value >= 0) and (Value <> FPageSize) then begin\n FPageSize := Value;\n end;\nend;\n\n// setting the object category will require a new search\n// therefore set internal flag FSearchExecuted to false\nprocedure TADSISearch.SetObjectClass(const Value: Widestring);\nbegin\n if (FObjectClass <> Value) then begin\n if (Value = '') then\n FObjectClass := '*'\n else\n FObjectClass := Value;\n FSearchExecuted := False;\n end;\nend;\n\n// ---------------------------------------------------------------------------\n// Private helper methods\n// ---------------------------------------------------------------------------\n\n// EnumerateColumns iterates through all the columns in the current row of\n// the search results and builds the string list of results\n{$IFDEF UNICODE}\nprocedure TADSISearch.EnumerateColumns(aStrList: TWideStringList);\n{$ELSE}\nprocedure TADSISearch.EnumerateColumns(aStrList: TStringList);\n{$ENDIF}\nvar\n ix : Integer;\n bMultiple : Boolean;\n pwColName : PWideChar;\n oSrchColumn : ads_search_column;\n wsColName, wsValue : WideString;\nbegin\n // determine name of next column to fetch\n FResult := FDirSrchIntf.GetNextColumnName(FSearchHandle, pwColName);\n\n // as long as no error occured and we still do have columns....\n while Succeeded(FResult) and (FResult <> S_ADS_NOMORE_COLUMNS) do begin\n // get the column from the result set\n FResult := FDirSrchIntf.GetColumn(FSearchHandle, pwColName, oSrchColumn);\n\n if Succeeded(FResult) then begin\n // check if it's a multi-valued attribute\n bMultiple := (oSrchColumn.dwNumValues > 1);\n\n if bMultiple then begin\n // if it's a multi-valued attribute, iterate through the values\n for ix := 0 to oSrchColumn.dwNumValues-1 do begin\n wsColName := Format('%s[%d]', [oSrchColumn.pszAttrName, ix]);\n wsValue := GetStringValue(oSrchColumn, ix);\n aStrList.Add(wsColName + '=' + wsValue);\n end;\n end\n else begin\n // single valued attributes are quite straightforward\n wsColName := oSrchColumn.pszAttrName;\n wsValue := GetStringValue(oSrchColumn, 0);\n aStrList.Add(wsColName + '=' + wsValue);\n end;\n end;\n\n // free the memory associated with the search column, and the column name\n FDirSrchIntf.FreeColumn(oSrchColumn);\n FreeADsMem(pwColName);\n\n // get next column name\n FResult := FDirSrchIntf.GetNextColumnName(FSearchHandle, pwColName);\n end;\nend;\n\n// Get string value will turn the supported types of data into a string representation\n// for inclusion in the resulting string list\n// For a complete list of possible values, see the ADSTYPE_xxx constants in the\n// ActiveDs_TLB.pas file\nfunction TADSISearch.GetStringValue(oSrchColumn: ads_search_column; Index: Integer): WideString;\nvar\n wrkPointer : PADSValue;\n oSysTime : _SYSTEMTIME;\n dtDate,\n dtTime : TDateTime;\nbegin\n Result := '';\n\n // advance the value pointer to the correct one of the potentially multiple\n // values in the \"array of values\" for this attribute\n wrkPointer := oSrchColumn.pADsValues;\n Inc(wrkPointer, Index);\n\n // depending on the type of the value, turning it into a string is more\n // or less straightforward\n case oSrchColumn.dwADsType of\n ADSTYPE_CASE_EXACT_STRING : Result := wrkPointer^.__MIDL_0010.CaseExactString;\n ADSTYPE_CASE_IGNORE_STRING : Result := wrkPointer^.__MIDL_0010.CaseIgnoreString;\n ADSTYPE_DN_STRING : Result := wrkPointer^.__MIDL_0010.DNString;\n ADSTYPE_OBJECT_CLASS : Result := wrkPointer^.__MIDL_0010.ClassName;\n ADSTYPE_PRINTABLE_STRING : Result := wrkPointer^.__MIDL_0010.PrintableString;\n ADSTYPE_NUMERIC_STRING : Result := wrkPointer^.__MIDL_0010.NumericString;\n ADSTYPE_BOOLEAN : Result := IntToStr(wrkPointer^.__MIDL_0010.Boolean);\n ADSTYPE_INTEGER : Result := IntToStr(wrkPointer^.__MIDL_0010.Integer);\n ADSTYPE_LARGE_INTEGER : Result := IntToStr(wrkPointer^.__MIDL_0010.LargeInteger);\n ADSTYPE_UTC_TIME:\n begin\n // ADS_UTC_TIME maps to a _SYSTEMTIME structure\n Move(wrkPointer^.__MIDL_0010.UTCTime, oSysTime, SizeOf(oSysTime));\n // create two TDateTime values for the date and the time\n dtDate := EncodeDate(oSysTime.wYear, oSysTime.wMonth, oSysTime.wDay);\n dtTime := EncodeTime(oSysTime.wHour, oSysTime.wMinute, oSysTime.wSecond, oSysTime.wMilliseconds);\n // add the two TDateTime's (really only a Float), and turn into a string\n Result := DateTimeToStr(dtDate+dtTime);\n end;\n else Result := Format(rc_UnknownDataType, [oSrchColumn.dwADsType]);\n end;\nend;\n\n// ---------------------------------------------------------------------------\n// Public methods\n// ---------------------------------------------------------------------------\n\n// Check if any object matching the criteria as defined in the properties exists\nfunction TADSISearch.CheckIfExists(): Boolean;\nvar\n{$IFDEF UNICODE}\n slTemp : TWideStringList;\n{$ELSE}\n slTemp : TStringList;\n{$ENDIF}\n iOldMaxRows : Integer;\n wsOldAttributes : WideString;\nbegin\n Result := False;\n\n // save the settings of the MaxRows and Attributes properties\n iOldMaxRows := FMaxRows;\n wsOldAttributes := FAttributes;\n\n try\n // set the attributes to return just one row (that's good enough for\n // making sure it exists), and the Attribute of instanceType which is\n // one attribute that must exist for any of the ADSI objects\n FMaxRows := 1;\n FAttributes := 'instanceType';\n\n try\n Search;\n\n // did we get any results?? If so, at least one object exists!\n slTemp := GetFirstRow();\n Result := (slTemp <> nil);\n slTemp.Free;\n\n except\n on EADSISearchException do ;\n end;\n\n finally\n // restore the attributes to what they were before\n FMaxRows := iOldMaxRows;\n FAttributes := wsOldAttributes;\n end;\nend;\n\n{$IFDEF UNICODE}\nfunction TADSISearch.GetFirstRow(): TWideStringList;\nvar\n slTemp : TWideStringList;\n{$ELSE}\nfunction TADSISearch.GetFirstRow(): TStringList;\nvar\n slTemp : TStringList;\n{$ENDIF}\nbegin\n slTemp := nil;\n\n try\n if FSearchExecuted then begin\n // get the first row of the result set\n FResult := FDirSrchIntf.GetFirstRow(FSearchHandle);\n\n // did we succeed? ATTENTION: if we don't have any more rows,\n // we still get a \"success\" value back from ADSI!!\n if Succeeded(FResult) then begin\n // any more rows in the result set?\n if (FResult <> S_ADS_NOMORE_ROWS) then begin\n // create a string list\n{$IFDEF UNICODE}\n slTemp := TWideStringList.Create;\n{$ELSE}\n slTemp := TStringList.Create;\n{$ENDIF}\n // enumerate all columns into that resulting string list\n EnumerateColumns(slTemp);\n end;\n end\n else begin\n raise EADSISearchException.CreateFmt(rc_GetFirstFailed, [FResult]);\n end;\n end\n else begin\n raise EADSISearchException.Create(rc_SearchNotExec);\n end;\n\n finally\n Result := slTemp;\n end;\nend;\n\n{$IFDEF UNICODE}\nfunction TADSISearch.GetNextRow(): TWideStringList;\nvar\n slTemp : TWideStringList;\n{$ELSE}\nfunction TADSISearch.GetNextRow(): TStringList;\nvar\n slTemp : TStringList;\n{$ENDIF}\nbegin\n slTemp := nil;\n\n try\n if FSearchExecuted then begin\n // get the next row of the result set\n FResult := FDirSrchIntf.GetNextRow(FSearchHandle);\n\n // did we succeed? ATTENTION: if we don't have any more rows,\n // we still get a \"success\" value back from ADSI!!\n if Succeeded(FResult) then begin\n // any more rows in the result set?\n if (FResult <> S_ADS_NOMORE_ROWS) then begin\n // create result string list\n{$IFDEF UNICODE}\n slTemp := TWideStringList.Create;\n{$ELSE}\n slTemp := TStringList.Create;\n{$ENDIF}\n // enumerate all columns in result set\n EnumerateColumns(slTemp);\n end;\n end\n else begin\n raise EADSISearchException.CreateFmt(rc_GetNextFailed, [FResult]);\n end;\n end\n else begin\n raise EADSISearchException.Create(rc_SearchNotExec);\n end;\n\n finally\n Result := slTemp;\n end;\nend;\n\n// this is the core piece of the component - the actual search method\nprocedure TADSISearch.Search;\nvar\n ix : Integer;\n wsFilter : WideString;\n{$IFDEF UNICODE}\n slTemp : TWideStringList;\n{$ELSE}\n slTemp : TStringList;\n{$ENDIF}\n AttrCount : Cardinal;\n AttrArray : array of WideString;\n SrchPrefInfo : array of ads_searchpref_info;\n DSO :IADsOpenDSObject;\n Dispatch:IDispatch;\n\nbegin\n // check to see if we have assigned an IADs, if not, bind to it\n if (FBaseIADs = nil) then begin\n ADsGetObject('LDAP:', IID_IADsOpenDSObject, DSO);\n Dispatch := DSO.OpenDSObject(FBasePath, FUsername, FPassword, ADS_SECURE_AUTHENTICATION);\n FResult := Dispatch.QueryInterface(IID_IADs, FBaseIADs);\n //FResult := ADsGetObject(@FBasePath[1], IID_IADs, FBaseIADs);\n\n if not Succeeded(FResult) then begin\n raise EADSISearchException.CreateFmt(rc_CouldNotBind, [FBasePath, FResult]);\n end;\n end;\n\n // get the IDirectorySearch interface from the base object\n FDirSrchIntf := (FBaseIADs as IDirectorySearch);\n\n if (FDirSrchIntf = nil) then begin\n raise EADSISearchException.CreateFmt(rc_CouldNotGetIDS, [FBasePath, FResult]);\n end;\n\n // if we still have a valid search handle => close it\n if (FSearchHandle <> 0) then begin\n FResult := FDirSrchIntf.CloseSearchHandle(FSearchHandle);\n\n if not Succeeded(FResult) then begin\n raise EADSISearchException.CreateFmt(rc_CouldNotFreeSH, [FResult]);\n end;\n end;\n\n // we are currently setting 3 search preferences\n // for a complete list of possible search preferences, please check\n // the ADS_SEARCHPREF_xxx values in ActiveDs_TLB.pas\n SetLength(SrchPrefInfo, 4);\n\n // Set maximum number of rows to be what is defined in the MaxRows property\n SrchPrefInfo[0].dwSearchPref := ADS_SEARCHPREF_SIZE_LIMIT;\n SrchPrefInfo[0].vValue.dwType := ADSTYPE_INTEGER;\n SrchPrefInfo[0].vValue.__MIDL_0010.Integer := FMaxRows;\n\n // set the \"chase referrals\" search preference\n SrchPrefInfo[1].dwSearchPref := ADS_SEARCHPREF_CHASE_REFERRALS;\n SrchPrefInfo[1].vValue.dwType := ADSTYPE_BOOLEAN;\n SrchPrefInfo[1].vValue.__MIDL_0010.Boolean := Ord(FChaseReferrals);\n\n // set the \"search scope\" search preference\n SrchPrefInfo[2].dwSearchPref := ADS_SEARCHPREF_SEARCH_SCOPE;\n SrchPrefInfo[2].vValue.dwType := ADSTYPE_INTEGER;\n SrchPrefInfo[2].vValue.__MIDL_0010.Integer := Ord(FSearchScope);\n\n // set the \"page size \" search preference\n SrchPrefInfo[3].dwSearchPref := ADS_SEARCHPREF_PAGESIZE;\n SrchPrefInfo[3].vValue.dwType := ADSTYPE_INTEGER;\n SrchPrefInfo[3].vValue.__MIDL_0010.Integer := FPageSize;\n\n // set the search preferences of our directory search interface\n FResult := FDirSrchIntf.SetSearchPreference(Pointer(SrchPrefInfo), Length(SrchPrefInfo));\n\n if not Succeeded(FResult) then begin\n raise EADSISearchException.CreateFmt(rc_SetSrchPrefFailed, \n"
},
{
"answer_id": 339123,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "unit ADSI;\n\ninterface\n\nuses\n SysUtils, Classes, ActiveX, Windows, ComCtrls, ExtCtrls, ActiveDs_TLB,\n adshlp, oleserver, Variants;\n\ntype\n TPassword = record\n Expired: boolean;\n NeverExpires: boolean;\n CannotChange: boolean;\nend;\n\ntype\n TADSIUserInfo = record\n UID: string;\n UserName: string;\n Description: string;\n Password: TPassword;\n Disabled: boolean;\n LockedOut: boolean;\n Groups: string; //CSV\nend;\n\ntype\n TADSI = class(TComponent)\n\n private\n FUserName: string;\n FPassword: string;\n FCurrentUser: string;\n FCurrentDomain: string;\n\n function GetCurrentUserName: string;\n function GetCurrentDomain: string;\n\n\n protected\n { Protected declarations }\n public\n constructor Create(AOwner: TComponent); override;\n destructor Destroy; override;\n\n property CurrentUserName: string read FCurrentUser;\n property CurrentDomain: string read FCurrentDomain;\n\n function GetUser(Domain, UserName: string; var ADSIUser: TADSIUserInfo): boolean;\n function Authenticate(Domain, UserName, Group: string): boolean;\n\n published\n property LoginUserName: string read FUserName write FUserName;\n property LoginPassword: string read FPassword write FPassword;\n end;\n\nprocedure Register;\n\nimplementation\n\n\nfunction ContainsValComma(s1,s: string): boolean; \nvar \n sub,str: string; \nbegin \n Result:=false; \n if (s='') or (s1='') then exit; \n if SameText(s1,s) then begin \n Result:=true; \n exit; \n end; \n sub:=','+lowercase(trim(s1))+','; str:=','+lowercase(trim(s))+','; \n Result:=(pos(sub, str)>0); \nend;\n\nprocedure Register;\nbegin\n RegisterComponents('ADSI', [TADSI]);\nend;\n\nconstructor TADSI.Create(AOwner: TComponent);\nbegin\n inherited Create(AOwner);\n\n FCurrentUser:=GetCurrentUserName;\n FCurrentDomain:=GetCurrentDomain;\n FUserName:='';\n FPassword:='';\nend;\n\ndestructor TADSI.Destroy;\nbegin\n\n inherited Destroy;\nend;\n\nfunction TADSI.GetCurrentUserName : string;\nconst\n cnMaxUserNameLen = 254;\nvar\n sUserName : string;\n dwUserNameLen : DWord;\nbegin\n dwUserNameLen := cnMaxUserNameLen-1;\n SetLength(sUserName, cnMaxUserNameLen );\n GetUserName(PChar(sUserName), dwUserNameLen );\n SetLength(sUserName, dwUserNameLen);\n Result := sUserName;\nend;\n\nfunction TADSI.GetCurrentDomain: string;\nconst\n DNLEN = 255;\nvar\n sid : PSID;\n sidSize : DWORD;\n sidNameUse : DWORD;\n domainNameSize : DWORD; \n domainName : array[0..DNLEN] of char;\n\nbegin\n sidSize := 65536; \n GetMem(sid, sidSize); \n domainNameSize := DNLEN + 1;\n sidNameUse := SidTypeUser;\n try\n if LookupAccountName(nil, PChar(FCurrentUser), sid, sidSize,\n domainName, domainNameSize, sidNameUse) then\n Result:=StrPas(domainName);\n finally\n FreeMem(sid);\n end;\nend;\n\nfunction TADSI.Authenticate(Domain, UserName, Group: string): boolean;\nvar\n aUser: TADSIUserInfo;\nbegin\n Result:=false;\n if GetUser(Domain,UserName,aUser) then begin\n if not aUser.Disabled and not aUser.LockedOut then begin\n if Group='' then\n Result:=true\n else\n Result:=ContainsValComma(Group, aUser.Groups);\n end;\n end;\nend;\n\nfunction TADSI.GetUser(Domain, UserName: string; var ADSIUser: TADSIUserInfo): boolean;\nvar\n usr : IAdsUser;\n flags : integer;\n Enum : IEnumVariant;\n grps : IAdsMembers;\n grp : IAdsGroup;\n varGroup : OleVariant;\n Temp : LongWord;\n dom1, uid1: string;\n\n //ui: TADSIUserInfo;\n\nbegin\n ADSIUser.UID:='';\n ADSIUser.UserName:='';\n ADSIUser.Description:='';\n ADSIUser.Disabled:=true;\n ADSIUser.LockedOut:=true;\n ADSIUser.Groups:='';\n Result:=false;\n\n if UserName='' then\n uid1:=FCurrentUser\n else\n uid1:=UserName;\n\n if Domain='' then\n dom1:=FCurrentDomain\n else\n dom1:=Domain;\n\n if uid1='' then exit;\n if dom1='' then exit;\n\n try\n if trim(FUserName)<>'' then\n ADsOpenObject('WinNT://' + dom1 + '/' + uid1, FUserName, FPassword, 1, IADsUser, usr)\n else\n ADsGetObject('WinNT://' + dom1 + '/' + uid1, IADsUser, usr);\n\n if usr=nil then exit;\n\n ADSIUser.UID:= UserName;\n ADSIUser.UserName := usr.FullName;\n ADSIUser.Description := usr.Description;\n flags := usr.Get('userFlags');\n ADSIUser.Password.Expired := usr.Get('PasswordExpired');\n ADSIUser.Password.CannotChange := (flags AND ADS_UF_PASSWD_CANT_CHANGE)<>0;\n ADSIUser.Password.NeverExpires := (flags and ADS_UF_DONT_EXPIRE_PASSWD)<>0;\n ADSIUser.Disabled := usr.AccountDisabled;\n ADSIUser.LockedOut := usr.IsAccountLocked;\n\n ADSIUser.Groups:='';\n grps := usr.Groups;\n Enum := grps._NewEnum as IEnumVariant;\n if Enum <> nil then begin\n while (Enum.Next(1,varGroup, Temp) = S_OK) do begin\n grp := IDispatch(varGroup) as IAdsGroup;\n //sGroupType := GetGroupType(grp);\n if ADSIUser.Groups<>'' then ADSIUser.Groups:=ADSIUser.Groups+',';\n ADSIUser.Groups:=ADSIUser.Groups+grp.Name;\n VariantClear(varGroup);\n end;\n end;\n usr:=nil;\n Result:=true;\n except\n on e: exception do begin\n Result:=false;\n exit;\n end;\n end;\nend;\n\nend.\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
337,304 | <p>Which Eclipse files is it appropriate to put under source control, aside from the sources obviously?</p>
<p>In my project, specifically, I'm wondering about:</p>
<blockquote>
<p>.metadata/*<br>
project-dir/.project<br>
project-dir/.classpath<br>
project-dir/.settings/* </p>
</blockquote>
<p>If there are any of these for which it depends, please explain your guidelines.</p>
| [
{
"answer_id": 337317,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 8,
"selected": true,
"text": ".launch [eclipse-workspace]\\.metadata\\.plugins\\org.eclipse.debug.core\\.launches\n project-dir/.project\nproject-dir/.classpath\nproject-dir/.settings/* \n .project .classpath project-dir"
},
{
"answer_id": 10884014,
"author": "Alex McCarrier",
"author_id": 1298438,
"author_profile": "https://Stackoverflow.com/users/1298438",
"pm_score": 2,
"selected": false,
"text": ".classpath\n.project\n.launch\n"
},
{
"answer_id": 72657899,
"author": "Aaron Digulla",
"author_id": 34088,
"author_profile": "https://Stackoverflow.com/users/34088",
"pm_score": 1,
"selected": false,
"text": "project-dir/.project\nproject-dir/.classpath\nproject-dir/.settings/* \n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] |
337,305 | <p>Is it architecturally sound to use Rails and Oracle?
My concern is that Oracle would be too "heavy and hi-end" for Rails.
Any thoughts?
Thanks.</p>
| [
{
"answer_id": 337470,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 4,
"selected": true,
"text": "DATE"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/430254/"
] |
337,330 | <p>I'm hopeless at Javascript. This is what I have:</p>
<pre><code><script type="text/javascript">
function beginrefresh(){
//set the id of the target object
var marquee = document.getElementById("marquee_text");
if(marquee.scrollLeft >= marquee.scrollWidth - parseInt(marquee.style.width)) {
marquee.scrollLeft = 0;
}
marquee.scrollLeft += 1;
// set the delay (ms), bigger delay, slower movement
setTimeout("beginrefresh()", 10);
}
</script>
</code></pre>
<p>It scrolls to the left but I need it to repeat relatively seamlessly. At the moment it just jumps back to the beginning. It might not be possible the way I've done it, if not, anyone have a better method?</p>
| [
{
"answer_id": 26372490,
"author": "Stano",
"author_id": 1422309,
"author_profile": "https://Stackoverflow.com/users/1422309",
"pm_score": 3,
"selected": false,
"text": "window.addEventListener('load', function () {\n function go() {\n i = i < width ? i + step : 1;\n m.style.marginLeft = -i + 'px';\n }\n var i = 0,\n step = 3,\n space = ' ';\n var m = document.getElementById('marquee');\n var t = m.innerHTML; //text\n m.innerHTML = t + space;\n m.style.position = 'absolute'; // http://stackoverflow.com/questions/2057682/determine-pixel-length-of-string-in-javascript-jquery/2057789#2057789\n var width = (m.clientWidth + 1);\n m.style.position = '';\n m.innerHTML = t + space + t + space + t + space + t + space + t + space + t + space + t + space;\n m.addEventListener('mouseenter', function () {\n step = 0;\n }, true);\n m.addEventListener('mouseleave', function () {\n step = 3;\n }, true);\n var x = setInterval(go, 50);\n}, true); #marquee {\n background:#eee;\n overflow:hidden;\n white-space: nowrap;\n } <div id=\"marquee\">\n 1 Hello world! 2 Hello world! <a href=\"#\">3 Hello world!</a>\n</div>"
},
{
"answer_id": 26434054,
"author": "Manikandan",
"author_id": 1967211,
"author_profile": "https://Stackoverflow.com/users/1967211",
"pm_score": 2,
"selected": false,
"text": "<div class=\"cycle-slideshow\" data-cycle-fx=\"scrollHorz\" data-cycle-speed=\"9000\" data-cycle-timeout=\"1\" data-cycle-easing=\"linear\" data-cycle-pause-on-hover=\"true\" data-cycle-slides=\"> div\" >\n <div> Text 1 </div>\n <div> Text 2 </div>\n</div> \n"
},
{
"answer_id": 41542080,
"author": "M. Lak",
"author_id": 7250759,
"author_profile": "https://Stackoverflow.com/users/7250759",
"pm_score": 1,
"selected": false,
"text": "<script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function() {\n \n $('.scrollingtext').bind('marquee', function() {\n var ob = $(this);\n var tw = ob.width();\n var ww = ob.parent().width();\n ob.css({ right: -tw });\n ob.animate({ right: ww }, 20000, 'linear', function() {\n ob.trigger('marquee');\n });\n }).trigger('marquee');\n \n });\n </script>\n\n\n<div class=\"scroll\">\n <div class=\"scrollingtext\"> Flash message without marquee tag using javascript! </div>\n </div>\n"
},
{
"answer_id": 52833317,
"author": "Ale",
"author_id": 2157656,
"author_profile": "https://Stackoverflow.com/users/2157656",
"pm_score": 0,
"selected": false,
"text": "marquee div marquee direction scrolldelay scrollamount jQuery(function ($) {\n\n if ($('marquee').length == 0) {\n return;\n }\n\n $('marquee').each(function () {\n\n let direction = $(this).attr('direction');\n let scrollamount = $(this).attr('scrollamount');\n let scrolldelay = $(this).attr('scrolldelay');\n\n let newMarquee = $('<div class=\"new-marquee\"></div>');\n $(newMarquee).html($(this).html());\n $(newMarquee).attr('direction',direction);\n $(newMarquee).attr('scrollamount',scrollamount);\n $(newMarquee).attr('scrolldelay',scrolldelay);\n $(newMarquee).css('white-space', 'nowrap');\n\n let wrapper = $('<div style=\"overflow:hidden\"></div>').append(newMarquee);\n $(this).replaceWith(wrapper);\n\n });\n\n function start_marquee() {\n\n let marqueeElements = document.getElementsByClassName('new-marquee');\n let marqueLen = marqueeElements.length\n for (let k = 0; k < marqueLen; k++) {\n\n\n let space = ' ';\n let marqueeEl = marqueeElements[k];\n\n let direction = marqueeEl.getAttribute('direction');\n let scrolldelay = marqueeEl.getAttribute('scrolldelay') * 100;\n let scrollamount = marqueeEl.getAttribute('scrollamount');\n\n let marqueeText = marqueeEl.innerHTML;\n\n marqueeEl.innerHTML = marqueeText + space;\n marqueeEl.style.position = 'absolute'; \n\n let width = (marqueeEl.clientWidth + 1);\n let i = (direction == 'rigth') ? width : 0;\n let step = (scrollamount !== undefined) ? parseInt(scrollamount) : 3;\n\n marqueeEl.style.position = '';\n marqueeEl.innerHTML = marqueeText + space + marqueeText + space;\n\n\n\n let x = setInterval( function () {\n\n if ( direction.toLowerCase() == 'left') {\n\n i = i < width ? i + step : 1;\n marqueeEl.style.marginLeft = -i + 'px';\n\n } else {\n\n i = i > -width ? i - step : width;\n marqueeEl.style.marginLeft = -i + 'px';\n\n }\n\n }, scrolldelay);\n\n }\n }\n\n start_marquee ();\n});\n"
},
{
"answer_id": 68656166,
"author": "OGadoury",
"author_id": 8702062,
"author_profile": "https://Stackoverflow.com/users/8702062",
"pm_score": 0,
"selected": false,
"text": "<div id=\"marquee\">\n <script type=\"text/javascript\">\n\n let marquee = $('#marquee p');\n const appendToMarquee = (content) => {\n marquee.append(content);\n }\n \n const fillMarquee = (itemsToAppend, content) => {\n for (let i = 0; i < itemsToAppend; i++) {\n appendToMarquee(content);\n }\n }\n \n const animateMarquee = (itemsToAppend, content, width) => {\n fillMarquee(itemsToAppend, content);\n marquee.animate({left: `-=${width}`,}, width*10, 'linear', function() {\n animateMarquee(itemsToAppend, content, width);\n })\n }\n\n\n const initMarquee = () => {\n let width = $(window).width(),\n marqueeContent = \"YOUR TEXT\",\n itemsToAppend = width / marqueeContent.split(\"\").length / 2;\n animateMarquee(itemsToAppend, marqueeContent, width);\n }\n\n initMarquee();\n</script>\n #marquee {\n overflow: hidden;\n margin: 0;\n padding: 0.5em 0;\n bottom: 0;\n left: 0;\n right: 0;\n background-color: #000;\n color: #fff;\n}\n\n#marquee p {\n white-space: nowrap;\n margin: 0;\n overflow: visible;\n position: relative;\n left: 0;\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31168/"
] |
337,333 | <p>I want to insert a new row into an Access database. I'm looking at doing something like: </p>
<pre><code>oConnection = new Connection("connectionstring")
oTable = oCennection.table("Orders")
oRow = oTable.NewRow
oRow.field("OrderNo")=21
oRow.field("Customer") = "ABC001"
oTable.insert
</code></pre>
<p>Which seems to be a sensible way of doing things to me. </p>
<p>However, All examples I look for on the net seem to insert data by building SQL statements, or by creating a "SELECT * From ...", and then using this to create a multitude of objects, one of which appears to allow you to ...<br>
- populate an array with the current contents of the table.<br>
- insert a new row into this array.<br>
- update the database with the changes to the array. </p>
<p>What's the easiest way of using vb.net to insert data into an Access database?<br>
Is there a method I can use that is similar to my pCode above? </p>
| [
{
"answer_id": 337461,
"author": "Stefan",
"author_id": 19307,
"author_profile": "https://Stackoverflow.com/users/19307",
"pm_score": 3,
"selected": true,
"text": "cn = New OleDbConnection(\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\emp.mdb;\")\ncn.Open()\nstr = \"insert into table1 values(21,'ABC001')\"\ncmd = New OleDbCommand(str, cn)\ncmd.ExecuteNonQuery\n Dim UserDS As New UserDS\n Dim UserDA As New UserDSTableAdapters.UsersTableAdapter\n Dim NewUser As UserDS.UsersRow = UserDS.Users.NewUsersRow\n\n NewUser.UserName = \"Stefan\"\n NewUser.LastName = \"Karlsson\"\n\n UserDS.User.AddUserRow(NewUser)\n\n UserDA.Update(UserDS.Users)\n"
},
{
"answer_id": 729596,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Try\n cn = New OleDbConnection(\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\User\\My Documents\\db1.mdb;\")\n cn.Open()\n str = \"insert into table1 values(\" & CInt(t2.Text) & \",'\" & (t1.Text) & \") \"\n cmd = New OleDbCommand(str, cn)\n icount = cmd.ExecuteNonQuery\n MessageBox.Show(\"stored\")\nCatch\nEnd Try\ncn.Close()\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726/"
] |
337,334 | <p>I am trying to send an anonymous object over a web service. Is there anyway I can do this without manually creating a class and casting it to that class? Currently its throwing an exception saying Anonymous object could not be serialized.</p>
<pre><code>// Some code has been removed here to simplify the example.
[WebMethod(EnableSession = true)]
public Response GetPatientList() {
var patientList = from patient in ((User)Session["user"]).Practice.Patients
select new {
patientID = patient.PatientID,
status = patient.Active ? "Active" : "Inactive",
patientIdentifier = patient.PatientIdentifier,
physician = (patient.Physician.FirstName + " " + patient.Physician.LastName).Trim(),
lastModified = patient.Visits.Max(v => v.VisitDate)
};
return patientList;
}
</code></pre>
<p>Thanks in advance.</p>
<p><em>Edit:</em> Here is an example of what I mean by manually creating a class to return and fill it with the anonymous object...</p>
<pre><code>public class Result {
public bool success;
public bool loggedIn;
public string message;
}
public class PracticeInfoResult : Result {
public string practiceName;
public string address;
public string city;
public string state;
public string zipCode;
public string phone;
public string fax;
}
</code></pre>
| [
{
"answer_id": 337366,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "new {"
},
{
"answer_id": 339320,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 1,
"selected": false,
"text": "[WebMethod(EnableSession = true)]\npublic PatientsResult GetPatientList(bool returnInactivePatients) {\n if (!IsLoggedIn()) {\n return new PatientsResult() {\n Success = false,\n LoggedIn = false,\n Message = \"Not logged in\"\n };\n }\n Func<IEnumerable<PatientResult>, IEnumerable<PatientResult>> filterActive = \n patientList => returnInactivePatients ? patientList : patientList.Where(p => p.Status == \"Active\");\n User u = (User)Session[\"user\"];\n return new PatientsResult() {\n Success = true,\n LoggedIn = true,\n Message = \"\",\n Patients = filterActive((from p in u.Practice.Patients\n select new PatientResult() {\n PhysicianID = p.PhysicianID,\n Status = p.Active ? \"Active\" : \"Inactive\",\n PatientIdentifier = p.PatientIdentifier,\n PatientID = p.PatientID,\n LastVisit = p.Visits.Count > 0 ? p.Visits.Max(v => v.VisitDate).ToShortDateString() : \"\",\n Physician = (p.Physician == null ? \"\" : p.Physician.FirstName + \" \" + p.Physician == null ? \"\" : p.Physician.LastName).Trim(),\n })).ToList<PatientResult>()\n };\n}\npublic class Result {\n public bool Success { get; set; }\n public bool LoggedIn { get; set; }\n public string Message { get; set; }\n}\npublic class PatientsResult : Result {\n public List<PatientResult> Patients { get; set; }\n}\npublic class PatientResult {\n public int PatientID { get; set; }\n public string Status { get; set; }\n public string PatientIdentifier { get; set; }\n public string Physician { get; set; }\n public int? PhysicianID {get;set;}\n public string LastVisit { get; set; }\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] |
337,352 | <p>Is there a way to 'pre-build' a snippet of HTML before adding it to the DOM?</p>
<p>For example:</p>
<pre><code>$mysnippet.append("<h1>hello</h1>");
$mysnippet.append("<h1>world</h1>");
$("destination").append($mysnippet);
</code></pre>
<p>where <strong>$mysnippet</strong> doesnt exist in the DOM. I'd like to dynamically build up some lumps of html and then insert them into the page at appropriate points later.</p>
| [
{
"answer_id": 337385,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 6,
"selected": true,
"text": "$('<div>').attr('id', 'yourid').addClass('yourclass').append().append()...\n .appendTo($(\"#parentid\"));\n"
},
{
"answer_id": 337387,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "$mysnippet = \"<h1>hello</h1>\";\n$mysnippet = $mysnippet + \"<h1>world</h1>\";\n$(\"destination\").append($mysnippet);\n"
},
{
"answer_id": 1091493,
"author": "fbuchinger",
"author_id": 113936,
"author_profile": "https://Stackoverflow.com/users/113936",
"pm_score": 6,
"selected": false,
"text": "<div class=\"template-node\" style=\"display:none;\">\n <h2>Template Headline</h2>\n <p class=\"summary\">Summary goes here</p>\n <a href=\"#\" class=\"storylink\">View full story</a>\n</div>\n var $clone = $('.template-node').clone();\n$clone.find('h2').text('My new headline');\n$clone.find('p').text('My article summary');\n$clone.find('a').attr('href','article_page.html');\n$('#destination').append($clone);\n"
},
{
"answer_id": 13952809,
"author": "bart s",
"author_id": 474535,
"author_profile": "https://Stackoverflow.com/users/474535",
"pm_score": 3,
"selected": false,
"text": "var memtag = $('<div />', {\n 'class' : 'yourclass',\n 'id' : 'theId',\n 'data-aaa' : 'attributevalue',\n html : 'text between the div tags'\n});\n memtag img"
},
{
"answer_id": 37485904,
"author": "Timothy Gonzalez",
"author_id": 2646126,
"author_profile": "https://Stackoverflow.com/users/2646126",
"pm_score": 0,
"selected": false,
"text": "var sample =\n $('<div></div>')\n .append(\n $('<div></div>')\n .addClass('testing-attributes')\n .text('testing'))\n .html();\n <div class=\"testing-attributes\">testing</div>\n"
},
{
"answer_id": 38675232,
"author": "Mitja Gustin",
"author_id": 1617366,
"author_profile": "https://Stackoverflow.com/users/1617366",
"pm_score": 0,
"selected": false,
"text": "var eltProps = {\n css: {\n border: 1,\n \"background-color\": \"red\",\n padding: \"5px\"\n },\n class: \"bblock\",\n id: \"bb_1\",\n html: \"<span>jQuery</span>\",\n data: {\n name: \"normal-div\",\n role: \"building-block\"\n },\n click: function() {\n alert(\"I was clicked. My id is\" + $(this).attr(\"id\"));\n }\n};\n\nvar elt = $(\"<div/>\", eltProps);\n\n$(\"body\").append(elt);\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39655/"
] |
337,355 | <p>I need to bitwise shift a value 64 times in JavaScript. But JavaScript starts rounding after <code>32</code>.</p>
<p>For example:</p>
<pre><code>for(var j = 0; j < 64; j++)
{
mask = mask << 1;
console.log(mask);
}
</code></pre>
<p>This prints value from <code>0</code> to <code>1073741824</code> but then rounds of and starts printing <code>0</code>.</p>
| [
{
"answer_id": 337572,
"author": "itsadok",
"author_id": 7581,
"author_profile": "https://Stackoverflow.com/users/7581",
"pm_score": 6,
"selected": true,
"text": "for(var j = 0; j < 64; j++) {\n mask = mask * 2;\n console.log(mask);\n}\n function lshift(num, bits) {\n return num * Math.pow(2,bits);\n}\n"
},
{
"answer_id": 72466714,
"author": "Attila Molnár",
"author_id": 19250969,
"author_profile": "https://Stackoverflow.com/users/19250969",
"pm_score": 2,
"selected": false,
"text": ">>> console.log(1n << 32n); // 4294967296n\nconsole.log(1n << 40n); // 1099511627776n\n\nconsole.log((1n << 40n).toString(2)); // 1 00000000 00000000 00000000 00000000 00000000\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42846/"
] |
337,389 | <p>This should be easy for many of you, but for me it's just another bit of rust needing to be chipped away as I get back into basic Java coding. Using bloody associative arrays for so long in other languages have turned me nice and spoiled. :P</p>
<p>My problem is simple: I'm storing a set of objects, each containing a string and a number, in a list. I would like each object inserted into this list to be sorted alphabetically by its string. I would also like to be able to retrieve objects from the list by their string as well. I would like to do this as formally and/or efficiently as possible.</p>
<p>Is there something already available in the Java standard libraries for this?</p>
| [
{
"answer_id": 337410,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 2,
"selected": false,
"text": " TreeSet<Pair<String, Number>>"
},
{
"answer_id": 338926,
"author": "Duc",
"author_id": 335066,
"author_profile": "https://Stackoverflow.com/users/335066",
"pm_score": 1,
"selected": false,
"text": "Multimap<String, Pair> mm = new TreeMultimap<String, Pair>(\n new Comparator<String>(){...}, \n new PairComparator());\nmm.put(\"A\", new Pair(\"A\", 1));\nmm.put(\"B\", new Pair(\"B\", 2));\nmm.put(\"B\", new Pair(\"B\", 3));\nCollection values = mm.values(); \n // values are [Pair(\"A\", 1), Pair(\"B\", 2), Pair(\"B\", 3)]\nCollection bValues = mm.get(\"B\"); \n // bValues are [Pair(\"B\", 2), Pair(\"B\", 3)]\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19825/"
] |
337,406 | <p>In Visual Studio as most of you will have noticed that related file can be collapsed in to one. E.G.</p>
<ul>
<li>Form1.cs
<ul>
<li>Form1.Designer.cs</li>
</ul></li>
</ul>
<p>I'm creating a DAL library and will be splitting partial classes in to several files such as:</p>
<ul>
<li>SomeTableClass.cs
<ul>
<li>SomeTableClass.Generated.cs</li>
<li>SomeTableClass.SomethingElse.cs</li>
</ul></li>
</ul>
<p>Is there any way in Visual Studio to recognise these file are related to each other an create the collapsible effect?</p>
<p>Thanks</p>
<p>Tony</p>
| [
{
"answer_id": 337458,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": true,
"text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\8.0\\Projects\\{E24C65DC-7377-472B-9ABA-BC803B73C61A}\\RelatedFiles \\8.0\\ \\9.0\\"
},
{
"answer_id": 698303,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 2,
"selected": false,
"text": "DependentUpon <Compile Include=\"SomeTableClass.cs\" />\n<Compile Include=\"SomeTableClass.Generated.cs\">\n <DependentUpon>SomeTableClass.cs</DependentUpon>\n</Compile>\n"
},
{
"answer_id": 1657716,
"author": "dansays",
"author_id": 1923,
"author_profile": "https://Stackoverflow.com/users/1923",
"pm_score": 2,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\9.0\\Projects\\{E24C65DC-7377-472B-9ABA-BC803B73C61A}\\RelatedFiles"
},
{
"answer_id": 19745439,
"author": "Sebastian",
"author_id": 281306,
"author_profile": "https://Stackoverflow.com/users/281306",
"pm_score": 2,
"selected": false,
"text": "HKCU HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\11.0_Config\\{E24C65DC-7377-472B-9ABA-BC803B73C61A}\\RelatedFiles"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35389/"
] |
337,419 | <p>What is the best way to ascertain the length (in characters) of the longest element in an array?</p>
<p>I need to find the longest element in an array of option values for a select box so that I can set the width dynamically.</p>
| [
{
"answer_id": 337435,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 1,
"selected": false,
"text": "fixed width"
},
{
"answer_id": 337441,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 1,
"selected": false,
"text": "$longval = 0;\n$index = -1;\n\nfor($i = 0; $i < count($array); $i++) {\n if($len = strlen($array[$i]) > $longval) { \n $longval = $len;\n $index = $i;\n }\n}\n $array[$index] $longval"
},
{
"answer_id": 337451,
"author": "Logan Serman",
"author_id": 29595,
"author_profile": "https://Stackoverflow.com/users/29595",
"pm_score": 0,
"selected": false,
"text": "$longest_length = 0;\n\nforeach($array as $key => $value\n{\n if(isset($value[$longest_length + 1]))\n {\n $longest_length = strlen($value);\n }\n}\n"
},
{
"answer_id": 337484,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": 2,
"selected": true,
"text": "function array_longest_value( $array, &$val = null )\n{\n $val = null;\n $result = null;\n\n foreach( array_keys( $array ) as $i )\n {\n $l = strlen( $array[ $i ] );\n if ( $l > $result )\n {\n $result = $i;\n $val = $array[ $i ];\n }\n }\n\n return $result;\n} \n"
},
{
"answer_id": 337500,
"author": "Sander Versluys",
"author_id": 2172,
"author_profile": "https://Stackoverflow.com/users/2172",
"pm_score": 0,
"selected": false,
"text": "$array = array('andy', 'patrick', 'mat', 'perenenappels');\n\nfunction len_sort($a, $b) {\n return strlen($a) > strlen($b) ? 1 : 0;\n}\n\nusort($array, 'len_sort');\n\necho array_pop($array);\n"
},
{
"answer_id": 337508,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 2,
"selected": false,
"text": "$x = array( \n 'foo ', 'bar ____' , 'baz', 'q-----------', 'doo' \n);\n\nfunction max_str( $stringArray )\n{\n $m = '_'; \n foreach($stringArray as $item ) \n {\n $m[ strlen($item) ] = '_'; \n }\n return strlen( $m ); \n}\n\n\nprint max_str( $x ); \n $m \"\" $m substr( $m , 0 , strlen($item)) = $item; \n iiiiiiiiii llllllllll oooooooooo mmmmmmmmmm"
},
{
"answer_id": 337562,
"author": "OIS",
"author_id": 36175,
"author_profile": "https://Stackoverflow.com/users/36175",
"pm_score": 2,
"selected": false,
"text": "echo max(array_map('strlen', $arr));\n function array_longest_strings(array $arr)\n{\n $arr2 = array_map('strlen', $arr);\n $arr3 = array_intersect($arr2, array(max($arr2)));\n return array_intersect_key($arr, $arr3);\n}\nprint_r(array_longest_strings($arr));\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69346/"
] |
337,422 | <p>How to UDP Broadcast with C in Linux?</p>
| [
{
"answer_id": 337437,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "sendto()"
},
{
"answer_id": 337465,
"author": "shodanex",
"author_id": 11589,
"author_profile": "https://Stackoverflow.com/users/11589",
"pm_score": 4,
"selected": false,
"text": "static void\nbroadcast(const char *mess)\n{\n #define BROADCAST_PORT 30000u\n struct sockaddr_in s;\n\n int broadcastSock = socket(AF_INET, SOCK_DGRAM, 0);\n \n if(broadcastSock < 0)\n return;\n\n memset(&s, '\\0', sizeof(struct sockaddr_in));\n s.sin_family = AF_INET;\n s.sin_port = htons(BROADCAST_PORT)\n s.sin_addr.s_addr = INADDR_BROADCAST; /* This is not correct : htonl(INADDR_BROADCAST); */\n\n cli_dbgmsg(\"broadcast %s to %d\\n\", mess, broadcastSock);\n if(sendto(broadcastSock, mess, strlen(mess), 0, (struct sockaddr *)&s, sizeof(struct sockaddr_in)) < 0)\n perror(\"sendto\");\n}\n"
},
{
"answer_id": 361876,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "#include <stdlib.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <time.h>\n#include <string.h>\n#include <stdio.h>\n\n#include <unistd.h>\n\n\n#define BYE_OFFICE 12346\n#define HELLO_PORT 12345\n#define HELLO_GROUP \"225.0.0.37\"\n\nint main(int argc, char *argv[])\n{\n struct sockaddr_in addr;\n struct sockaddr_in addr2;\n int fd;\n int fd2;\n char *message = \"Hello, World!\";\n char *message2 = \"Bye, Office!\";\n\n if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)\n {\n perror(\"socket\");\n exit(1);\n }\n\n if ((fd2 = socket(AF_INET, SOCK_DGRAM, 0)) < 0)\n {\n perror(\"socket\");\n exit(1);\n }\n\n /* set up destination address */\n memset(&addr,0,sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_addr.s_addr = inet_addr(HELLO_GROUP);\n addr.sin_port=htons(HELLO_PORT);\n\n memset(&addr2,0,sizeof(addr2));\n addr2.sin_family = AF_INET;\n addr2.sin_addr.s_addr = inet_addr(HELLO_GROUP);\n addr2.sin_port=htons(BYE_OFFICE);\n\n while (1)\n {\n if (sendto(fd, message, strlen(message), 0,(struct sockaddr *) &addr, sizeof(addr)) < 0)\n {\n perror(\"sendto\");\n exit(1);\n }\n sleep(3);\n if (sendto(fd2, message2, strlen(message2), 0,(struct sockaddr *) &addr2, sizeof(addr2)) < 0)\n {\n perror(\"sendto2\");\n exit(1);\n }\n sleep(3);\n }\n}\n"
},
{
"answer_id": 11567421,
"author": "skoylu",
"author_id": 1538849,
"author_profile": "https://Stackoverflow.com/users/1538849",
"pm_score": 6,
"selected": false,
"text": "bcast_sock = socket(AF_INET, SOCK_DGRAM, 0);\nint broadcastEnable=1;\nint ret=setsockopt(bcast_sock, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable));\n\n/* Add other code, sockaddr, sendto() etc. */\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] |
337,431 | <p>I've been doing some performance testing around the use of System.Diagnostics.Debug, and it seems that all code related to the static class Debug gets completely removed when the Release configuration is built. I was wondering how the compiler knows that. Maybe there is some class or configuration attribute that allows to specify exactly that behavior.</p>
<p>I am trying to create some debugging code that I want completely removed from the Release configuration, and I was wondering if I could do it just like the Debug class where simply changing the configuration parameters removes the code.</p>
| [
{
"answer_id": 337444,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 2,
"selected": false,
"text": "#if DEBUG\n //code\n#endif\n"
},
{
"answer_id": 337462,
"author": "Dave R.",
"author_id": 42841,
"author_profile": "https://Stackoverflow.com/users/42841",
"pm_score": 4,
"selected": false,
"text": "#ifdef DEBUG\n // Your code\n#endif\n [Conditional(\"DEBUG\")]\nprivate void MyDebugMethod()\n{\n // Your code\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10688/"
] |
337,449 | <p>I need to declare an array of pointers to functions like so:</p>
<pre><code>extern void function1(void);
extern void function2(void);
...
void (*MESSAGE_HANDLERS[])(void) = {
function1,
function2,
...
};
</code></pre>
<p>However, I want the the array to be declared as constant -- both the data in the array and the pointer to the data. Unfortunately, I do not recall where to place the const key-word(s).</p>
<p>I'm assuming the actual pointer, MESSAGE_HANDLERS in this case, is already constant because it is declared as an array. On the otherhand, couldn't the function pointers within the array be change at runtime if it is declared as shown?</p>
| [
{
"answer_id": 337477,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 4,
"selected": false,
"text": "typedef typedef void MESSAGE_HANDLER(void);\n MESSAGE_HANDLER * const handlers[] = { function1, function2 };\n typedef"
},
{
"answer_id": 337486,
"author": "David Norman",
"author_id": 34502,
"author_profile": "https://Stackoverflow.com/users/34502",
"pm_score": 1,
"selected": false,
"text": "void (* const MESSAGE_HANDLERS[])(void) = {\n NULL,\n NULL\n};\n\nint main ()\n{\n /* Gives error \n '=' : left operand must be l-value\n */\n MESSAGE_HANDLERS = NULL;\n\n /* Gives error \n l-value specifies const object\n */\n MESSAGE_HANDLERS[0] = NULL;\n}\n"
},
{
"answer_id": 337488,
"author": "qrdl",
"author_id": 28494,
"author_profile": "https://Stackoverflow.com/users/28494",
"pm_score": 4,
"selected": false,
"text": "cdecl cdecl> explain void (* const foo[])(void)\ndeclare foo as array of const pointer to function (void) returning void\n"
},
{
"answer_id": 337553,
"author": "Curro",
"author_id": 10688,
"author_profile": "https://Stackoverflow.com/users/10688",
"pm_score": 1,
"selected": false,
"text": "typedef void (*MESSAGE_HANDLER)(); MESSAGE_HANDLER const handlers[] = {function1, function2}; typedef"
},
{
"answer_id": 337750,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 7,
"selected": true,
"text": "T t[5];\n void t[5](void);\n void * t[5](void);\n void (*t[5])(void);\n int (*t[5])[3];\n void (*f(int))(void);\n f(10)();\n f(10)(true)(3.4);\n void (*(*f(int))(bool))(double);\n int (*(*f(int))(bool))[3];\n const T c * c * c ... * c name;\n T c int const * const * name;\n name *name int const * const\n **name int const\n void (* const t[5])(void);\n const const void (const * t[5])(void);\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1491/"
] |
337,459 | <p>In every form we derive from <code>FormBaseControl</code>, we have the following code. I'm sure there is a better way to type the controller object than this, but at the moment we have it included in every page. In the example below, <code>base.Controller</code> is of type <code>BaseController</code>, from which <code>ExportController</code> derives. I find duplication of this code in each derivation of <code>FormBaseControl</code> to not smell right, but I can't quite figure a way of righting it.</p>
<pre><code> private ExportController MyController
{
get { return base.Controller as ExportController; }
}
protected void Page_Load(object sender, EventArgs e)
{
base.Controller = new ExportController(WebNavigator.Current);
</code></pre>
| [
{
"answer_id": 337495,
"author": "Andrew Rollings",
"author_id": 40410,
"author_profile": "https://Stackoverflow.com/users/40410",
"pm_score": 2,
"selected": true,
"text": " private ExportController MyController\n {\n get { return base.Controller as ExportController; }\n }\n protected T MyController\n {\n get { return this as T; }\n }\n BaseController<T>"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
337,476 | <p>I have a <code>ListBox</code> where the number of items is added based on and integer property set by a user. The items are created from a <code>ControlTemplate</code> resource that which is comprised of a Label and a <code>TextBox</code> inside of a <code>DockPanel</code>. The label is not data bound but I would like for it to have somewhat dynamic content based on the (index + 1) of the <code>ListboxItem</code> for which it is contained. My question/problem is that I want to be able update the content of the label for each <code>ListboxItem</code>, but cannot access the label for some reason. I am unaware of any way to do this through data-binding of the label since the label is in a template and has no knowledge that it has a parent that is a <code>ListboxItem</code>. Can anyone help me clear up some of these confusions to get me back on the right track, please?</p>
<pre><code><ControlTemplate TargetType="{x:Type ListBoxItem}">
<DockPanel Background="Transparent" Height="28" Name="playerDockPanel" VerticalAlignment="Bottom">
<Label Name="playerNameLabel" DockPanel.Dock="Left" Content="Player"></Label>
<TextBox Height="23" Width ="150" Name="playerName" DockPanel.Dock="Right"/>
</DockPanel>
</ControlTemplate>
</code></pre>
<p>I would like to be able to bind the content of the <code>Label</code> in xaml, or update the content of the <code>Label</code> in the code behind. I'm not sure what the best route would be.</p>
| [
{
"answer_id": 337495,
"author": "Andrew Rollings",
"author_id": 40410,
"author_profile": "https://Stackoverflow.com/users/40410",
"pm_score": 2,
"selected": true,
"text": " private ExportController MyController\n {\n get { return base.Controller as ExportController; }\n }\n protected T MyController\n {\n get { return this as T; }\n }\n BaseController<T>"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42858/"
] |
337,479 | <p>MySQL ResultSets are by default retrieved completely from the server before any work can be done. In cases of huge result sets this becomes unusable. I would like instead to actually retrieve the rows one by one from the server.</p>
<p>In Java, following the instructions <a href="http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-implementation-notes.html" rel="noreferrer">here</a> (under "ResultSet"), I create a statement like this:</p>
<pre><code>stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(Integer.MIN_VALUE);
</code></pre>
<p>This works nicely in Java. My question is: is there a way to do the same in python?</p>
<p>One thing I tried is to limit the query to a 1000 rows at a time, like this:</p>
<pre><code>start_row = 0
while True:
cursor = conn.cursor()
cursor.execute("SELECT item FROM items LIMIT %d,1000" % start_row)
rows = cursor.fetchall()
if not rows:
break
start_row += 1000
# Do something with rows...
</code></pre>
<p>However, this seems to get slower the higher start_row is.</p>
<p>And no, using <code>fetchone()</code> instead of <code>fetchall()</code> doesn't change anything.</p>
<h2>Clarification:</h2>
<p>The naive code I use to reproduce this problem looks like this:</p>
<pre><code>import MySQLdb
conn = MySQLdb.connect(user="user", passwd="password", db="mydb")
cur = conn.cursor()
print "Executing query"
cur.execute("SELECT * FROM bigtable");
print "Starting loop"
row = cur.fetchone()
while row is not None:
print ", ".join([str(c) for c in row])
row = cur.fetchone()
cur.close()
conn.close()
</code></pre>
<p>On a ~700,000 rows table, this code runs quickly. But on a ~9,000,000 rows table it prints "Executing Query" and then hangs for a long long time. That is why it makes no difference if I use <code>fetchone()</code> or <code>fetchall()</code>.</p>
| [
{
"answer_id": 337560,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": "row = cursor.fetchone() \nwhile row is not None:\n # process\n row = cursor.fetchone()\n row = cursor.fetchmany(size=1)\n while row is not None:\n # process\n row = cursor.fetchmany( size=1 )\n cursor.arraysize=-2**31\n"
},
{
"answer_id": 337706,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 7,
"selected": true,
"text": "cursorclass = MySQLdb.cursors.SSCursor MySQLdb.connect(user=\"user\", \n passwd=\"password\",\n db=\"mydb\",\n cursorclass = MySQLdb.cursors.SSCursor\n )\n fetchall SSCursor MySQLdb.cursors"
},
{
"answer_id": 337922,
"author": "A. Coady",
"author_id": 36433,
"author_profile": "https://Stackoverflow.com/users/36433",
"pm_score": 4,
"selected": false,
"text": "from MySQLdb import cursors\ncursor = conn.cursor(cursors.SSCursor)\n"
},
{
"answer_id": 18712314,
"author": "hahakubile",
"author_id": 709096,
"author_profile": "https://Stackoverflow.com/users/709096",
"pm_score": 2,
"selected": false,
"text": "con = MySQLdb.connect(host=host,\n user=user,\n passwd=pwd,\n charset=charset,\n port=port,\n cursorclass=MySQLdb.cursors.SSDictCursor);\ncur = con.cursor()\ncur.execute(\"select f1, f2 from table\")\nfor row in cur:\n print row['f1'], row['f2']\n"
},
{
"answer_id": 26559000,
"author": "Garren S",
"author_id": 1942007,
"author_profile": "https://Stackoverflow.com/users/1942007",
"pm_score": 2,
"selected": false,
"text": "cursorclass=MySQLdb.cursors.SSDictCursor pymysql.cursors.SSDictCursor while rows is not None cur.fetchmany(size=10000) [] query = \"\"\"SELECT * FROM my_table\"\"\"\nconn = pymysql.connect(host=MYSQL_CREDENTIALS['host'], user=MYSQL_CREDENTIALS['user'],\n passwd=MYSQL_CREDENTIALS['passwd'], charset='utf8', cursorclass = pymysql.cursors.SSDictCursor)\ncur = conn.cursor()\nresults = cur.execute(query)\nrows = cur.fetchmany(size=100)\nwhile rows:\n for row in rows: \n process(row)\n rows = cur.fetchmany(size=100)\ncur.close()\nconn.close()\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7581/"
] |
337,482 | <p>I want to display print dialog in servlet/jsp. Below is my code:</p>
<pre><code>DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet () ;
PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
PrintService service = javax.print.ServiceUI.printDialog(null, 200, 200, printService, defaultService, flavor, pras);
if (service != null)
{
DocPrintJob job = service.createPrintJob();
Doc doc = new SimpleDoc(decodedImageData, flavor, null);
job.print(doc, null);
}
</code></pre>
<p>It works well in a standalone application. However, I am not able to display print dialog in servlet/jsp.</p>
| [
{
"answer_id": 341754,
"author": "Paul Whelan",
"author_id": 3050,
"author_profile": "https://Stackoverflow.com/users/3050",
"pm_score": 0,
"selected": false,
"text": "window.print(); <html>\n<body>\n\n<a href=\"javascript:print()\">Print</a>\n</body>\n\n</html>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
337,503 | <p>When designing tables, I've developed a habit of having one column that is unique and that I make the primary key. This is achieved in three ways depending on requirements:</p>
<ol>
<li>Identity integer column that auto increments.</li>
<li>Unique identifier (GUID)</li>
<li>A short character(x) or integer (or other relatively small numeric type) column that can serve as a row identifier column</li>
</ol>
<p>Number 3 would be used for fairly small lookup, mostly read tables that might have a unique static length string code, or a numeric value such as a year or other number.</p>
<p>For the most part, all other tables will either have an auto-incrementing integer or unique identifier primary key.</p>
<h1>The Question :-)</h1>
<p>I have recently started working with databases that have no consistent row identifier and primary keys are currently clustered across various columns. Some examples:</p>
<ul>
<li>datetime/character</li>
<li>datetime/integer</li>
<li>datetime/varchar</li>
<li>char/nvarchar/nvarchar</li>
</ul>
<p>Is there a valid case for this? I would have always defined an identity or unique identifier column for these cases.</p>
<p>In addition there are many tables without primary keys at all. What are the valid reasons, if any, for this?</p>
<p>I'm trying to understand why tables were designed as they were, and it appears to be a big mess to me, but maybe there were good reasons for it.</p>
<p>A third question to sort of help me decipher the answers: In cases where multiple columns are used to comprise the compound primary key, is there a specific advantage to this method vs. a surrogate/artificial key? I'm thinking mostly in regards to performance, maintenance, administration, etc.?</p>
| [
{
"answer_id": 337716,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 7,
"selected": false,
"text": "state_id state_code state_name\n137 TX Texas\n... ... ...\n249 TX Texas\n"
},
{
"answer_id": 343451,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 5,
"selected": false,
"text": "Company:\n CompanyId (primary key)\n\nCostCenter:\n CompanyId (primary key, foreign key to Company)\n CostCentre (primary key)\n\nCostElement\n CompanyId (primary key, foreign key to Company)\n CostElement (primary key)\n\nInvoice:\n InvoiceId (primary key)\n CompanyId (primary key, in foreign key to CostCentre, in foreign key to CostElement)\n CostCentre (in foreign key to CostCentre)\n CostElement (in foreign key to CostElement)\n Invoice.CompanyId"
},
{
"answer_id": 401729,
"author": "Keith Williams",
"author_id": 50189,
"author_profile": "https://Stackoverflow.com/users/50189",
"pm_score": 0,
"selected": false,
"text": "SUSER_SNAME() EventId, AttendeeId"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21807/"
] |
337,505 | <p>I am trying to develop a way to change a flash file displayed on the screen to another file by clicking a button. I have been able to do this with jpg images, but I can't get it to work with flash files. Can anyone help? I would greatly appreciate it.
Below are two html's: the first one changes jpg images and it works, the second one I constructed to be similar to do the same with flash files but it does not work.</p>
<p>//Html 1. This changes Image 1 to Image 2 on click. It works
</p>
function changeSrc()
{
document.getElementById("myImage").src="Image 2.jpg";
}
<p></p>
<p></p>
<p></p>
<p><br /><br /></p>
<p></p>
<p></p>
<p></p>
<p>//Html 2. This is intended to change Flash 1 to Flash 2 on click. It does not work
</p>
function changeSrc()
{
document.getElementById("myImage").src="Flash 2.swf";
}
<p></p>
<p></p>
<p>
</p>
<p><br /><br /></p>
<p></p>
<p></p>
<p></p>
| [
{
"answer_id": 337716,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 7,
"selected": false,
"text": "state_id state_code state_name\n137 TX Texas\n... ... ...\n249 TX Texas\n"
},
{
"answer_id": 343451,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 5,
"selected": false,
"text": "Company:\n CompanyId (primary key)\n\nCostCenter:\n CompanyId (primary key, foreign key to Company)\n CostCentre (primary key)\n\nCostElement\n CompanyId (primary key, foreign key to Company)\n CostElement (primary key)\n\nInvoice:\n InvoiceId (primary key)\n CompanyId (primary key, in foreign key to CostCentre, in foreign key to CostElement)\n CostCentre (in foreign key to CostCentre)\n CostElement (in foreign key to CostElement)\n Invoice.CompanyId"
},
{
"answer_id": 401729,
"author": "Keith Williams",
"author_id": 50189,
"author_profile": "https://Stackoverflow.com/users/50189",
"pm_score": 0,
"selected": false,
"text": "SUSER_SNAME() EventId, AttendeeId"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39973/"
] |
337,519 | <p>I moved an ex-site based on joomla to wordpress. Import worked fine but the problem is that the old links don't work anymore.
Because there is only 50 or so articles, i thought will be a good idea to put a rule for each post (in .htaccess).</p>
<p>Well... Not always things are like you want, so redirects dont work at all :(</p>
<p>Old joomla links looks like this:</p>
<pre><code>http://site.com/index.php?option=com_content&task=view&id=49&Itemid=29
http://site.com/index.php?option=com_content&task=view&id=42&Itemid=29
http://site.com/index.php?option=com_content&task=view&id=68&Itemid=29
</code></pre>
<p>And need to be translated to:</p>
<pre><code>http://site.com/?p=23
http://site.com/?p=24
http://site.com/?p=25
</code></pre>
<ul>
<li><p>basically no relations between old and new links, so i don't think a regex will help</p></li>
<li><p>both old and new site are on the same domain</p></li>
</ul>
<p>Ok, the problem is that any rule i've tried (and i tried a LOT!), none worked. in few cases i get 500 error, but most of times the redirect didn't work.</p>
<p>So, any of you guys had same problem? I don't necessary want to have nice permalinks, but if i can, that will be better. The problem is that i have many backlinks to old url's and i don't want to loose them.</p>
<p>Thanks a lot guys!</p>
| [
{
"answer_id": 338449,
"author": "Ionuț Staicu",
"author_id": 23810,
"author_profile": "https://Stackoverflow.com/users/23810",
"pm_score": 1,
"selected": false,
"text": "if(isset($_GET['option'])) {\n if(is_numeric($_GET['id'])){\n header ('HTTP/1.1 301 Moved Permanently');\n header(\"Location: http://www.site.com/?p={$_GET['id']}\");\n die();\n }else {\n die('Hacking attempt');\n }\n}\n"
},
{
"answer_id": 46414551,
"author": "Webdesigner",
"author_id": 5427950,
"author_profile": "https://Stackoverflow.com/users/5427950",
"pm_score": 0,
"selected": false,
"text": "RewriteEngine On\n# now the first Example\nRewriteCond %{QUERY_STRING} ^option=com_content&task=view&id=49&Itemid=29$\nRewriteRule ^index\\.php$ /?p=23 [R=301,L]\n# Repeat last two lines for all your URLs\n https://example.com/path/to/new/page https://example.com/path/to/new/page?option=com_content&task=view&id=49&Itemid=29 RewriteCond %{QUERY_STRING} ^option=com_content&task=view&id=49&Itemid=29$\nRewriteRule ^index\\.php$ /path/to/new/page? [R=301,L]\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23810/"
] |
337,522 | <p>I'm trying to write a windows batch file that can delete files from subdirectories. I would rather not hard code the directory structure in, so I can use this process with other projects.</p>
<ul>
<li>I need to delete files of X type,</li>
<li>I have the parent folder <code>C:\MyProject</code>,</li>
<li>There are Y subfolders <code>C:\MyProject\?</code>,</li>
<li>There are N files to delete.</li>
</ul>
<p>Is there a quick <code>del</code> (of type) function I am simply missing?</p>
| [
{
"answer_id": 337542,
"author": "Pedrin",
"author_id": 36183,
"author_profile": "https://Stackoverflow.com/users/36183",
"pm_score": 6,
"selected": true,
"text": "c:\ncd MyProject\ndel /S *.type\n"
},
{
"answer_id": 341244,
"author": "Joe Pineda",
"author_id": 21258,
"author_profile": "https://Stackoverflow.com/users/21258",
"pm_score": 1,
"selected": false,
"text": "dir MyProject\\*.* /ad /s /b | gawk \"{print \\\"del \\\\\\\"\\\" $0 \\\"\\\\*.type\\\\\\\"\\\";}\" | cmd\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34183/"
] |
337,570 | <p>I'm currently building a project and I would like to make use of some simple javascript - I know some people have it disabled to prevent XSS and other things. Should I...</p>
<p>a) Use the simple javascript, those users with it disabled are missing out</p>
<p>b) Don't use the simple javascript, users with it enabled have to click a little more</p>
<p>c) Code both javascript-enabled and javascript-disabled functionality</p>
<p>I'm not really sure as the web is always changing, what do you recommend?</p>
| [
{
"answer_id": 337782,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 4,
"selected": false,
"text": ":set sarcasm :set ignoreSpelling :set iq=76 :set nosarcasm"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29595/"
] |
337,581 | <p>In the case when I want to check, if a certain entry in the database exists I have two options.</p>
<p>I can create an sql query using COUNT() and then check, if the result is >0...</p>
<p>...or I can just retrieve the record(s) and then count the number of rows in the returned rowset. For example with $result->num_rows;</p>
<p>What's better/faster? in mysql? in general?</p>
| [
{
"answer_id": 337595,
"author": "rebra",
"author_id": 2282296,
"author_profile": "https://Stackoverflow.com/users/2282296",
"pm_score": 2,
"selected": false,
"text": "SELECT EXISTS ([your query here])\n"
},
{
"answer_id": 337634,
"author": "TravisO",
"author_id": 35116,
"author_profile": "https://Stackoverflow.com/users/35116",
"pm_score": 0,
"selected": false,
"text": "SELECT COUNT(*) FROM table\n SELECT id FROM table\n COUNT(*) the table * column"
},
{
"answer_id": 337654,
"author": "John MacIntyre",
"author_id": 29043,
"author_profile": "https://Stackoverflow.com/users/29043",
"pm_score": 1,
"selected": false,
"text": "Select count(*) ...\n"
},
{
"answer_id": 337681,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 2,
"selected": true,
"text": "SELECT 1 \n FROM (SELECT 1) t \n WHERE EXISTS( SELECT * FROM foo WHERE id = 42 )\n"
},
{
"answer_id": 337876,
"author": "derobert",
"author_id": 27727,
"author_profile": "https://Stackoverflow.com/users/27727",
"pm_score": 0,
"selected": false,
"text": "SELECT 1 FROM table_name WHERE ... LIMIT 1\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11995/"
] |
337,588 | <p>According to <a href="http://www.builderau.com.au/program/perl/soa/Obtain-user-group-and-process-information-in-Perl/0,339028313,339222142,00.htm" rel="nofollow noreferrer">this site</a> I can simply write </p>
<pre><code>$user = getlogin();
</code></pre>
<p>but the group handling functions seem not to be able to accept a username/userid as a parameter. Should I really iterate over all the /etc/group file lines and parse the group names from it?</p>
| [
{
"answer_id": 337640,
"author": "fB.",
"author_id": 36218,
"author_profile": "https://Stackoverflow.com/users/36218",
"pm_score": 4,
"selected": true,
"text": "use strict;\nuse warnings;\n\n# use $< for the real uid and $> for the effective uid\nmy ($user, $passwd, $uid, $gid ) = getpwuid $< ;\nmy $group = getgrgid $gid ;\n\nprintf \"user: %s (%d), group: %s (%d)\\n\", $user, $uid, $group, $gid;\n my $group = getgrgid $(\n use POSIX qw(getgroups)\n"
},
{
"answer_id": 337648,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 2,
"selected": false,
"text": "getpw* getgr* getu*"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686/"
] |
337,598 | <p>Ok, bear with me guys and girls as I'm learning. Here's my question.</p>
<p>I can't figure out why I can't override a method from a parent class. Here's the code from the base class (yes, I pilfered the java code from an OOP book and am trying to rewrite it in C#).</p>
<pre><code>using System;
public class MoodyObject
{
protected String getMood()
{
return "moody";
}
public void queryMood()
{
Console.WriteLine("I feel " + getMood() + " today!");
}
}
</code></pre>
<p>and here are my other 2 objects that inherit the base class (MoodyObject):</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class SadObject: MoodyObject
{
protected String getMood()
{
return "sad";
}
//specialization
public void cry()
{
Console.WriteLine("wah...boohoo");
}
}
}
</code></pre>
<p>And:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class HappyObject: MoodyObject
{
protected String getMood()
{
return "happy";
}
public void laugh()
{
Console.WriteLine("hehehehehehe.");
}
}
}
</code></pre>
<p>and here is my main:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MoodyObject moodyObject = new MoodyObject();
SadObject sadObject = new SadObject();
HappyObject happyObject = new HappyObject();
Console.WriteLine("How does the moody object feel today?");
moodyObject.queryMood();
Console.WriteLine("");
Console.WriteLine("How does the sad object feel today?");
sadObject.queryMood();
sadObject.cry();
Console.WriteLine("");
Console.WriteLine("How does the happy object feel today?");
happyObject.queryMood();
happyObject.laugh();
}
}
}
</code></pre>
<p>As you can see, pretty basic stuff, but here's the output:</p>
<blockquote>
<p>How does the moody object feel today?
I feel moody today!</p>
<p>How does the sad object feel today? I
feel moody today! wah...boohoo</p>
<p>How does the happy object feel today?
I feel moody today! hehehehehehe.
Press any key to continue . . .</p>
</blockquote>
<p>Not as I expected. I've tried to make the base method virtual and calling override when trying to override it and that just gets me this error "cannot override inherited member 'MoodyObject.getMood()' because it is not marked virtual, abstract, or override". I also tried it without the virtual and override and it thinks I'm trying to hide the base method. Again, I'm new to OOP and would appreciate any guidance.</p>
<p><strong>EDITED TO ADD: I found it! The MoodyObject.cs was only a "solution item" in the solution explorer as opposed to a "ConsoleApplication1" item. I dragged it down to where it belonged in the solution explorer and voila! It works now. I marked Luc's answer below as the answer because he offered the help I needed to get to where I have it resolved... I'm learning so much here. It's amazing and you guys and girls are crazy smart!</strong></p>
| [
{
"answer_id": 337622,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "public class SadObject: MoodyObject\n {\n override String getMood()\n"
},
{
"answer_id": 337630,
"author": "Luc Touraille",
"author_id": 20984,
"author_profile": "https://Stackoverflow.com/users/20984",
"pm_score": 2,
"selected": false,
"text": "virtual override public class MoodyObject\n{\n protected virtual String getMood()\n {\n return \"moody\";\n }\n\n public void queryMood()\n {\n Console.WriteLine(\"I feel \" + getMood() + \" today!\");\n }\n}\n\npublic class SadObject : MoodyObject\n{\n protected override String getMood()\n {\n return \"sad\";\n }\n\n //specialization\n public void cry()\n {\n Console.WriteLine(\"wah...boohoo\");\n }\n}\n\npublic class HappyObject : MoodyObject\n{\n protected override String getMood()\n {\n return \"happy\";\n }\n\n public void laugh()\n {\n Console.WriteLine(\"hehehehehehe.\");\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n MoodyObject moodyObject = new MoodyObject();\n SadObject sadObject = new SadObject();\n HappyObject happyObject = new HappyObject();\n\n Console.WriteLine(\"How does the moody object feel today?\");\n moodyObject.queryMood();\n Console.WriteLine(\"\");\n Console.WriteLine(\"How does the sad object feel today?\");\n sadObject.queryMood();\n sadObject.cry();\n Console.WriteLine(\"\");\n Console.WriteLine(\"How does the happy object feel today?\");\n happyObject.queryMood();\n happyObject.laugh();\n\n Console.Read();\n }\n}\n"
},
{
"answer_id": 337635,
"author": "Dan C.",
"author_id": 26391,
"author_profile": "https://Stackoverflow.com/users/26391",
"pm_score": 3,
"selected": false,
"text": "protected virtual string getMood() ... protected override string getMood()..."
},
{
"answer_id": 337636,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 7,
"selected": true,
"text": "class Base \n{\n protected virtual string GetMood() {...}\n}\n class Derived : Base\n{\n protected override string GetMood() {...}\n}\n protected sealed override string GetMood() {...}\n"
},
{
"answer_id": 337643,
"author": "Jeremiah",
"author_id": 34183,
"author_profile": "https://Stackoverflow.com/users/34183",
"pm_score": 2,
"selected": false,
"text": "public class SadObject: MoodyObject \n{ \n override String getMood()\n"
},
{
"answer_id": 337647,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 2,
"selected": false,
"text": "virtual override public class BaseObject\n{\n protected virtual String getMood()\n {\n return \"Base mood\";\n }\n\n //...\n}\n\npublic class DerivedObject: BaseObject\n{\n protected override String getMood()\n {\n return \"Derived mood\";\n }\n //...\n}\n using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n { \n // leaving out your implementation to save space... \n }\n } \n\n public class SadObject : MoodyObject\n {\n protected override String getMood()\n {\n return \"sad\";\n }\n\n //specialization\n public void cry()\n {\n Console.WriteLine(\"wah...boohoo\");\n }\n }\n\n public class HappyObject : MoodyObject\n {\n protected override String getMood()\n {\n return \"happy\";\n }\n\n public void laugh()\n {\n Console.WriteLine(\"hehehehehehe.\");\n }\n }\n}\n"
},
{
"answer_id": 337671,
"author": "JoshBerke",
"author_id": 26160,
"author_profile": "https://Stackoverflow.com/users/26160",
"pm_score": 3,
"selected": false,
"text": "public class MoodyObject\n{\n protected virtual String getMood() \n { \n return \"moody\"; \n } \n public void queryMood() \n { \n Console.WriteLine(\"I feel \" + getMood() + \" today!\"); \n }\n}\n\npublic class HappyObject : MoodyObject\n{\n protected override string getMood()\n {\n return \"happy\";\n }\n}\n public abstract class MoodyObject\n{\n protected abstract String getMood();\n\n public void queryMood() \n { \n Console.WriteLine(\"I feel \" + getMood() + \" today!\"); \n }\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38317/"
] |
337,601 | <p>Is there a simple process in SQL 2005 for spitting all of my stored procedures out to individual .sql files. I'd like to move them into VSS, but am not too excited by the prospect of clicking on each one to get the source, dumping it into a text file and so on.. </p>
| [
{
"answer_id": 337619,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 3,
"selected": false,
"text": "select\n O.name, M.definition\nfrom\n sys.objects as O\nleft join\n sys.sql_modules as M\n on O.object_id = M.object_id\nwhere\n type = 'P'\n"
},
{
"answer_id": 8226757,
"author": "ArekBee",
"author_id": 978807,
"author_profile": "https://Stackoverflow.com/users/978807",
"pm_score": 1,
"selected": false,
"text": "//C:\\Program Files\\Microsoft SQL Server\\{version}\\SDK\\Assemblies\\\nusing Microsoft.SqlServer;\nusing Microsoft.SqlServer.Server;\nusing Microsoft.SqlServer.Management.Smo;\nusing Microsoft.SqlServer.Management.Common;\nusing System.Data.SqlClient;\n\nstring sqlConnectionString=\"\";\nstring databaseName=\"\";\n\nvar Connection = new SqlConnection(sqlConnectionString);\nConnection.Open();\nint counter = 0;\nvar db= new Server(new ServerConnection(Connection)).Databases[databaseName];\n\nforeach (var item in db.StoredProcedures.OfType<StoredProcedure>())\n{\n if (item.IsSystemObject == false)\n {\n using (TextWriter writer = new StreamWriter(item.Name+\".sql\", false))\n {\n writer.WriteLine(item.TextHeader + item.TextBody);\n }\n }\n}\n"
},
{
"answer_id": 13018138,
"author": "NeverHopeless",
"author_id": 751527,
"author_profile": "https://Stackoverflow.com/users/751527",
"pm_score": 1,
"selected": false,
"text": "DECLARE @name varchar(100)\nDECLARE @Definition varchar(max)\nDECLARE @sql varchar(300)\nCREATE TABLE TEMPTABLE (ID INT IDENTITY(1,1), def varchar(max))\nDECLARE script CURSOR \nFOR\nSELECT OBJECT_NAME(SYS.SQL_MODULES.OBJECT_ID), [DEFINITION] FROM \nSYS.SQL_MODULES INNER JOIN SYS.OBJECTS ON\nSYS.OBJECTS.OBJECT_ID = SYS.SQL_MODULES.OBJECT_ID \nWHERE SYS.OBJECTS.TYPE='P'\nOPEN script\nFETCH NEXT FROM script INTO @name, @Definition\nWHILE @@FETCH_STATUS = 0 \nBEGIN\n FETCH NEXT FROM script INTO @name, @Definition\n INSERT INTO TEMPTABLE VALUES(@definition)\n SET @Sql = ('BCP \"SELECT TOP 1 def FROM TEMPTABLE ORDER BY ID DESC\" queryout \"C:\\' + @name + '.sql\" -c -T')\n EXEC XP_CmdShell @Sql\nEND \nCLOSE script\nDEALLOCATE script\nDROP TABLE TEMPTABLE\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13954/"
] |
337,602 | <p>I'm trying to search using the windows search one of my web directories for any uses of scriptlets. However, the search seems to be ignoring all files ending in .jsp. I searched for plain words, and that didn't work either. Is there a reason Windows ignores these files when searching?</p>
| [
{
"answer_id": 337900,
"author": "Alex. S.",
"author_id": 18300,
"author_profile": "https://Stackoverflow.com/users/18300",
"pm_score": 2,
"selected": false,
"text": "findstr /c:bla /s *.jsp bla jsp"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23249/"
] |
337,620 | <p>I'm trying to inverse a matrix with version Boost boost_1_37_0 and MTL mtl4-alpha-1-r6418. I can't seem to locate the matrix inversion code. I've googled for examples and they seem to reference lu.h that seems to be missing in the above release(s). Any hints?</p>
<p><a href="https://stackoverflow.com/users/8643/matt-cruikshank">@Matt</a> suggested copying lu.h, but that seems to be from MTL2 rather than MTL4. I'm having trouble compiling with MTL2 with VS05 or higher. </p>
<p>So, any idea how to do a matrix inversion in MTL4?</p>
<p>Update: I think I understand Matt better and I'm heading down <a href="http://www.osl.iu.edu/research/itl/" rel="nofollow noreferrer">this ITL path</a>.</p>
| [
{
"answer_id": 337652,
"author": "Matt Cruikshank",
"author_id": 8643,
"author_profile": "https://Stackoverflow.com/users/8643",
"pm_score": 3,
"selected": true,
"text": "lu_factor lu_inverse lu_inverse()"
},
{
"answer_id": 12725876,
"author": "Szymon Wygnański",
"author_id": 582704,
"author_profile": "https://Stackoverflow.com/users/582704",
"pm_score": 0,
"selected": false,
"text": "mtl::matrix::inv(Matrix const &A, MatrixOut &Inv);\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3225/"
] |
337,631 | <p>Say I have a bitmap image, is it possible to iterate through all the individual bytes in the image? If yes, how?</p>
| [
{
"answer_id": 337651,
"author": "Filip Ekberg",
"author_id": 39106,
"author_profile": "https://Stackoverflow.com/users/39106",
"pm_score": 3,
"selected": false,
"text": "System.Drawing.Bitmap bmp = GetTheBitmap();\nSystem.IO.MemoryStream stream = new System.IO.MemoryStream();\nbmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);\nstream.Position = 0;\nbyte[] data = new byte[stream.Length];\nstream.Read(data, 0, stream.Length);\n"
},
{
"answer_id": 337670,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 2,
"selected": false,
"text": " public static void AdjustBrightness(Bitmap image, int brightness)\n {\n int offset = 0;\n brightness = (brightness * 255) / 100;\n // GDI+ still lies to us - the return format is BGR, NOT RGB.\n BitmapData bmData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);\n\n int stride = bmData.Stride;\n IntPtr Scan0 = bmData.Scan0;\n\n int nVal = 0;\n int nOffset = stride - image.Width * 3;\n int nWidth = image.Width * 3;\n\n for (int y = 0; y < image.Height; ++y)\n {\n for (int x = 0; x < nWidth; ++x)\n {\n nVal = Marshal.ReadByte(Scan0, offset) + brightness;\n\n if (nVal < 0)\n nVal = 0;\n if (nVal > 255)\n nVal = 255;\n\n Marshal.WriteByte(Scan0, offset, (byte)nVal);\n ++offset;\n }\n offset += nOffset;\n }\n image.UnlockBits(bmData);\n }\n"
},
{
"answer_id": 337859,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 3,
"selected": false,
"text": " BitmapData data;\n int x = 0; //or whatever\n int y = 0;\n unsafe\n {\n byte* row = (byte*)data.Scan0 + (y * data.Stride);\n int columnOffset = x * 4;\n byte B = row[columnOffset];\n byte G = row[columnOffset + 1];\n byte R = row[columnOffset + 2];\n byte A = row[columnOffset + 3];\n }\n"
},
{
"answer_id": 849182,
"author": "Keith",
"author_id": 43370,
"author_profile": "https://Stackoverflow.com/users/43370",
"pm_score": 0,
"selected": false,
"text": "using (Bitmap bmp = new Bitmap(fname)) {\n // Convert image to int32 array with each int being one pixel\n int cnt = bmp.Width * bmp.Height * 4 / 4;\n BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),\n ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);\n Int32[] rgbValues = new Int32[cnt];\n\n // Copy the RGB values into the array.\n System.Runtime.InteropServices.Marshal.Copy(bmData.Scan0, rgbValues, 0, cnt);\n bmp.UnlockBits(bmData);\n for (int i = 0; i < cnt; ++i) {\n if (rgbValues[i] == 0xFFFF0000)\n Console.WriteLine (\"Red byte\");\n }\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] |
337,649 | <p>I'm building a <a href="https://en.wikipedia.org/wiki/Windows_Forms" rel="nofollow noreferrer">Windows Forms</a> form in C# with various elements in a panel that starts out either invisible, disabled, or set to null (labels, combo boxes, grids, etc.). As the user goes through and makes choices, these elements are populated, selected, etc.</p>
<p>The idea is to upload files, read them, and process entries to a database. Once the processing for this directory has completed, I'd like to be able to have the user select another directory without exiting and restarting the Windows Forms application, by pressing a button that becomes visible when the process has completed.</p>
<p>Is there an easy call to reset the application (or the panel that contains the elements), similar to when a webform is refreshed, or do I have to write a function that "resets" all of those elements one at a time?</p>
<hr/>
<p>As the result of a development meeting, my project has changed direction. I thank the two of you who helped with answers, and am going to close the question.</p>
| [
{
"answer_id": 337685,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 3,
"selected": true,
"text": "Panel CreatePanelWithDynamicControls() {\n Panel ret = new Panel();\n ret.Dock = DockStyle.Fill;\n // Some logic, which initializes content of panel\n\n return ret;\n}\n\nvoid InitializeDynamicControls() {\n this.Controls.Clear();\n Panel pnl = this.CreatePanelWithDynamiControls();\n this.Controls.Add(pnl);\n}\n\nvoid Form1_Load(object sender, EventArgs e) {\n if (!this.DesignMode) {\n this.InitializeDynamicControls();\n }\n}\n\n// I don't know exactly, on which situation\n// do you want reset controls\nvoid SomeEvent(object sender, EventArgs e) {\n this.InitializeDynamicControls();\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28939/"
] |
337,656 | <p>I set up a simple event handler as mentioned <a href="https://stackoverflow.com/questions/49510/how-do-you-set-your-cocoa-application-as-the-default-web-browser">here</a>, but it appears that the selector isn't called. I put the code in my AppDelegate class and wired up the delegate in IB. Tried putting in some NSLog()s and breakpoints in the selector I expect to be called, but none of it is hit. The URL scheme works inasmuch as it launches my app, but it doesn't do anything after that. Can anyone advise how to troubleshoot this? Thanks!</p>
| [
{
"answer_id": 339405,
"author": "jxpx777",
"author_id": 34386,
"author_profile": "https://Stackoverflow.com/users/34386",
"pm_score": 0,
"selected": false,
"text": "- (void)init{\n self = [super init];\n if(self){\n [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self andSelector:@selector(getUrl:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];\n }\n}\n\n- (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent\n{ \n NSString *url = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];\n NSLog(url);\n // now you can create an NSURL and grab the necessary parts\n}\n"
},
{
"answer_id": 339576,
"author": "Boaz Stuller",
"author_id": 1464654,
"author_profile": "https://Stackoverflow.com/users/1464654",
"pm_score": 3,
"selected": true,
"text": "-init id return self; - (id)init\n{\n self = [super init];\n if (self) {\n [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self andSelector:@selector(getUrl:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];\n }\n return self;\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34386/"
] |
337,664 | <p>I'm designing an algorithm to do the following: Given array <code>A[1... n]</code>, for every <code>i < j</code>, find all inversion pairs such that <code>A[i] > A[j]</code>. I'm using merge sort and copying array A to array B and then comparing the two arrays, but I'm having a difficult time seeing how I can use this to find the number of inversions. Any hints or help would be greatly appreciated.</p>
| [
{
"answer_id": 337773,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 1,
"selected": false,
"text": "int counter = 0;\n\nfor(int i = 0; i < n - 1; i++)\n{\n for(int j = i+1; j < n; j++)\n {\n if( A[i] > A[j] )\n {\n counter++;\n }\n }\n}\n\nreturn counter;\n"
},
{
"answer_id": 6424847,
"author": "Marek Kirejczyk",
"author_id": 592872,
"author_profile": "https://Stackoverflow.com/users/592872",
"pm_score": 7,
"selected": false,
"text": "long merge(int[] arr, int[] left, int[] right) {\n int i = 0, j = 0;\n long count = 0;\n while (i < left.length || j < right.length) {\n if (i == left.length) {\n arr[i+j] = right[j];\n j++;\n } else if (j == right.length) {\n arr[i+j] = left[i];\n i++;\n } else if (left[i] <= right[j]) {\n arr[i+j] = left[i];\n i++; \n } else {\n arr[i+j] = right[j];\n count += left.length-i;\n j++;\n }\n }\n return count;\n}\n\nlong invCount(int[] arr) {\n if (arr.length < 2)\n return 0;\n\n int m = (arr.length + 1) / 2;\n int left[] = Arrays.copyOfRange(arr, 0, m);\n int right[] = Arrays.copyOfRange(arr, m, arr.length);\n\n return invCount(left) + invCount(right) + merge(arr, left, right);\n}\n"
},
{
"answer_id": 13635050,
"author": "mbreining",
"author_id": 338982,
"author_profile": "https://Stackoverflow.com/users/338982",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n\nint count = 0;\nint inversions(int a[], int len);\nvoid mergesort(int a[], int left, int right);\nvoid merge(int a[], int left, int mid, int right);\n\nint main() {\n int a[] = { 1, 5, 2, 4, 0 };\n printf(\"%d\\n\", inversions(a, 5));\n}\n\nint inversions(int a[], int len) {\n mergesort(a, 0, len - 1);\n return count;\n}\n\nvoid mergesort(int a[], int left, int right) {\n if (left < right) {\n int mid = (left + right) / 2;\n mergesort(a, left, mid);\n mergesort(a, mid + 1, right);\n merge(a, left, mid, right);\n }\n}\n\nvoid merge(int a[], int left, int mid, int right) {\n int i = left;\n int j = mid + 1;\n int k = 0;\n int b[right - left + 1];\n while (i <= mid && j <= right) {\n if (a[i] <= a[j]) {\n b[k++] = a[i++];\n } else {\n printf(\"right element: %d\\n\", a[j]);\n count += (mid - i + 1);\n printf(\"new count: %d\\n\", count);\n b[k++] = a[j++];\n }\n }\n while (i <= mid)\n b[k++] = a[i++];\n while (j <= right)\n b[k++] = a[j++];\n for (i = left, k = 0; i <= right; i++, k++) {\n a[i] = b[k];\n }\n}\n"
},
{
"answer_id": 15151050,
"author": "mkso",
"author_id": 470682,
"author_profile": "https://Stackoverflow.com/users/470682",
"pm_score": 5,
"selected": false,
"text": "# O(n log n)\n\ndef count_inversion(lst):\n return merge_count_inversion(lst)[1]\n\ndef merge_count_inversion(lst):\n if len(lst) <= 1:\n return lst, 0\n middle = int( len(lst) / 2 )\n left, a = merge_count_inversion(lst[:middle])\n right, b = merge_count_inversion(lst[middle:])\n result, c = merge_count_split_inversion(left, right)\n return result, (a + b + c)\n\ndef merge_count_split_inversion(left, right):\n result = []\n count = 0\n i, j = 0, 0\n left_len = len(left)\n while i < left_len and j < len(right):\n if left[i] <= right[j]:\n result.append(left[i])\n i += 1\n else:\n result.append(right[j])\n count += left_len - i\n j += 1\n result += left[i:]\n result += right[j:]\n return result, count \n\n\n#test code\ninput_array_1 = [] #0\ninput_array_2 = [1] #0\ninput_array_3 = [1, 5] #0\ninput_array_4 = [4, 1] #1\ninput_array_5 = [4, 1, 2, 3, 9] #3\ninput_array_6 = [4, 1, 3, 2, 9, 5] #5\ninput_array_7 = [4, 1, 3, 2, 9, 1] #8\n\nprint count_inversion(input_array_1)\nprint count_inversion(input_array_2)\nprint count_inversion(input_array_3)\nprint count_inversion(input_array_4)\nprint count_inversion(input_array_5)\nprint count_inversion(input_array_6)\nprint count_inversion(input_array_7)\n"
},
{
"answer_id": 15312592,
"author": "banarun",
"author_id": 2020229,
"author_profile": "https://Stackoverflow.com/users/2020229",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nint _mergeSort(int arr[], int temp[], int left, int right);\nint merge(int arr[], int temp[], int left, int mid, int right);\n\n/* This function sorts the input array and returns the\n number of inversions in the array */\nint mergeSort(int arr[], int array_size)\n{\n int *temp = (int *)malloc(sizeof(int)*array_size);\n return _mergeSort(arr, temp, 0, array_size - 1);\n}\n\n/* An auxiliary recursive function that sorts the input array and\n returns the number of inversions in the array. */\nint _mergeSort(int arr[], int temp[], int left, int right)\n{\n int mid, inv_count = 0;\n if (right > left)\n {\n /* Divide the array into two parts and call _mergeSortAndCountInv()\n for each of the parts */\n mid = (right + left)/2;\n\n /* Inversion count will be sum of inversions in left-part, right-part\n and number of inversions in merging */\n inv_count = _mergeSort(arr, temp, left, mid);\n inv_count += _mergeSort(arr, temp, mid+1, right);\n\n /*Merge the two parts*/\n inv_count += merge(arr, temp, left, mid+1, right);\n }\n return inv_count;\n}\n\n/* This funt merges two sorted arrays and returns inversion count in\n the arrays.*/\nint merge(int arr[], int temp[], int left, int mid, int right)\n{\n int i, j, k;\n int inv_count = 0;\n\n i = left; /* i is index for left subarray*/\n j = mid; /* i is index for right subarray*/\n k = left; /* i is index for resultant merged subarray*/\n while ((i <= mid - 1) && (j <= right))\n {\n if (arr[i] <= arr[j])\n {\n temp[k++] = arr[i++];\n }\n else\n {\n temp[k++] = arr[j++];\n\n /*this is tricky -- see above explanation/diagram for merge()*/\n inv_count = inv_count + (mid - i);\n }\n }\n\n /* Copy the remaining elements of left subarray\n (if there are any) to temp*/\n while (i <= mid - 1)\n temp[k++] = arr[i++];\n\n /* Copy the remaining elements of right subarray\n (if there are any) to temp*/\n while (j <= right)\n temp[k++] = arr[j++];\n\n /*Copy back the merged elements to original array*/\n for (i=left; i <= right; i++)\n arr[i] = temp[i];\n\n return inv_count;\n}\n\n/* Driver progra to test above functions */\nint main(int argv, char** args)\n{\n int arr[] = {1, 20, 6, 4, 5};\n printf(\" Number of inversions are %d \\n\", mergeSort(arr, 5));\n getchar();\n return 0;\n}\n"
},
{
"answer_id": 16056139,
"author": "prasadvk",
"author_id": 135042,
"author_profile": "https://Stackoverflow.com/users/135042",
"pm_score": 2,
"selected": false,
"text": "Node { \n int data;\n Node* left, *right;\n int rightSubTreeSize;\n\n Node(int data) { \n rightSubTreeSize = 0;\n } \n};\n\nNode* root = null;\nint totCnt = 0;\nfor(i = 0; i < n; ++i) { \n Node* p = new Node(a[i]);\n if(root == null) { \n root = p;\n continue;\n } \n\n Node* q = root;\n int curCnt = 0;\n while(q) { \n if(p->data <= q->data) { \n curCnt += 1 + q->rightSubTreeSize;\n if(q->left) { \n q = q->left;\n } else { \n q->left = p;\n break;\n }\n } else { \n q->rightSubTreeSize++;\n if(q->right) { \n q = q->right;\n } else { \n q->right = p;\n break;\n }\n }\n }\n\n totCnt += curCnt;\n }\n return totCnt;\n"
},
{
"answer_id": 17827552,
"author": "Trying",
"author_id": 2109070,
"author_profile": "https://Stackoverflow.com/users/2109070",
"pm_score": 2,
"selected": false,
"text": "public static int mergeSort(int[] a, int p, int r)\n{\n int countInversion = 0;\n if(p < r)\n {\n int q = (p + r)/2;\n countInversion = mergeSort(a, p, q);\n countInversion += mergeSort(a, q+1, r);\n countInversion += merge(a, p, q, r);\n }\n return countInversion;\n}\n\npublic static int merge(int[] a, int p, int q, int r)\n{\n //p=0, q=1, r=3\n int countingInversion = 0;\n int n1 = q-p+1;\n int n2 = r-q;\n int[] temp1 = new int[n1+1];\n int[] temp2 = new int[n2+1];\n for(int i=0; i<n1; i++) temp1[i] = a[p+i];\n for(int i=0; i<n2; i++) temp2[i] = a[q+1+i];\n\n temp1[n1] = Integer.MAX_VALUE;\n temp2[n2] = Integer.MAX_VALUE;\n int i = 0, j = 0;\n\n for(int k=p; k<=r; k++)\n {\n if(temp1[i] <= temp2[j])\n {\n a[k] = temp1[i];\n i++;\n }\n else\n {\n a[k] = temp2[j];\n j++;\n countingInversion=countingInversion+(n1-i); \n }\n }\n return countingInversion;\n}\npublic static void main(String[] args)\n{\n int[] a = {1, 20, 6, 4, 5};\n int countInversion = mergeSort(a, 0, a.length-1);\n System.out.println(countInversion);\n}\n"
},
{
"answer_id": 18819251,
"author": "oo_miguel",
"author_id": 2430189,
"author_profile": "https://Stackoverflow.com/users/2430189",
"pm_score": 0,
"selected": false,
"text": "#include <algorithm>\n\nvector<int> merge(vector<int>left, vector<int>right, int &counter)\n{\n\n vector<int> result;\n\n vector<int>::iterator it_l=left.begin();\n vector<int>::iterator it_r=right.begin();\n\n int index_left=0;\n\n while(it_l!=left.end() || it_r!=right.end())\n {\n\n // the following is true if we are finished with the left vector \n // OR if the value in the right vector is the smaller one.\n\n if(it_l==left.end() || (it_r!=right.end() && *it_r<*it_l) )\n {\n result.push_back(*it_r);\n it_r++;\n\n // increase inversion counter\n counter+=left.size()-index_left;\n }\n else\n {\n result.push_back(*it_l);\n it_l++;\n index_left++;\n\n }\n }\n\n return result;\n}\n\nvector<int> merge_sort_and_count(vector<int> A, int &counter)\n{\n\n int N=A.size();\n if(N==1)return A;\n\n vector<int> left(A.begin(),A.begin()+N/2);\n vector<int> right(A.begin()+N/2,A.end());\n\n left=merge_sort_and_count(left,counter);\n right=merge_sort_and_count(right,counter);\n\n\n return merge(left, right, counter);\n\n}\n"
},
{
"answer_id": 20219095,
"author": "Museful",
"author_id": 827280,
"author_profile": "https://Stackoverflow.com/users/827280",
"pm_score": -1,
"selected": false,
"text": "inversionNumber <- function(x){\n mergeSort <- function(x){\n if(length(x) == 1){\n inv <- 0\n } else {\n n <- length(x)\n n1 <- ceiling(n/2)\n n2 <- n-n1\n y1 <- mergeSort(x[1:n1])\n y2 <- mergeSort(x[n1+1:n2])\n inv <- y1$inversions + y2$inversions\n x1 <- y1$sortedVector\n x2 <- y2$sortedVector\n i1 <- 1\n i2 <- 1\n while(i1+i2 <= n1+n2+1){\n if(i2 > n2 || i1 <= n1 && x1[i1] <= x2[i2]){\n x[i1+i2-1] <- x1[i1]\n i1 <- i1 + 1\n } else {\n inv <- inv + n1 + 1 - i1\n x[i1+i2-1] <- x2[i2]\n i2 <- i2 + 1\n }\n }\n }\n return (list(inversions=inv,sortedVector=x))\n }\n r <- mergeSort(x)\n return (r$inversions)\n}\n"
},
{
"answer_id": 21076524,
"author": "Anwit",
"author_id": 2212869,
"author_profile": "https://Stackoverflow.com/users/2212869",
"pm_score": -1,
"selected": false,
"text": "import java.lang.reflect.Array;\nimport java.util.Arrays;\n\n\npublic class main {\n\npublic static void main(String[] args) {\n int[] arr = {6, 9, 1, 14, 8, 12, 3, 2};\n System.out.println(findinversion(arr,0,arr.length-1));\n}\n\npublic static int findinversion(int[] arr,int beg,int end) {\n if(beg >= end)\n return 0;\n\n int[] result = new int[end-beg+1];\n int index = 0;\n int mid = (beg+end)/2;\n int count = 0, leftinv,rightinv;\n //System.out.println(\"....\"+beg+\" \"+end+\" \"+mid);\n leftinv = findinversion(arr, beg, mid);\n rightinv = findinversion(arr, mid+1, end);\n l1:\n for(int i = beg, j = mid+1; i<=mid || j<=end;/*index < result.length;*/ ) {\n if(i>mid) {\n for(;j<=end;j++)\n result[index++]=arr[j];\n break l1;\n }\n if(j>end) {\n for(;i<=mid;i++)\n result[index++]=arr[i];\n break l1;\n }\n if(arr[i] <= arr[j]) {\n result[index++]=arr[i];\n i++; \n } else {\n System.out.println(arr[i]+\" \"+arr[j]);\n count = count+ mid-i+1;\n result[index++]=arr[j];\n j++; \n }\n }\n\n for(int i = 0, j=beg; i< end-beg+1; i++,j++)\n arr[j]= result[i];\n return (count+leftinv+rightinv);\n //System.out.println(Arrays.toString(arr));\n}\n\n}\n"
},
{
"answer_id": 21371661,
"author": "Sudheer Aedama",
"author_id": 1332911,
"author_profile": "https://Stackoverflow.com/users/1332911",
"pm_score": -1,
"selected": false,
"text": "trait MergeSort {\n def mergeSort(ls: List[Int]): List[Int] = {\n def merge(ls1: List[Int], ls2: List[Int]): List[Int] =\n (ls1, ls2) match {\n case (_, Nil) => ls1\n case (Nil, _) => ls2\n case (lowsHead :: lowsTail, highsHead :: highsTail) =>\n if (lowsHead <= highsHead) lowsHead :: merge(lowsTail, ls2)\n else highsHead :: merge(ls1, highsTail)\n }\n\n ls match {\n case Nil => Nil\n case head :: Nil => ls\n case _ =>\n val (lows, highs) = ls.splitAt(ls.size / 2)\n merge(mergeSort(lows), mergeSort(highs))\n }\n }\n}\n\nobject InversionCounterApp extends App with MergeSort {\n @annotation.tailrec\n def calculate(list: List[Int], sortedListZippedWithIndex: List[(Int, Int)], counter: Int = 0): Int =\n list match {\n case Nil => counter\n case head :: tail => calculate(tail, sortedListZippedWithIndex.filterNot(_._1 == 1), counter + sortedListZippedWithIndex.find(_._1 == head).map(_._2).getOrElse(0))\n }\n\n val list: List[Int] = List(6, 9, 1, 14, 8, 12, 3, 2)\n val sortedListZippedWithIndex: List[(Int, Int)] = mergeSort(list).zipWithIndex\n println(\"inversion counter = \" + calculate(list, sortedListZippedWithIndex))\n // prints: inversion counter = 28 \n}\n"
},
{
"answer_id": 21815334,
"author": "Tim Babych",
"author_id": 176270,
"author_profile": "https://Stackoverflow.com/users/176270",
"pm_score": 2,
"selected": false,
"text": "import bisect\ndef solution(A):\n sorted_left = []\n res = 0\n for i in xrange(1, len(A)):\n bisect.insort_left(sorted_left, A[i-1])\n # i is also the length of sorted_left\n res += (i - bisect.bisect(sorted_left, A[i]))\n return res\n"
},
{
"answer_id": 23201616,
"author": "Niklas B.",
"author_id": 916657,
"author_profile": "https://Stackoverflow.com/users/916657",
"pm_score": 5,
"selected": false,
"text": "def count_inversions(a):\n res = 0\n counts = [0]*(len(a)+1)\n rank = { v : i+1 for i, v in enumerate(sorted(a)) }\n for x in reversed(a):\n i = rank[x] - 1\n while i:\n res += counts[i]\n i -= i & -i\n i = rank[x]\n while i <= len(a):\n counts[i] += 1\n i += i & -i\n return res\n"
},
{
"answer_id": 24591272,
"author": "Ayush",
"author_id": 3714537,
"author_profile": "https://Stackoverflow.com/users/3714537",
"pm_score": -1,
"selected": false,
"text": "#include<stdio.h>\n#include<stdlib.h>\n\n//To print an array\nvoid print(int arr[],int n)\n{\n int i;\n for(i=0,printf(\"\\n\");i<n;i++)\n printf(\"%d \",arr[i]);\n printf(\"\\n\");\n}\n\n//Merge Sort\nint merge(int arr[],int left[],int right[],int l,int r)\n{\n int i=0,j=0,count=0;\n while(i<l || j<r)\n {\n if(i==l)\n {\n arr[i+j]=right[j];\n j++;\n }\n else if(j==r)\n {\n arr[i+j]=left[i];\n i++;\n }\n else if(left[i]<=right[j])\n {\n arr[i+j]=left[i];\n i++;\n }\n else\n {\n arr[i+j]=right[j];\n count+=l-i;\n j++;\n }\n }\n //printf(\"\\ncount:%d\\n\",count);\n return count;\n}\n\n//Inversion Finding\nint inversions(int arr[],int high)\n{\n if(high<1)\n return 0;\n\n int mid=(high+1)/2;\n int left[mid];\n int right[high-mid+1];\n\n int i,j;\n for(i=0;i<mid;i++)\n left[i]=arr[i];\n\n\n for(i=high-mid,j=high;j>=mid;i--,j--)\n right[i]=arr[j];\n\n //print(arr,high+1);\n //print(left,mid);\n //print(right,high-mid+1);\n\n return inversions(left,mid-1) + inversions(right,high-mid) + merge(arr,left,right,mid,high-mid+1);\n\n}\nint main()\n{\n int arr[]={6,9,1,14,8,12,3,2};\n int n=sizeof(arr)/sizeof(arr[0]);\n print(arr,n);\n printf(\"%d \",inversions(arr,n-1));\n return 0;\n}\n"
},
{
"answer_id": 24715960,
"author": "Andrey Petrov",
"author_id": 1695274,
"author_profile": "https://Stackoverflow.com/users/1695274",
"pm_score": 1,
"selected": false,
"text": " public class FindInversions {\n\n public static int solution(int[] input) {\n if (input == null)\n return 0;\n int[] helper = new int[input.length];\n return mergeSort(0, input.length - 1, input, helper);\n }\n\n public static int mergeSort(int low, int high, int[] input, int[] helper) {\n int inversionCount = 0;\n if (low < high) {\n int medium = low + (high - low) / 2;\n inversionCount += mergeSort(low, medium, input, helper);\n inversionCount += mergeSort(medium + 1, high, input, helper);\n inversionCount += merge(low, medium, high, input, helper);\n }\n return inversionCount;\n }\n\n public static int merge(int low, int medium, int high, int[] input, int[] helper) {\n int inversionCount = 0;\n\n for (int i = low; i <= high; i++)\n helper[i] = input[i];\n\n int i = low;\n int j = medium + 1;\n int k = low;\n\n while (i <= medium && j <= high) {\n if (helper[i] <= helper[j]) {\n input[k] = helper[i];\n i++;\n } else {\n input[k] = helper[j];\n // the number of elements in the first half which the j element needs to jump over.\n // there is an inversion between each of those elements and j.\n inversionCount += (medium + 1 - i);\n j++;\n }\n k++;\n }\n\n // finish writing back in the input the elements from the first part\n while (i <= medium) {\n input[k] = helper[i];\n i++;\n k++;\n }\n return inversionCount;\n }\n\n}\n"
},
{
"answer_id": 25130614,
"author": "Brandon",
"author_id": 1015300,
"author_profile": "https://Stackoverflow.com/users/1015300",
"pm_score": 0,
"selected": false,
"text": "def solution(t)\n sorted, inversion_count = sort_inversion_count(t)\n return inversion_count\nend\n\ndef sort_inversion_count(t)\n midpoint = t.length / 2\n left_half = t[0...midpoint]\n right_half = t[midpoint..t.length]\n\n if midpoint == 0\n return t, 0\n end\n\n sorted_left_half, left_half_inversion_count = sort_inversion_count(left_half)\n sorted_right_half, right_half_inversion_count = sort_inversion_count(right_half)\n\n sorted = []\n inversion_count = 0\n while sorted_left_half.length > 0 or sorted_right_half.length > 0\n if sorted_left_half.empty?\n sorted.push sorted_right_half.shift\n elsif sorted_right_half.empty?\n sorted.push sorted_left_half.shift\n else\n if sorted_left_half[0] > sorted_right_half[0]\n inversion_count += sorted_left_half.length\n sorted.push sorted_right_half.shift\n else\n sorted.push sorted_left_half.shift\n end\n end\n end\n\n return sorted, inversion_count + left_half_inversion_count + right_half_inversion_count\nend\n require \"minitest/autorun\"\n\nclass TestCodility < Minitest::Test\n def test_given_example\n a = [-1, 6, 3, 4, 7, 4]\n assert_equal solution(a), 4\n end\n\n def test_empty\n a = []\n assert_equal solution(a), 0\n end\n\n def test_singleton\n a = [0]\n assert_equal solution(a), 0\n end\n\n def test_none\n a = [1,2,3,4,5,6,7]\n assert_equal solution(a), 0\n end\n\n def test_all\n a = [5,4,3,2,1]\n assert_equal solution(a), 10\n end\n\n def test_clones\n a = [4,4,4,4,4,4]\n assert_equal solution(a), 0\n end\nend\n"
},
{
"answer_id": 27133571,
"author": "Dheeraj Sachan",
"author_id": 3314058,
"author_profile": "https://Stackoverflow.com/users/3314058",
"pm_score": 2,
"selected": false,
"text": "/**\n*array sorting needed to verify if first arrays n'th element is greater than sencond arrays\n*some element then all elements following n will do the same\n*/\n#include<stdio.h>\n#include<iostream>\nusing namespace std;\nint countInversions(int array[],int size);\nint merge(int arr1[],int size1,int arr2[],int size2,int[]);\nint main()\n{\n int array[] = {2, 4, 1, 3, 5};\n int size = sizeof(array) / sizeof(array[0]);\n int x = countInversions(array,size);\n printf(\"number of inversions = %d\",x);\n}\n\nint countInversions(int array[],int size)\n{\n if(size > 1 )\n {\n int mid = size / 2;\n int count1 = countInversions(array,mid);\n int count2 = countInversions(array+mid,size-mid);\n int temp[size];\n int count3 = merge(array,mid,array+mid,size-mid,temp);\n for(int x =0;x<size ;x++)\n {\n array[x] = temp[x];\n }\n return count1 + count2 + count3;\n }else{\n return 0;\n }\n}\n\nint merge(int arr1[],int size1,int arr2[],int size2,int temp[])\n{\n int count = 0;\n int a = 0;\n int b = 0;\n int c = 0;\n while(a < size1 && b < size2)\n {\n if(arr1[a] < arr2[b])\n {\n temp[c] = arr1[a];\n c++;\n a++;\n }else{\n temp[c] = arr2[b];\n b++;\n c++;\n count = count + size1 -a;\n }\n }\n\n while(a < size1)\n {\n temp[c] = arr1[a];\n c++;a++;\n }\n\nwhile(b < size2)\n {\n temp[c] = arr2[b];\n c++;b++;\n }\n\n return count;\n}\n"
},
{
"answer_id": 28222543,
"author": "Omid",
"author_id": 119707,
"author_profile": "https://Stackoverflow.com/users/119707",
"pm_score": 1,
"selected": false,
"text": "sub sort_and_count {\n my ($arr, $n) = @_;\n return ($arr, 0) unless $n > 1;\n\n my $mid = $n % 2 == 1 ? ($n-1)/2 : $n/2;\n my @left = @$arr[0..$mid-1];\n my @right = @$arr[$mid..$n-1];\n\n my ($sleft, $x) = sort_and_count( \\@left, $mid );\n my ($sright, $y) = sort_and_count( \\@right, $n-$mid);\n my ($merged, $z) = merge_and_countsplitinv( $sleft, $sright, $n );\n\n return ($merged, $x+$y+$z);\n}\n\nsub merge_and_countsplitinv {\n my ($left, $right, $n) = @_;\n\n my ($l_c, $r_c) = ($#$left+1, $#$right+1);\n my ($i, $j) = (0, 0);\n my @merged;\n my $inv = 0;\n\n for my $k (0..$n-1) {\n if ($i<$l_c && $j<$r_c) {\n if ( $left->[$i] < $right->[$j]) {\n push @merged, $left->[$i];\n $i+=1;\n } else {\n push @merged, $right->[$j];\n $j+=1;\n $inv += $l_c - $i;\n }\n } else {\n if ($i>=$l_c) {\n push @merged, @$right[ $j..$#$right ];\n } else {\n push @merged, @$left[ $i..$#$left ];\n }\n last;\n }\n }\n\n return (\\@merged, $inv);\n}\n"
},
{
"answer_id": 29451168,
"author": "B. M.",
"author_id": 4016285,
"author_profile": "https://Stackoverflow.com/users/4016285",
"pm_score": 3,
"selected": false,
"text": "def merge(l1,l2):\n l = []\n # global count\n while l1 and l2:\n if l1[-1] <= l2[-1]:\n l.append(l2.pop())\n else:\n l.append(l1.pop())\n # count += len(l2)\n l.reverse()\n return l1 + l2 + l\n\ndef sort(l): \n t = len(l) // 2\n return merge(sort(l[:t]), sort(l[t:])) if t > 0 else l\n\ncount=0\nprint(sort([5,1,2,4,9,3]), count)\n# [1, 2, 3, 4, 5, 9] 6\n def part(l):\n pivot=l[-1]\n small,big = [],[]\n count = big_count = 0\n for x in l:\n if x <= pivot:\n small.append(x)\n count += big_count\n else:\n big.append(x)\n big_count += 1\n return count,small,big\n\ndef quick_count(l):\n if len(l)<2 : return 0\n count,small,big = part(l)\n small.pop()\n return count + quick_count(small) + quick_count(big)\n def count_inversions(a):\n n = a.size\n counts = np.arange(n) & -np.arange(n) # The BIT\n ags = a.argsort(kind='mergesort') \n return BIT(ags,counts,n)\n @numba.njit\ndef BIT(ags,counts,n):\n res = 0 \n for x in ags :\n i = x\n while i:\n res += counts[i]\n i -= i & -i\n i = x+1\n while i < n:\n counts[i] -= 1\n i += i & -i\n return res \n"
},
{
"answer_id": 33505678,
"author": "python",
"author_id": 4593743,
"author_profile": "https://Stackoverflow.com/users/4593743",
"pm_score": 1,
"selected": false,
"text": "def binarySearch(alist, item):\n first = 0\n last = len(alist) - 1\n found = False\n\n while first <= last and not found:\n midpoint = (first + last)//2\n if alist[midpoint] == item:\n return midpoint\n else:\n if item < alist[midpoint]:\n last = midpoint - 1\n else:\n first = midpoint + 1\n\ndef solution(A):\n\n B = list(A)\n B.sort()\n inversion_count = 0\n for i in range(len(A)):\n j = binarySearch(B, A[i])\n while B[j] == B[j - 1]:\n if j < 1:\n break\n j -= 1\n\n inversion_count += j\n B.pop(j)\n\n if inversion_count > 1000000000:\n return -1\n else:\n return inversion_count\n\nprint solution([4, 10, 11, 1, 3, 9, 10])\n"
},
{
"answer_id": 37824591,
"author": "Varun Garg",
"author_id": 4728372,
"author_profile": "https://Stackoverflow.com/users/4728372",
"pm_score": 1,
"selected": false,
"text": "//Code\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n int i,n;\n cin >> n;\n int arr[n],inv[n];\n for(i=0;i<n;i++){\n cin >> arr[i];\n }\n vector<int> v;\n v.push_back(arr[n-1]);\n inv[n-1]=0;\n for(i=n-2;i>=0;i--){\n auto it = lower_bound(v.begin(),v.end(),arr[i]); \n //calculating least element in vector v which is greater than arr[i]\n inv[i]=it-v.begin();\n //calculating distance from starting of vector\n v.insert(it,arr[i]);\n //inserting that element into vector v\n }\n for(i=0;i<n;i++){\n cout << inv[i] << \" \";\n }\n cout << endl;\n return 0;\n}\n //INPUT \n4\n2 1 4 3\n\n//OUTPUT \n1 0 1 0\n\n//To calculate total inversion count just add up all the elements in output array\n"
},
{
"answer_id": 38720631,
"author": "M Sach",
"author_id": 802050,
"author_profile": "https://Stackoverflow.com/users/802050",
"pm_score": 0,
"selected": false,
"text": "mergeToParent (left[leftunPicked] < right[rightunPicked]) public class TestInversionThruMergeSort {\n \n static int count =0;\n\n public static void main(String[] args) {\n int[] arr = {6, 9, 1, 14, 8, 12, 3, 2};\n \n\n partition(arr);\n\n for (int i = 0; i < arr.length; i++) {\n\n System.out.println(arr[i]);\n }\n \n System.out.println(\"inversions are \"+count);\n\n }\n\n public static void partition(int[] arr) {\n\n if (arr.length > 1) {\n\n int mid = (arr.length) / 2;\n int[] left = null;\n\n if (mid > 0) {\n left = new int[mid];\n\n for (int i = 0; i < mid; i++) {\n left[i] = arr[i];\n }\n }\n\n int[] right = new int[arr.length - left.length];\n\n if ((arr.length - left.length) > 0) {\n int j = 0;\n for (int i = mid; i < arr.length; i++) {\n right[j] = arr[i];\n ++j;\n }\n }\n\n partition(left);\n partition(right);\n mergeToParent(left, right, arr);\n }\n\n }\n\n public static void mergeToParent(int[] left, int[] right, int[] parent) {\n\n int leftunPicked = 0;\n int rightunPicked = 0;\n int parentIndex = -1;\n\n while (rightunPicked < right.length && leftunPicked < left.length) {\n\n if (left[leftunPicked] < right[rightunPicked]) {\n parent[++parentIndex] = left[leftunPicked];\n ++leftunPicked;\n\n } else {\n count = count + left.length-leftunPicked;\n if ((rightunPicked < right.length)) {\n parent[++parentIndex] = right[rightunPicked];\n ++rightunPicked;\n }\n }\n\n }\n\n while (leftunPicked < left.length) {\n parent[++parentIndex] = left[leftunPicked];\n ++leftunPicked;\n }\n\n while (rightunPicked < right.length) {\n parent[++parentIndex] = right[rightunPicked];\n ++rightunPicked;\n }\n\n }\n\n}\n import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\n\n\npublic class TestInversion {\n\n public static void main(String[] args) {\n \n Integer [] arr1 = {6, 9, 1, 14, 8, 12, 3, 2};\n \n List<Integer> arr = new ArrayList(Arrays.asList(arr1));\n List<Integer> sortArr = new ArrayList<Integer>();\n \n for(int i=0;i<arr.size();i++){\n sortArr.add(arr.get(i));\n \n }\n \n \n Collections.sort(sortArr);\n \n int inversion = 0;\n \n Iterator<Integer> iter = arr.iterator();\n \n while(iter.hasNext()){\n \n Integer el = (Integer)iter.next();\n int index = sortArr.indexOf(el);\n \n if(index+1 > 1){\n inversion = inversion + ((index+1)-1);\n }\n \n //iter.remove();\n sortArr.remove(el);\n \n }\n \n System.out.println(\"Inversions are \"+inversion);\n \n \n \n\n }\n\n\n}\n"
},
{
"answer_id": 38859289,
"author": "Zhe Hu",
"author_id": 1905022,
"author_profile": "https://Stackoverflow.com/users/1905022",
"pm_score": -1,
"selected": false,
"text": "def inv_cnt(a):\nn = len(a)\nif n==1:\n return a,0\nleft = a[0:n//2] # should be smaller\nleft,cnt1 = inv_cnt(left) \nright = a[n//2:] # should be larger\nright, cnt2 = inv_cnt(right)\n\ncnt = 0 \ni_left = i_right = i_a = 0\nwhile i_a < n:\n if (i_right>=len(right)) or (i_left < len(left) and left[i_left] <= right[i_right]):\n a[i_a] = left[i_left]\n i_left += 1\n else:\n a[i_a] = right[i_right]\n i_right += 1 \n if i_left < len(left):\n cnt += len(left) - i_left \n i_a += 1 \n\nreturn (a, (cnt1 + cnt2 + cnt))\n"
},
{
"answer_id": 43063622,
"author": "Suhail Gupta",
"author_id": 648138,
"author_profile": "https://Stackoverflow.com/users/648138",
"pm_score": 0,
"selected": false,
"text": "n maxPossibleInversions = (n * (n-1) ) / 2\n 6 15 n logn inversionCount += leftSubArray.length var arr = [6,5,4,3,2,1]; // Sample input array\n\nvar inversionCount = 0;\n\nfunction mergeSort(arr) {\n if(arr.length == 1)\n return arr;\n\n if(arr.length > 1) {\n let breakpoint = Math.ceil((arr.length/2));\n // Left list starts with 0, breakpoint-1\n let leftList = arr.slice(0,breakpoint);\n // Right list starts with breakpoint, length-1\n let rightList = arr.slice(breakpoint,arr.length);\n\n // Make a recursive call\n leftList = mergeSort(leftList);\n rightList = mergeSort(rightList);\n\n var a = merge(leftList,rightList);\n return a;\n }\n}\n\nfunction merge(leftList,rightList) {\n let result = [];\n while(leftList.length && rightList.length) {\n /**\n * The shift() method removes the first element from an array\n * and returns that element. This method changes the length\n * of the array.\n */\n if(leftList[0] <= rightList[0]) {\n result.push(leftList.shift());\n }else{\n inversionCount += leftList.length;\n result.push(rightList.shift());\n }\n }\n\n while(leftList.length)\n result.push(leftList.shift());\n\n while(rightList.length)\n result.push(rightList.shift());\n\n console.log(result);\n return result;\n}\n\nmergeSort(arr);\nconsole.log('Number of inversions: ' + inversionCount);\n"
},
{
"answer_id": 46868726,
"author": "davejlin",
"author_id": 5464788,
"author_profile": "https://Stackoverflow.com/users/5464788",
"pm_score": 0,
"selected": false,
"text": "nSwaps += mid + 1 - iL \n func merge(arr: inout [Int], arr2: inout [Int], low: Int, mid: Int, high: Int) -> Int {\n var nSwaps = 0;\n\n var i = low;\n var iL = low;\n var iR = mid + 1;\n\n while iL <= mid && iR <= high {\n if arr2[iL] <= arr2[iR] {\n arr[i] = arr2[iL]\n iL += 1\n i += 1\n } else {\n arr[i] = arr2[iR]\n nSwaps += mid + 1 - iL\n iR += 1\n i += 1\n }\n }\n\n while iL <= mid {\n arr[i] = arr2[iL]\n iL += 1\n i += 1\n }\n\n while iR <= high {\n arr[i] = arr2[iR]\n iR += 1\n i += 1\n }\n\n return nSwaps\n}\n\nfunc mergeSort(arr: inout [Int]) -> Int {\n var arr2 = arr\n let nSwaps = mergeSort(arr: &arr, arr2: &arr2, low: 0, high: arr.count-1)\n return nSwaps\n}\n\nfunc mergeSort(arr: inout [Int], arr2: inout [Int], low: Int, high: Int) -> Int {\n\n if low >= high {\n return 0\n }\n\n let mid = low + ((high - low) / 2)\n\n var nSwaps = 0;\n nSwaps += mergeSort(arr: &arr2, arr2: &arr, low: low, high: mid)\n nSwaps += mergeSort(arr: &arr2, arr2: &arr, low: mid+1, high: high)\n nSwaps += merge(arr: &arr, arr2: &arr2, low: low, mid: mid, high: high)\n\n return nSwaps\n}\n\nvar arrayToSort: [Int] = [2, 1, 3, 1, 2]\nlet nSwaps = mergeSort(arr: &arrayToSort)\n\nprint(arrayToSort) // [1, 1, 2, 2, 3]\nprint(nSwaps) // 4\n"
},
{
"answer_id": 47845960,
"author": "PM 2Ring",
"author_id": 4014959,
"author_profile": "https://Stackoverflow.com/users/4014959",
"pm_score": 4,
"selected": false,
"text": "sum def count_inversions(a):\n total = 0\n counts = [0] * len(a)\n rank = {v: i for i, v in enumerate(sorted(a))}\n for u in reversed(a):\n i = rank[u]\n total += sum(counts[:i])\n counts[i] += 1\n return total\n sum for range(b**m) b seq range(n) seq seq seq seq = [15, 14, 11, 12, 10, 13]\nb = [t[::-1] for t in enumerate(seq)]\nprint(b)\nb.sort()\nprint(b)\n [(15, 0), (14, 1), (11, 2), (12, 3), (10, 4), (13, 5)]\n[(10, 4), (11, 2), (12, 3), (13, 5), (14, 1), (15, 0)]\n seq seq seq range(n) print(sorted(range(len(seq)), key=lambda k: seq[k]))\n [4, 2, 3, 5, 1, 0]\n lambda seq .__getitem__ sorted(range(len(seq)), key=seq.__getitem__)\n timeit sum timeit timeit sum while #!/usr/bin/env python3\n\n''' Test speeds of various ways of counting inversions in a list\n\n The inversion count is a measure of how sorted an array is.\n A pair of items in a are inverted if i < j but a[j] > a[i]\n\n See https://stackoverflow.com/questions/337664/counting-inversions-in-an-array\n\n This program contains code by the following authors:\n mkso\n Niklas B\n B. M.\n Tim Babych\n python\n Zhe Hu\n prasadvk\n noman pouigt\n PM 2Ring\n\n Timing and verification code by PM 2Ring\n Collated 2017.12.16\n Updated 2017.12.21\n'''\n\nfrom timeit import Timer\nfrom random import seed, randrange\nfrom bisect import bisect, insort_left\n\nseed('A random seed string')\n\n# Merge sort version by mkso\ndef count_inversion_mkso(lst):\n return merge_count_inversion(lst)[1]\n\ndef merge_count_inversion(lst):\n if len(lst) <= 1:\n return lst, 0\n middle = len(lst) // 2\n left, a = merge_count_inversion(lst[:middle])\n right, b = merge_count_inversion(lst[middle:])\n result, c = merge_count_split_inversion(left, right)\n return result, (a + b + c)\n\ndef merge_count_split_inversion(left, right):\n result = []\n count = 0\n i, j = 0, 0\n left_len = len(left)\n while i < left_len and j < len(right):\n if left[i] <= right[j]:\n result.append(left[i])\n i += 1\n else:\n result.append(right[j])\n count += left_len - i\n j += 1\n result += left[i:]\n result += right[j:]\n return result, count\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n# Using a Binary Indexed Tree, aka a Fenwick tree, by Niklas B.\ndef count_inversions_NiklasB(a):\n res = 0\n counts = [0] * (len(a) + 1)\n rank = {v: i for i, v in enumerate(sorted(a), 1)}\n for x in reversed(a):\n i = rank[x] - 1\n while i:\n res += counts[i]\n i -= i & -i\n i = rank[x]\n while i <= len(a):\n counts[i] += 1\n i += i & -i\n return res\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n# Merge sort version by B.M\n# Modified by PM 2Ring to deal with the global counter\nbm_count = 0\n\ndef merge_count_BM(seq):\n global bm_count\n bm_count = 0\n sort_bm(seq)\n return bm_count\n\ndef merge_bm(l1,l2):\n global bm_count\n l = []\n while l1 and l2:\n if l1[-1] <= l2[-1]:\n l.append(l2.pop())\n else:\n l.append(l1.pop())\n bm_count += len(l2)\n l.reverse()\n return l1 + l2 + l\n\ndef sort_bm(l):\n t = len(l) // 2\n return merge_bm(sort_bm(l[:t]), sort_bm(l[t:])) if t > 0 else l\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n# Bisection based method by Tim Babych\ndef solution_TimBabych(A):\n sorted_left = []\n res = 0\n for i in range(1, len(A)):\n insort_left(sorted_left, A[i-1])\n # i is also the length of sorted_left\n res += (i - bisect(sorted_left, A[i]))\n return res\n\n# Slightly faster, except for very small lists\ndef solutionE_TimBabych(A):\n res = 0\n sorted_left = []\n for i, u in enumerate(A):\n # i is also the length of sorted_left\n res += (i - bisect(sorted_left, u))\n insort_left(sorted_left, u)\n return res\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n# Bisection based method by \"python\"\ndef solution_python(A):\n B = list(A)\n B.sort()\n inversion_count = 0\n for i in range(len(A)):\n j = binarySearch_python(B, A[i])\n while B[j] == B[j - 1]:\n if j < 1:\n break\n j -= 1\n inversion_count += j\n B.pop(j)\n return inversion_count\n\ndef binarySearch_python(alist, item):\n first = 0\n last = len(alist) - 1\n found = False\n while first <= last and not found:\n midpoint = (first + last) // 2\n if alist[midpoint] == item:\n return midpoint\n else:\n if item < alist[midpoint]:\n last = midpoint - 1\n else:\n first = midpoint + 1\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n# Merge sort version by Zhe Hu\ndef inv_cnt_ZheHu(a):\n _, count = inv_cnt(a.copy())\n return count\n\ndef inv_cnt(a):\n n = len(a)\n if n==1:\n return a, 0\n left = a[0:n//2] # should be smaller\n left, cnt1 = inv_cnt(left)\n right = a[n//2:] # should be larger\n right, cnt2 = inv_cnt(right)\n\n cnt = 0\n i_left = i_right = i_a = 0\n while i_a < n:\n if (i_right>=len(right)) or (i_left < len(left)\n and left[i_left] <= right[i_right]):\n a[i_a] = left[i_left]\n i_left += 1\n else:\n a[i_a] = right[i_right]\n i_right += 1\n if i_left < len(left):\n cnt += len(left) - i_left\n i_a += 1\n return (a, cnt1 + cnt2 + cnt)\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n# Merge sort version by noman pouigt\n# From https://stackoverflow.com/q/47830098\ndef reversePairs_nomanpouigt(nums):\n def merge(left, right):\n if not left or not right:\n return (0, left + right)\n #if everything in left is less than right\n if left[len(left)-1] < right[0]:\n return (0, left + right)\n else:\n left_idx, right_idx, count = 0, 0, 0\n merged_output = []\n\n # check for condition before we merge it\n while left_idx < len(left) and right_idx < len(right):\n #if left[left_idx] > 2 * right[right_idx]:\n if left[left_idx] > right[right_idx]:\n count += len(left) - left_idx\n right_idx += 1\n else:\n left_idx += 1\n\n #merging the sorted list\n left_idx, right_idx = 0, 0\n while left_idx < len(left) and right_idx < len(right):\n if left[left_idx] > right[right_idx]:\n merged_output += [right[right_idx]]\n right_idx += 1\n else:\n merged_output += [left[left_idx]]\n left_idx += 1\n if left_idx == len(left):\n merged_output += right[right_idx:]\n else:\n merged_output += left[left_idx:]\n return (count, merged_output)\n\n def partition(nums):\n count = 0\n if len(nums) == 1 or not nums:\n return (0, nums)\n pivot = len(nums)//2\n left_count, l = partition(nums[:pivot])\n right_count, r = partition(nums[pivot:])\n temp_count, temp_list = merge(l, r)\n return (temp_count + left_count + right_count, temp_list)\n return partition(nums)[0]\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n# PM 2Ring\ndef merge_PM2R(seq):\n seq, count = merge_sort_count_PM2R(seq)\n return count\n\ndef merge_sort_count_PM2R(seq):\n mid = len(seq) // 2\n if mid == 0:\n return seq, 0\n left, left_total = merge_sort_count_PM2R(seq[:mid])\n right, right_total = merge_sort_count_PM2R(seq[mid:])\n total = left_total + right_total\n result = []\n i = j = 0\n left_len, right_len = len(left), len(right)\n while i < left_len and j < right_len:\n if left[i] <= right[j]:\n result.append(left[i])\n i += 1\n else:\n result.append(right[j])\n j += 1\n total += left_len - i\n result.extend(left[i:])\n result.extend(right[j:])\n return result, total\n\ndef rank_sum_PM2R(a):\n total = 0\n counts = [0] * len(a)\n rank = {v: i for i, v in enumerate(sorted(a))}\n for u in reversed(a):\n i = rank[u]\n total += sum(counts[:i])\n counts[i] += 1\n return total\n\n# Fenwick tree functions adapted from C code on Wikipedia\ndef fen_sum(tree, i):\n ''' Return the sum of the first i elements, 0 through i-1 '''\n total = 0\n while i:\n total += tree[i-1]\n i -= i & -i\n return total\n\ndef fen_add(tree, delta, i):\n ''' Add delta to element i and thus \n to fen_sum(tree, j) for all j > i \n '''\n size = len(tree)\n while i < size:\n tree[i] += delta\n i += (i+1) & -(i+1)\n\ndef fenwick_PM2R(a):\n total = 0\n counts = [0] * len(a)\n rank = {v: i for i, v in enumerate(sorted(a))}\n for u in reversed(a):\n i = rank[u]\n total += fen_sum(counts, i)\n fen_add(counts, 1, i)\n return total\n\ndef fenwick_inline_PM2R(a):\n total = 0\n size = len(a)\n counts = [0] * size\n rank = {v: i for i, v in enumerate(sorted(a))}\n for u in reversed(a):\n i = rank[u]\n j = i + 1\n while i:\n total += counts[i]\n i -= i & -i\n while j < size:\n counts[j] += 1\n j += j & -j\n return total\n\ndef bruteforce_loops_PM2R(a):\n total = 0\n for i in range(1, len(a)):\n u = a[i]\n for j in range(i):\n if a[j] > u:\n total += 1\n return total\n\ndef bruteforce_sum_PM2R(a):\n return sum(1 for i in range(1, len(a)) for j in range(i) if a[j] > a[i])\n\n# Using binary tree counting, derived from C++ code (?) by prasadvk\n# https://stackoverflow.com/a/16056139\ndef ltree_count_PM2R(a):\n total, root = 0, None\n for u in a:\n # Store data in a list-based tree structure\n # [data, count, left_child, right_child]\n p = [u, 0, None, None]\n if root is None:\n root = p\n continue\n q = root\n while True:\n if p[0] < q[0]:\n total += 1 + q[1]\n child = 2\n else:\n q[1] += 1\n child = 3\n if q[child]:\n q = q[child]\n else:\n q[child] = p\n break\n return total\n\n# Counting based on radix sort, recursive version\ndef radix_partition_rec(a, L):\n if len(a) < 2:\n return 0\n if len(a) == 2:\n return a[1] < a[0]\n left, right = [], []\n count = 0\n for u in a:\n if u & L:\n right.append(u)\n else:\n count += len(right)\n left.append(u)\n L >>= 1\n if L:\n count += radix_partition_rec(left, L) + radix_partition_rec(right, L)\n return count\n\n# The following functions determine swaps using a permutation of \n# range(len(a)) that has the same inversion count as `a`. We can create\n# this permutation with `sorted(range(len(a)), key=lambda k: a[k])`\n# but `sorted(range(len(a)), key=a.__getitem__)` is a little faster.\n\n# Counting based on radix sort, iterative version\ndef radix_partition_iter(seq, L):\n count = 0\n parts = [seq]\n while L and parts:\n newparts = []\n for a in parts:\n if len(a) < 2:\n continue\n if len(a) == 2:\n count += a[1] < a[0]\n continue\n left, right = [], []\n for u in a:\n if u & L:\n right.append(u)\n else:\n count += len(right)\n left.append(u)\n if left:\n newparts.append(left)\n if right:\n newparts.append(right)\n parts = newparts\n L >>= 1\n return count\n\ndef perm_radixR_PM2R(a):\n size = len(a)\n b = sorted(range(size), key=a.__getitem__)\n n = size.bit_length() - 1\n return radix_partition_rec(b, 1 << n)\n\ndef perm_radixI_PM2R(a):\n size = len(a)\n b = sorted(range(size), key=a.__getitem__)\n n = size.bit_length() - 1\n return radix_partition_iter(b, 1 << n)\n\n# Plain sum of the counts of the permutation\ndef perm_sum_PM2R(a):\n total = 0\n size = len(a)\n counts = [0] * size\n for i in reversed(sorted(range(size), key=a.__getitem__)):\n total += sum(counts[:i])\n counts[i] = 1\n return total\n\n# Fenwick sum of the counts of the permutation\ndef perm_fenwick_PM2R(a):\n total = 0\n size = len(a)\n counts = [0] * size\n for i in reversed(sorted(range(size), key=a.__getitem__)):\n j = i + 1\n while i:\n total += counts[i]\n i -= i & -i\n while j < size:\n counts[j] += 1\n j += j & -j\n return total\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n# All the inversion-counting functions\nfuncs = (\n solution_TimBabych,\n solutionE_TimBabych,\n solution_python,\n count_inversion_mkso,\n count_inversions_NiklasB,\n merge_count_BM,\n inv_cnt_ZheHu,\n reversePairs_nomanpouigt,\n fenwick_PM2R,\n fenwick_inline_PM2R,\n merge_PM2R,\n rank_sum_PM2R,\n bruteforce_loops_PM2R,\n bruteforce_sum_PM2R,\n ltree_count_PM2R,\n perm_radixR_PM2R,\n perm_radixI_PM2R,\n perm_sum_PM2R,\n perm_fenwick_PM2R,\n)\n\ndef time_test(seq, loops, verify=False):\n orig = seq\n timings = []\n for func in funcs:\n seq = orig.copy()\n value = func(seq) if verify else None\n t = Timer(lambda: func(seq))\n result = sorted(t.repeat(3, loops))\n timings.append((result, func.__name__, value))\n assert seq==orig, 'Sequence altered by {}!'.format(func.__name__)\n first = timings[0][-1]\n timings.sort()\n for result, name, value in timings:\n result = ', '.join([format(u, '.5f') for u in result])\n print('{:24} : {}'.format(name, result))\n\n if verify:\n # Check that all results are identical\n bad = ['%s: %d' % (name, value)\n for _, name, value in timings if value != first]\n if bad:\n print('ERROR. Value: {}, bad: {}'.format(first, ', '.join(bad)))\n else:\n print('Value: {}'.format(first))\n print()\n\n#Run the tests\nsize, loops = 5, 1 << 12\nverify = True\nfor _ in range(7):\n hi = size // 2\n print('Size = {}, hi = {}, {} loops'.format(size, hi, loops))\n seq = [randrange(hi) for _ in range(size)]\n time_test(seq, loops, verify)\n loops >>= 1\n size <<= 1\n\n#size, loops = 640, 8\n#verify = False\n#for _ in range(5):\n #hi = size // 2\n #print('Size = {}, hi = {}, {} loops'.format(size, hi, loops))\n #seq = [randrange(hi) for _ in range(size)]\n #time_test(seq, loops, verify)\n #size <<= 1\n\n#size, loops = 163840, 4\n#verify = False\n#for _ in range(3):\n #hi = size // 2\n #print('Size = {}, hi = {}, {} loops'.format(size, hi, loops))\n #seq = [randrange(hi) for _ in range(size)]\n #time_test(seq, loops, verify)\n #size <<= 1\n"
},
{
"answer_id": 47925603,
"author": "PM 2Ring",
"author_id": 4014959,
"author_profile": "https://Stackoverflow.com/users/4014959",
"pm_score": 2,
"selected": false,
"text": "timeit count_inversions speed test results\n\nSize = 5, hi = 2, 4096 loops\nltree_count_PM2R : 0.04871, 0.04872, 0.04876\nbruteforce_loops_PM2R : 0.05696, 0.05700, 0.05776\nsolution_TimBabych : 0.05760, 0.05822, 0.05943\nsolutionE_TimBabych : 0.06642, 0.06704, 0.06760\nbruteforce_sum_PM2R : 0.07523, 0.07545, 0.07563\nperm_sum_PM2R : 0.09873, 0.09875, 0.09935\nrank_sum_PM2R : 0.10449, 0.10463, 0.10468\nsolution_python : 0.13034, 0.13061, 0.13221\nfenwick_inline_PM2R : 0.14323, 0.14610, 0.18802\nperm_radixR_PM2R : 0.15146, 0.15203, 0.15235\nmerge_count_BM : 0.16179, 0.16267, 0.16467\nperm_radixI_PM2R : 0.16200, 0.16202, 0.16768\nperm_fenwick_PM2R : 0.16887, 0.16920, 0.17075\nmerge_PM2R : 0.18262, 0.18271, 0.18418\ncount_inversions_NiklasB : 0.19183, 0.19279, 0.20388\ncount_inversion_mkso : 0.20060, 0.20141, 0.20398\ninv_cnt_ZheHu : 0.20815, 0.20841, 0.20906\nfenwick_PM2R : 0.22109, 0.22137, 0.22379\nreversePairs_nomanpouigt : 0.29620, 0.29689, 0.30293\nValue: 5\n\nSize = 10, hi = 5, 2048 loops\nsolution_TimBabych : 0.05954, 0.05989, 0.05991\nsolutionE_TimBabych : 0.05970, 0.05972, 0.05998\nperm_sum_PM2R : 0.07517, 0.07519, 0.07520\nltree_count_PM2R : 0.07672, 0.07677, 0.07684\nbruteforce_loops_PM2R : 0.07719, 0.07724, 0.07817\nrank_sum_PM2R : 0.08587, 0.08823, 0.08864\nbruteforce_sum_PM2R : 0.09470, 0.09472, 0.09484\nsolution_python : 0.13126, 0.13154, 0.13185\nperm_radixR_PM2R : 0.14239, 0.14320, 0.14474\nperm_radixI_PM2R : 0.14632, 0.14669, 0.14679\nfenwick_inline_PM2R : 0.16796, 0.16831, 0.17030\nperm_fenwick_PM2R : 0.18189, 0.18212, 0.18638\nmerge_count_BM : 0.19816, 0.19870, 0.19948\ncount_inversions_NiklasB : 0.21807, 0.22031, 0.22215\nmerge_PM2R : 0.22037, 0.22048, 0.26106\nfenwick_PM2R : 0.24290, 0.24314, 0.24744\ncount_inversion_mkso : 0.24895, 0.24899, 0.25205\ninv_cnt_ZheHu : 0.26253, 0.26259, 0.26590\nreversePairs_nomanpouigt : 0.35711, 0.35762, 0.35973\nValue: 20\n\nSize = 20, hi = 10, 1024 loops\nsolutionE_TimBabych : 0.05687, 0.05696, 0.05720\nsolution_TimBabych : 0.06126, 0.06151, 0.06168\nperm_sum_PM2R : 0.06875, 0.06906, 0.07054\nrank_sum_PM2R : 0.07988, 0.07995, 0.08002\nltree_count_PM2R : 0.11232, 0.11239, 0.11257\nbruteforce_loops_PM2R : 0.12553, 0.12584, 0.12592\nsolution_python : 0.13472, 0.13540, 0.13694\nbruteforce_sum_PM2R : 0.15820, 0.15849, 0.16021\nperm_radixI_PM2R : 0.17101, 0.17148, 0.17229\nperm_radixR_PM2R : 0.17891, 0.18087, 0.18366\nperm_fenwick_PM2R : 0.20554, 0.20708, 0.21412\nfenwick_inline_PM2R : 0.21161, 0.21163, 0.22047\nmerge_count_BM : 0.24125, 0.24261, 0.24565\ncount_inversions_NiklasB : 0.25712, 0.25754, 0.25778\nmerge_PM2R : 0.26477, 0.26566, 0.31297\nfenwick_PM2R : 0.28178, 0.28216, 0.29069\ncount_inversion_mkso : 0.30286, 0.30290, 0.30652\ninv_cnt_ZheHu : 0.32024, 0.32041, 0.32447\nreversePairs_nomanpouigt : 0.45812, 0.45822, 0.46172\nValue: 98\n\nSize = 40, hi = 20, 512 loops\nsolutionE_TimBabych : 0.05784, 0.05787, 0.05958\nsolution_TimBabych : 0.06452, 0.06475, 0.06479\nperm_sum_PM2R : 0.07254, 0.07261, 0.07263\nrank_sum_PM2R : 0.08537, 0.08540, 0.08572\nltree_count_PM2R : 0.11744, 0.11749, 0.11792\nsolution_python : 0.14262, 0.14285, 0.14465\nperm_radixI_PM2R : 0.18774, 0.18776, 0.18922\nperm_radixR_PM2R : 0.19425, 0.19435, 0.19609\nbruteforce_loops_PM2R : 0.21500, 0.21511, 0.21686\nperm_fenwick_PM2R : 0.23338, 0.23375, 0.23674\nfenwick_inline_PM2R : 0.24947, 0.24958, 0.25189\nbruteforce_sum_PM2R : 0.27627, 0.27646, 0.28041\nmerge_count_BM : 0.28059, 0.28128, 0.28294\ncount_inversions_NiklasB : 0.28557, 0.28759, 0.29022\nmerge_PM2R : 0.29886, 0.29928, 0.30317\nfenwick_PM2R : 0.30241, 0.30259, 0.35237\ncount_inversion_mkso : 0.34252, 0.34356, 0.34441\ninv_cnt_ZheHu : 0.37468, 0.37569, 0.37847\nreversePairs_nomanpouigt : 0.50725, 0.50770, 0.50943\nValue: 369\n\nSize = 80, hi = 40, 256 loops\nsolutionE_TimBabych : 0.06339, 0.06373, 0.06513\nsolution_TimBabych : 0.06984, 0.06994, 0.07009\nperm_sum_PM2R : 0.09171, 0.09172, 0.09186\nrank_sum_PM2R : 0.10468, 0.10474, 0.10500\nltree_count_PM2R : 0.14416, 0.15187, 0.18541\nsolution_python : 0.17415, 0.17423, 0.17451\nperm_radixI_PM2R : 0.20676, 0.20681, 0.20936\nperm_radixR_PM2R : 0.21671, 0.21695, 0.21736\nperm_fenwick_PM2R : 0.26197, 0.26252, 0.26264\nfenwick_inline_PM2R : 0.28111, 0.28249, 0.28382\ncount_inversions_NiklasB : 0.31746, 0.32448, 0.32451\nmerge_count_BM : 0.31964, 0.33842, 0.35276\nmerge_PM2R : 0.32890, 0.32941, 0.33322\nfenwick_PM2R : 0.34355, 0.34377, 0.34873\ncount_inversion_mkso : 0.37689, 0.37698, 0.38079\ninv_cnt_ZheHu : 0.42923, 0.42941, 0.43249\nbruteforce_loops_PM2R : 0.43544, 0.43601, 0.43902\nbruteforce_sum_PM2R : 0.52106, 0.52160, 0.52531\nreversePairs_nomanpouigt : 0.57805, 0.58156, 0.58252\nValue: 1467\n\nSize = 160, hi = 80, 128 loops\nsolutionE_TimBabych : 0.06766, 0.06784, 0.06963\nsolution_TimBabych : 0.07433, 0.07489, 0.07516\nperm_sum_PM2R : 0.13143, 0.13175, 0.13179\nrank_sum_PM2R : 0.14428, 0.14440, 0.14922\nsolution_python : 0.20072, 0.20076, 0.20084\nltree_count_PM2R : 0.20314, 0.20583, 0.24776\nperm_radixI_PM2R : 0.23061, 0.23078, 0.23525\nperm_radixR_PM2R : 0.23894, 0.23915, 0.24234\nperm_fenwick_PM2R : 0.30984, 0.31181, 0.31503\nfenwick_inline_PM2R : 0.31933, 0.32680, 0.32722\nmerge_count_BM : 0.36003, 0.36387, 0.36409\ncount_inversions_NiklasB : 0.36796, 0.36814, 0.37106\nmerge_PM2R : 0.36847, 0.36848, 0.37127\nfenwick_PM2R : 0.37833, 0.37847, 0.38095\ncount_inversion_mkso : 0.42746, 0.42747, 0.43184\ninv_cnt_ZheHu : 0.48969, 0.48974, 0.49293\nreversePairs_nomanpouigt : 0.67791, 0.68157, 0.72420\nbruteforce_loops_PM2R : 0.82816, 0.83175, 0.83282\nbruteforce_sum_PM2R : 1.03322, 1.03378, 1.03562\nValue: 6194\n\nSize = 320, hi = 160, 64 loops\nsolutionE_TimBabych : 0.07467, 0.07470, 0.07483\nsolution_TimBabych : 0.08036, 0.08066, 0.08077\nperm_sum_PM2R : 0.21142, 0.21201, 0.25766\nsolution_python : 0.22410, 0.22644, 0.22897\nrank_sum_PM2R : 0.22820, 0.22851, 0.22877\nltree_count_PM2R : 0.24424, 0.24595, 0.24645\nperm_radixI_PM2R : 0.25690, 0.25710, 0.26191\nperm_radixR_PM2R : 0.26501, 0.26504, 0.26729\nperm_fenwick_PM2R : 0.33483, 0.33507, 0.33845\nfenwick_inline_PM2R : 0.34413, 0.34484, 0.35153\nmerge_count_BM : 0.39875, 0.39919, 0.40302\nfenwick_PM2R : 0.40434, 0.40439, 0.40845\nmerge_PM2R : 0.40814, 0.41531, 0.51417\ncount_inversions_NiklasB : 0.41681, 0.42009, 0.42128\ncount_inversion_mkso : 0.47132, 0.47192, 0.47385\ninv_cnt_ZheHu : 0.54468, 0.54750, 0.54893\nreversePairs_nomanpouigt : 0.76164, 0.76389, 0.80357\nbruteforce_loops_PM2R : 1.59125, 1.60430, 1.64131\nbruteforce_sum_PM2R : 2.03734, 2.03834, 2.03975\nValue: 24959\n\nRun 2\n\nSize = 640, hi = 320, 8 loops\nsolutionE_TimBabych : 0.04135, 0.04374, 0.04575\nltree_count_PM2R : 0.06738, 0.06758, 0.06874\nperm_radixI_PM2R : 0.06928, 0.06943, 0.07019\nfenwick_inline_PM2R : 0.07850, 0.07856, 0.08059\nperm_fenwick_PM2R : 0.08151, 0.08162, 0.08170\nperm_sum_PM2R : 0.09122, 0.09133, 0.09221\nrank_sum_PM2R : 0.09549, 0.09603, 0.11270\nmerge_count_BM : 0.10733, 0.10807, 0.11032\ncount_inversions_NiklasB : 0.12460, 0.19865, 0.20205\nsolution_python : 0.13514, 0.13585, 0.13814\n\nSize = 1280, hi = 640, 8 loops\nsolutionE_TimBabych : 0.04714, 0.04742, 0.04752\nperm_radixI_PM2R : 0.15325, 0.15388, 0.15525\nsolution_python : 0.15709, 0.15715, 0.16076\nfenwick_inline_PM2R : 0.16048, 0.16160, 0.16403\nltree_count_PM2R : 0.16213, 0.16238, 0.16428\nperm_fenwick_PM2R : 0.16408, 0.16416, 0.16449\ncount_inversions_NiklasB : 0.19755, 0.19833, 0.19897\nmerge_count_BM : 0.23736, 0.23793, 0.23912\nperm_sum_PM2R : 0.32946, 0.32969, 0.33277\nrank_sum_PM2R : 0.34637, 0.34756, 0.34858\n\nSize = 2560, hi = 1280, 8 loops\nsolutionE_TimBabych : 0.10898, 0.11005, 0.11025\nperm_radixI_PM2R : 0.33345, 0.33352, 0.37656\nltree_count_PM2R : 0.34670, 0.34786, 0.34833\nperm_fenwick_PM2R : 0.34816, 0.34879, 0.35214\nfenwick_inline_PM2R : 0.36196, 0.36455, 0.36741\nsolution_python : 0.36498, 0.36637, 0.40887\ncount_inversions_NiklasB : 0.42274, 0.42745, 0.42995\nmerge_count_BM : 0.50799, 0.50898, 0.50917\nperm_sum_PM2R : 1.27773, 1.27897, 1.27951\nrank_sum_PM2R : 1.29728, 1.30389, 1.30448\n\nSize = 5120, hi = 2560, 8 loops\nsolutionE_TimBabych : 0.26914, 0.26993, 0.27253\nperm_radixI_PM2R : 0.71416, 0.71634, 0.71753\nperm_fenwick_PM2R : 0.71976, 0.72078, 0.72078\nfenwick_inline_PM2R : 0.72776, 0.72804, 0.73143\nltree_count_PM2R : 0.81972, 0.82043, 0.82290\nsolution_python : 0.83714, 0.83756, 0.83962\ncount_inversions_NiklasB : 0.87282, 0.87395, 0.92087\nmerge_count_BM : 1.09496, 1.09584, 1.10207\nrank_sum_PM2R : 5.02564, 5.06277, 5.06666\nperm_sum_PM2R : 5.09088, 5.12999, 5.13512\n\nSize = 10240, hi = 5120, 8 loops\nsolutionE_TimBabych : 0.71556, 0.71718, 0.72201\nperm_radixI_PM2R : 1.54785, 1.55096, 1.55515\nperm_fenwick_PM2R : 1.55103, 1.55353, 1.59298\nfenwick_inline_PM2R : 1.57118, 1.57240, 1.57271\nltree_count_PM2R : 1.76240, 1.76247, 1.80944\ncount_inversions_NiklasB : 1.86543, 1.86851, 1.87208\nsolution_python : 2.01490, 2.01519, 2.06423\nmerge_count_BM : 2.35215, 2.35301, 2.40023\nrank_sum_PM2R : 20.07048, 20.08399, 20.13200\nperm_sum_PM2R : 20.10187, 20.12551, 20.12683\n\nRun 3\nSize = 20480, hi = 10240, 4 loops\nsolutionE_TimBabych : 1.07636, 1.08243, 1.09569\nperm_radixI_PM2R : 1.59579, 1.60519, 1.61785\nperm_fenwick_PM2R : 1.66885, 1.68549, 1.71109\nfenwick_inline_PM2R : 1.72073, 1.72752, 1.77217\nltree_count_PM2R : 1.96900, 1.97820, 2.02578\ncount_inversions_NiklasB : 2.03257, 2.05005, 2.18548\nmerge_count_BM : 2.46768, 2.47377, 2.52133\nsolution_python : 2.49833, 2.50179, 3.79819\n\nSize = 40960, hi = 20480, 4 loops\nsolutionE_TimBabych : 3.51733, 3.52008, 3.56996\nperm_radixI_PM2R : 3.51736, 3.52365, 3.56459\nperm_fenwick_PM2R : 3.76097, 3.80900, 3.87974\nfenwick_inline_PM2R : 3.95099, 3.96300, 3.99748\nltree_count_PM2R : 4.49866, 4.54652, 5.39716\ncount_inversions_NiklasB : 4.61851, 4.64303, 4.73026\nmerge_count_BM : 5.31945, 5.35378, 5.35951\nsolution_python : 6.78756, 6.82911, 6.98217\n\nSize = 81920, hi = 40960, 4 loops\nperm_radixI_PM2R : 7.68723, 7.71986, 7.72135\nperm_fenwick_PM2R : 8.52404, 8.53349, 8.53710\nfenwick_inline_PM2R : 8.97082, 8.97561, 8.98347\nltree_count_PM2R : 10.01142, 10.01426, 10.03216\ncount_inversions_NiklasB : 10.60807, 10.62424, 10.70425\nmerge_count_BM : 11.42149, 11.42342, 11.47003\nsolutionE_TimBabych : 12.83390, 12.83485, 12.89747\nsolution_python : 19.66092, 19.67067, 20.72204\n\nSize = 163840, hi = 81920, 4 loops\nperm_radixI_PM2R : 17.14153, 17.16885, 17.22240\nperm_fenwick_PM2R : 19.25944, 19.27844, 20.27568\nfenwick_inline_PM2R : 19.78221, 19.80219, 19.80766\nltree_count_PM2R : 22.42240, 22.43259, 22.48837\ncount_inversions_NiklasB : 22.97341, 23.01516, 23.98052\nmerge_count_BM : 24.42683, 24.48559, 24.51488\nsolutionE_TimBabych : 60.96006, 61.20145, 63.71835\nsolution_python : 73.75132, 73.79854, 73.95874\n\nSize = 327680, hi = 163840, 4 loops\nperm_radixI_PM2R : 36.56715, 36.60221, 37.05071\nperm_fenwick_PM2R : 42.21616, 42.21838, 42.26053\nfenwick_inline_PM2R : 43.04987, 43.09075, 43.13287\nltree_count_PM2R : 49.87400, 50.08509, 50.69292\ncount_inversions_NiklasB : 50.74591, 50.75012, 50.75551\nmerge_count_BM : 52.37284, 52.51491, 53.43003\nsolutionE_TimBabych : 373.67198, 377.03341, 377.42360\nsolution_python : 411.69178, 411.92691, 412.83856\n\nSize = 655360, hi = 327680, 4 loops\nperm_radixI_PM2R : 78.51927, 78.66327, 79.46325\nperm_fenwick_PM2R : 90.64711, 90.80328, 91.76126\nfenwick_inline_PM2R : 93.32482, 93.39086, 94.28880\ncount_inversions_NiklasB : 107.74393, 107.80036, 108.71443\nltree_count_PM2R : 109.11328, 109.23592, 110.18247\nmerge_count_BM : 111.05633, 111.07840, 112.05861\nsolutionE_TimBabych : 1830.46443, 1836.39960, 1849.53918\nsolution_python : 1911.03692, 1912.04484, 1914.69786\n"
},
{
"answer_id": 58990145,
"author": "Ankit Sharma",
"author_id": 7972621,
"author_profile": "https://Stackoverflow.com/users/7972621",
"pm_score": 2,
"selected": false,
"text": "MergeSort O(nlogn) Balanced Binary Search Tree Node *insert(Node* root, int data, int& count){\n if(!root) return new Node(data);\n if(root->data == data){\n root->freq++;\n count += getSize(root->right);\n }\n else if(root->data > data){\n count += getSize(root->right) + root->freq;\n root->left = insert(root->left, data, count);\n }\n else root->right = insert(root->right, data, count);\n return balance(root);\n}\n\nint getCount(int *a, int n){\n int c = 0;\n Node *root = NULL;\n for(auto i=0; i<n; i++) root = insert(root, a[i], c);\n return c;\n}\n Binary Indexed Tree int getInversions(int[] a) {\n int n = a.length, inversions = 0;\n int[] bit = new int[n+1];\n compress(a);\n BIT b = new BIT();\n for (int i=n-1; i>=0; i--) {\n inversions += b.getSum(bit, a[i] - 1);\n b.update(bit, n, a[i], 1);\n }\n return inversions;\n}\n Segment Tree [0, a[i]-1] a[i] with 1 int getInversions(int *a, int n) {\n int N = n + 1, c = 0;\n compress(a, n);\n int tree[N<<1] = {0};\n for (int i=n-1; i>=0; i--) {\n c+= query(tree, N, 0, a[i] - 1);\n update(tree, N, a[i], 1);\n }\n return c;\n}\n BIT Segment-Tree Coordinate compression void compress(int *a, int n) {\n int temp[n];\n for (int i=0; i<n; i++) temp[i] = a[i];\n sort(temp, temp+n);\n for (int i=0; i<n; i++) a[i] = lower_bound(temp, temp+n, a[i]) - temp + 1;\n}\n\n"
},
{
"answer_id": 61781351,
"author": "Nikhil Badyal",
"author_id": 12136319,
"author_profile": "https://Stackoverflow.com/users/12136319",
"pm_score": -1,
"selected": false,
"text": "int merge(vector<int>&nums , int low , int mid , int high){\n int size1 = mid - low +1;\n int size2= high - mid;\n vector<int>left;\n vector<int>right;\n for(int i = 0 ; i < size1 ; ++i){\n left.push_back(nums[low+i]);\n }\n for(int i = 0 ; i <size2 ; ++i){\n right.push_back(nums[mid+i+1]);\n }\n left.push_back(INT_MAX);\n right.push_back(INT_MAX);\n int i = 0 ;\n int j = 0;\n int start = low;\n int inversion = 0 ;\n while(i < size1 && j < size2){\n if(left[i]<right[j]){\n nums[start] = left[i];\n start++;\n i++;\n }else{\n for(int l = i ; l < size1; ++l){\n cout<<\"(\"<<left[l]<<\",\"<<right[j]<<\")\"<<endl;\n }\n inversion += size1 - i;\n nums[start] = right[j];\n start++;\n j++;\n }\n }\n if(i == size1){\n for(int c = j ; c< size2 ; ++c){\n nums[start] = right[c];\n start++;\n }\n }\n if(j == size2){\n for(int c = i ; c< size1 ; ++c){\n nums[start] = left[c];\n start++;\n }\n }\n return inversion;\n}\nint inversion_count(vector<int>& nums , int low , int high){\n if(high>low){\n int mid = low + (high-low)/2;\n int left = inversion_count(nums,low,mid);\n int right = inversion_count(nums,mid+1,high);\n int inversion = merge(nums,low,mid,high) + left + right;\n return inversion;\n }\n return 0 ;\n}\n"
},
{
"answer_id": 64389150,
"author": "Shah Vipul",
"author_id": 12535554,
"author_profile": "https://Stackoverflow.com/users/12535554",
"pm_score": -1,
"selected": false,
"text": "def countInversions(arr):\n n = len(arr)\n if n == 1:\n return 0\n n1 = n // 2\n n2 = n - n1\n arr1 = arr[:n1]\n arr2 = arr[n1:]\n # print(n1,'||',n1,'||',arr1,'||',arr2)\n ans = countInversions(arr1) + countInversions(arr2)\n print(ans)\n i1 = 0\n i2 = 0\n for i in range(n):\n # print(i1,n1,i2,n2)\n if i1 < n1 and (i2 >= n2 or arr1[i1] <= arr2[i2]):\n arr[i] = arr1[i1]\n ans += i2\n i1 += 1\n elif i2 < n2:\n arr[i] = arr2[i2]\n i2 += 1\n return ans\n def countInversions(arr):\n count = 0\n for i in range(len(arr)):\n for j in range(i, len(arr)):\n # print(arr[i:len(arr)])\n if arr[i] > arr[j]:\n print(arr[i], arr[j])\n count += 1\n print(count)\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27884/"
] |
337,688 | <p>Does python have the ability to create dynamic keywords?</p>
<p>For example:</p>
<pre><code>qset.filter(min_price__usd__range=(min_price, max_price))
</code></pre>
<p>I want to be able to change the <strong>usd</strong> part based on a selected currency.</p>
| [
{
"answer_id": 337714,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 7,
"selected": true,
"text": "**kwargs def f(**kwargs):\n print kwargs.keys()\n\n\nf(a=2, b=\"b\") # -> ['a', 'b']\nf(**{'d'+'e': 1}) # -> ['de']\n"
},
{
"answer_id": 337727,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "def filter(self, **kwargs):\n for key,value in kwargs:\n if key.startswith('min_price__') and key.endswith('__range'):\n currency = key.replace('min_price__', '').replace('__range','')\n rate = self.current_conversion_rates[currency]\n self.setCurrencyRange(value[0]*rate, value[1]*rate)\n"
},
{
"answer_id": 337733,
"author": "Benjamin Pollack",
"author_id": 2354,
"author_profile": "https://Stackoverflow.com/users/2354",
"pm_score": 4,
"selected": false,
"text": "def filter(**kwargs):\n kwargs ** someFunction(**theDictionary)\n"
},
{
"answer_id": 337735,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 5,
"selected": false,
"text": "qset.filter(**{\n 'min_price_' + selected_currency + '_range' :\n (min_price, max_price)})\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42876/"
] |
337,691 | <p>I'm attempting to find the best methodology for finding a specific pattern and then
replace the ending portion of the pattern. Here is a quick example (in C#):</p>
<p>//Find any year value starting with a bracket or underscore</p>
<pre><code>string patternToFind = "[[_]2007";
Regex yearFind = new Regex(patternToFind);
</code></pre>
<p>//I want to change any of these values to x2008 where x is the bracket or underscore originally in the text. I was trying to use Regex.Replace(), but cannot figure out if it can be applied. </p>
<p>If all else fails, I can find Matches using the MatchCollection and then switch out the 2007 value with 2008; however, I'm hoping for something more elegant</p>
<pre><code>MatchCollections matches = yearFind.Matches(" 2007 [2007 _2007");
foreach (Match match in matches){
//use match to find and replace value
}
</code></pre>
| [
{
"answer_id": 337709,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 3,
"selected": false,
"text": "\\[|_ /^(\\[|_)2007/ string s = Regex.Replace(source, @\"^(\\[|_)2007\", @\"$12008\");\n"
},
{
"answer_id": 337736,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 1,
"selected": false,
"text": "aaa _2007\nbbb , 2007\nccc [2007]\n :1,$ s/\\([_[ ]\\)\\(2007\\)/\\12008/g\n aaa _2008\nbbb , 2008\nccc [2008]\n"
},
{
"answer_id": 337747,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 2,
"selected": false,
"text": "Regex yearFind = new Regex(\"([[_])2007\");\nyearFine.Replace(\"_2007\", @\"$12008\"); // => \"_2008\"\nyearFine.Replace(\"[2007\", @\"$12008\"); // => \"[2008\"\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
337,694 | <p>On a page I want to dynamically list years and all the months in each year so an archive for each month can be viewed. I want to show the current year first but the current year may not be over yet so I only want to show the months that have passed, and the current month. Then I want all years and all months in the past since this year (i.e. 2008).</p>
<p>The PHP code I have created that does the job is below. Is there a more efficient way of achieving this? I am running PHP 5.2.</p>
<pre><code>$current_year = date('Y');
$months = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
// Loop through all the months and create an array up to and including the current month
foreach ($months as $month)
{
if ($month <= date('m'))
{
switch ($month)
{
case 1:
$years[$current_year][] = 'January';
break;
case 2:
$years[$current_year][] = 'February';
break;
case 3:
$years[$current_year][] = 'March';
break;
case 4:
$years[$current_year][] = 'April';
break;
case 5:
$years[$current_year][] = 'May';
break;
case 6:
$years[$current_year][] = 'June';
break;
case 7:
$years[$current_year][] = 'July';
break;
case 8:
$years[$current_year][] = 'August';
break;
case 9:
$years[$current_year][] = 'September';
break;
case 10:
$years[$current_year][] = 'October';
break;
case 11:
$years[$current_year][] = 'November';
break;
case 12:
$years[$current_year][] = 'December';
break;
}
}
}
// Previous years
$years_to_create = $current_year - 2008;
if (!empty($years_to_create))
{
for ($i = 1; $i <= $years_to_create; $i++)
{
$years[$current_year - $i] = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
}
}
</code></pre>
| [
{
"answer_id": 337712,
"author": "Filip Ekberg",
"author_id": 39106,
"author_profile": "https://Stackoverflow.com/users/39106",
"pm_score": 0,
"selected": false,
"text": " -> Get current Year\n\n -> Loop the current year untill the current month is reached\n\n -> Print Month\n"
},
{
"answer_id": 337720,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 2,
"selected": false,
"text": "$years = 5;\n\nfor ($i = 0; $i < (12* $years); $i++)\n{\n if (date('Y',strtotime(\"-\".$i.\" month\")) > (date('Y') - $years) )\n {\n echo date('F Y',strtotime(\"-\".$i.\" month\")) . '<br />'; \n }\n}\n $years = 5;\n$myarray = array();\n\nfor ($i = 0; $i < (12* $years); $i++)\n{\n if (date('Y',strtotime(\"-\".$i.\" month\")) > (date('Y') - $years) )\n {\n $year_key = date('Y') - date('Y',strtotime(\"-\".$i.\" month\")); \n $myarray[$year_key][] = date('F',strtotime(\"-\".$i.\" month\"));\n }\n}\n\n//Write it out to the screen\nforeach ($myarray as $yearkey=>$eachyear)\n{\n foreach ($eachyear as $eachmonth)\n { \n echo (date('Y')-$yearkey) . ' ' . $eachmonth . '<br>';\n }\n}\n"
},
{
"answer_id": 337745,
"author": "OIS",
"author_id": 36175,
"author_profile": "https://Stackoverflow.com/users/36175",
"pm_score": 1,
"selected": false,
"text": "function getMonthsFromYear($start = 2008, $end = null, array $months = null) {\n static $sMonths = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');\n $thisYear = intval(date('Y'));\n if (!is_array($months) || (count($months) < 12))\n $months = $sMonths;\n if (!is_int($end))\n $end = $thisYear;\n if ($end > $thisYear)\n return array_fill($start, $end - $start + 1, $months);\n if ($start < $end)\n $monthsInDuration = array_fill($start, $end - $start, $months);\n $monthsInDuration[$end] = array_slice($months, 0, (int) date('m'));\n return $monthsInDuration;\n}\nprint_r(getMonthsFromYear());\nprint_r(getMonthsFromYear(2006));\nprint_r(getMonthsFromYear(2008, 2010));\n"
},
{
"answer_id": 350980,
"author": "Jack",
"author_id": 24998,
"author_profile": "https://Stackoverflow.com/users/24998",
"pm_score": 3,
"selected": true,
"text": "$current_year = date('Y');\n$months = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);\n$month_names = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');\n\n// Loop through all the months and create an array up to and including the current month\n\nfor ($month=1;$month<=date('m');$month++)\n{\n$years[$current_year][] = $month_names[$month-1];\n}\n\n// Previous years\n$years_to_create = $current_year - 2008;\n\nif (!empty($years_to_create))\n{\n for ($i = 1; $i <= $years_to_create; $i++)\n {\n $years[$current_year - $i] = $month_names;\n }\n}\n"
},
{
"answer_id": 364696,
"author": "Adam",
"author_id": 30084,
"author_profile": "https://Stackoverflow.com/users/30084",
"pm_score": 1,
"selected": false,
"text": "$current_year = date('Y');\n$month_names = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');\n$years[$current_year] = array_slice($month_names, 0, date('m'));\n\nfor ($i = 2008; $i < $current_year; $i++) {\n $years[$i] = $month_names;\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
] |
337,702 | <p>I wonder how can I write a <strong><em>catch'em all</em></strong> exception handler in the application level which will give the user the option to resume the application flow?</p>
| [
{
"answer_id": 337761,
"author": "Vincent Van Den Berghe",
"author_id": 39259,
"author_profile": "https://Stackoverflow.com/users/39259",
"pm_score": 5,
"selected": false,
"text": "Application.ThreadException"
},
{
"answer_id": 337847,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": -1,
"selected": false,
"text": "try\n{\n MyMethodThatMightThrow();\n}\ncatch(Exception ex)\n{\n bool rethrow = ExceptionPolicy.HandleException(ex, \"SomePolicy\");\n if (rethrow) throw;\n}\n"
},
{
"answer_id": 337884,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": -1,
"selected": false,
"text": "On Error Resume Next"
},
{
"answer_id": 338030,
"author": "Sam Meldrum",
"author_id": 16005,
"author_profile": "https://Stackoverflow.com/users/16005",
"pm_score": 5,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication2 {\n static class Program {\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main() {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Form1 form1 = new Form1();\n Application.ThreadException += new ThreadExceptionEventHandler(form1.UnhandledThreadExceptionHandler);\n Application.Run(form1);\n }\n }\n}\n using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication2 {\n public partial class Form1 : Form {\n public Form1() {\n InitializeComponent();\n }\n\n public void UnhandledThreadExceptionHandler(object sender, ThreadExceptionEventArgs e) {\n this.HandleUnhandledException(e.Exception);\n }\n\n public void HandleUnhandledException(Exception e) {\n // do what you want here.\n if (MessageBox.Show(\"An unexpected error has occurred. Continue?\",\n \"My application\", MessageBoxButtons.YesNo, MessageBoxIcon.Stop,\n MessageBoxDefaultButton.Button2) == DialogResult.No) {\n Application.Exit();\n }\n }\n\n private void button1_Click(object sender, EventArgs e) {\n throw new ApplicationException(\"Exception\");\n }\n\n }\n}\n"
},
{
"answer_id": 10597725,
"author": "Ravi Patel",
"author_id": 1273550,
"author_profile": "https://Stackoverflow.com/users/1273550",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Windows.Forms;\nusing System.Net;\nusing System.Net.Mail;\nusing System.Threading; \n\nnamespace ExceptionHandlerTest\n{\n static class Program\n {\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main()\n {\n Application.ThreadException +=\n new ThreadExceptionEventHandler(Application_ThreadException);\n\n // Your designer generated commands.\n }\n\n static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) \n {\n\n var fromAddress = new MailAddress(\"your Gmail address\", \"Your name\");\n var toAddress = new MailAddress(\"email address where you want to receive reports\", \"Your name\");\n const string fromPassword = \"your password\";\n const string subject = \"exception report\";\n Exception exception = e.Exception;\n string body = exception.Message + \"\\n\" + exception.Data + \"\\n\" + exception.StackTrace + \"\\n\" + exception.Source;\n\n var smtp = new SmtpClient\n {\n Host = \"smtp.gmail.com\",\n Port = 587,\n EnableSsl = true,\n DeliveryMethod = SmtpDeliveryMethod.Network,\n UseDefaultCredentials = false,\n Credentials = new NetworkCredential(fromAddress.Address, fromPassword)\n };\n using (var message = new MailMessage(fromAddress, toAddress)\n {\n Subject = subject,\n Body = body\n })\n {\n //You can also use SendAsync method instead of Send so your application begin invoking instead of waiting for send mail to complete. SendAsync(MailMessage, Object) :- Sends the specified e-mail message to an SMTP server for delivery. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes. \n smtp.Send(message);\n }\n }\n }\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
337,704 | <p>How do I parameterize a query containing an <code>IN</code> clause with a variable number of arguments, like this one?</p>
<pre><code>SELECT * FROM Tags
WHERE Name IN ('ruby','rails','scruffy','rubyonrails')
ORDER BY Count DESC
</code></pre>
<p>In this query, the number of arguments could be anywhere from 1 to 5.</p>
<p>I would prefer not to use a dedicated stored procedure for this (or XML), but if there is some elegant way specific to <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2008" rel="noreferrer">SQL Server 2008</a>, I am open to that.</p>
| [
{
"answer_id": 337752,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 7,
"selected": false,
"text": "DECLARE @tags\n\nSET @tags = ‘ruby|rails|scruffy|rubyonrails’\n\nselect * from Tags \nwhere Name in (SELECT item from fnSplit(@tags, ‘|’))\norder by Count desc\n CREATE FUNCTION [dbo].[fnSplit](\n @sInputList VARCHAR(8000) -- List of delimited items\n , @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items\n) RETURNS @List TABLE (item VARCHAR(8000))\n\nBEGIN\nDECLARE @sItem VARCHAR(8000)\nWHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0\n BEGIN\n SELECT\n @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),\n @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))\n\n IF LEN(@sItem) > 0\n INSERT INTO @List SELECT @sItem\n END\n\nIF LEN(@sInputList) > 0\n INSERT INTO @List SELECT @sInputList -- Put the last item in\nRETURN\nEND\n"
},
{
"answer_id": 337765,
"author": "eulerfx",
"author_id": 13855,
"author_profile": "https://Stackoverflow.com/users/13855",
"pm_score": 4,
"selected": false,
"text": "where exists sp_xml_preparedocument"
},
{
"answer_id": 337774,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 4,
"selected": false,
"text": "SELECT ...\n ...\n WHERE tag IN( @tag1, ISNULL( @tag2, @tag1 ), ISNULL( @tag3, @tag1 ), etc. )\n"
},
{
"answer_id": 337792,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 10,
"selected": false,
"text": "string[] tags = new string[] { \"ruby\", \"rails\", \"scruffy\", \"rubyonrails\" };\nstring cmdText = \"SELECT * FROM Tags WHERE Name IN ({0})\";\n\nstring[] paramNames = tags.Select(\n (s, i) => \"@tag\" + i.ToString()\n).ToArray();\n\nstring inClause = string.Join(\", \", paramNames);\nusing (SqlCommand cmd = new SqlCommand(string.Format(cmdText, inClause))) {\n for(int i = 0; i < paramNames.Length; i++) {\n cmd.Parameters.AddWithValue(paramNames[i], tags[i]);\n }\n}\n cmd.CommandText = \"SELECT * FROM Tags WHERE Name IN (@tag0, @tag1, @tag2, @tag3)\"\ncmd.Parameters[\"@tag0\"] = \"ruby\"\ncmd.Parameters[\"@tag1\"] = \"rails\"\ncmd.Parameters[\"@tag2\"] = \"scruffy\"\ncmd.Parameters[\"@tag3\"] = \"rubyonrails\"\n"
},
{
"answer_id": 337817,
"author": "Joel Spolsky",
"author_id": 4,
"author_profile": "https://Stackoverflow.com/users/4",
"pm_score": 9,
"selected": true,
"text": "SELECT * FROM Tags\nWHERE '|ruby|rails|scruffy|rubyonrails|'\nLIKE '%|' + Name + '|%'\n string[] tags = new string[] { \"ruby\", \"rails\", \"scruffy\", \"rubyonrails\" };\nconst string cmdText = \"select * from tags where '|' + @tags + '|' like '%|' + Name + '|%'\";\n\nusing (SqlCommand cmd = new SqlCommand(cmdText)) {\n cmd.Parameters.AddWithValue(\"@tags\", string.Join(\"|\", tags);\n}\n LIKE \"%...%\" |"
},
{
"answer_id": 337864,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 8,
"selected": false,
"text": "CREATE TYPE dbo.TagNamesTableType AS TABLE ( Name nvarchar(50) )\n string[] tags = new string[] { \"ruby\", \"rails\", \"scruffy\", \"rubyonrails\" };\ncmd.CommandText = \"SELECT Tags.* FROM Tags JOIN @tagNames as P ON Tags.Name = P.Name\";\n\n// value must be IEnumerable<SqlDataRecord>\ncmd.Parameters.AddWithValue(\"@tagNames\", tags.AsSqlDataRecord(\"Name\")).SqlDbType = SqlDbType.Structured;\ncmd.Parameters[\"@tagNames\"].TypeName = \"dbo.TagNamesTableType\";\n\n// Extension method for converting IEnumerable<string> to IEnumerable<SqlDataRecord>\npublic static IEnumerable<SqlDataRecord> AsSqlDataRecord(this IEnumerable<string> values, string columnName) {\n if (values == null || !values.Any()) return null; // Annoying, but SqlClient wants null instead of 0 rows\n var firstRecord = values.First();\n var metadata= new SqlMetaData(columnName, SqlDbType.NVarChar, 50); //50 as per SQL Type\n return values.Select(v => \n {\n var r = new SqlDataRecord(metadata);\n r.SetValues(v);\n return r;\n });\n}\n var metadata = SqlMetaData.InferFromValue(firstRecord, columnName); var metadata= new SqlMetaData(columnName, SqlDbType.NVarChar, maxLen); -1"
},
{
"answer_id": 337907,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 5,
"selected": false,
"text": "INSERT IN JOIN"
},
{
"answer_id": 337931,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 5,
"selected": false,
"text": "ALTER FUNCTION [dbo].[Fn_sqllist_to_table](@list AS VARCHAR(8000),\n @delim AS VARCHAR(10))\nRETURNS @listTable TABLE(\n Position INT,\n Value VARCHAR(8000))\nAS\n BEGIN\n DECLARE @myPos INT\n\n SET @myPos = 1\n\n WHILE Charindex(@delim, @list) > 0\n BEGIN\n INSERT INTO @listTable\n (Position,Value)\n VALUES (@myPos,LEFT(@list, Charindex(@delim, @list) - 1))\n\n SET @myPos = @myPos + 1\n\n IF Charindex(@delim, @list) = Len(@list)\n INSERT INTO @listTable\n (Position,Value)\n VALUES (@myPos,'')\n\n SET @list = RIGHT(@list, Len(@list) - Charindex(@delim, @list))\n END\n\n IF Len(@list) > 0\n INSERT INTO @listTable\n (Position,Value)\n VALUES (@myPos,@list)\n\n RETURN\n END \n @Name varchar(8000) = null // parameter for search values \n\nselect * from Tags \nwhere Name in (SELECT value From fn_sqllist_to_table(@Name,',')))\norder by Count desc\n"
},
{
"answer_id": 357753,
"author": "rip747",
"author_id": 31278,
"author_profile": "https://Stackoverflow.com/users/31278",
"pm_score": 3,
"selected": false,
"text": "<cfset myvalues = \"ruby|rails|scruffy|rubyonrails\">\n <cfquery name=\"q\">\n select * from sometable where values in <cfqueryparam value=\"#myvalues#\" list=\"true\">\n </cfquery>\n"
},
{
"answer_id": 380185,
"author": "Peter Meyer",
"author_id": 1875,
"author_profile": "https://Stackoverflow.com/users/1875",
"pm_score": 6,
"selected": false,
"text": "var inValues = new [] { \"ruby\",\"rails\",\"scruffy\",\"rubyonrails\" };\n\nvar results = from tag in Tags\n where inValues.Contains(tag.Name)\n select tag;\n Contains IN"
},
{
"answer_id": 512749,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": " with qry(n, names) as\n (select len(list.names) - len(replace(list.names, ',', '')) - 1 as n,\n substring(list.names, 2, len(list.names)) as names\n from (select ',Doc,Grumpy,Happy,Sneezy,Bashful,Sleepy,Dopey,' names) as list\n union all\n select (n - 1) as n,\n substring(names, 1 + charindex(',', names), len(names)) as names\n from qry\n where n > 1)\n select n, substring(names, 1, charindex(',', names) - 1) dwarf\n from qry;\n select n, substr(name, 1, instr(name, ',') - 1) dwarf\n from (select n,\n substr(val, 1 + instr(val, ',', 1, n)) name\n from (select rownum as n,\n list.val\n from (select ',Doc,Grumpy,Happy,Sneezy,Bashful,Sleepy,Dopey,' val\n from dual) list\n connect by level < length(list.val) -\n length(replace(list.val, ',', ''))));\n select pivot.n,\n substring_index(substring_index(list.val, ',', 1 + pivot.n), ',', -1) from (select 1 as n\n union all\n select 2 as n\n union all\n select 3 as n\n union all\n select 4 as n\n union all\n select 5 as n\n union all\n select 6 as n\n union all\n select 7 as n\n union all\n select 8 as n\n union all\n select 9 as n\n union all\n select 10 as n) pivot, (select ',Doc,Grumpy,Happy,Sneezy,Bashful,Sleepy,Dopey,' val) as list where pivot.n < length(list.val) -\n length(replace(list.val, ',', ''));\n"
},
{
"answer_id": 928523,
"author": "spencer7593",
"author_id": 107744,
"author_profile": "https://Stackoverflow.com/users/107744",
"pm_score": 8,
"selected": false,
"text": "Name % 'pe%ter' select ...\n where '|peanut|butter|' like '%|' + 'pe%ter' + '|%'\n select ...\n where '|butter|peanut|' like '%|' + 'pe%ter' + '|%'\n pe%ter LIKE % select ...\n where '|peanut|butter|'\n like '%|' + 'pe\\%ter' + '|%' escape '\\'\n REPLACE % select ...\n where '|pe%ter|'\n like '%|' + REPLACE( 'pe%ter' ,'%','\\%') + '|%' escape '\\'\n select ...\n where '|pe%t!r|'\n like '%|' + REPLACE(REPLACE( 'pe%t!r' ,'!','!!'),'%','!%') + '|%' escape '!'\n REPLACE select ...\n where '|p_%t!r|'\n like '%|' + REPLACE(REPLACE(REPLACE( 'p_%t!r' ,'$','$$'),'%','$%'),'_','$_') + '|%' escape '$'\n [] - ^ % _"
},
{
"answer_id": 2254502,
"author": "ArtOfCoding",
"author_id": 272067,
"author_profile": "https://Stackoverflow.com/users/272067",
"pm_score": 3,
"selected": false,
"text": "SELECT * \nFROM Tags \nWHERE PATINDEX('%<' + Name + '>%','<jo>,<john>,<scruffy>,<rubyonrails>') > 0\n"
},
{
"answer_id": 3310117,
"author": "Paulo Henrique",
"author_id": 302751,
"author_profile": "https://Stackoverflow.com/users/302751",
"pm_score": 4,
"selected": false,
"text": "CREATE FUNCTION dbo.fnParseArray (@Array VARCHAR(1000),@separator CHAR(1))\nRETURNS @T Table (col1 varchar(50))\nAS \nBEGIN\n --DECLARE @T Table (col1 varchar(50)) \n -- @Array is the array we wish to parse\n -- @Separator is the separator charactor such as a comma\n DECLARE @separator_position INT -- This is used to locate each separator character\n DECLARE @array_value VARCHAR(1000) -- this holds each array value as it is returned\n -- For my loop to work I need an extra separator at the end. I always look to the\n -- left of the separator character for each array value\n\n SET @array = @array + @separator\n\n -- Loop through the string searching for separtor characters\n WHILE PATINDEX('%' + @separator + '%', @array) <> 0 \n BEGIN\n -- patindex matches the a pattern against a string\n SELECT @separator_position = PATINDEX('%' + @separator + '%',@array)\n SELECT @array_value = LEFT(@array, @separator_position - 1)\n -- This is where you process the values passed.\n INSERT into @T VALUES (@array_value) \n -- Replace this select statement with your processing\n -- @array_value holds the value of this element of the array\n -- This replaces what we just processed with and empty string\n SELECT @array = STUFF(@array, 1, @separator_position, '')\n END\n RETURN \nEND\n SELECT * FROM dbo.fnParseArray('a,b,c,d,e,f', ',')\n"
},
{
"answer_id": 5825528,
"author": "Jason Henriksen",
"author_id": 534156,
"author_profile": "https://Stackoverflow.com/users/534156",
"pm_score": 2,
"selected": false,
"text": "and ( {1}==0 or b.CompanyId in ({2},{3},{4},{5},{6}) )\n int origCount = idList.Count;\n if (origCount > 5) {\n throw new Exception(\"You may only specify up to five originators to filter on.\");\n }\n while (idList.Count < 5) { idList.Add(-1); } // -1 is an impossible value\n return ExecuteQuery<PublishDate>(getValuesInListSQL, \n origCount, \n idList[0], idList[1], idList[2], idList[3], idList[4]);\n"
},
{
"answer_id": 5993875,
"author": "Runonthespot",
"author_id": 305970,
"author_profile": "https://Stackoverflow.com/users/305970",
"pm_score": 3,
"selected": false,
"text": "DECLARE @InputString varchar(8000) = 'ruby,rails,scruffy,rubyonrails'\n\nSELECT @InputString = @InputString + ','\n\n;WITH RecursiveCSV(x,y) \nAS \n(\n SELECT \n x = SUBSTRING(@InputString,0,CHARINDEX(',',@InputString,0)),\n y = SUBSTRING(@InputString,CHARINDEX(',',@InputString,0)+1,LEN(@InputString))\n UNION ALL\n SELECT \n x = SUBSTRING(y,0,CHARINDEX(',',y,0)),\n y = SUBSTRING(y,CHARINDEX(',',y,0)+1,LEN(y))\n FROM \n RecursiveCSV \n WHERE\n SUBSTRING(y,CHARINDEX(',',y,0)+1,LEN(y)) <> '' OR \n SUBSTRING(y,0,CHARINDEX(',',y,0)) <> ''\n)\nSELECT\n * \nFROM \n Tags\nWHERE \n Name IN (select x FROM RecursiveCSV)\nOPTION (MAXRECURSION 32767);\n"
},
{
"answer_id": 6356730,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": false,
"text": "string[] names = new string[] {\"ruby\",\"rails\",\"scruffy\",\"rubyonrails\"};\nvar tags = dataContext.Query<Tags>(@\"\nselect * from Tags \nwhere Name in @names\norder by Count desc\", new {names});\n string[] names = new string[] {\"ruby\",\"rails\",\"scruffy\",\"rubyonrails\"};\nvar tags = from tag in dataContext.Tags\n where names.Contains(tag.Name)\n orderby tag.Count descending\n select tag;\n"
},
{
"answer_id": 7880246,
"author": "MindLoggedOut",
"author_id": 999456,
"author_profile": "https://Stackoverflow.com/users/999456",
"pm_score": 3,
"selected": false,
"text": " declare @x xml\n set @x='<items>\n <item myvalue=\"29790\" />\n <item myvalue=\"31250\" />\n </items>\n ';\n With CTE AS (\n SELECT \n x.item.value('@myvalue[1]', 'decimal') AS myvalue\n FROM @x.nodes('//items/item') AS x(item) )\n\n select * from YourTable where tableColumnName in (select myvalue from cte)\n"
},
{
"answer_id": 10808268,
"author": "Rockfish",
"author_id": 1424866,
"author_profile": "https://Stackoverflow.com/users/1424866",
"pm_score": 3,
"selected": false,
"text": "-- Create a user defined type for the list.\nCREATE TYPE [dbo].[StringList] AS TABLE(\n [StringValue] [nvarchar](max) NOT NULL\n)\n\n-- Create a sample list using the list table type.\nDECLARE @list [dbo].[StringList]; \nINSERT INTO @list VALUES ('one'), ('two'), ('three'), ('four')\n\n-- Build a string in which we recreate the list so we can pass it to exec\n-- This can be done in any language since we're just building a string.\nDECLARE @str nvarchar(max);\nSET @str = 'DECLARE @list [dbo].[StringList]; INSERT INTO @list VALUES '\n\n-- Add all the values we want to the string. This would be a loop in C++.\nSELECT @str = @str + '(''' + StringValue + '''),' FROM @list\n\n-- Remove the trailing comma so the query is valid sql.\nSET @str = substring(@str, 1, len(@str)-1)\n\n-- Add a select to test the string.\nSET @str = @str + '; SELECT * FROM @list;'\n\n-- Execute the string and see we've pass the table correctly.\nEXEC(@str)\n"
},
{
"answer_id": 11663054,
"author": "mangeshkt",
"author_id": 353999,
"author_profile": "https://Stackoverflow.com/users/353999",
"pm_score": 3,
"selected": false,
"text": " create stored procedure GetSearchMachingTagNames \n @PipeDelimitedTagNames varchar(max), \n @delimiter char(1) \n as \n begin\n select * from Tags \n where Name in (select data from [dbo].[Split](@PipeDelimitedTagNames,@delimiter) \n end\n"
},
{
"answer_id": 11973246,
"author": "Jodrell",
"author_id": 659190,
"author_profile": "https://Stackoverflow.com/users/659190",
"pm_score": 4,
"selected": false,
"text": "[SqlFunction(\n DataAccessKind.None,\n IsDeterministic = true,\n SystemDataAccess = SystemDataAccessKind.None,\n IsPrecise = true,\n FillRowMethodName = \"SplitFillRow\",\n TableDefinintion = \"s NVARCHAR(MAX)\"]\npublic static IEnumerable Split(SqlChars seperator, SqlString s)\n{\n if (s.IsNull)\n return new string[0];\n\n return s.ToString().Split(seperator.Buffer);\n}\n\npublic static void SplitFillRow(object row, out SqlString s)\n{\n s = new SqlString(row.ToString());\n}\n declare @desiredTags nvarchar(MAX);\nset @desiredTags = 'ruby,rails,scruffy,rubyonrails';\n\nselect * from Tags\nwhere Name in [dbo].[Split] (',', @desiredTags)\norder by Count desc\n"
},
{
"answer_id": 13534053,
"author": "Gowdhaman008",
"author_id": 1176133,
"author_profile": "https://Stackoverflow.com/users/1176133",
"pm_score": 3,
"selected": false,
"text": "CREATE TABLE Tags\n ([ID] int, [Name] varchar(20))\n;\n\nINSERT INTO Tags\n ([ID], [Name])\nVALUES\n (1, 'ruby'),\n (2, 'rails'),\n (3, 'scruffy'),\n (4, 'rubyonrails')\n;\n DECLARE @Param nvarchar(max)\n\nSET @Param = 'ruby,rails,scruffy,rubyonrails'\n\nSELECT * FROM Tags\nWHERE CharIndex(Name,@Param)>0\n Create table SelectedTags\n(Name nvarchar(20));\n\nINSERT INTO SelectedTags values ('ruby'),('rails')\n DECLARE @list nvarchar(max)\nSELECT @list=coalesce(@list+',','')+st.Name FROM SelectedTags st\n\nSELECT * FROM Tags\nWHERE CharIndex(Name,@Param)>0\n"
},
{
"answer_id": 15846417,
"author": "Metaphor",
"author_id": 2123899,
"author_profile": "https://Stackoverflow.com/users/2123899",
"pm_score": 3,
"selected": false,
"text": "CREATE PROCEDURE [dbo].[sp_myproc]\n @UnitList varchar(MAX) = '1,2,3'\nAS\nselect column from table\nwhere ph.UnitID in (select * from CsvToInt(@UnitList))\n CREATE Function [dbo].[CsvToInt] ( @Array varchar(MAX))\nreturns @IntTable table\n(IntValue int)\nAS\nbegin\n declare @separator char(1)\n set @separator = ','\n declare @separator_position int\n declare @array_value varchar(MAX)\n\n set @array = @array + ','\n\n while patindex('%,%' , @array) <> 0\n begin\n\n select @separator_position = patindex('%,%' , @array)\n select @array_value = left(@array, @separator_position - 1)\n\n Insert @IntTable\n Values (Cast(@array_value as int))\n select @array = stuff(@array, 1, @separator_position, '')\n end\n return\nend\n"
},
{
"answer_id": 16907149,
"author": "Darek",
"author_id": 564092,
"author_profile": "https://Stackoverflow.com/users/564092",
"pm_score": 3,
"selected": false,
"text": " private static DataSet GetDataSet(SqlConnectionStringBuilder scsb, string strSql, params object[] pars)\n {\n var ds = new DataSet();\n using (var sqlConn = new SqlConnection(scsb.ConnectionString))\n {\n var sqlParameters = new List<SqlParameter>();\n var replacementStrings = new Dictionary<string, string>();\n if (pars != null)\n {\n for (int i = 0; i < pars.Length; i++)\n {\n if (pars[i] is IEnumerable<object>)\n {\n List<object> enumerable = (pars[i] as IEnumerable<object>).ToList();\n replacementStrings.Add(\"@\" + i, String.Join(\",\", enumerable.Select((value, pos) => String.Format(\"@_{0}_{1}\", i, pos))));\n sqlParameters.AddRange(enumerable.Select((value, pos) => new SqlParameter(String.Format(\"@_{0}_{1}\", i, pos), value ?? DBNull.Value)).ToArray());\n }\n else\n {\n sqlParameters.Add(new SqlParameter(String.Format(\"@{0}\", i), pars[i] ?? DBNull.Value));\n }\n }\n }\n strSql = replacementStrings.Aggregate(strSql, (current, replacementString) => current.Replace(replacementString.Key, replacementString.Value));\n using (var sqlCommand = new SqlCommand(strSql, sqlConn))\n {\n if (pars != null)\n {\n sqlCommand.Parameters.AddRange(sqlParameters.ToArray());\n }\n else\n {\n //Fail-safe, just in case a user intends to pass a single null parameter\n sqlCommand.Parameters.Add(new SqlParameter(\"@0\", DBNull.Value));\n }\n using (var sqlDataAdapter = new SqlDataAdapter(sqlCommand))\n {\n sqlDataAdapter.Fill(ds);\n }\n }\n }\n return ds;\n }\n"
},
{
"answer_id": 20871852,
"author": "Sandip Bantawa",
"author_id": 1903674,
"author_profile": "https://Stackoverflow.com/users/1903674",
"pm_score": 2,
"selected": false,
"text": "DECLARE @invalue VARCHAR(100)\nSELECT @invalue = '''Bishnu'',''Gautam'''\n\nDECLARE @dynamicSQL VARCHAR(MAX)\nSELECT @dynamicSQL = 'SELECT * FROM #temp WHERE [name] IN (' + @invalue + ')'\nEXEC (@dynamicSQL)\n"
},
{
"answer_id": 21069780,
"author": "Erik Hart",
"author_id": 832306,
"author_profile": "https://Stackoverflow.com/users/832306",
"pm_score": 2,
"selected": false,
"text": "public static T[][] SplitSqlValues<T>(IEnumerable<T> values)\n{\n var sizes = new int[] { 1000, 500, 250, 125, 63, 32, 16, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };\n int processed = 0;\n int currSizeIdx = sizes.Length - 1; /* start with last (smallest) */\n var splitLists = new List<T[]>();\n\n var valuesDistSort = values.Distinct().ToList(); /* remove redundant */\n valuesDistSort.Sort();\n int totalValues = valuesDistSort.Count;\n\n while (totalValues > sizes[currSizeIdx] && currSizeIdx > 0)\n currSizeIdx--; /* bigger size, by array pos. */\n\n while (processed < totalValues)\n {\n while (totalValues - processed < sizes[currSizeIdx]) \n currSizeIdx++; /* smaller size, by array pos. */\n var partList = new T[sizes[currSizeIdx]];\n valuesDistSort.CopyTo(processed, partList, 0, sizes[currSizeIdx]);\n splitLists.Add(partList);\n processed += sizes[currSizeIdx];\n }\n return splitLists.ToArray();\n}\n foreach(int[] partList in splitLists)\n{\n /* here: question mark for param variable, use named/numbered params if required */\n string sql = \"select * from Items where Id in(\"\n + string.Join(\",\", partList.Select(p => \"?\")) \n + \")\"; /* comma separated ?, one for each partList entry */\n\n /* create command with sql string, set parameters, execute, merge results */\n}\n SELECT * FROM MyTable WHERE Id IN (@p1, @p2, @p3, ... , @p[batch-size])\n SELECT * FROM MyTable WHERE Id=@id\n"
},
{
"answer_id": 29017255,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 3,
"selected": false,
"text": "List<SqlParameter> parameters = tags.Select((s, i) => new SqlParameter(\"@tag\" + i.ToString(), SqlDbType.NVarChar(50)) { Value = s}).ToList();\n\nvar whereCondition = string.Format(\"tags in ({0})\", String.Join(\",\",parameters.Select(s => s.ParameterName)));\n var parameters = new List<SqlParameter>();\nvar paramNames = new List<string>();\nfor (var i = 0; i < tags.Length; i++) \n{\n var paramName = \"@tag\" + i;\n\n //Include size and set value explicitly (not AddWithValue)\n //Because SQL Server may use an implicit conversion if it doesn't know\n //the actual size.\n var p = new SqlParameter(paramName, SqlDbType.NVarChar(50) { Value = tags[i]; } \n paramNames.Add(paramName);\n parameters.Add(p);\n}\n\nvar inClause = string.Join(\",\", paramNames);\n"
},
{
"answer_id": 29116544,
"author": "ASP.Net Developer",
"author_id": 2839109,
"author_profile": "https://Stackoverflow.com/users/2839109",
"pm_score": 2,
"selected": false,
"text": " create FUNCTION [dbo].[ConvertStringToList]\n\n\n (@str VARCHAR (MAX), @delimeter CHAR (1))\n RETURNS \n @result TABLE (\n [ID] INT NULL)\n AS\n BEG\n\nIN\n\n DECLARE @x XML \n SET @x = '<t>' + REPLACE(@str, @delimeter, '</t><t>') + '</t>'\n\n INSERT INTO @result\n SELECT DISTINCT x.i.value('.', 'int') AS token\n FROM @x.nodes('//t') x(i)\n ORDER BY 1\n\nRETURN\nEND\n select * from table where id in ([dbo].[ConvertStringToList(YOUR comma separated string ,',')])\n"
},
{
"answer_id": 30784838,
"author": "Eli Ekstein",
"author_id": 2108149,
"author_profile": "https://Stackoverflow.com/users/2108149",
"pm_score": 3,
"selected": false,
"text": "CREATE FUNCTION [dbo].[Split] (@sep char(1), @s varchar(8000))\nRETURNS table\nAS\nRETURN (\n WITH Pieces(pn, start, stop) AS (\n SELECT 1, 1, CHARINDEX(@sep, @s)\n UNION ALL\n SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)\n FROM Pieces\n WHERE stop > 0\n )\n SELECT \n SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s\n FROM Pieces\n )\n select * from Tags \nwhere Name in (select s from dbo.split(';','ruby;rails;scruffy;rubyonrails'))\norder by Count desc\n"
},
{
"answer_id": 33584131,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 3,
"selected": false,
"text": "OPENJSON CREATE TABLE dbo.Tags\n (\n Name VARCHAR(50),\n Count INT\n )\n\nINSERT INTO dbo.Tags\nVALUES ('VB',982), ('ruby',1306), ('rails',1478), ('scruffy',1), ('C#',1784)\n\nGO\n\nCREATE PROC dbo.SomeProc\n@Tags VARCHAR(MAX)\nAS\nSELECT T.*\nFROM dbo.Tags T\nWHERE T.Name IN (SELECT J.Value COLLATE Latin1_General_CI_AS\n FROM OPENJSON(CONCAT('[', @Tags, ']')) J)\nORDER BY T.Count DESC\n\nGO\n\nEXEC dbo.SomeProc @Tags = '\"ruby\",\"rails\",\"scruffy\",\"rubyonrails\"'\n\nDROP TABLE dbo.Tags \n"
},
{
"answer_id": 35052699,
"author": "Bryan",
"author_id": 313072,
"author_profile": "https://Stackoverflow.com/users/313072",
"pm_score": 2,
"selected": false,
"text": "public static class SqlWhereInParamBuilder\n{\n public static string BuildWhereInClause<t>(string partialClause, string paramPrefix, IEnumerable<t> parameters)\n {\n string[] parameterNames = parameters.Select(\n (paramText, paramNumber) => \"@\" + paramPrefix + paramNumber.ToString())\n .ToArray();\n\n string inClause = string.Join(\",\", parameterNames);\n string whereInClause = string.Format(partialClause.Trim(), inClause);\n\n return whereInClause;\n }\n\n public static void AddParamsToCommand<t>(this SqlCommand cmd, string paramPrefix, IEnumerable<t> parameters)\n {\n string[] parameterValues = parameters.Select((paramText) => paramText.ToString()).ToArray();\n\n string[] parameterNames = parameterValues.Select(\n (paramText, paramNumber) => \"@\" + paramPrefix + paramNumber.ToString()\n ).ToArray();\n\n for (int i = 0; i < parameterNames.Length; i++)\n {\n cmd.Parameters.AddWithValue(parameterNames[i], parameterValues[i]);\n }\n }\n}\n"
},
{
"answer_id": 36980115,
"author": "Lukasz Szozda",
"author_id": 5070879,
"author_profile": "https://Stackoverflow.com/users/5070879",
"pm_score": 5,
"selected": false,
"text": "SQL Server 2016+ STRING_SPLIT DECLARE @names NVARCHAR(MAX) = 'ruby,rails,scruffy,rubyonrails';\n\nSELECT * \nFROM Tags\nWHERE Name IN (SELECT [value] FROM STRING_SPLIT(@names, ','))\nORDER BY [Count] DESC;\n DECLARE @names NVARCHAR(MAX) = 'ruby,rails,scruffy,rubyonrails';\n\nSELECT t.*\nFROM Tags t\nJOIN STRING_SPLIT(@names,',')\n ON t.Name = [value]\nORDER BY [Count] DESC;\n SELECT ProductId, Name, Tags\nFROM Product\nWHERE ',1,2,3,' LIKE '%,' + CAST(ProductId AS VARCHAR(20)) + ',%';\n STRING_SPLIT DECLARE @names NVARCHAR(MAX) = 'ruby,rails,scruffy,rubyonrails,sql';\n\nCREATE TABLE #t(val NVARCHAR(120));\nINSERT INTO #t(val) SELECT s.[value] FROM STRING_SPLIT(@names, ',') s;\n\nSELECT *\nFROM Tags tg\nJOIN #t t\n ON t.val = tg.TagName\nORDER BY [Count] DESC;\n SQL Server 2008"
},
{
"answer_id": 41390255,
"author": "Derek Greer",
"author_id": 1219618,
"author_profile": "https://Stackoverflow.com/users/1219618",
"pm_score": 2,
"selected": false,
"text": "public static class ParameterExtensions\n{\n public static Tuple<string, SqlParameter[]> ToParameterTuple<T>(this IEnumerable<T> values)\n {\n var createName = new Func<int, string>(index => \"@value\" + index.ToString());\n var paramTuples = values.Select((value, index) => \n new Tuple<string, SqlParameter>(createName(index), new SqlParameter(createName(index), value))).ToArray();\n var inClause = string.Join(\",\", paramTuples.Select(t => t.Item1));\n var parameters = paramTuples.Select(t => t.Item2).ToArray();\n return new Tuple<string, SqlParameter[]>(inClause, parameters);\n }\n}\n string[] tags = {\"ruby\", \"rails\", \"scruffy\", \"rubyonrails\"};\n var paramTuple = tags.ToParameterTuple();\n var cmdText = $\"SELECT * FROM Tags WHERE Name IN ({paramTuple.Item1})\";\n\n using (var cmd = new SqlCommand(cmdText))\n {\n cmd.Parameters.AddRange(paramTuple.Item2);\n }\n"
},
{
"answer_id": 43366116,
"author": "Bartosz X",
"author_id": 5243515,
"author_profile": "https://Stackoverflow.com/users/5243515",
"pm_score": 2,
"selected": false,
"text": "/* Create table-value string: */\nCREATE TYPE [String_List] AS TABLE ([Your_String_Element] varchar(max) PRIMARY KEY);\nGO\n/* Create procedure which takes this table as parameter: */\n\nCREATE PROCEDURE [dbo].[usp_ListCheck]\n@String_List_In [String_List] READONLY \nAS \nSELECT a.*\nFROM [dbo].[Tags] a\nJOIN @String_List_In b ON a.[Name] = b.[Your_String_Element];\n"
},
{
"answer_id": 45403417,
"author": "guru008",
"author_id": 8376512,
"author_profile": "https://Stackoverflow.com/users/8376512",
"pm_score": 1,
"selected": false,
"text": "select * from Tags \nwhere Name in (select distinct name from temp)\norder by Count desc\n"
},
{
"answer_id": 54871120,
"author": "Milad",
"author_id": 3785523,
"author_profile": "https://Stackoverflow.com/users/3785523",
"pm_score": 1,
"selected": false,
"text": "DECLARE @InParaSeprated VARCHAR(MAX) = 'ruby,rails,scruffy,rubyonrails'\nDECLARE @Delimeter VARCHAR(10) = ','\nSELECT \n * \nFROM \n Tags T\n INNER JOIN STRING_SPLIT(@InputParameters,@Delimeter) SS ON T.Name = SS.value\nORDER BY \n Count DESC\n"
},
{
"answer_id": 57013850,
"author": "Adel Mourad",
"author_id": 1594274,
"author_profile": "https://Stackoverflow.com/users/1594274",
"pm_score": 1,
"selected": false,
"text": "string[] Ids = new string[] { \"3\", \"6\", \"14\" };\nstring IdsSP = string.Format(\"'|{0}|'\", string.Join(\"|\", Ids));\n @CurrentShipmentStatusIdArray [nvarchar](255) = NULL\n Where @CurrentShipmentStatusIdArray is null or @CurrentShipmentStatusIdArray LIKE '%|' + convert(nvarchar,Shipments.CurrentShipmentStatusId) + '|%'\n Where @CurrentShipmentStatusIdArray is null or @CurrentShipmentStatusIdArray LIKE '%|' + Shipments.CurrentShipmentStatusId+ '|%'\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1/"
] |
337,713 | <p>I'm developing an ASP.NET 2.0 application that includes Crystal Reports (version 10, included with VS 2005). Originally, the reports were working properly, both when run from my machine using the ASP.NET development web server, and also when deployed to an IIS server.</p>
<p>I made some changes to the reports and re-deployed the app to the IIS server, but the report changes are not showing up when I run the application (although they are showing up when serving the app locally on my machine). Is it possible the IIS server is caching older copies of the rpt files and not flushing them properly? I suggested this possibility to the guy managing the server, but he said he re-started the app pool and it didn't make a difference. Any ideas?</p>
| [
{
"answer_id": 337752,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 7,
"selected": false,
"text": "DECLARE @tags\n\nSET @tags = ‘ruby|rails|scruffy|rubyonrails’\n\nselect * from Tags \nwhere Name in (SELECT item from fnSplit(@tags, ‘|’))\norder by Count desc\n CREATE FUNCTION [dbo].[fnSplit](\n @sInputList VARCHAR(8000) -- List of delimited items\n , @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items\n) RETURNS @List TABLE (item VARCHAR(8000))\n\nBEGIN\nDECLARE @sItem VARCHAR(8000)\nWHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0\n BEGIN\n SELECT\n @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),\n @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))\n\n IF LEN(@sItem) > 0\n INSERT INTO @List SELECT @sItem\n END\n\nIF LEN(@sInputList) > 0\n INSERT INTO @List SELECT @sInputList -- Put the last item in\nRETURN\nEND\n"
},
{
"answer_id": 337765,
"author": "eulerfx",
"author_id": 13855,
"author_profile": "https://Stackoverflow.com/users/13855",
"pm_score": 4,
"selected": false,
"text": "where exists sp_xml_preparedocument"
},
{
"answer_id": 337774,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 4,
"selected": false,
"text": "SELECT ...\n ...\n WHERE tag IN( @tag1, ISNULL( @tag2, @tag1 ), ISNULL( @tag3, @tag1 ), etc. )\n"
},
{
"answer_id": 337792,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 10,
"selected": false,
"text": "string[] tags = new string[] { \"ruby\", \"rails\", \"scruffy\", \"rubyonrails\" };\nstring cmdText = \"SELECT * FROM Tags WHERE Name IN ({0})\";\n\nstring[] paramNames = tags.Select(\n (s, i) => \"@tag\" + i.ToString()\n).ToArray();\n\nstring inClause = string.Join(\", \", paramNames);\nusing (SqlCommand cmd = new SqlCommand(string.Format(cmdText, inClause))) {\n for(int i = 0; i < paramNames.Length; i++) {\n cmd.Parameters.AddWithValue(paramNames[i], tags[i]);\n }\n}\n cmd.CommandText = \"SELECT * FROM Tags WHERE Name IN (@tag0, @tag1, @tag2, @tag3)\"\ncmd.Parameters[\"@tag0\"] = \"ruby\"\ncmd.Parameters[\"@tag1\"] = \"rails\"\ncmd.Parameters[\"@tag2\"] = \"scruffy\"\ncmd.Parameters[\"@tag3\"] = \"rubyonrails\"\n"
},
{
"answer_id": 337817,
"author": "Joel Spolsky",
"author_id": 4,
"author_profile": "https://Stackoverflow.com/users/4",
"pm_score": 9,
"selected": true,
"text": "SELECT * FROM Tags\nWHERE '|ruby|rails|scruffy|rubyonrails|'\nLIKE '%|' + Name + '|%'\n string[] tags = new string[] { \"ruby\", \"rails\", \"scruffy\", \"rubyonrails\" };\nconst string cmdText = \"select * from tags where '|' + @tags + '|' like '%|' + Name + '|%'\";\n\nusing (SqlCommand cmd = new SqlCommand(cmdText)) {\n cmd.Parameters.AddWithValue(\"@tags\", string.Join(\"|\", tags);\n}\n LIKE \"%...%\" |"
},
{
"answer_id": 337864,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 8,
"selected": false,
"text": "CREATE TYPE dbo.TagNamesTableType AS TABLE ( Name nvarchar(50) )\n string[] tags = new string[] { \"ruby\", \"rails\", \"scruffy\", \"rubyonrails\" };\ncmd.CommandText = \"SELECT Tags.* FROM Tags JOIN @tagNames as P ON Tags.Name = P.Name\";\n\n// value must be IEnumerable<SqlDataRecord>\ncmd.Parameters.AddWithValue(\"@tagNames\", tags.AsSqlDataRecord(\"Name\")).SqlDbType = SqlDbType.Structured;\ncmd.Parameters[\"@tagNames\"].TypeName = \"dbo.TagNamesTableType\";\n\n// Extension method for converting IEnumerable<string> to IEnumerable<SqlDataRecord>\npublic static IEnumerable<SqlDataRecord> AsSqlDataRecord(this IEnumerable<string> values, string columnName) {\n if (values == null || !values.Any()) return null; // Annoying, but SqlClient wants null instead of 0 rows\n var firstRecord = values.First();\n var metadata= new SqlMetaData(columnName, SqlDbType.NVarChar, 50); //50 as per SQL Type\n return values.Select(v => \n {\n var r = new SqlDataRecord(metadata);\n r.SetValues(v);\n return r;\n });\n}\n var metadata = SqlMetaData.InferFromValue(firstRecord, columnName); var metadata= new SqlMetaData(columnName, SqlDbType.NVarChar, maxLen); -1"
},
{
"answer_id": 337907,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 5,
"selected": false,
"text": "INSERT IN JOIN"
},
{
"answer_id": 337931,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 5,
"selected": false,
"text": "ALTER FUNCTION [dbo].[Fn_sqllist_to_table](@list AS VARCHAR(8000),\n @delim AS VARCHAR(10))\nRETURNS @listTable TABLE(\n Position INT,\n Value VARCHAR(8000))\nAS\n BEGIN\n DECLARE @myPos INT\n\n SET @myPos = 1\n\n WHILE Charindex(@delim, @list) > 0\n BEGIN\n INSERT INTO @listTable\n (Position,Value)\n VALUES (@myPos,LEFT(@list, Charindex(@delim, @list) - 1))\n\n SET @myPos = @myPos + 1\n\n IF Charindex(@delim, @list) = Len(@list)\n INSERT INTO @listTable\n (Position,Value)\n VALUES (@myPos,'')\n\n SET @list = RIGHT(@list, Len(@list) - Charindex(@delim, @list))\n END\n\n IF Len(@list) > 0\n INSERT INTO @listTable\n (Position,Value)\n VALUES (@myPos,@list)\n\n RETURN\n END \n @Name varchar(8000) = null // parameter for search values \n\nselect * from Tags \nwhere Name in (SELECT value From fn_sqllist_to_table(@Name,',')))\norder by Count desc\n"
},
{
"answer_id": 357753,
"author": "rip747",
"author_id": 31278,
"author_profile": "https://Stackoverflow.com/users/31278",
"pm_score": 3,
"selected": false,
"text": "<cfset myvalues = \"ruby|rails|scruffy|rubyonrails\">\n <cfquery name=\"q\">\n select * from sometable where values in <cfqueryparam value=\"#myvalues#\" list=\"true\">\n </cfquery>\n"
},
{
"answer_id": 380185,
"author": "Peter Meyer",
"author_id": 1875,
"author_profile": "https://Stackoverflow.com/users/1875",
"pm_score": 6,
"selected": false,
"text": "var inValues = new [] { \"ruby\",\"rails\",\"scruffy\",\"rubyonrails\" };\n\nvar results = from tag in Tags\n where inValues.Contains(tag.Name)\n select tag;\n Contains IN"
},
{
"answer_id": 512749,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": " with qry(n, names) as\n (select len(list.names) - len(replace(list.names, ',', '')) - 1 as n,\n substring(list.names, 2, len(list.names)) as names\n from (select ',Doc,Grumpy,Happy,Sneezy,Bashful,Sleepy,Dopey,' names) as list\n union all\n select (n - 1) as n,\n substring(names, 1 + charindex(',', names), len(names)) as names\n from qry\n where n > 1)\n select n, substring(names, 1, charindex(',', names) - 1) dwarf\n from qry;\n select n, substr(name, 1, instr(name, ',') - 1) dwarf\n from (select n,\n substr(val, 1 + instr(val, ',', 1, n)) name\n from (select rownum as n,\n list.val\n from (select ',Doc,Grumpy,Happy,Sneezy,Bashful,Sleepy,Dopey,' val\n from dual) list\n connect by level < length(list.val) -\n length(replace(list.val, ',', ''))));\n select pivot.n,\n substring_index(substring_index(list.val, ',', 1 + pivot.n), ',', -1) from (select 1 as n\n union all\n select 2 as n\n union all\n select 3 as n\n union all\n select 4 as n\n union all\n select 5 as n\n union all\n select 6 as n\n union all\n select 7 as n\n union all\n select 8 as n\n union all\n select 9 as n\n union all\n select 10 as n) pivot, (select ',Doc,Grumpy,Happy,Sneezy,Bashful,Sleepy,Dopey,' val) as list where pivot.n < length(list.val) -\n length(replace(list.val, ',', ''));\n"
},
{
"answer_id": 928523,
"author": "spencer7593",
"author_id": 107744,
"author_profile": "https://Stackoverflow.com/users/107744",
"pm_score": 8,
"selected": false,
"text": "Name % 'pe%ter' select ...\n where '|peanut|butter|' like '%|' + 'pe%ter' + '|%'\n select ...\n where '|butter|peanut|' like '%|' + 'pe%ter' + '|%'\n pe%ter LIKE % select ...\n where '|peanut|butter|'\n like '%|' + 'pe\\%ter' + '|%' escape '\\'\n REPLACE % select ...\n where '|pe%ter|'\n like '%|' + REPLACE( 'pe%ter' ,'%','\\%') + '|%' escape '\\'\n select ...\n where '|pe%t!r|'\n like '%|' + REPLACE(REPLACE( 'pe%t!r' ,'!','!!'),'%','!%') + '|%' escape '!'\n REPLACE select ...\n where '|p_%t!r|'\n like '%|' + REPLACE(REPLACE(REPLACE( 'p_%t!r' ,'$','$$'),'%','$%'),'_','$_') + '|%' escape '$'\n [] - ^ % _"
},
{
"answer_id": 2254502,
"author": "ArtOfCoding",
"author_id": 272067,
"author_profile": "https://Stackoverflow.com/users/272067",
"pm_score": 3,
"selected": false,
"text": "SELECT * \nFROM Tags \nWHERE PATINDEX('%<' + Name + '>%','<jo>,<john>,<scruffy>,<rubyonrails>') > 0\n"
},
{
"answer_id": 3310117,
"author": "Paulo Henrique",
"author_id": 302751,
"author_profile": "https://Stackoverflow.com/users/302751",
"pm_score": 4,
"selected": false,
"text": "CREATE FUNCTION dbo.fnParseArray (@Array VARCHAR(1000),@separator CHAR(1))\nRETURNS @T Table (col1 varchar(50))\nAS \nBEGIN\n --DECLARE @T Table (col1 varchar(50)) \n -- @Array is the array we wish to parse\n -- @Separator is the separator charactor such as a comma\n DECLARE @separator_position INT -- This is used to locate each separator character\n DECLARE @array_value VARCHAR(1000) -- this holds each array value as it is returned\n -- For my loop to work I need an extra separator at the end. I always look to the\n -- left of the separator character for each array value\n\n SET @array = @array + @separator\n\n -- Loop through the string searching for separtor characters\n WHILE PATINDEX('%' + @separator + '%', @array) <> 0 \n BEGIN\n -- patindex matches the a pattern against a string\n SELECT @separator_position = PATINDEX('%' + @separator + '%',@array)\n SELECT @array_value = LEFT(@array, @separator_position - 1)\n -- This is where you process the values passed.\n INSERT into @T VALUES (@array_value) \n -- Replace this select statement with your processing\n -- @array_value holds the value of this element of the array\n -- This replaces what we just processed with and empty string\n SELECT @array = STUFF(@array, 1, @separator_position, '')\n END\n RETURN \nEND\n SELECT * FROM dbo.fnParseArray('a,b,c,d,e,f', ',')\n"
},
{
"answer_id": 5825528,
"author": "Jason Henriksen",
"author_id": 534156,
"author_profile": "https://Stackoverflow.com/users/534156",
"pm_score": 2,
"selected": false,
"text": "and ( {1}==0 or b.CompanyId in ({2},{3},{4},{5},{6}) )\n int origCount = idList.Count;\n if (origCount > 5) {\n throw new Exception(\"You may only specify up to five originators to filter on.\");\n }\n while (idList.Count < 5) { idList.Add(-1); } // -1 is an impossible value\n return ExecuteQuery<PublishDate>(getValuesInListSQL, \n origCount, \n idList[0], idList[1], idList[2], idList[3], idList[4]);\n"
},
{
"answer_id": 5993875,
"author": "Runonthespot",
"author_id": 305970,
"author_profile": "https://Stackoverflow.com/users/305970",
"pm_score": 3,
"selected": false,
"text": "DECLARE @InputString varchar(8000) = 'ruby,rails,scruffy,rubyonrails'\n\nSELECT @InputString = @InputString + ','\n\n;WITH RecursiveCSV(x,y) \nAS \n(\n SELECT \n x = SUBSTRING(@InputString,0,CHARINDEX(',',@InputString,0)),\n y = SUBSTRING(@InputString,CHARINDEX(',',@InputString,0)+1,LEN(@InputString))\n UNION ALL\n SELECT \n x = SUBSTRING(y,0,CHARINDEX(',',y,0)),\n y = SUBSTRING(y,CHARINDEX(',',y,0)+1,LEN(y))\n FROM \n RecursiveCSV \n WHERE\n SUBSTRING(y,CHARINDEX(',',y,0)+1,LEN(y)) <> '' OR \n SUBSTRING(y,0,CHARINDEX(',',y,0)) <> ''\n)\nSELECT\n * \nFROM \n Tags\nWHERE \n Name IN (select x FROM RecursiveCSV)\nOPTION (MAXRECURSION 32767);\n"
},
{
"answer_id": 6356730,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": false,
"text": "string[] names = new string[] {\"ruby\",\"rails\",\"scruffy\",\"rubyonrails\"};\nvar tags = dataContext.Query<Tags>(@\"\nselect * from Tags \nwhere Name in @names\norder by Count desc\", new {names});\n string[] names = new string[] {\"ruby\",\"rails\",\"scruffy\",\"rubyonrails\"};\nvar tags = from tag in dataContext.Tags\n where names.Contains(tag.Name)\n orderby tag.Count descending\n select tag;\n"
},
{
"answer_id": 7880246,
"author": "MindLoggedOut",
"author_id": 999456,
"author_profile": "https://Stackoverflow.com/users/999456",
"pm_score": 3,
"selected": false,
"text": " declare @x xml\n set @x='<items>\n <item myvalue=\"29790\" />\n <item myvalue=\"31250\" />\n </items>\n ';\n With CTE AS (\n SELECT \n x.item.value('@myvalue[1]', 'decimal') AS myvalue\n FROM @x.nodes('//items/item') AS x(item) )\n\n select * from YourTable where tableColumnName in (select myvalue from cte)\n"
},
{
"answer_id": 10808268,
"author": "Rockfish",
"author_id": 1424866,
"author_profile": "https://Stackoverflow.com/users/1424866",
"pm_score": 3,
"selected": false,
"text": "-- Create a user defined type for the list.\nCREATE TYPE [dbo].[StringList] AS TABLE(\n [StringValue] [nvarchar](max) NOT NULL\n)\n\n-- Create a sample list using the list table type.\nDECLARE @list [dbo].[StringList]; \nINSERT INTO @list VALUES ('one'), ('two'), ('three'), ('four')\n\n-- Build a string in which we recreate the list so we can pass it to exec\n-- This can be done in any language since we're just building a string.\nDECLARE @str nvarchar(max);\nSET @str = 'DECLARE @list [dbo].[StringList]; INSERT INTO @list VALUES '\n\n-- Add all the values we want to the string. This would be a loop in C++.\nSELECT @str = @str + '(''' + StringValue + '''),' FROM @list\n\n-- Remove the trailing comma so the query is valid sql.\nSET @str = substring(@str, 1, len(@str)-1)\n\n-- Add a select to test the string.\nSET @str = @str + '; SELECT * FROM @list;'\n\n-- Execute the string and see we've pass the table correctly.\nEXEC(@str)\n"
},
{
"answer_id": 11663054,
"author": "mangeshkt",
"author_id": 353999,
"author_profile": "https://Stackoverflow.com/users/353999",
"pm_score": 3,
"selected": false,
"text": " create stored procedure GetSearchMachingTagNames \n @PipeDelimitedTagNames varchar(max), \n @delimiter char(1) \n as \n begin\n select * from Tags \n where Name in (select data from [dbo].[Split](@PipeDelimitedTagNames,@delimiter) \n end\n"
},
{
"answer_id": 11973246,
"author": "Jodrell",
"author_id": 659190,
"author_profile": "https://Stackoverflow.com/users/659190",
"pm_score": 4,
"selected": false,
"text": "[SqlFunction(\n DataAccessKind.None,\n IsDeterministic = true,\n SystemDataAccess = SystemDataAccessKind.None,\n IsPrecise = true,\n FillRowMethodName = \"SplitFillRow\",\n TableDefinintion = \"s NVARCHAR(MAX)\"]\npublic static IEnumerable Split(SqlChars seperator, SqlString s)\n{\n if (s.IsNull)\n return new string[0];\n\n return s.ToString().Split(seperator.Buffer);\n}\n\npublic static void SplitFillRow(object row, out SqlString s)\n{\n s = new SqlString(row.ToString());\n}\n declare @desiredTags nvarchar(MAX);\nset @desiredTags = 'ruby,rails,scruffy,rubyonrails';\n\nselect * from Tags\nwhere Name in [dbo].[Split] (',', @desiredTags)\norder by Count desc\n"
},
{
"answer_id": 13534053,
"author": "Gowdhaman008",
"author_id": 1176133,
"author_profile": "https://Stackoverflow.com/users/1176133",
"pm_score": 3,
"selected": false,
"text": "CREATE TABLE Tags\n ([ID] int, [Name] varchar(20))\n;\n\nINSERT INTO Tags\n ([ID], [Name])\nVALUES\n (1, 'ruby'),\n (2, 'rails'),\n (3, 'scruffy'),\n (4, 'rubyonrails')\n;\n DECLARE @Param nvarchar(max)\n\nSET @Param = 'ruby,rails,scruffy,rubyonrails'\n\nSELECT * FROM Tags\nWHERE CharIndex(Name,@Param)>0\n Create table SelectedTags\n(Name nvarchar(20));\n\nINSERT INTO SelectedTags values ('ruby'),('rails')\n DECLARE @list nvarchar(max)\nSELECT @list=coalesce(@list+',','')+st.Name FROM SelectedTags st\n\nSELECT * FROM Tags\nWHERE CharIndex(Name,@Param)>0\n"
},
{
"answer_id": 15846417,
"author": "Metaphor",
"author_id": 2123899,
"author_profile": "https://Stackoverflow.com/users/2123899",
"pm_score": 3,
"selected": false,
"text": "CREATE PROCEDURE [dbo].[sp_myproc]\n @UnitList varchar(MAX) = '1,2,3'\nAS\nselect column from table\nwhere ph.UnitID in (select * from CsvToInt(@UnitList))\n CREATE Function [dbo].[CsvToInt] ( @Array varchar(MAX))\nreturns @IntTable table\n(IntValue int)\nAS\nbegin\n declare @separator char(1)\n set @separator = ','\n declare @separator_position int\n declare @array_value varchar(MAX)\n\n set @array = @array + ','\n\n while patindex('%,%' , @array) <> 0\n begin\n\n select @separator_position = patindex('%,%' , @array)\n select @array_value = left(@array, @separator_position - 1)\n\n Insert @IntTable\n Values (Cast(@array_value as int))\n select @array = stuff(@array, 1, @separator_position, '')\n end\n return\nend\n"
},
{
"answer_id": 16907149,
"author": "Darek",
"author_id": 564092,
"author_profile": "https://Stackoverflow.com/users/564092",
"pm_score": 3,
"selected": false,
"text": " private static DataSet GetDataSet(SqlConnectionStringBuilder scsb, string strSql, params object[] pars)\n {\n var ds = new DataSet();\n using (var sqlConn = new SqlConnection(scsb.ConnectionString))\n {\n var sqlParameters = new List<SqlParameter>();\n var replacementStrings = new Dictionary<string, string>();\n if (pars != null)\n {\n for (int i = 0; i < pars.Length; i++)\n {\n if (pars[i] is IEnumerable<object>)\n {\n List<object> enumerable = (pars[i] as IEnumerable<object>).ToList();\n replacementStrings.Add(\"@\" + i, String.Join(\",\", enumerable.Select((value, pos) => String.Format(\"@_{0}_{1}\", i, pos))));\n sqlParameters.AddRange(enumerable.Select((value, pos) => new SqlParameter(String.Format(\"@_{0}_{1}\", i, pos), value ?? DBNull.Value)).ToArray());\n }\n else\n {\n sqlParameters.Add(new SqlParameter(String.Format(\"@{0}\", i), pars[i] ?? DBNull.Value));\n }\n }\n }\n strSql = replacementStrings.Aggregate(strSql, (current, replacementString) => current.Replace(replacementString.Key, replacementString.Value));\n using (var sqlCommand = new SqlCommand(strSql, sqlConn))\n {\n if (pars != null)\n {\n sqlCommand.Parameters.AddRange(sqlParameters.ToArray());\n }\n else\n {\n //Fail-safe, just in case a user intends to pass a single null parameter\n sqlCommand.Parameters.Add(new SqlParameter(\"@0\", DBNull.Value));\n }\n using (var sqlDataAdapter = new SqlDataAdapter(sqlCommand))\n {\n sqlDataAdapter.Fill(ds);\n }\n }\n }\n return ds;\n }\n"
},
{
"answer_id": 20871852,
"author": "Sandip Bantawa",
"author_id": 1903674,
"author_profile": "https://Stackoverflow.com/users/1903674",
"pm_score": 2,
"selected": false,
"text": "DECLARE @invalue VARCHAR(100)\nSELECT @invalue = '''Bishnu'',''Gautam'''\n\nDECLARE @dynamicSQL VARCHAR(MAX)\nSELECT @dynamicSQL = 'SELECT * FROM #temp WHERE [name] IN (' + @invalue + ')'\nEXEC (@dynamicSQL)\n"
},
{
"answer_id": 21069780,
"author": "Erik Hart",
"author_id": 832306,
"author_profile": "https://Stackoverflow.com/users/832306",
"pm_score": 2,
"selected": false,
"text": "public static T[][] SplitSqlValues<T>(IEnumerable<T> values)\n{\n var sizes = new int[] { 1000, 500, 250, 125, 63, 32, 16, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };\n int processed = 0;\n int currSizeIdx = sizes.Length - 1; /* start with last (smallest) */\n var splitLists = new List<T[]>();\n\n var valuesDistSort = values.Distinct().ToList(); /* remove redundant */\n valuesDistSort.Sort();\n int totalValues = valuesDistSort.Count;\n\n while (totalValues > sizes[currSizeIdx] && currSizeIdx > 0)\n currSizeIdx--; /* bigger size, by array pos. */\n\n while (processed < totalValues)\n {\n while (totalValues - processed < sizes[currSizeIdx]) \n currSizeIdx++; /* smaller size, by array pos. */\n var partList = new T[sizes[currSizeIdx]];\n valuesDistSort.CopyTo(processed, partList, 0, sizes[currSizeIdx]);\n splitLists.Add(partList);\n processed += sizes[currSizeIdx];\n }\n return splitLists.ToArray();\n}\n foreach(int[] partList in splitLists)\n{\n /* here: question mark for param variable, use named/numbered params if required */\n string sql = \"select * from Items where Id in(\"\n + string.Join(\",\", partList.Select(p => \"?\")) \n + \")\"; /* comma separated ?, one for each partList entry */\n\n /* create command with sql string, set parameters, execute, merge results */\n}\n SELECT * FROM MyTable WHERE Id IN (@p1, @p2, @p3, ... , @p[batch-size])\n SELECT * FROM MyTable WHERE Id=@id\n"
},
{
"answer_id": 29017255,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 3,
"selected": false,
"text": "List<SqlParameter> parameters = tags.Select((s, i) => new SqlParameter(\"@tag\" + i.ToString(), SqlDbType.NVarChar(50)) { Value = s}).ToList();\n\nvar whereCondition = string.Format(\"tags in ({0})\", String.Join(\",\",parameters.Select(s => s.ParameterName)));\n var parameters = new List<SqlParameter>();\nvar paramNames = new List<string>();\nfor (var i = 0; i < tags.Length; i++) \n{\n var paramName = \"@tag\" + i;\n\n //Include size and set value explicitly (not AddWithValue)\n //Because SQL Server may use an implicit conversion if it doesn't know\n //the actual size.\n var p = new SqlParameter(paramName, SqlDbType.NVarChar(50) { Value = tags[i]; } \n paramNames.Add(paramName);\n parameters.Add(p);\n}\n\nvar inClause = string.Join(\",\", paramNames);\n"
},
{
"answer_id": 29116544,
"author": "ASP.Net Developer",
"author_id": 2839109,
"author_profile": "https://Stackoverflow.com/users/2839109",
"pm_score": 2,
"selected": false,
"text": " create FUNCTION [dbo].[ConvertStringToList]\n\n\n (@str VARCHAR (MAX), @delimeter CHAR (1))\n RETURNS \n @result TABLE (\n [ID] INT NULL)\n AS\n BEG\n\nIN\n\n DECLARE @x XML \n SET @x = '<t>' + REPLACE(@str, @delimeter, '</t><t>') + '</t>'\n\n INSERT INTO @result\n SELECT DISTINCT x.i.value('.', 'int') AS token\n FROM @x.nodes('//t') x(i)\n ORDER BY 1\n\nRETURN\nEND\n select * from table where id in ([dbo].[ConvertStringToList(YOUR comma separated string ,',')])\n"
},
{
"answer_id": 30784838,
"author": "Eli Ekstein",
"author_id": 2108149,
"author_profile": "https://Stackoverflow.com/users/2108149",
"pm_score": 3,
"selected": false,
"text": "CREATE FUNCTION [dbo].[Split] (@sep char(1), @s varchar(8000))\nRETURNS table\nAS\nRETURN (\n WITH Pieces(pn, start, stop) AS (\n SELECT 1, 1, CHARINDEX(@sep, @s)\n UNION ALL\n SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)\n FROM Pieces\n WHERE stop > 0\n )\n SELECT \n SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s\n FROM Pieces\n )\n select * from Tags \nwhere Name in (select s from dbo.split(';','ruby;rails;scruffy;rubyonrails'))\norder by Count desc\n"
},
{
"answer_id": 33584131,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 3,
"selected": false,
"text": "OPENJSON CREATE TABLE dbo.Tags\n (\n Name VARCHAR(50),\n Count INT\n )\n\nINSERT INTO dbo.Tags\nVALUES ('VB',982), ('ruby',1306), ('rails',1478), ('scruffy',1), ('C#',1784)\n\nGO\n\nCREATE PROC dbo.SomeProc\n@Tags VARCHAR(MAX)\nAS\nSELECT T.*\nFROM dbo.Tags T\nWHERE T.Name IN (SELECT J.Value COLLATE Latin1_General_CI_AS\n FROM OPENJSON(CONCAT('[', @Tags, ']')) J)\nORDER BY T.Count DESC\n\nGO\n\nEXEC dbo.SomeProc @Tags = '\"ruby\",\"rails\",\"scruffy\",\"rubyonrails\"'\n\nDROP TABLE dbo.Tags \n"
},
{
"answer_id": 35052699,
"author": "Bryan",
"author_id": 313072,
"author_profile": "https://Stackoverflow.com/users/313072",
"pm_score": 2,
"selected": false,
"text": "public static class SqlWhereInParamBuilder\n{\n public static string BuildWhereInClause<t>(string partialClause, string paramPrefix, IEnumerable<t> parameters)\n {\n string[] parameterNames = parameters.Select(\n (paramText, paramNumber) => \"@\" + paramPrefix + paramNumber.ToString())\n .ToArray();\n\n string inClause = string.Join(\",\", parameterNames);\n string whereInClause = string.Format(partialClause.Trim(), inClause);\n\n return whereInClause;\n }\n\n public static void AddParamsToCommand<t>(this SqlCommand cmd, string paramPrefix, IEnumerable<t> parameters)\n {\n string[] parameterValues = parameters.Select((paramText) => paramText.ToString()).ToArray();\n\n string[] parameterNames = parameterValues.Select(\n (paramText, paramNumber) => \"@\" + paramPrefix + paramNumber.ToString()\n ).ToArray();\n\n for (int i = 0; i < parameterNames.Length; i++)\n {\n cmd.Parameters.AddWithValue(parameterNames[i], parameterValues[i]);\n }\n }\n}\n"
},
{
"answer_id": 36980115,
"author": "Lukasz Szozda",
"author_id": 5070879,
"author_profile": "https://Stackoverflow.com/users/5070879",
"pm_score": 5,
"selected": false,
"text": "SQL Server 2016+ STRING_SPLIT DECLARE @names NVARCHAR(MAX) = 'ruby,rails,scruffy,rubyonrails';\n\nSELECT * \nFROM Tags\nWHERE Name IN (SELECT [value] FROM STRING_SPLIT(@names, ','))\nORDER BY [Count] DESC;\n DECLARE @names NVARCHAR(MAX) = 'ruby,rails,scruffy,rubyonrails';\n\nSELECT t.*\nFROM Tags t\nJOIN STRING_SPLIT(@names,',')\n ON t.Name = [value]\nORDER BY [Count] DESC;\n SELECT ProductId, Name, Tags\nFROM Product\nWHERE ',1,2,3,' LIKE '%,' + CAST(ProductId AS VARCHAR(20)) + ',%';\n STRING_SPLIT DECLARE @names NVARCHAR(MAX) = 'ruby,rails,scruffy,rubyonrails,sql';\n\nCREATE TABLE #t(val NVARCHAR(120));\nINSERT INTO #t(val) SELECT s.[value] FROM STRING_SPLIT(@names, ',') s;\n\nSELECT *\nFROM Tags tg\nJOIN #t t\n ON t.val = tg.TagName\nORDER BY [Count] DESC;\n SQL Server 2008"
},
{
"answer_id": 41390255,
"author": "Derek Greer",
"author_id": 1219618,
"author_profile": "https://Stackoverflow.com/users/1219618",
"pm_score": 2,
"selected": false,
"text": "public static class ParameterExtensions\n{\n public static Tuple<string, SqlParameter[]> ToParameterTuple<T>(this IEnumerable<T> values)\n {\n var createName = new Func<int, string>(index => \"@value\" + index.ToString());\n var paramTuples = values.Select((value, index) => \n new Tuple<string, SqlParameter>(createName(index), new SqlParameter(createName(index), value))).ToArray();\n var inClause = string.Join(\",\", paramTuples.Select(t => t.Item1));\n var parameters = paramTuples.Select(t => t.Item2).ToArray();\n return new Tuple<string, SqlParameter[]>(inClause, parameters);\n }\n}\n string[] tags = {\"ruby\", \"rails\", \"scruffy\", \"rubyonrails\"};\n var paramTuple = tags.ToParameterTuple();\n var cmdText = $\"SELECT * FROM Tags WHERE Name IN ({paramTuple.Item1})\";\n\n using (var cmd = new SqlCommand(cmdText))\n {\n cmd.Parameters.AddRange(paramTuple.Item2);\n }\n"
},
{
"answer_id": 43366116,
"author": "Bartosz X",
"author_id": 5243515,
"author_profile": "https://Stackoverflow.com/users/5243515",
"pm_score": 2,
"selected": false,
"text": "/* Create table-value string: */\nCREATE TYPE [String_List] AS TABLE ([Your_String_Element] varchar(max) PRIMARY KEY);\nGO\n/* Create procedure which takes this table as parameter: */\n\nCREATE PROCEDURE [dbo].[usp_ListCheck]\n@String_List_In [String_List] READONLY \nAS \nSELECT a.*\nFROM [dbo].[Tags] a\nJOIN @String_List_In b ON a.[Name] = b.[Your_String_Element];\n"
},
{
"answer_id": 45403417,
"author": "guru008",
"author_id": 8376512,
"author_profile": "https://Stackoverflow.com/users/8376512",
"pm_score": 1,
"selected": false,
"text": "select * from Tags \nwhere Name in (select distinct name from temp)\norder by Count desc\n"
},
{
"answer_id": 54871120,
"author": "Milad",
"author_id": 3785523,
"author_profile": "https://Stackoverflow.com/users/3785523",
"pm_score": 1,
"selected": false,
"text": "DECLARE @InParaSeprated VARCHAR(MAX) = 'ruby,rails,scruffy,rubyonrails'\nDECLARE @Delimeter VARCHAR(10) = ','\nSELECT \n * \nFROM \n Tags T\n INNER JOIN STRING_SPLIT(@InputParameters,@Delimeter) SS ON T.Name = SS.value\nORDER BY \n Count DESC\n"
},
{
"answer_id": 57013850,
"author": "Adel Mourad",
"author_id": 1594274,
"author_profile": "https://Stackoverflow.com/users/1594274",
"pm_score": 1,
"selected": false,
"text": "string[] Ids = new string[] { \"3\", \"6\", \"14\" };\nstring IdsSP = string.Format(\"'|{0}|'\", string.Join(\"|\", Ids));\n @CurrentShipmentStatusIdArray [nvarchar](255) = NULL\n Where @CurrentShipmentStatusIdArray is null or @CurrentShipmentStatusIdArray LIKE '%|' + convert(nvarchar,Shipments.CurrentShipmentStatusId) + '|%'\n Where @CurrentShipmentStatusIdArray is null or @CurrentShipmentStatusIdArray LIKE '%|' + Shipments.CurrentShipmentStatusId+ '|%'\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17777/"
] |
337,729 | <p>I was thinking of centralizing this functionality by having a single method that gets passed an AppState argument and it deals with changing the properties of all GUI elements based on this argument. Every time the app changes its state (ready, busy, downloading so partially busy, etc), this function is called with the appropriate state (or perhaps it's a bit field or something) and it does its magic.</p>
<p>If I scatter changing the state of GUI elements all over the place, then it becomes very easy to forget that when the app is in some state, this other widget over there needs to be disabled too, etc. </p>
<p>Any other ways to deal with this sort of thing?</p>
| [
{
"answer_id": 337820,
"author": "Stefan",
"author_id": 19307,
"author_profile": "https://Stackoverflow.com/users/19307",
"pm_score": 0,
"selected": false,
"text": "Sub UIControlStates_StateChanged(sender as object, e as UIControlStateArgs)\n if e.Oldstate=UIControlStates.Edit and e.NewState=UIControlStates.Normal then\n rem Edit was aborted, reset fields\n ResetFields()\n end if\n select case e.NewState\n case UIControlStates.Edit\n Rem enalbe/disable/hide/show, whatever\n\n Case UIControlStates.Normal\n Rem enalbe/disable/hide/show, whatever\n Case UIControlStates.Busy\n Rem enalbe/disable/hide/show, whatever\n Case Else\n Rem enalbe/disable/hide/show, whatever\n end select\nend sub\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30581/"
] |
337,732 | <p>I am looking to persistently display a game score in an iPhone app using cocos2d. Going off the code that cocos2d shows the FPS the app is running at:</p>
<pre><code>-(void) showFPS
{
frames++;
accumDt += dt;
if ( accumDt > 0.1) {
frameRate = frames/accumDt;
frames = 0;
accumDt = 0;
}
NSString *str = [NSString stringWithFormat:@"%.1f",frameRate];
[FPSLabel setString:str];
[FPSLabel draw];
}
</code></pre>
<p>I can get the score to display properly, but it flickers, even though the app is running at faster that 60 FPS... Any ideas?</p>
| [
{
"answer_id": 339276,
"author": "user21293",
"author_id": 21293,
"author_profile": "https://Stackoverflow.com/users/21293",
"pm_score": 3,
"selected": false,
"text": "scoreLabel = [Label labelWithString: [NSString stringWithFormat:@\"%d\", score] dimensions: CGSizeMake(180, 20) alignment: UITextAlignmentRight fontName:@\"Arial\" fontSize: 20];\n[scoreLabel setPosition: cpv(100,100)];\n[self add: scoreLabel];\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21293/"
] |
337,734 | <p>Is it possible to merge elements using XSLT.</p>
<p>If I have the following XML</p>
<pre><code><data>
<item column="left" value="1" />
<item column="left" value="2" />
<item column="right" value="3" />
<item column="left" value="4" />
<item column="right" value="5" />
<item column="right" value="6" />
<item column="right" value="7" />
<item column="left" value="8" />
<item column="right" value="9" />
<item column="right" value="10" />
</data>
</code></pre>
<p>I want the following output:</p>
<pre><code><data>
<item left="1" right="3 />
<item left="2" right="5" />
<item left="4" right="6" />
<item left="8" right="7" />
<item left="" right="9" />
<item left="" right="10" />
</data>
</code></pre>
<p>But I have absolutely no idea if this is possible using XSLT</p>
| [
{
"answer_id": 337800,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": -1,
"selected": false,
"text": "<xsl:element name=\"item\">\n <xsl:attribute name=\"left\"><xsl:value-of select=\"$theLeft\"/></xsl:attribute>\n <xsl:attribute name=\"right\"><xsl:value-of select=\"$theRight\"/></xsl:attribute>\n</xsl:element>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/274/"
] |
337,737 | <p>I'm using PUT and DELETE more and more w/ my ajax work and wanted to see if it would be a "bad idea" to add these verbs to the .aspx application extension in IIS.</p>
| [
{
"answer_id": 337800,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": -1,
"selected": false,
"text": "<xsl:element name=\"item\">\n <xsl:attribute name=\"left\"><xsl:value-of select=\"$theLeft\"/></xsl:attribute>\n <xsl:attribute name=\"right\"><xsl:value-of select=\"$theRight\"/></xsl:attribute>\n</xsl:element>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701/"
] |
337,739 | <p>In rails I want to log some information in a different log file and not the standard development.log or production.log. I want to do this logging from a model class.</p>
| [
{
"answer_id": 337971,
"author": "Thiago Arrais",
"author_id": 17801,
"author_profile": "https://Stackoverflow.com/users/17801",
"pm_score": 9,
"selected": true,
"text": "logger class User < ActiveRecord::Base\n def my_logger\n @@my_logger ||= Logger.new(\"#{Rails.root}/log/my.log\")\n end\n\n def before_save\n my_logger.info(\"Creating user with name #{self.name}\")\n end\nend\n my_logger ActiveRecord::Base"
},
{
"answer_id": 809957,
"author": "Tony",
"author_id": 45849,
"author_profile": "https://Stackoverflow.com/users/45849",
"pm_score": 2,
"selected": false,
"text": "class Article < ActiveRecord::Base \n\n LOGFILE = File.join(RAILS_ROOT, '/log/', \"article_#{RAILS_ENV}.log\") \n\n def validate \n log \"was validated!\" \n end \n\n def log(*args) \n args.size == 1 ? (message = args; severity = :info) : (severity, message = args) \n Article.logger severity, \"Article##{self.id}: #{message}\" \n end \n\n def self.logger(severity = nil, message = nil) \n @article_logger ||= Article.open_log \n if !severity.nil? && !message.nil? && @article_logger.respond_to?(severity) \n @article_logger.send severity, \"[#{Time.now.to_s(:db)}] [#{severity.to_s.capitalize}] #{message}\\n\" \n end \n message or @article_logger \n end \n\n def self.open_log \n ActiveSupport::BufferedLogger.new(LOGFILE) \n end \n\n end \n"
},
{
"answer_id": 9504214,
"author": "Vaughn Draughon",
"author_id": 1238269,
"author_profile": "https://Stackoverflow.com/users/1238269",
"pm_score": 5,
"selected": false,
"text": "app/models app/models/my_log.rb class MyLog\n def self.debug(message=nil)\n @my_log ||= Logger.new(\"#{Rails.root}/log/my.log\")\n @my_log.debug(message) unless message.nil?\n end\nend\n Post.create(:title => \"Hello world\", :contents => \"Lorum ipsum\"); MyLog.debug \"Hello world\"\n"
},
{
"answer_id": 12380618,
"author": "lulalala",
"author_id": 474597,
"author_profile": "https://Stackoverflow.com/users/474597",
"pm_score": 5,
"selected": false,
"text": "MultiLogger.add_logger('post')\n Rails.logger.post.error('hi')\n# or call logger.post.error('hi') if it is accessible.\n lib/ config/initializers/ # Custom Post logger\nrequire 'singleton'\nclass PostLogger < Logger\n include Singleton\n\n def initialize\n super(Rails.root.join('log/post_error.log'))\n self.formatter = formatter()\n self\n end\n\n # Optional, but good for prefixing timestamps automatically\n def formatter\n Proc.new{|severity, time, progname, msg|\n formatted_severity = sprintf(\"%-5s\",severity.to_s)\n formatted_time = time.strftime(\"%Y-%m-%d %H:%M:%S\")\n \"[#{formatted_severity} #{formatted_time} #{$$}] #{msg.to_s.strip}\\n\"\n }\n end\n\n class << self\n delegate :error, :debug, :fatal, :info, :warn, :add, :log, :to => :instance\n end\nend\n\nPostLogger.error('hi')\n# [ERROR 2012-09-12 10:40:15] hi\n"
},
{
"answer_id": 25205657,
"author": "Dorian",
"author_id": 407213,
"author_profile": "https://Stackoverflow.com/users/407213",
"pm_score": 2,
"selected": false,
"text": "class DebugLog\n def self.debug(message=nil)\n return unless Rails.env.development? and message.present?\n @logger ||= Logger.new(File.join(Rails.root, 'log', 'debug.log'))\n @logger.debug(message) \n end\nend\n"
},
{
"answer_id": 36956044,
"author": "Artem P",
"author_id": 712308,
"author_profile": "https://Stackoverflow.com/users/712308",
"pm_score": 1,
"selected": false,
"text": "class Post < ActiveRecord::Base\n def initialize(attributes)\n super(attributes)\n @logger = Logger.new(\"#{Rails.root}/log/post.log\")\n end\n\n def logger\n @logger\n end\n\n def some_method\n logger.info('Test 1')\n end\nend\n\nps = Post.new\nps.some_method\nps.logger.info('Test 2')\nPost.new.logger.info('Test 3')\n"
},
{
"answer_id": 44168717,
"author": "Les Nightingill",
"author_id": 451893,
"author_profile": "https://Stackoverflow.com/users/451893",
"pm_score": 4,
"selected": false,
"text": "class SpecialLog\n LogFile = Rails.root.join('log', 'special.log')\n class << self\n cattr_accessor :logger\n delegate :debug, :info, :warn, :error, :fatal, :to => :logger\n end\nend\n SpecialLog.logger = Logger.new(SpecialLog::LogFile)\nSpecialLog.logger.level = 'debug' # could be debug, info, warn, error or fatal\n SpecialLog.debug(\"something went wrong\")\n# or\nSpecialLog.info(\"life is good\")\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29653/"
] |
337,760 | <p>I am trying to create an array starting with today and going back the last 30 days with PHP and I am having trouble. I can estimate but I don’t know a good way of doing it and taking into account the number of days in the previous month etc. Does anyone have a good solution? I can’t get close but I need to make sure it is 100% accurate.</p>
| [
{
"answer_id": 337794,
"author": "ThoKra",
"author_id": 38254,
"author_profile": "https://Stackoverflow.com/users/38254",
"pm_score": 5,
"selected": false,
"text": "<?php \n$d = array();\nfor($i = 0; $i < 30; $i++) \n $d[] = date(\"d\", strtotime('-'. $i .' days'));\n?>\n"
},
{
"answer_id": 337795,
"author": "Pedrin",
"author_id": 36183,
"author_profile": "https://Stackoverflow.com/users/36183",
"pm_score": 0,
"selected": false,
"text": "for ($i = 0; $i < 30; $i++)\n{\n $timestamp = time();\n $tm = 86400 * $i; // 60 * 60 * 24 = 86400 = 1 day in seconds\n $tm = $timestamp - $tm;\n\n $the_date = date(\"m/d/Y\", $tm);\n}\n"
},
{
"answer_id": 36596383,
"author": "Flash Thunder",
"author_id": 2463948,
"author_profile": "https://Stackoverflow.com/users/2463948",
"pm_score": 0,
"selected": false,
"text": "$d = array();\nfor($i = 0; $i < 30; $i++)\n array_unshift($d,strtotime('-'. $i .' days'));\n"
},
{
"answer_id": 44071470,
"author": "Josiah",
"author_id": 6693825,
"author_profile": "https://Stackoverflow.com/users/6693825",
"pm_score": 1,
"selected": false,
"text": " $sales = Sale::find_all();//the sales object or array\n\n for($i=0; $i<7; $i++){\n $sale_sum = 0; //sum of sale initial\n if($i==0){ \n $day = strtotime(\"today\"); \n } else {\n $day = strtotime(\"$i days ago\");\n }\n $thisDayInWords = strftime(\"%A\", $day);\n\n foreach($sales as $sale){\n $date = strtotime($sale->date_of_sale)); //May 30th 2018 10:00:00 AM\n $dateInWords = strftime(\"%A\", $date);\n\n if($dateInWords == $thisDayInWords){\n $sale_sum += $sale->total_sale;//add only sales of this date... or whatever\n } \n } \n //display the results of each day's sale\n echo $thisDayInWords.\"-\".$sale_sum; ?> \n\n } \n"
},
{
"answer_id": 56251110,
"author": "Rahul",
"author_id": 6556397,
"author_profile": "https://Stackoverflow.com/users/6556397",
"pm_score": 2,
"selected": false,
"text": "$today = new DateTime(); // today\n$begin = $today->sub(new DateInterval('P30D')); //created 30 days interval back\n$end = new DateTime();\n$end = $end->modify('+1 day'); // interval generates upto last day\n$interval = new DateInterval('P1D'); // 1d interval range\n$daterange = new DatePeriod($begin, $interval, $end); // it always runs forwards in date\nforeach ($daterange as $date) { // date object\n $d[] = $date->format(\"Y-m-d\"); // your date\n}\nprint_r($d);\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
337,766 | <p>Due to the way my serverside script outputs I receive multiple JSON objects. <code>{jsonhere}{jsonhere1}{jsonhere2}{jsonhere3} etc..</code> They aren't seperated by anything. If I would do a split based <code>}{</code> I would lose those brackets. So is there an outerloop I can put over the regular <code>$.each</code> loop to make this work?</p>
<p>Thank you,</p>
<p>Ice</p>
| [
{
"answer_id": 337882,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 0,
"selected": false,
"text": "{\"foo\": \"}{\", \"bar\": 42}\n"
},
{
"answer_id": 337998,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 2,
"selected": false,
"text": "Define a stack\nDefine an array\nLOOP on each character in the string\n IF the top item of the stack is a single or double quote THEN\n LOOP through each character until you find a matching single or double quote, then pop it from the stack.\n ELSE\n IF \"{\", push onto the stack\n IF \"}\" THEN\n pop a \"{\" from the stack if it is on top \n IF the stack is empty THEN //we just finished a full json object\n Throw this json object into an array for later consumption\n END IF\n END IF\n IF single-quote, push onto the stack\n IF double-quote, push onto the stack \n END IF\nEND LOOP\n"
},
{
"answer_id": 339047,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 0,
"selected": false,
"text": "<html>\n<head>\n <script type=\"text/javascript\" src=\"jquery-1.2.6.js\"></script>\n <script type=\"text/javascript\">\n\n function handleClick() {\n var jsonStrs = parse();\n var jsonObjs = [];\n for(var j=0;j<jsonStrs.length;j++) jsonObjs.push( parseJSON(jsonStrs[j]) );\n\n //jsonObjs now contains an array of json objects \n\n document.getElementById('log').innerHTML = '';\n displayResults(jsonObjs);\n }\n\n function displayResults(jsonObjs) {\n for(var k=0; k<jsonObjs.length; k++) {\n ShowObjProperties(jsonObjs[k]);\n }\n }\n\n function ShowObjProperties(obj) {\n var property, propCollection = \"\";\n\n for(property in obj) {\n propCollection += (property + \": \" + obj[property] + \"<br>\");\n }\n\n log(propCollection);\n }\n\n\n function parseJSON(str) {\n var x_result = null;\n eval('x_result = ' + str);\n return x_result;\n }\n\n function parse() {\n //Setup\n var out = $('#output');\n var rawinput = $('#inputtext').val();\n var input = rawinput.split('');\n var stack = [];\n stack.top = function() {\n if (this.length == 0) return null;\n return this[this.length-1];\n }\n var jsonStrs = [];\n\n //Main Loop\n var ch = '';\n var top = '';\n var cursor = 0;\n var i = 0;\n while (i<input.length) {\n //Current Character\n ch = input[i];\n\n top = stack.top(); \n\n if(top == \"'\" || top == '\"') { //Ignore the rest of the string\n //You can add validation for possible unsafe javascript inside a string, here.\n\n ch = input[++i];\n\n while(ch != top) {\n i++;\n if(i>=input.length) {\n alert('malformed string');\n break;\n }\n ch = input[i];\n }\n stack.pop();\n\n } else {\n //You can add validation for unsafe javascript here.\n\n if(ch == ' ') {\n i++;\n continue; // Ignore spaces\n }\n\n if(ch == \"{\" || ch == \"'\" || ch == '\"') stack.push(ch);\n if(ch == \"}\") {\n if(top==\"{\") {\n stack.pop();\n } else {\n alert('malformed string');\n break;\n }\n\n if(stack.length == 0) {\n var str = rawinput.substring(cursor, i+1)\n jsonStrs.push(str);\n cursor = i+1;\n }\n }\n }\n\n i++;\n }\n\n return jsonStrs;\n }\n\n function log(msg) {\n document.getElementById('log').innerHTML += msg + '<br>';\n }\n\n </script>\n</head>\n\n<body>\n <textarea id=\"inputtext\" rows=\"5\" cols=\"40\" style=\"overflow:auto\">{foo:'bar'}</textarea><br>\n <button id=\"btnParse\" onclick=\"handleClick();\">Parse!</button><br /><br />\n\n <div id=\"output\">\n </div>\n\n <b>Results:</b>\n <div id=\"log\"></div>\n\n</body>\n</html>\n"
},
{
"answer_id": 354579,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 0,
"selected": false,
"text": "var jsonWrong = '{a:1}{a:2}{a:3}';\nvar jsonRight = jsonWrong.replace('}{', '},{');\nvar json = eval('('+jsonRight+')');\n"
},
{
"answer_id": 2706714,
"author": "user302811",
"author_id": 302811,
"author_profile": "https://Stackoverflow.com/users/302811",
"pm_score": 1,
"selected": false,
"text": "[\n {JSON},\n {JSON},\n {JSON},\n {JSON}\n]\n var string = \"{\\\"key\\\":\\\"val}{ue\\\"}{'key':'val}{ue'}{ \\\"asdf\\\" : 500 }\";\nvar result = string.match(/('.*?')|(\".*?\")|(\\d+)|({)|(:)|(})/g);\nvar newstring = \"\";\nfor (var i in result) {\n var next = parseInt(i) + 1;\n if (next <= result.length) {\n if (result[i] == \"}\" && result[next] == \"{\") {\n newstring += \"},\";\n }\n else {\n newstring += result[i];\n }\n}\n $.each(eval(newstring), function() {\n //code that uses the JSON values\n alert(this.value1);\n alert(this.value2);\n});\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
337,769 | <p>I use the following statement prepared and bound in ODBC:</p>
<pre><code>SELECT (CASE profile WHEN ? THEN 1 ELSE 2 END) AS profile_order
FROM engine_properties;
</code></pre>
<p>Executed in an ODBC 3.0 connection to an Oracle 10g database in AL32UTF8 charset, even after binding to a wchar_t string using <code>SQLBindParameter(SQL_C_WCHAR)</code>, it still gives the error ORA-12704: character set mismatch. </p>
<p>Why? I'm binding as wchar. Shouldn't a wchar be considered an NCHAR? </p>
<p>If I change the parameter to wrap it with <code>TO_NCHAR()</code> then the query works without error. However since these queries are used for multiple database backends, I don't want to add TO_NCHAR just on Oracle text bindings. Is there something that I am missing? Another way to solve this without the TO_NCHAR hammer?</p>
<p>I haven't been able to find anything relevant via searches or in the manuals.</p>
<p>More details...</p>
<p>-- error</p>
<pre><code>SELECT (CASE profile WHEN '_default' THEN 1 ELSE 2 END) AS profile_order
FROM engine_properties;
</code></pre>
<p>-- ok</p>
<pre><code>SELECT (CASE profile WHEN TO_NCHAR('_default') THEN 1 ELSE 2 END) AS profile_order
FROM engine_properties;
</code></pre>
<pre>
SQL> describe engine_properties;
Name Null? Type
----------------------------------------- -------- ----------------------------
EID NOT NULL NVARCHAR2(22)
LID NOT NULL NUMBER(11)
PROFILE NOT NULL NVARCHAR2(32)
PKEY NOT NULL NVARCHAR2(50)
VALUE NOT NULL NVARCHAR2(64)
READONLY NOT NULL NUMBER(5)
</pre>
<p>This version without TO_NCHAR works fine in SQL Server and PostgreSQL (via ODBC) and SQLite (direct). However in Oracle it returns "ORA-12704: character set mismatch".</p>
<pre><code>SQLPrepare(SELECT (CASE profile WHEN ? THEN 1 ELSE 2 END) AS profile_order
FROM engine_properties;) = SQL_SUCCESS
SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_WCHAR,
SQL_VARCHAR, 32, 0, "_default", 18, 16) = SQL_SUCCESS
SQLExecute() = SQL_ERROR
SQLGetDiagRec(1) = SQL_SUCCESS
[SQLSTATE: HY000, NATIVE: 12704, MESSAGE: [Oracle][ODBC]
[Ora]ORA-12704: character set mismatch]
SQLGetDiagRec(2) = SQL_NO_DATA
</code></pre>
<p>If I do use TO_NCHAR, it's okay (but won't work in SQL Server, Postgres, SQLite, etc).</p>
<pre><code>SQLPrepare(SELECT (CASE profile WHEN TO_NCHAR(?) THEN 1 ELSE 2 END) AS profile_order
FROM engine_properties;) = SQL_SUCCESS
SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_WCHAR,
SQL_VARCHAR, 32, 0, "_default", 18, 16) = SQL_SUCCESS
SQLExecute() = SQL_SUCCESS
SQLNumResultCols() = SQL_SUCCESS (count = 1)
SQLFetch() = SQL_SUCCESS
</code></pre>
| [
{
"answer_id": 337882,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 0,
"selected": false,
"text": "{\"foo\": \"}{\", \"bar\": 42}\n"
},
{
"answer_id": 337998,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 2,
"selected": false,
"text": "Define a stack\nDefine an array\nLOOP on each character in the string\n IF the top item of the stack is a single or double quote THEN\n LOOP through each character until you find a matching single or double quote, then pop it from the stack.\n ELSE\n IF \"{\", push onto the stack\n IF \"}\" THEN\n pop a \"{\" from the stack if it is on top \n IF the stack is empty THEN //we just finished a full json object\n Throw this json object into an array for later consumption\n END IF\n END IF\n IF single-quote, push onto the stack\n IF double-quote, push onto the stack \n END IF\nEND LOOP\n"
},
{
"answer_id": 339047,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 0,
"selected": false,
"text": "<html>\n<head>\n <script type=\"text/javascript\" src=\"jquery-1.2.6.js\"></script>\n <script type=\"text/javascript\">\n\n function handleClick() {\n var jsonStrs = parse();\n var jsonObjs = [];\n for(var j=0;j<jsonStrs.length;j++) jsonObjs.push( parseJSON(jsonStrs[j]) );\n\n //jsonObjs now contains an array of json objects \n\n document.getElementById('log').innerHTML = '';\n displayResults(jsonObjs);\n }\n\n function displayResults(jsonObjs) {\n for(var k=0; k<jsonObjs.length; k++) {\n ShowObjProperties(jsonObjs[k]);\n }\n }\n\n function ShowObjProperties(obj) {\n var property, propCollection = \"\";\n\n for(property in obj) {\n propCollection += (property + \": \" + obj[property] + \"<br>\");\n }\n\n log(propCollection);\n }\n\n\n function parseJSON(str) {\n var x_result = null;\n eval('x_result = ' + str);\n return x_result;\n }\n\n function parse() {\n //Setup\n var out = $('#output');\n var rawinput = $('#inputtext').val();\n var input = rawinput.split('');\n var stack = [];\n stack.top = function() {\n if (this.length == 0) return null;\n return this[this.length-1];\n }\n var jsonStrs = [];\n\n //Main Loop\n var ch = '';\n var top = '';\n var cursor = 0;\n var i = 0;\n while (i<input.length) {\n //Current Character\n ch = input[i];\n\n top = stack.top(); \n\n if(top == \"'\" || top == '\"') { //Ignore the rest of the string\n //You can add validation for possible unsafe javascript inside a string, here.\n\n ch = input[++i];\n\n while(ch != top) {\n i++;\n if(i>=input.length) {\n alert('malformed string');\n break;\n }\n ch = input[i];\n }\n stack.pop();\n\n } else {\n //You can add validation for unsafe javascript here.\n\n if(ch == ' ') {\n i++;\n continue; // Ignore spaces\n }\n\n if(ch == \"{\" || ch == \"'\" || ch == '\"') stack.push(ch);\n if(ch == \"}\") {\n if(top==\"{\") {\n stack.pop();\n } else {\n alert('malformed string');\n break;\n }\n\n if(stack.length == 0) {\n var str = rawinput.substring(cursor, i+1)\n jsonStrs.push(str);\n cursor = i+1;\n }\n }\n }\n\n i++;\n }\n\n return jsonStrs;\n }\n\n function log(msg) {\n document.getElementById('log').innerHTML += msg + '<br>';\n }\n\n </script>\n</head>\n\n<body>\n <textarea id=\"inputtext\" rows=\"5\" cols=\"40\" style=\"overflow:auto\">{foo:'bar'}</textarea><br>\n <button id=\"btnParse\" onclick=\"handleClick();\">Parse!</button><br /><br />\n\n <div id=\"output\">\n </div>\n\n <b>Results:</b>\n <div id=\"log\"></div>\n\n</body>\n</html>\n"
},
{
"answer_id": 354579,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 0,
"selected": false,
"text": "var jsonWrong = '{a:1}{a:2}{a:3}';\nvar jsonRight = jsonWrong.replace('}{', '},{');\nvar json = eval('('+jsonRight+')');\n"
},
{
"answer_id": 2706714,
"author": "user302811",
"author_id": 302811,
"author_profile": "https://Stackoverflow.com/users/302811",
"pm_score": 1,
"selected": false,
"text": "[\n {JSON},\n {JSON},\n {JSON},\n {JSON}\n]\n var string = \"{\\\"key\\\":\\\"val}{ue\\\"}{'key':'val}{ue'}{ \\\"asdf\\\" : 500 }\";\nvar result = string.match(/('.*?')|(\".*?\")|(\\d+)|({)|(:)|(})/g);\nvar newstring = \"\";\nfor (var i in result) {\n var next = parseInt(i) + 1;\n if (next <= result.length) {\n if (result[i] == \"}\" && result[next] == \"{\") {\n newstring += \"},\";\n }\n else {\n newstring += result[i];\n }\n}\n $.each(eval(newstring), function() {\n //code that uses the JSON values\n alert(this.value1);\n alert(this.value2);\n});\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31423/"
] |
337,781 | <p>In ASP.NET, the tilde (~) is treated as a token in URLs and treats paths prefixed with that as relative to the application root. This is well-known functionality.</p>
<p>In MOSS, there are other tokens, such as ~sitecollection/mypath... which behaves in a similar way, but treats the path as relative to the site collection root. How is this accomplished? After a cursory search I could not find any info on how to add tokens like this to the .NET URL resolution mechanism.</p>
| [
{
"answer_id": 436582,
"author": "dahlbyk",
"author_id": 54249,
"author_profile": "https://Stackoverflow.com/users/54249",
"pm_score": 4,
"selected": true,
"text": "<link runat=\"server\" rel=\"stylesheet\" type=\"text/css\"\n href=\"<% $SPUrl:~SiteCollection/Style Library/MyStyles/style.css %>\" />\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67/"
] |
337,784 | <p>I have created a mutli-column combobox in VB.net 2008 using windows forms 2.0. I am having trouble accessing data once selected to use in the remainder of the form. There does not seem to be a selected event to use in conjunction with the winform 2.0 combobox.</p>
<p>Does anyone have any experience using winforms 2.0? Also I guess a better question would be: is there a site with a break down of windows forms 2.0? As so far nothing seems to be that detailed including MSDN.</p>
| [
{
"answer_id": 436582,
"author": "dahlbyk",
"author_id": 54249,
"author_profile": "https://Stackoverflow.com/users/54249",
"pm_score": 4,
"selected": true,
"text": "<link runat=\"server\" rel=\"stylesheet\" type=\"text/css\"\n href=\"<% $SPUrl:~SiteCollection/Style Library/MyStyles/style.css %>\" />\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5578/"
] |
337,789 | <p>I have at my SQL Server 2000 Database a column with type <strong>Image</strong>. How can I map it into NHibernate?</p>
| [
{
"answer_id": 22835673,
"author": "Abhijit_Srikumar",
"author_id": 3446197,
"author_profile": "https://Stackoverflow.com/users/3446197",
"pm_score": 1,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n<hibernate-mapping xmlns=\"urn:nhibernate-mapping-2.2\" auto-import=\"true\">\n<class name=\"EAS.MINDSPACE.Infrastructure.Business.Entities.BlogMaster,EAS.MINDSPACE.Infrastructure.Business.Entities\" lazy=\"false\" table=\"BlogMaster\" schema=\"dbo\" >\n<id name=\"BlogId\" column=\"BlogId\">\n <generator class=\"native\" />\n</id>\n<property name=\"BlogData\" column=\"BlogData\" />\n<property name=\"BlogImage\" column=\"BlogImage\" length=\"2147483647\" />\n<property name=\"UserId\" column=\"UserId\" />\n <property name=\"CreatedByName\" column=\"CreatedBy\" />\n <property name=\"CreatedOn\" column=\"CreatedOn\" />\n <property name=\"ReplyCount\" column=\"ReplyCount\" />\n\n </class>\n</hibernate-mapping>\n"
},
{
"answer_id": 29388055,
"author": "Tobias",
"author_id": 734648,
"author_profile": "https://Stackoverflow.com/users/734648",
"pm_score": 0,
"selected": false,
"text": "Create table tblCompany (..., Logo image);\n <class name=\"Company\"\n table=\"tblCompany\">\n ... \n <property name=\"_logo\"\n column=\"Logo\"\n not-null=\"false\"\n length=\"2147483647\"\n access=\"field\" />\n ...\n</class>\n public class Company {\n ...\n private Image _logo;\n ...\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21668/"
] |
337,793 | <p>The log file from a JVM crash contains all sorts of useful information for debugging, such as shared libraries loaded and the complete environment. Can I force the JVM to generate one of these programmatically; either by executing code that crashes it or some other way? Or alternatively access the same information another way?</p>
| [
{
"answer_id": 67457102,
"author": "gmode",
"author_id": 3349358,
"author_profile": "https://Stackoverflow.com/users/3349358",
"pm_score": 1,
"selected": false,
"text": "kill -4 <PID>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19276/"
] |
337,797 | <p>When we use datatable.newrow command, a new empty row added to bottom of rows. However I want newrow to added to top of datatable. How can I make it?</p>
| [
{
"answer_id": 337818,
"author": "Nick DeVore",
"author_id": 1380,
"author_profile": "https://Stackoverflow.com/users/1380",
"pm_score": 7,
"selected": true,
"text": "myDataTable.Rows.InsertAt(myDataRow, 0);\n"
},
{
"answer_id": 3309475,
"author": "Ksamy",
"author_id": 399152,
"author_profile": "https://Stackoverflow.com/users/399152",
"pm_score": 2,
"selected": false,
"text": "myDataTable.Rows.InsertAt(0,myDataRow); \n myDataTable.Rows.InsertAt(myDataRow,0);\n"
},
{
"answer_id": 37050872,
"author": "Sunil Acharya",
"author_id": 2021533,
"author_profile": "https://Stackoverflow.com/users/2021533",
"pm_score": 5,
"selected": false,
"text": "DataRow newRow = myDataTable.NewRow();\nnewRow[0] = \"0\";\nnewRow[1] = \"Select one\";\nmyDataTable.Rows.InsertAt(newRow, 0);\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439507/"
] |
337,803 | <p>I have a ComponentResourceKey defined in my resource dictionary like this:</p>
<pre><code><Style x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:Resources}, ResourceId=BaseControlStyle}" TargetType="{x:Type FrameworkElement}">
<Setter Property="Margin" Value="4,4,0,0" />
</Style>
</code></pre>
<p>I have a static class that I use as a shortcut to provide the resource keys liek this:</p>
<pre><code>public class Resources
{
public static ComponentResourceKey BaseControlStyleKey
{
get
{
return new ComponentResourceKey(typeof(Resources), "BaseControlStyle");
}
}
}
</code></pre>
<p>Now typically when I use this style I do something like this:</p>
<pre><code><TextBlock Style="{DynamicResource {x:Static local:Resources.BaseControlStyleKey}}"/>
</code></pre>
<p>However, I have a scenario where I need to set a style in code like this:</p>
<pre><code>myTextBox.Style = Resources.BaseControlStyleKey // Does not work.
</code></pre>
<p>Any ideas how I extract the style from the ComponentResourceKey?</p>
| [
{
"answer_id": 337838,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 3,
"selected": true,
"text": "myTextBox.Style = \n Application.Current.TryFindResource(Resources.BaseControlStyleKey)\n as Style;\n"
},
{
"answer_id": 686136,
"author": "Denis Vuyka",
"author_id": 80816,
"author_profile": "https://Stackoverflow.com/users/80816",
"pm_score": 1,
"selected": false,
"text": "<Style x:Key=\"{ComponentResourceKey TypeInTargetAssembly={x:Type local:Resources}, ResourceId=BaseControlStyle}\" TargetType=\"{x:Type FrameworkElement}\">\n <Setter Property=\"Margin\" Value=\"4,4,0,0\" />\n</Style>\n <Style x:Key=\"{x:Static local:Resources.BaseControlStyle}\" TargetType=\"{x:Type FrameworkElement}\">\n <Setter Property=\"Margin\" Value=\"4,4,0,0\" />\n</Style>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17744/"
] |
337,853 | <p>We have a lot of unit tests but they aren't run every night. I have setup some batch files that compile all the code from the SVN repository and I would like to run NUnit. This is not a big problem because I can call it from the batch file after the compilation BUT the output is stored in the network drive and I need to open it every morning to check if errors happen. This is where the problem is.</p>
<p>Do you have a better way to do the same thing that will take the code from the repository, execute test and tell me in a "more fast convenient way" if errors appears?</p>
<p><strong>Update</strong>
I have installed Team City 4.0 and it work like a charm. Maybe Cruise Control .Net could have been done the same, but Team City website/documentation/features looked better. </p>
| [
{
"answer_id": 337983,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 0,
"selected": false,
"text": "type NUnitLogFile.txt>>tmp.txt\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/337853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.