qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
179,708
<p>Can anybody recommend a good method for determining the Rect of some wrapped text on an iPhone? I've tried all the built-in methods for NSString in the 2.1 SDK to no avail. The size methods never return sizes that allow me to completely fit wrapped text in my custom view.</p> <p>I'm drawing some user customizable text that should always be as big as possible within the limits of my custom view. If I can determine the rect needed to completely enclose wrapped text for a given max width and font size, I can raise or lower the font size until the text is just big enough to completely fill the custom view without being clipped.</p> <p>Any help is much appreciated!</p>
[ { "answer_id": 179963, "author": "Mike McMaster", "author_id": 544, "author_profile": "https://Stackoverflow.com/users/544", "pm_score": 2, "selected": false, "text": "<p>NSString's sizeWithFont:constrainedToSize: method might be useful:</p>\n\n<pre><code>CGSize sizeForText = [theText sizeWithFont:theFont constrainedToSize:CGSizeMake(myMaxWidth, 9999)];\n</code></pre>\n\n<p>You say you've tried all the size methods, but based on your description, it sounds like what you're looking for.</p>\n" }, { "answer_id": 179999, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 0, "selected": false, "text": "<p>Since you know your view size, call NSString's sizeWithFont:forWidth:lineBreakMode:, starting with your minimum font size, the width of your view, and UILineBreakModeWordWrap. Then increase the font size until the returned size is as tall as your view.</p>\n\n<p>If you want to set a maximum font size, you could also implement this as a binary search, rather than stepping up the font size.</p>\n" }, { "answer_id": 1804577, "author": "spstanley", "author_id": 96210, "author_profile": "https://Stackoverflow.com/users/96210", "pm_score": 0, "selected": false, "text": "<p>I found that whenever you set your UITextView's text property, it updates its contentSize property. That makes it very easy to resize the text view's frame for displaying within a scroll view, etc.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Can anybody recommend a good method for determining the Rect of some wrapped text on an iPhone? I've tried all the built-in methods for NSString in the 2.1 SDK to no avail. The size methods never return sizes that allow me to completely fit wrapped text in my custom view. I'm drawing some user customizable text that should always be as big as possible within the limits of my custom view. If I can determine the rect needed to completely enclose wrapped text for a given max width and font size, I can raise or lower the font size until the text is just big enough to completely fill the custom view without being clipped. Any help is much appreciated!
NSString's sizeWithFont:constrainedToSize: method might be useful: ``` CGSize sizeForText = [theText sizeWithFont:theFont constrainedToSize:CGSizeMake(myMaxWidth, 9999)]; ``` You say you've tried all the size methods, but based on your description, it sounds like what you're looking for.
179,713
<p>How can you change the <code>href</code> attribute (link target) for a hyperlink using jQuery?</p>
[ { "answer_id": 179717, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 12, "selected": true, "text": "<p>Using</p>\n\n<pre><code>$(\"a\").attr(\"href\", \"http://www.google.com/\")\n</code></pre>\n\n<p>will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. \"anchor\") anchor tags:</p>\n\n<pre><code>&lt;a name=\"MyLinks\"&gt;&lt;/a&gt;\n&lt;a href=\"http://www.codeproject.com/\"&gt;The CodeProject&lt;/a&gt;\n</code></pre>\n\n<p>...Then you probably don't want to accidentally add <code>href</code> attributes to them. For safety then, we can specify that our selector will only match <code>&lt;a&gt;</code> tags with an existing <code>href</code> attribute:</p>\n\n<pre><code>$(\"a[href]\") //...\n</code></pre>\n\n<p>Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing <code>href</code>, you might use something like this:</p>\n\n<pre><code>$(\"a[href='http://www.google.com/']\").attr('href', 'http://www.live.com/')\n</code></pre>\n\n<p>This will find links where the <code>href</code> exactly matches the string <code>http://www.google.com/</code>. A more involved task might be matching, then updating only part of the <code>href</code>:</p>\n\n<pre><code>$(\"a[href^='http://stackoverflow.com']\")\n .each(function()\n { \n this.href = this.href.replace(/^http:\\/\\/beta\\.stackoverflow\\.com/, \n \"http://stackoverflow.com\");\n });\n</code></pre>\n\n<p>The first part selects only links where the href <em>starts</em> with <code>http://stackoverflow.com</code>. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.</p>\n" }, { "answer_id": 179719, "author": "Peter Shinners", "author_id": 17209, "author_profile": "https://Stackoverflow.com/users/17209", "pm_score": 6, "selected": false, "text": "<p>Use the <code>attr</code> method on your lookup. You can switch out any attribute with a new value.</p>\n\n<pre><code>$(\"a.mylink\").attr(\"href\", \"http://cupcream.com\");\n</code></pre>\n" }, { "answer_id": 213166, "author": "flamingLogos", "author_id": 8161, "author_profile": "https://Stackoverflow.com/users/8161", "pm_score": 6, "selected": false, "text": "<p>Depending on whether you want to change all the identical links to something else or you want control over just the ones in a given section of the page or each one individually, you could do one of these.</p>\n\n<p>Change all links to Google so they point to Google Maps:</p>\n\n<pre><code>&lt;a href=\"http://www.google.com\"&gt;\n\n$(\"a[href='http://www.google.com/']\").attr('href', \n'http://maps.google.com/');\n</code></pre>\n\n<p>To change links in a given section, add the container div's class to the selector. This example will change the Google link in the content, but not in the footer:</p>\n\n<pre><code>&lt;div class=\"content\"&gt;\n &lt;p&gt;...link to &lt;a href=\"http://www.google.com/\"&gt;Google&lt;/a&gt;\n in the content...&lt;/p&gt;\n&lt;/div&gt;\n\n&lt;div class=\"footer\"&gt;\n Links: &lt;a href=\"http://www.google.com/\"&gt;Google&lt;/a&gt;\n&lt;/div&gt;\n\n$(\".content a[href='http://www.google.com/']\").attr('href', \n'http://maps.google.com/');\n</code></pre>\n\n<p>To change individual links regardless of where they fall in the document, add an id to the link and then add that id to the selector. This example will change the second Google link in the content, but not the first one or the one in the footer:</p>\n\n<pre><code>&lt;div class=\"content\"&gt;\n &lt;p&gt;...link to &lt;a href=\"http://www.google.com/\"&gt;Google&lt;/a&gt;\n in the content...&lt;/p&gt;\n &lt;p&gt;...second link to &lt;a href=\"http://www.google.com/\" \n id=\"changeme\"&gt;Google&lt;/a&gt;\n in the content...&lt;/p&gt;\n&lt;/div&gt;\n\n&lt;div class=\"footer\"&gt;\n Links: &lt;a href=\"http://www.google.com/\"&gt;Google&lt;/a&gt;\n&lt;/div&gt;\n\n$(\"a#changeme\").attr('href', \n'http://maps.google.com/');\n</code></pre>\n" }, { "answer_id": 4406279, "author": "crafter", "author_id": 475178, "author_profile": "https://Stackoverflow.com/users/475178", "pm_score": 4, "selected": false, "text": "<p>This snippet invokes when a link of class 'menu_link' is clicked, and shows the text and url of the link. The return false prevents the link from being followed.</p>\n\n<pre><code>&lt;a rel='1' class=\"menu_link\" href=\"option1.html\"&gt;Option 1&lt;/a&gt;\n&lt;a rel='2' class=\"menu_link\" href=\"option2.html\"&gt;Option 2&lt;/a&gt;\n\n$('.menu_link').live('click', function() {\n var thelink = $(this);\n alert ( thelink.html() );\n alert ( thelink.attr('href') );\n alert ( thelink.attr('rel') );\n\n return false;\n});\n</code></pre>\n" }, { "answer_id": 6348239, "author": "Jerome", "author_id": 798281, "author_profile": "https://Stackoverflow.com/users/798281", "pm_score": 8, "selected": false, "text": "<p>With jQuery 1.6 and above you should use:</p>\n\n<pre><code>$(\"a\").prop(\"href\", \"http://www.jakcms.com\")\n</code></pre>\n\n<p>The difference between <code>prop</code> and <code>attr</code> is that <code>attr</code> grabs the HTML attribute whereas <code>prop</code> grabs the DOM property.</p>\n\n<p>You can find more details in this post: <a href=\"https://stackoverflow.com/questions/5874652/prop-vs-attr\">.prop() vs .attr()</a></p>\n" }, { "answer_id": 28016553, "author": "Josh Crozier", "author_id": 2680216, "author_profile": "https://Stackoverflow.com/users/2680216", "pm_score": 6, "selected": false, "text": "<p><sub>Even though the OP explicitly asked for a jQuery answer, you don't need to use jQuery for everything these days. </sub></p>\n\n<h2>A few methods without jQuery:</h2>\n\n<ul>\n<li><p>If you want to change the <code>href</code> value of <strong><em>all</em></strong> <code>&lt;a&gt;</code> elements, select them all and then iterate through the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/NodeList\">nodelist</a>: <a href=\"http://jsfiddle.net/kqw7h1nq/\"><strong>(example)</strong></a></p>\n\n<pre><code>var anchors = document.querySelectorAll('a');\nArray.prototype.forEach.call(anchors, function (element, index) {\n element.href = \"http://stackoverflow.com\";\n});\n</code></pre></li>\n<li><p>If you want to change the <code>href</code> value of all <code>&lt;a&gt;</code> elements that actually have an <code>href</code> attribute, select them by adding the <code>[href]</code> attribute selector (<code>a[href]</code>): <a href=\"http://jsfiddle.net/pLkr9497/\"><strong>(example)</strong></a></p>\n\n<pre><code>var anchors = document.querySelectorAll('a[href]');\nArray.prototype.forEach.call(anchors, function (element, index) {\n element.href = \"http://stackoverflow.com\";\n});\n</code></pre></li>\n<li><p>If you want to change the <code>href</code> value of <code>&lt;a&gt;</code> elements that <em>contain</em> a specific value, for instance <code>google.com</code>, use the attribute selector <code>a[href*=\"google.com\"]</code>: <a href=\"http://jsfiddle.net/eLw5svh2/\"><strong>(example)</strong></a></p>\n\n<pre><code>var anchors = document.querySelectorAll('a[href*=\"google.com\"]');\nArray.prototype.forEach.call(anchors, function (element, index) {\n element.href = \"http://stackoverflow.com\";\n});\n</code></pre>\n\n<p>Likewise, you can also use the other <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors\">attribute selectors</a>. For instance:</p>\n\n<ul>\n<li><p><code>a[href$=\".png\"]</code> could be used to select <code>&lt;a&gt;</code> elements whose <code>href</code> value ends with <code>.png</code>.</p></li>\n<li><p><code>a[href^=\"https://\"]</code> could be used to select <code>&lt;a&gt;</code> elements with <code>href</code> values that are <em>prefixed</em> with <code>https://</code>.</p></li>\n</ul></li>\n<li><p>If you want to change the <code>href</code> value of <code>&lt;a&gt;</code> elements that satisfy multiple conditions: <a href=\"http://jsfiddle.net/8fxekxLu/\"><strong>(example)</strong></a></p>\n\n<pre><code>var anchors = document.querySelectorAll('a[href^=\"https://\"], a[href$=\".png\"]');\nArray.prototype.forEach.call(anchors, function (element, index) {\n element.href = \"http://stackoverflow.com\";\n});\n</code></pre></li>\n</ul>\n\n<p>..no need for regex, in <em>most</em> cases.</p>\n" }, { "answer_id": 31382408, "author": "Anup", "author_id": 2047151, "author_profile": "https://Stackoverflow.com/users/2047151", "pm_score": 3, "selected": false, "text": "<pre><code> $(\"a[href^='http://stackoverflow.com']\")\n .each(function()\n { \n this.href = this.href.replace(/^http:\\/\\/beta\\.stackoverflow\\.com/, \n \"http://stackoverflow.com\");\n });\n</code></pre>\n" }, { "answer_id": 39276418, "author": "Pawel", "author_id": 696535, "author_profile": "https://Stackoverflow.com/users/696535", "pm_score": 4, "selected": false, "text": "<p>Stop using jQuery just for the sake of it! This is so simple with JavaScript only.</p>\n\n<pre><code>document.querySelector('#the-link').setAttribute('href', 'http://google.com');\n</code></pre>\n\n<p><a href=\"https://jsfiddle.net/bo77f8mg/1/\" rel=\"noreferrer\">https://jsfiddle.net/bo77f8mg/1/</a></p>\n" }, { "answer_id": 43006005, "author": "Cooper", "author_id": 7215091, "author_profile": "https://Stackoverflow.com/users/7215091", "pm_score": 2, "selected": false, "text": "<h1>Change the HREF of the Wordpress Avada Theme Logo Image</h1>\n\n<p>If you install the ShortCode Exec PHP plugin the you can create this Shortcode which I called myjavascript</p>\n\n<pre><code>?&gt;&lt;script type=\"text/javascript\"&gt;\njQuery(document).ready(function() {\njQuery(\"div.fusion-logo a\").attr(\"href\",\"tel:303-985-9850\");\n});\n&lt;/script&gt;\n</code></pre>\n\n<p>You can now go to Appearance/Widgets and pick one of the footer widget areas and use a text widget to add the following shortcode</p>\n\n<pre><code>[myjavascript]\n</code></pre>\n\n<p>The selector may change depending upon what image your using and if it's retina ready but you can always figure it out by using developers tools. </p>\n" }, { "answer_id": 49568546, "author": "Aman Chhabra", "author_id": 1262248, "author_profile": "https://Stackoverflow.com/users/1262248", "pm_score": 4, "selected": false, "text": "<p>The simple way to do so is : </p>\n\n<p><strong><a href=\"http://api.jquery.com/attr/#attr2\" rel=\"noreferrer\">Attr function</a> (since jQuery version 1.0)</strong> </p>\n\n<pre><code>$(\"a\").attr(\"href\", \"https://stackoverflow.com/\") \n</code></pre>\n\n<p>or</p>\n\n<p><strong><a href=\"http://api.jquery.com/prop/#prop2\" rel=\"noreferrer\">Prop function</a> (since jQuery version 1.6)</strong></p>\n\n<pre><code>$(\"a\").prop(\"href\", \"https://stackoverflow.com/\")\n</code></pre>\n\n<p>Also, the advantage of above way is that if selector selects a single anchor, it will update that anchor only and if selector returns a group of anchor, it will update the specific group through one statement only.</p>\n\n<p>Now, there are lot of ways to identify exact anchor or group of anchors:</p>\n\n<p><strong>Quite Simple Ones:</strong></p>\n\n<ol>\n<li>Select anchor through tag name : <code>$(\"a\")</code></li>\n<li>Select anchor through index: <code>$(\"a:eq(0)\")</code></li>\n<li>Select anchor for specific classes (as in this class only anchors\nwith class <code>active</code>) : <code>$(\"a.active\")</code></li>\n<li>Selecting anchors with specific ID (here in example <code>profileLink</code>\nID) : <code>$(\"a#proileLink\")</code></li>\n<li>Selecting first anchor href: <code>$(\"a:first\")</code></li>\n</ol>\n\n<p><strong>More useful ones:</strong></p>\n\n<ol start=\"6\">\n<li>Selecting all elements with href attribute : <code>$(\"[href]\")</code></li>\n<li>Selecting all anchors with specific href: <code>$(\"a[href='www.stackoverflow.com']\")</code></li>\n<li>Selecting all anchors not having specific href: <code>$(\"a[href!='www.stackoverflow.com']\")</code></li>\n<li>Selecting all anchors with href containing specific URL: <code>$(\"a[href*='www.stackoverflow.com']\")</code></li>\n<li>Selecting all anchors with href starting with specific URL: <code>$(\"a[href^='www.stackoverflow.com']\")</code></li>\n<li>Selecting all anchors with href ending with specific URL: <code>$(\"a[href$='www.stackoverflow.com']\")</code></li>\n</ol>\n\n<p>Now, if you want to amend specific URLs, you can do that as:</p>\n\n<p>For instance if you want to add proxy website for all the URLs going to google.com, you can implement it as follows:</p>\n\n<pre><code>$(\"a[href^='http://www.google.com']\")\n .each(function()\n { \n this.href = this.href.replace(/http:\\/\\/www.google.com\\//gi, function (x) {\n return \"http://proxywebsite.com/?query=\"+encodeURIComponent(x);\n });\n });\n</code></pre>\n" }, { "answer_id": 54263304, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 3, "selected": false, "text": "<p><code>href</code> in an attribute, so you can change it using pure JavaScript, but if you already have jQuery injected in your page, don't worry, I will show it both ways:</p>\n\n<p>Imagine you have this <code>href</code> below:</p>\n\n<pre><code>&lt;a id=\"ali\" alt=\"Ali\" href=\"http://dezfoolian.com.au\"&gt;Alireza Dezfoolian&lt;/a&gt;\n</code></pre>\n\n<p>And you like to change it the link...</p>\n\n<p>Using <strong>pure JavaScript</strong> without any library you can do:</p>\n\n<pre><code>document.getElementById(\"ali\").setAttribute(\"href\", \"https://stackoverflow.com\");\n</code></pre>\n\n<p>But also in <strong>jQuery</strong> you can do:</p>\n\n<pre><code>$(\"#ali\").attr(\"href\", \"https://stackoverflow.com\");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$(\"#ali\").prop(\"href\", \"https://stackoverflow.com\");\n</code></pre>\n\n<p>In this case, if you already have jQuery injected, probably jQuery one look shorter and more cross-browser...but other than that I go with the <code>JS</code> one...</p>\n" }, { "answer_id": 62503176, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 2, "selected": false, "text": "<p>Try</p>\n<pre><code>link.href = 'https://...'\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>link.href = 'https://stackoverflow.com'</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;a id=\"link\" href=\"#\"&gt;Click me&lt;/a&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 70064573, "author": "CooleKikker2", "author_id": 16966832, "author_profile": "https://Stackoverflow.com/users/16966832", "pm_score": 4, "selected": false, "text": "<p>Try this;</p>\n<pre><code>$(&quot;#link&quot;).attr(&quot;href&quot;, &quot;https://coenvink.com/&quot;)\n</code></pre>\n<p>A breakdown of what the code does:</p>\n<pre><code>$(&quot;#link&quot;)\n</code></pre>\n<p>This part of the code gets the element with id &quot;Link&quot;. After this you set the attribute 'href' (witch is basically the link-to-url) to your new url, witch, in this case, is my own website:</p>\n<pre><code>.attr(&quot;href&quot;, &quot;https://coenvink.com/&quot;)\n</code></pre>\n<p>I hope it is clear now!</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
How can you change the `href` attribute (link target) for a hyperlink using jQuery?
Using ``` $("a").attr("href", "http://www.google.com/") ``` will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags: ``` <a name="MyLinks"></a> <a href="http://www.codeproject.com/">The CodeProject</a> ``` ...Then you probably don't want to accidentally add `href` attributes to them. For safety then, we can specify that our selector will only match `<a>` tags with an existing `href` attribute: ``` $("a[href]") //... ``` Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing `href`, you might use something like this: ``` $("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/') ``` This will find links where the `href` exactly matches the string `http://www.google.com/`. A more involved task might be matching, then updating only part of the `href`: ``` $("a[href^='http://stackoverflow.com']") .each(function() { this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/, "http://stackoverflow.com"); }); ``` The first part selects only links where the href *starts* with `http://stackoverflow.com`. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.
179,723
<p>By that I mean, what do I need to do to have useful assertions in my code?</p> <p>MFC is quite easy, i just use ASSERT(something).</p> <p>What's the non-MFC way?</p> <p><strong>Edit:</strong> Is it possible to stop assert breaking in assert.c rather than than my file which called assert()?</p> <p><strong>Edit:</strong> What's the difference between <code>&lt;assert.h&gt;</code> &amp; <code>&lt;cassert&gt;</code>?</p> <p><strong>Accepted Answer:</strong> Loads of great answers in this post, I wish I could accept more than one answer (or someone would combine them all). So answer gets awarded to Ferruccio (for first answer).</p>
[ { "answer_id": 179733, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 6, "selected": true, "text": "<pre><code>#include &lt;cassert&gt;\n\nassert(something);\n</code></pre>\n\n<p>and for compile-time checking, Boost's static asserts are pretty useful:</p>\n\n<pre><code>#include &lt;boost/static_assert.hpp&gt;\n\nBOOST_STATIC_ASSERT(sizeof(int) == 4); // compile fails if ints aren't 32-bit\n</code></pre>\n" }, { "answer_id": 179778, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 3, "selected": false, "text": "<p>To break inside the file that called the assert, you can use a custom macro that throws an exception or calls <code>__debugbreak</code>:</p>\n\n<pre><code>#define MYASSERT(EXPR, MSG) if (!(EXPR)) throw MSG;\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>#define MYASSERT(EXPR) if (!(EXPR)) __debugbreak();\n</code></pre>\n" }, { "answer_id": 179802, "author": "philant", "author_id": 18804, "author_profile": "https://Stackoverflow.com/users/18804", "pm_score": 3, "selected": false, "text": "<p>To answer the question in your second \"edit\": </p>\n\n<p>&lt; assert.h> is the C header</p>\n\n<p>&lt; cassert> is the C++ Standard Library header ... it typically includes &lt; assert.h></p>\n" }, { "answer_id": 179848, "author": "Dustin Getz", "author_id": 20003, "author_profile": "https://Stackoverflow.com/users/20003", "pm_score": 1, "selected": false, "text": "<p>use intellisense to open it in visual studio (right click)</p>\n\n<pre><code>// cassert standard header\n#include &lt;yvals.h&gt;\n#include &lt;assert.h&gt;\n</code></pre>\n\n<p>yvals.h is windows stuff. so, as far as assert() itself is concerned, the two ways to include it are identical. it's good practice to use the <code>&lt;cxxx&gt;</code> because often it isn't that simple (namespace wrapping and maybe other magic)</p>\n\n<p>This breaks at caller site for me...</p>\n\n<p>here's an <a href=\"http://powerof2games.com/node/10\" rel=\"nofollow noreferrer\">article</a> explaining why you don't want to write this macro yourself.</p>\n" }, { "answer_id": 179876, "author": "Miquella", "author_id": 16313, "author_profile": "https://Stackoverflow.com/users/16313", "pm_score": 4, "selected": false, "text": "<p>It depends on whether or not you are looking for something that works outside of Visual C++. It also depends on what type of assertion you are looking for.</p>\n\n<p>There are a few types of assertions:</p>\n\n<ol>\n<li><p><strong>Preprocessor</strong><br>\nThese assertions are done using the preprocessor directive <code>#error</code><br>\nPreprocessor assertions are only evaluated during the preprocessing phase, and therefore are not useful for things such as templates.</p></li>\n<li><p><strong>Execute Time</strong><br>\nThese assertions are done using the <code>assert()</code> function defined in <code>&lt;cassert&gt;</code><br>\nExecute time assertions are only evaluated at run-time. And as BoltBait pointed out, are not compiled in if the <code>NDEBUG</code> macro has been defined.</p></li>\n<li><p><strong>Static</strong><br>\nThese assertions are done, as you said, by using the <code>ASSERT()</code> macro, but only if you are using MFC. I do not know of another way to do static assertions that is part of the C/C++ standard, however, the Boost library offers another solution: <code>static_assert</code>.<br>\nThe <code>static_assert</code> function from the Boost library is something that is going to be added in the <a href=\"http://en.wikipedia.org/wiki/C++0x\" rel=\"noreferrer\">C++0x standard</a>.</p></li>\n</ol>\n\n<p>As an additional warning, the <code>assert()</code> function that Ferruccio suggested does not have the same behavior as the MFC <code>ASSERT()</code> macro. The former is an execute time assertion, while the later is a static assertion.</p>\n\n<p>I hope this helps!</p>\n" }, { "answer_id": 179883, "author": "Michael Labbé", "author_id": 22244, "author_profile": "https://Stackoverflow.com/users/22244", "pm_score": 3, "selected": false, "text": "<h2>Basic Assert Usage</h2>\n\n<pre><code>#include &lt;cassert&gt;\n\n/* Some code later */\nassert( true );\n</code></pre>\n\n<h3>Best Practice Notes</h3>\n\n<p>Asserts are used to identify <em>runtime states that should be true</em>. As a result, they are compiled out in release mode. </p>\n\n<p>If you have a situation where you want an assert to always hit, you can pass false to it. For example:</p>\n\n<pre><code>switch ( someVal ):\n{\ncase 0:\ncase 1:\n break;\ndefault:\n assert( false ); /* should never happen */\n}\n</code></pre>\n\n<p>It is also possible to pass a message through assert:</p>\n\n<pre><code>assert( !\"This assert will always hit.\" );\n</code></pre>\n\n<p>Mature codebases frequently extend the assert functionality. Some of the common extensions include:</p>\n\n<ul>\n<li>Toggling asserts on a per-module basis to localize testing.</li>\n<li>Creating an additional assert macro that is compiled out in most debug builds. This is desirable for code that is called very frequently (millions of times per second) and is unlikely to be incorrect.</li>\n<li>Allowing users to disable the currently hit assert, all asserts in the compilation unit or all asserts in the codebase. This stops benign asserts from being triggered, creating unusable builds.</li>\n</ul>\n" }, { "answer_id": 180109, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 3, "selected": false, "text": "<p><strong>Microsoft-specific CRT asserts</strong></p>\n\n<pre><code>#include &lt;crtdbg.h&gt;\n#include &lt;sstream&gt;\n...\n// displays nondescript message box when x &lt;= 42\n_ASSERT(x &gt; 42);\n// displays message box with \"x &gt; 42\" message when x &lt;= 42\n_ASSERTE(x &gt; 42);\n// displays message box with computed message \"x is ...!\" when x &lt;= 42\n_ASSERT_EXPR(\n x &gt; 42, (std::stringstream() &lt;&lt; L\"x is \" &lt;&lt; x &lt;&lt; L\"!\").str().c_str());\n</code></pre>\n" }, { "answer_id": 180493, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 3, "selected": false, "text": "<h2>Assert is (usually) Debug Only</h2>\n<p>The problem with &quot;assert&quot; is that it is usually in debug binaries, and that some developers use them as if the code would still be in production.</p>\n<p>This is not evil per se, as the code is supposed to be intensively tested, and thus, the bugs producing the assert will surely be discovered, and removed.</p>\n<p>But sometimes (most of the times?), the tests are not as intensive as wanted. I won't speak about an old job where we had to code until the very last minute (<i>don't asks... Sometimes, managers are just... Ahem...</i>)... What's the point of an assert you adding to a code that will be compiled and delivered as a Release Binary to the client the next minute?</p>\n<h2>Assert in (some) real life applications</h2>\n<p>In our team, we needed something to detect the error, and at the same time something else to handle the error. And we needed it, potentially, on Release Build.</p>\n<p>Assert will both detect and handle the error only on debug build.</p>\n<p>So we added instead a XXX_ASSERT macro, as well as a XXX_RAISE_ERROR macro.</p>\n<p>The XXX_ASSERT macro would do the same thing as the ASSERT macro, but it would be built both in Debug and in Release. Its behaviour (write a log, open a messagebox, do nothing, etc.) could be controlled by a .INI file, and THEN, it would abort/exit the application.</p>\n<p>This was used as:</p>\n<pre><code>bool doSomething(MyObject * p)\n{\n // If p is NULL, then the app will abort/exit\n XXX_ASSERT((p != NULL), &quot;Hey ! p is NULL !&quot;) ;\n \n // etc.\n}\n</code></pre>\n<p>XXX_RAISE_ERROR macro would only &quot;log&quot; the error but would not try to handle it. This means that it could log the message in a file and/or open a MessageBox with the message , and a button to continue, and another to launch a debug session (as per .INI file config). This was used as:</p>\n<pre><code>bool doSomething(MyObject * p)\n{\n if(p == NULL)\n {\n // First, XXX_RAISE_ERROR will alert the user as configured in the INI file\n // perhaps even offering to open a debug session\n XXX_RAISE_ERROR(&quot;Hey ! p is NULL !&quot;) ;\n // here, you can handle the error as you wish\n // Than means allocating p, or throwing an exception, or\n // returning false, etc.\n // Whereas the XXX_ASSERT could simply crash.\n }\n \n // etc.\n}\n</code></pre>\n<p>One year after their introduction in our libs, only XXX_RAISE_ERROR is being used. Of course, it can't be used on time-critical parts of the app (we have a XXX_RAISE_ERROR_DBG for that), but everywhere else, it is good. And the facts that one can use whatever prefered error handling, and that it can be activated at will, either on the developer computer, or the tester, or even the user, is quite useful.</p>\n" }, { "answer_id": 1747422, "author": "Mike Lowe", "author_id": 212699, "author_profile": "https://Stackoverflow.com/users/212699", "pm_score": 2, "selected": false, "text": "<p>There is a more advanced open source library called ModAssert, that has assertions that work on both Visual C++ and gcc. Probably also on other compilers, don't know for sure. It takes some time to learn it, but if you want good assertions that don't depend on MFC, look at these. It's at <a href=\"http://sourceforge.net/projects/modassert/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/modassert/</a></p>\n" }, { "answer_id": 21687218, "author": "Gregory Pakosz", "author_id": 216063, "author_profile": "https://Stackoverflow.com/users/216063", "pm_score": 1, "selected": false, "text": "<p>Here is my most recent iteration of an Assertion facility in C++: <a href=\"http://pempek.net/articles/2013/11/17/cross-platform-cpp-assertion-library/\" rel=\"nofollow\">http://pempek.net/articles/2013/11/17/cross-platform-cpp-assertion-library/</a></p>\n\n<p>It's a drop-in 2 files lib you can easily add to your project.</p>\n" }, { "answer_id": 27034242, "author": "metamorphosis", "author_id": 3454889, "author_profile": "https://Stackoverflow.com/users/3454889", "pm_score": 1, "selected": false, "text": "<p>To answer the asker's third question:\nthe first reason we use \"cassert\" instead of \"assert.h\" is because, in the case of C++, there's an allowance made for the fact that the C++ compiler may not store the function descriptions in code files, but in a dll or in the compiler itself.\nThe second is that there may be minor changes made to functions in order to facilitate the differences between C and C++, either present or in the future. Because assert.h is a C library, the preference is to use \"cassert\" while in C++.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
By that I mean, what do I need to do to have useful assertions in my code? MFC is quite easy, i just use ASSERT(something). What's the non-MFC way? **Edit:** Is it possible to stop assert breaking in assert.c rather than than my file which called assert()? **Edit:** What's the difference between `<assert.h>` & `<cassert>`? **Accepted Answer:** Loads of great answers in this post, I wish I could accept more than one answer (or someone would combine them all). So answer gets awarded to Ferruccio (for first answer).
``` #include <cassert> assert(something); ``` and for compile-time checking, Boost's static asserts are pretty useful: ``` #include <boost/static_assert.hpp> BOOST_STATIC_ASSERT(sizeof(int) == 4); // compile fails if ints aren't 32-bit ```
179,742
<p>VB 2008.</p> <p>I have several text boxes on a form and I want each of them to use the same event handler. I know how to manually wire each one up to the handler, but I'm looking for a more generic way so if I add more text boxes they will automatically be hooked up to the event handler.</p> <p>Ideas?</p> <p>EDIT: Using the C# sample from MusiGenesis (and with the help of the comment left by nick), I wrote this VB code:</p> <pre><code>Private Sub AssociateTextboxEventHandler() For Each c As Control In Me.Controls If TypeOf c Is TextBox Then AddHandler c.TextChanged, AddressOf tb_TextChanged End If Next End Sub </code></pre> <p>Thanks a lot! SO is great.</p>
[ { "answer_id": 179771, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>It might be possible with a macro, but otherwise, I a m not aware of anything that would automatically wire an control to a generic handler.</p>\n\n<p>The only easy way I know of would be to select all appliciable textboxes, and simply set the eventhandler for the click event at the same time, but that isn't automatic.</p>\n" }, { "answer_id": 179817, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 2, "selected": false, "text": "<p>You could recursively iterate over the Controls collection in the OnLoad of the form and assign the event handler to any text boxes you find.</p>\n" }, { "answer_id": 179824, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 4, "selected": true, "text": "<p>Do something like this in your form's load event (C#, sorry, but it's easy to translate):</p>\n\n<pre><code>private void Form1_Load(object sender, EventArgs e)\n{\n foreach (Control ctrl in this.Controls)\n {\n if (ctrl is TextBox)\n {\n TextBox tb = (TextBox)ctrl;\n tb.TextChanged += new EventHandler(tb_TextChanged);\n }\n }\n\n}\n\nvoid tb_TextChanged(object sender, EventArgs e)\n{\n TextBox tb = (TextBox)sender;\n tb.Tag = \"CHANGED\"; // or whatever\n}\n</code></pre>\n\n<p>It's not properly recursive (it won't find text boxes on panels, for example), but you get the idea.</p>\n" }, { "answer_id": 179923, "author": "osp70", "author_id": 2357, "author_profile": "https://Stackoverflow.com/users/2357", "pm_score": 0, "selected": false, "text": "<p>I think this will update all text controls: </p>\n\n<pre><code>Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load\n UpdateControls(Me)\nEnd Sub\n\nPrivate Sub UpdateControls(ByVal myControlIN As Control)\n Dim myControl\n\n For Each myControl In myControlIN.Controls\n UpdateControls(myControl)\n Dim myTextbox As TextBox\n\n If TypeOf myControl Is TextBox Then\n myTextbox = myControl\n AddHandler myTextbox.TextChanged, AddressOf TextBox_TextChanged\n End If\n Next\n\nEnd Sub\n\nPrivate Sub TextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)\n MsgBox(\"text changed in \" &amp; CType(sender, TextBox).Name)\nEnd Sub\n</code></pre>\n" }, { "answer_id": 20282205, "author": "Sergio", "author_id": 1622364, "author_profile": "https://Stackoverflow.com/users/1622364", "pm_score": 2, "selected": false, "text": "<p>\"c As Control\" has no \"TextChanged\" event, so it will throw an error.\nYou may optimize that to Linq and also get rid of that error with:</p>\n\n<pre><code>For Each c As TextBox In Controls.OfType(Of TextBox)()\n AddHandler c.TextChanged, AddressOf tb_TextChanged\nNext\n</code></pre>\n\n<p>But that would avoid to go deeper than first level thou.</p>\n" }, { "answer_id": 34000103, "author": "hirnwunde", "author_id": 3382612, "author_profile": "https://Stackoverflow.com/users/3382612", "pm_score": 0, "selected": false, "text": "<p>I have many Textboxes inside many GroupBoxes inside a TabPage-Control.</p>\n\n<p>To add/define/delete the Handler of those Textboxes i had to iterate first through the Tabpages, then through the Groupboxes in every Tabpage and then i can access the Textboxes inside these Groupboxes.</p>\n\n<pre><code>' cycle through TabPages ...\nFor Each page As TabPage In Me.TabControl1.Controls.OfType(Of TabPage)()\n ' in every TabPage cycle through Groupboxes ...\n For Each gbox As GroupBox In page.Controls.OfType(Of GroupBox)()\n ' and in every TextBox inside the actual GroupBox\n For Each tbox As TextBox In gbox.Controls.OfType(Of TextBox)()\n AddHandler tbox.TextChanged, AddressOf _TextChanged\n Next\n Next\nNext\n\nPrivate Sub _TextChanged(sender As System.Object, e As System.EventArgs)\n somethingWasChanged = True\nEnd Sub\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2441/" ]
VB 2008. I have several text boxes on a form and I want each of them to use the same event handler. I know how to manually wire each one up to the handler, but I'm looking for a more generic way so if I add more text boxes they will automatically be hooked up to the event handler. Ideas? EDIT: Using the C# sample from MusiGenesis (and with the help of the comment left by nick), I wrote this VB code: ``` Private Sub AssociateTextboxEventHandler() For Each c As Control In Me.Controls If TypeOf c Is TextBox Then AddHandler c.TextChanged, AddressOf tb_TextChanged End If Next End Sub ``` Thanks a lot! SO is great.
Do something like this in your form's load event (C#, sorry, but it's easy to translate): ``` private void Form1_Load(object sender, EventArgs e) { foreach (Control ctrl in this.Controls) { if (ctrl is TextBox) { TextBox tb = (TextBox)ctrl; tb.TextChanged += new EventHandler(tb_TextChanged); } } } void tb_TextChanged(object sender, EventArgs e) { TextBox tb = (TextBox)sender; tb.Tag = "CHANGED"; // or whatever } ``` It's not properly recursive (it won't find text boxes on panels, for example), but you get the idea.
179,752
<p>Lets say on my page I have this function:</p> <pre><code> function ReturnFoo(bar) { return bar.toString() + "foo"; } </code></pre> <p>Now, I would like to have this called from ASP .NET, hopefully with the ASP .NET AJAX framework, as I am already using it in this codebase (I have already spent the 100k, might as well use it).</p> <p>Also, I would like to get back the output that is returned from this function and then assign it to a variable created on the server side. And this is restricted to ASP .NET 2.0</p>
[ { "answer_id": 179776, "author": "Matt", "author_id": 17759, "author_profile": "https://Stackoverflow.com/users/17759", "pm_score": 0, "selected": false, "text": "<p>I don't see how you expect server-side code to call a client-side function???</p>\n\n<p>AJAX calls are from the client-side to the server-side!</p>\n" }, { "answer_id": 179785, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 0, "selected": false, "text": "<p>I have done this before by using a text control marked as hidden with autopostback on change. Then, the function sets the text of that control which triggers a postback.</p>\n\n<p>To call the function from the server side, simply register some startup script and it will run when the page renders.</p>\n" }, { "answer_id": 179801, "author": "Vijesh VP", "author_id": 22016, "author_profile": "https://Stackoverflow.com/users/22016", "pm_score": 0, "selected": false, "text": "<p>If your intention is to reuse some functions in both server side and client side, I would suggest to write that function in server side (aspx or asmx) and call it from client side (JavaScript) using AJAX. Not sure whether you are looking for this.</p>\n" }, { "answer_id": 179804, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>Any time you transition between server-side and client-side, it's like the user clicked the refresh button on their browser in terms of performance.</p>\n\n<p>Is that really what you want to do, since your proposed scenario would mean at least two post-backs. </p>\n\n<p>What is the purpose of this? It would be better if you could keep this at the client.</p>\n" }, { "answer_id": 179815, "author": "Craig Wilson", "author_id": 25333, "author_profile": "https://Stackoverflow.com/users/25333", "pm_score": 1, "selected": false, "text": "<p>Yeah, this is a difficult one. Using MS Ajax will help you out a bit. You'll need to push in code from the server to call this function upon page load and assign the return value to a hidden field that can be accessed by the server on post back.</p>\n\n<p>I must say that this solution sucks, but I don't know another way. Hopefully, someone will have a better solution.</p>\n" }, { "answer_id": 233007, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 0, "selected": false, "text": "<p>In the first answer, Matt mentioned that this is not possible (to execute client-side code while still on the server). And that's true.</p>\n\n<p>Your comment about silverlight is not really accurate. Silverlight can't call client-side code <em>from the server</em>. Silverlight runs on the client just like JavaScript, so that's a client-to-client call.</p>\n\n<p>Can you clarify the scenario a bit... here's what I think you're asking:</p>\n\n<pre><code>private void Page_Load()\n{\n string someValue = EXECUTE_JS_ON_CLIENT_AND_GET_RESULT();\n\n // do some stuff here while still on the server...\n}\n</code></pre>\n\n<p>If this is what you want to do, it's not possible. While on the server, you can't communicate with the client.</p>\n\n<p>Is that what you meant?</p>\n\n<p>Thanks,\n-Timothy</p>\n" }, { "answer_id": 423381, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Write simply where you have to call javascript</p>\n\n<p>Response.Write(\n\" alert('hello');\")</p>\n" }, { "answer_id": 423389, "author": "Chris Missal", "author_id": 29689, "author_profile": "https://Stackoverflow.com/users/29689", "pm_score": 0, "selected": false, "text": "<p>I would check out JSON.Net (combined with a library [jQuery is also free]) they're open source solutions that makes these problems a lot easier.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952/" ]
Lets say on my page I have this function: ``` function ReturnFoo(bar) { return bar.toString() + "foo"; } ``` Now, I would like to have this called from ASP .NET, hopefully with the ASP .NET AJAX framework, as I am already using it in this codebase (I have already spent the 100k, might as well use it). Also, I would like to get back the output that is returned from this function and then assign it to a variable created on the server side. And this is restricted to ASP .NET 2.0
Yeah, this is a difficult one. Using MS Ajax will help you out a bit. You'll need to push in code from the server to call this function upon page load and assign the return value to a hidden field that can be accessed by the server on post back. I must say that this solution sucks, but I don't know another way. Hopefully, someone will have a better solution.
179,779
<p>I am writing code for a search results page that needs to highlight search terms. The terms happen to occur within table cells (the app is iterating through GridView Row Cells), and these table cells may have HTML.</p> <p>Currently, my code looks like this (relevant hunks shown below):</p> <pre><code>const string highlightPattern = @"&lt;span class=""Highlight""&gt;$0&lt;/span&gt;"; DataBoundLiteralControl litCustomerComments = (DataBoundLiteralControl)e.Row.Cells[CUSTOMERCOMMENTS_COLUMN].Controls[0]; // Turn "term1 term2" into "(term1|term2)" string spaceDelimited = txtTextFilter.Text.Trim(); string pipeDelimited = string.Join("|", spaceDelimited.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries)); string searchPattern = "(" + pipeDelimited + ")"; // Highlight search terms in Customer - Comments column e.Row.Cells[CUSTOMERCOMMENTS_COLUMN].Text = Regex.Replace(litCustomerComments.Text, searchPattern, highlightPattern, RegexOptions.IgnoreCase); </code></pre> <p>Amazingly it works. BUT, sometimes the text I am matching on is HTML that looks like this:</p> <pre><code>&lt;span class="CustomerName"&gt;Fred&lt;/span&gt; was a classy individual. </code></pre> <p>And if you search for "class" I want the highlight code to wrap the "class" in "classy" but of course not the HTML attribute "class" that happens to be in there! If you search for "Fred", that should be highlighted.</p> <p>So what's a good regex that will make sure matches happen only OUTSIDE the html tags? It doesn't have to be super hardcore. Simply making sure the match is not between &lt; and > would work fine, I think.</p>
[ { "answer_id": 179819, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 2, "selected": false, "text": "<p>You can use a regex with balancing groups and backreferences, but I strongly recommend that you use a <a href=\"http://www.antlr.org/\" rel=\"nofollow noreferrer\">parser</a> here. </p>\n" }, { "answer_id": 180248, "author": "WolfmanDragon", "author_id": 13491, "author_profile": "https://Stackoverflow.com/users/13491", "pm_score": 0, "selected": false, "text": "<p>Hmm, I'm not a C# programmer so I don't know the flavor of regex it uses but (?!&lt;.+?>) should ignore anything inside of tags. It will force you to use &amp;#60 &amp;#62 in your HTML code, but you should be doing that anyway.</p>\n" }, { "answer_id": 181882, "author": "Julien Hoarau", "author_id": 12248, "author_profile": "https://Stackoverflow.com/users/12248", "pm_score": 5, "selected": true, "text": "<p>This regex should do the job : <code>(?&lt;!&lt;[^&gt;]*)(regex you want to check: Fred|span)</code> It checks that it is impossible to match the regex <code>&lt;[^&gt;]*</code> going backward starting from a matching string.</p>\n\n<p>Modified code below:</p>\n\n<pre><code>const string notInsideBracketsRegex = @\"(?&lt;!&lt;[^&gt;]*)\";\nconst string highlightPattern = @\"&lt;span class=\"\"Highlight\"\"&gt;$0&lt;/span&gt;\";\nDataBoundLiteralControl litCustomerComments = (DataBoundLiteralControl)e.Row.Cells[CUSTOMERCOMMENTS_COLUMN].Controls[0];\n\n// Turn \"term1 term2\" into \"(term1|term2)\"\nstring spaceDelimited = txtTextFilter.Text.Trim();\nstring pipeDelimited = string.Join(\"|\", spaceDelimited.Split(new[] {\" \"}, StringSplitOptions.RemoveEmptyEntries));\nstring searchPattern = \"(\" + pipeDelimited + \")\";\nsearchPattern = notInsideBracketsRegex + searchPattern;\n\n// Highlight search terms in Customer - Comments column\ne.Row.Cells[CUSTOMERCOMMENTS_COLUMN].Text = Regex.Replace(litCustomerComments.Text, searchPattern, highlightPattern, RegexOptions.IgnoreCase);\n</code></pre>\n" }, { "answer_id": 181902, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "<p>Writing a regex that can handle CDATA sections is going to be hard. You may no longer asssume that > closes a tag.</p>\n\n<p>For instance, <code>\"&lt;span class=\"CustomerName&gt;Fred.&lt;/span&gt; is a good customer (&lt;![CDATA[ &gt;10000$ ]]&gt; )\"</code></p>\n\n<p>The solution is (as noted earlier) a parser. They're much better in dealing with the kind of mess you find in a <code>CDATA</code>. madgnome's backwards check cannot be used to find the starting <code>&lt;![CDATA</code> from a <code>]]&gt;</code>, as a <code>CDATA</code> section may include the literal <code>&lt;![CDATA</code>. </p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13700/" ]
I am writing code for a search results page that needs to highlight search terms. The terms happen to occur within table cells (the app is iterating through GridView Row Cells), and these table cells may have HTML. Currently, my code looks like this (relevant hunks shown below): ``` const string highlightPattern = @"<span class=""Highlight"">$0</span>"; DataBoundLiteralControl litCustomerComments = (DataBoundLiteralControl)e.Row.Cells[CUSTOMERCOMMENTS_COLUMN].Controls[0]; // Turn "term1 term2" into "(term1|term2)" string spaceDelimited = txtTextFilter.Text.Trim(); string pipeDelimited = string.Join("|", spaceDelimited.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries)); string searchPattern = "(" + pipeDelimited + ")"; // Highlight search terms in Customer - Comments column e.Row.Cells[CUSTOMERCOMMENTS_COLUMN].Text = Regex.Replace(litCustomerComments.Text, searchPattern, highlightPattern, RegexOptions.IgnoreCase); ``` Amazingly it works. BUT, sometimes the text I am matching on is HTML that looks like this: ``` <span class="CustomerName">Fred</span> was a classy individual. ``` And if you search for "class" I want the highlight code to wrap the "class" in "classy" but of course not the HTML attribute "class" that happens to be in there! If you search for "Fred", that should be highlighted. So what's a good regex that will make sure matches happen only OUTSIDE the html tags? It doesn't have to be super hardcore. Simply making sure the match is not between < and > would work fine, I think.
This regex should do the job : `(?<!<[^>]*)(regex you want to check: Fred|span)` It checks that it is impossible to match the regex `<[^>]*` going backward starting from a matching string. Modified code below: ``` const string notInsideBracketsRegex = @"(?<!<[^>]*)"; const string highlightPattern = @"<span class=""Highlight"">$0</span>"; DataBoundLiteralControl litCustomerComments = (DataBoundLiteralControl)e.Row.Cells[CUSTOMERCOMMENTS_COLUMN].Controls[0]; // Turn "term1 term2" into "(term1|term2)" string spaceDelimited = txtTextFilter.Text.Trim(); string pipeDelimited = string.Join("|", spaceDelimited.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries)); string searchPattern = "(" + pipeDelimited + ")"; searchPattern = notInsideBracketsRegex + searchPattern; // Highlight search terms in Customer - Comments column e.Row.Cells[CUSTOMERCOMMENTS_COLUMN].Text = Regex.Replace(litCustomerComments.Text, searchPattern, highlightPattern, RegexOptions.IgnoreCase); ```
179,799
<p>Yesterday I tried to get started with Java RMI. I found this sun tutorial (<a href="http://java.sun.com/docs/books/tutorial/rmi/index.html" rel="nofollow noreferrer">http://java.sun.com/docs/books/tutorial/rmi/index.html</a>) and started with the server implemantation. But everytime I start the pogram (the rmiregistry is running) I get an AccessControlException with the following StackTrace:</p> <pre><code>LoginImpl exception: java.security.AccessControlException: access denied (java.io.FilePermission \\\C\ProjX\server\serverProj\bin\usermanager read) at java.security.AccessControlContext.checkPermission(AccessControlContext.java:264) at java.security.AccessController.checkPermission(AccessController.java:427) at java.lang.SecurityManager.checkPermission(SecurityManager.java:532) at java.lang.SecurityManager.checkRead(SecurityManager.java:871) at java.io.File.exists(File.java:700) at sun.net.www.protocol.file.Handler.openConnection(Handler.java:80) at sun.net.www.protocol.file.Handler.openConnection(Handler.java:55) at java.net.URL.openConnection(URL.java:943) at sun.rmi.server.LoaderHandler.addPermissionsForURLs(LoaderHandler.java:1020) at sun.rmi.server.LoaderHandler.access$300(LoaderHandler.java:52) at sun.rmi.server.LoaderHandler$Loader.&lt;init&gt;(LoaderHandler.java:1108) at sun.rmi.server.LoaderHandler$Loader.&lt;init&gt;(LoaderHandler.java:1089) at sun.rmi.server.LoaderHandler$1.run(LoaderHandler.java:861) at java.security.AccessController.doPrivileged(Native Method) at sun.rmi.server.LoaderHandler.lookupLoader(LoaderHandler.java:858) at sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:541) at java.rmi.server.RMIClassLoader$2.loadProxyClass(RMIClassLoader.java:628) at java.rmi.server.RMIClassLoader.loadProxyClass(RMIClassLoader.java:294) at sun.rmi.server.MarshalInputStream.resolveProxyClass(MarshalInputStream.java:238) at java.io.ObjectInputStream.readProxyDesc(ObjectInputStream.java:1494) at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1457) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1693) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1299) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:339) at sun.rmi.registry.RegistryImpl_Skel.dispatch(Unknown Source) at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:375) at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:240) at sun.rmi.transport.Transport$1.run(Transport.java:153) at java.security.AccessController.doPrivileged(Native Method) at sun.rmi.transport.Transport.serviceCall(Transport.java:149) at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:460) at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:701) at java.lang.Thread.run(Thread.java:595) at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source) at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source) at sun.rmi.server.UnicastRef.invoke(Unknown Source) at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source) at startserver.StartServer.main(StartServer.java:22) </code></pre> <p>My <code>server.policy</code> file looks like this:</p> <pre><code>grant { permission java.security.AllPermission; }; </code></pre> <p>But I have also tried this one:</p> <pre><code>grant { permission java.security.AllPermission; permission java.io.FilePermission &quot;file://C:/ProjX/server/serverProj/bin/usermanager&quot;, &quot;read&quot;; }; </code></pre> <p>... and this one (and several others :-():</p> <pre><code>grant codeBase &quot;file:///-&quot; { permission java.security.AllPermission; }; </code></pre> <p>But in every case the result is the same. And yes, the policy file is in path (I see a Parse Exception, when I write wrong statments into the policy-file). I tried out several other &quot;/&quot; and &quot;&quot; constellations but it has no effect.</p> <p>I use Eclipse and my VM-Parameters are like this:</p> <pre><code>-cp C:\ProjX\server\serverProj\bin\usermanager\ -Djava.rmi.server.codebase=file://C:/ProjX/server/serverProj/bin/usermanager/ -Djava.rmi.server.hostname=XYZ (anonymized) -Djava.security.policy=server.policy </code></pre> <p>The compiled Remote-Interface and the interface-implementation class (LoginImpl) classes are in this path: &quot;C:/ProjX/server/serverProj/bin/usermanager/&quot;. The main method, where I instanciate and rebind the stub to the registry is in another package and looks like this:</p> <pre><code>public static void main(String[] args) { if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } try { String name = &quot;Login&quot;; Login login = new LoginImpl(); Login stub = (Login) UnicastRemoteObject.exportObject(login, 0); Registry registry = LocateRegistry.getRegistry(); registry.rebind(name, stub); System.out.println(&quot;LoginImpl bound&quot;); } catch (Exception e) { System.err.println(&quot;LoginImpl exception:&quot;); e.printStackTrace(); } } </code></pre> <p>Does anybody have an advice for me?</p> <hr /> <p>So the question is the same (the <code>java.rmi.UnmarshalException</code> shows that changing the codebase is not the solution of my AccessControlException). And no: I don't want to buy a plugin &quot;G B&quot;.</p>
[ { "answer_id": 180176, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 3, "selected": false, "text": "<p>Grant of all permissions to all code is a really bad. Any RMI client could do what it wanted as logged in user. In general try to restrict permissions as much as reasonable, particularly when you don't know where the code has come from.</p>\n\n<p>Back to the question...</p>\n\n<pre><code>-Djava.rmi.server.codebase=file://C:/ProjX/server/serverProj/bin/usermanager/\n</code></pre>\n\n<p>That should be either <code>\"file:///C:/...\"</code> or <code>\"file:/C:/...\"</code>. Think of http. <code>\"http://C:/...\"</code> refers to a host named <code>C</code>. Note that the exception message has dropped the colon, because that's just syntax for port number.</p>\n\n<p>The reason why you get a security exception even if you grant permissions to all code, is that RMI is restricting permissions to that appropriate given the URLs involved (using AccessController doPrivileged two argument form).</p>\n" }, { "answer_id": 201917, "author": "bhavanki", "author_id": 24184, "author_profile": "https://Stackoverflow.com/users/24184", "pm_score": 0, "selected": false, "text": "<p>I think the exception is actually coming out of rmiregistry. This part of the stack trace is what makes me think so. The stub for rmiregistry is receiving the exception and passing it back up as the result of the attempt to rebind.</p>\n\n<pre>\n at sun.rmi.transport.StreamRemoteCall.<b>exceptionReceivedFromServer</b>(Unknown Source)\n at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)\n at sun.rmi.server.UnicastRef.invoke(Unknown Source)\n at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)\n</pre>\n\n<p>Try running rmiregistry with <code>-J-Djava.security.policy=all.policy</code>, where the policy file grants all permissions (at least to get things going).</p>\n\n<p>Eventually you may also wish to switch to an HTTP codebase URL, just so that you can run clients on a machine separate from your server's.</p>\n" }, { "answer_id": 202213, "author": "user25913", "author_id": 25913, "author_profile": "https://Stackoverflow.com/users/25913", "pm_score": 3, "selected": false, "text": "<p>Ok, I have it. It wasn&acute;t the rmiregistry property (works without any parameters). There were two errors in my codebase VM-Parameter:</p>\n\n<pre><code>-cp C:\\ProjX\\server\\serverProj\\bin\\usermanager\\\n-Djava.rmi.server.codebase=file://C:/ProjX/server/serverProj/bin/usermanager/\n-Djava.rmi.server.hostname=XYZ (anonymized)\n-Djava.security.policy=server.policy\n</code></pre>\n\n<p>... should instead look like this:</p>\n\n<pre><code>-Djava.rmi.server.codebase=file:/C:/ProjX/server/serverProj/bin/\n-Djava.rmi.server.hostname=XYZ (anonymized)\n-Djava.security.policy=server.policy\n</code></pre>\n\n<p>=> file:/ (only one slash) + wrong package ending.</p>\n\n<p>But the trace was so confusing, my first thought was, that somthing must be wrong with the policy-file or policy-configuration.</p>\n\n<p>Nevertheless: Thank you for help and happy hacking. ;-)</p>\n" }, { "answer_id": 284827, "author": "Piotr Kochański", "author_id": 34102, "author_profile": "https://Stackoverflow.com/users/34102", "pm_score": 2, "selected": false, "text": "<p>You can also set programatically java.rmi.server.codebase property:</p>\n\n<pre><code>Hello h = null;\nProperties props = System.getProperties();\nSystem.setProperty(\"java.rmi.server.codebase\", \"file:/C:/PROJECTX/bin/\");\ntry {\n h = new HelloImpl();\n Naming.bind(\"//localhost:1099/HelloService\", h);\n System.out.println(\"Serwis gotów...\");\n} catch (RemoteException e) {\n e.printStackTrace();\n} catch (MalformedURLException e) {\n e.printStackTrace();\n} catch (AlreadyBoundException e) {\n e.printStackTrace();\n}\n</code></pre>\n\n<p>for some hypothetical <code>Hello</code> RMI service.</p>\n" }, { "answer_id": 18377197, "author": "Tarek", "author_id": 2706845, "author_profile": "https://Stackoverflow.com/users/2706845", "pm_score": 0, "selected": false, "text": "<p>It just works fine when I fixed the CLASSPATH variable before starting the rmi registry. I think the idea is that the RMI Registry will load your remote stubs and it should has access. That's was easy by putting my classes on the CLASSPATH before running the registry. So it is not related to any other reason such as JDK 7 or file:/ protocol.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25913/" ]
Yesterday I tried to get started with Java RMI. I found this sun tutorial (<http://java.sun.com/docs/books/tutorial/rmi/index.html>) and started with the server implemantation. But everytime I start the pogram (the rmiregistry is running) I get an AccessControlException with the following StackTrace: ``` LoginImpl exception: java.security.AccessControlException: access denied (java.io.FilePermission \\\C\ProjX\server\serverProj\bin\usermanager read) at java.security.AccessControlContext.checkPermission(AccessControlContext.java:264) at java.security.AccessController.checkPermission(AccessController.java:427) at java.lang.SecurityManager.checkPermission(SecurityManager.java:532) at java.lang.SecurityManager.checkRead(SecurityManager.java:871) at java.io.File.exists(File.java:700) at sun.net.www.protocol.file.Handler.openConnection(Handler.java:80) at sun.net.www.protocol.file.Handler.openConnection(Handler.java:55) at java.net.URL.openConnection(URL.java:943) at sun.rmi.server.LoaderHandler.addPermissionsForURLs(LoaderHandler.java:1020) at sun.rmi.server.LoaderHandler.access$300(LoaderHandler.java:52) at sun.rmi.server.LoaderHandler$Loader.<init>(LoaderHandler.java:1108) at sun.rmi.server.LoaderHandler$Loader.<init>(LoaderHandler.java:1089) at sun.rmi.server.LoaderHandler$1.run(LoaderHandler.java:861) at java.security.AccessController.doPrivileged(Native Method) at sun.rmi.server.LoaderHandler.lookupLoader(LoaderHandler.java:858) at sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:541) at java.rmi.server.RMIClassLoader$2.loadProxyClass(RMIClassLoader.java:628) at java.rmi.server.RMIClassLoader.loadProxyClass(RMIClassLoader.java:294) at sun.rmi.server.MarshalInputStream.resolveProxyClass(MarshalInputStream.java:238) at java.io.ObjectInputStream.readProxyDesc(ObjectInputStream.java:1494) at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1457) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1693) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1299) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:339) at sun.rmi.registry.RegistryImpl_Skel.dispatch(Unknown Source) at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:375) at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:240) at sun.rmi.transport.Transport$1.run(Transport.java:153) at java.security.AccessController.doPrivileged(Native Method) at sun.rmi.transport.Transport.serviceCall(Transport.java:149) at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:460) at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:701) at java.lang.Thread.run(Thread.java:595) at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source) at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source) at sun.rmi.server.UnicastRef.invoke(Unknown Source) at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source) at startserver.StartServer.main(StartServer.java:22) ``` My `server.policy` file looks like this: ``` grant { permission java.security.AllPermission; }; ``` But I have also tried this one: ``` grant { permission java.security.AllPermission; permission java.io.FilePermission "file://C:/ProjX/server/serverProj/bin/usermanager", "read"; }; ``` ... and this one (and several others :-(): ``` grant codeBase "file:///-" { permission java.security.AllPermission; }; ``` But in every case the result is the same. And yes, the policy file is in path (I see a Parse Exception, when I write wrong statments into the policy-file). I tried out several other "/" and "" constellations but it has no effect. I use Eclipse and my VM-Parameters are like this: ``` -cp C:\ProjX\server\serverProj\bin\usermanager\ -Djava.rmi.server.codebase=file://C:/ProjX/server/serverProj/bin/usermanager/ -Djava.rmi.server.hostname=XYZ (anonymized) -Djava.security.policy=server.policy ``` The compiled Remote-Interface and the interface-implementation class (LoginImpl) classes are in this path: "C:/ProjX/server/serverProj/bin/usermanager/". The main method, where I instanciate and rebind the stub to the registry is in another package and looks like this: ``` public static void main(String[] args) { if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } try { String name = "Login"; Login login = new LoginImpl(); Login stub = (Login) UnicastRemoteObject.exportObject(login, 0); Registry registry = LocateRegistry.getRegistry(); registry.rebind(name, stub); System.out.println("LoginImpl bound"); } catch (Exception e) { System.err.println("LoginImpl exception:"); e.printStackTrace(); } } ``` Does anybody have an advice for me? --- So the question is the same (the `java.rmi.UnmarshalException` shows that changing the codebase is not the solution of my AccessControlException). And no: I don't want to buy a plugin "G B".
Grant of all permissions to all code is a really bad. Any RMI client could do what it wanted as logged in user. In general try to restrict permissions as much as reasonable, particularly when you don't know where the code has come from. Back to the question... ``` -Djava.rmi.server.codebase=file://C:/ProjX/server/serverProj/bin/usermanager/ ``` That should be either `"file:///C:/..."` or `"file:/C:/..."`. Think of http. `"http://C:/..."` refers to a host named `C`. Note that the exception message has dropped the colon, because that's just syntax for port number. The reason why you get a security exception even if you grant permissions to all code, is that RMI is restricting permissions to that appropriate given the URLs involved (using AccessController doPrivileged two argument form).
179,826
<p>Does anyone know of crossbrowser equivalent of explicitOriginalTarget event parameter? This parameter is Mozilla specific and it gives me the element that caused the blur. Let's say i have a text input and a link on my page. Text input has the focus. If I click on the link, text input's blur event gives me the link element in Firefox via explicitOriginalTarget parameter.</p> <p>I am extending Autocompleter.Base's onBlur method to not hide the search results when search field loses focus to given elements. By default, onBlur method hides if search-field loses focus to any element.</p> <pre><code>Autocompleter.Base.prototype.onBlur = Autocompleter.Base.prototype.onBlur.wrap( function(origfunc, ev) { var newTargetElement = (ev.explicitOriginalTarget.nodeType == 3 ? ev.explicitOriginalTarget.parentNode: ev.explicitOriginalTarget); // FIX: This works only in firefox because of event's explicitOriginalTarget property var callOriginalFunction = true; for (i = 0; i &lt; obj.options.validEventElements.length; i++) { if ($(obj.options.validEventElements[i])) { if (newTargetElement.descendantOf($(obj.options.validEventElements[i])) == true || newTargetElement == $(obj.options.validEventElements[i])) { callOriginalFunction = false; break; } } } if (callOriginalFunction) { return origFunc(ev); } } ); new Ajax.Autocompleter("search-field", "search-results", 'getresults.php', { validEventElements: ['search-field','result-count'] }); </code></pre> <p>Thanks.</p>
[ { "answer_id": 179991, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "<p>Looks like it is more designed for extension writers than for Web design...</p>\n\n<p>I would watch the blur/focus events on both targets (or potential targets) and share their information.<br>\nThe exact implementation might depend on the purpose, actually.</p>\n" }, { "answer_id": 180197, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 4, "selected": true, "text": "<p>There is no equivalent to explicitOriginalTarget in any of the other than Gecko-based browsers. In Gecko this is an internal property and it is not supposed to be used by an application developer (maybe by XBL binding writers).</p>\n" }, { "answer_id": 2246802, "author": "WMSigEp", "author_id": 271301, "author_profile": "https://Stackoverflow.com/users/271301", "pm_score": 2, "selected": false, "text": "<p>The rough equivalent for Mozilla's .explicitOriginalTarget in IE is document.activeElement. I say rough equivalent because it will sometimes return a slightly different level in the DOM node tree depending on your circumstance, but it's still a useful tool. Unfortunately I'm still looking for a Google Chrome equivalent.</p>\n" }, { "answer_id": 9607278, "author": "Kotei", "author_id": 1255475, "author_profile": "https://Stackoverflow.com/users/1255475", "pm_score": 0, "selected": false, "text": "<p>For IE you can use <code>srcElement</code>, and forced it.</p>\n\n<pre><code>if( !selectTag.explicitOriginalTarget )\n selectTag.explicitOriginalTarget = selectTag.srcElement;\n</code></pre>\n" }, { "answer_id": 10457820, "author": "Allan Rofer", "author_id": 1376136, "author_profile": "https://Stackoverflow.com/users/1376136", "pm_score": 2, "selected": false, "text": "<p>IE <code>srcElement</code> does not contain the same element as FF <code>explicitOriginalTarget</code>. It's easy to see this: if you have a button field with <code>onClick</code> action and a text field with <code>onChange</code> action, change the text field and move the cursor directly to the button and click it. At that point the IE <code>srcElement</code> will be the text field, but the <code>explicitOriginalTarget</code> will be the button field. For IE, you can get the x,y coordinates of the mouse click from the <code>event.x</code> and <code>event.y</code> properties.</p>\n\n<p>Unfortunately, the Chrome browser provides neither the <code>explicitOriginalTarget</code> nor the mouse coordinates for the click. You are left to your own devices to figure out where the <code>onChange</code> event was fired from. To do this, judicious use of <code>mousemove</code> and <code>mouseout</code> events can provide mouse tracking which can then be inspected in the <code>onChange</code> handler. </p>\n" }, { "answer_id": 28663211, "author": "ss ulrey", "author_id": 144022, "author_profile": "https://Stackoverflow.com/users/144022", "pm_score": 2, "selected": false, "text": "<p>2015 update... you can use event.relatedTarget on Chrome. Such a basic thing, hopefully the other browsers will follow... </p>\n" }, { "answer_id": 73765924, "author": "balping", "author_id": 898783, "author_profile": "https://Stackoverflow.com/users/898783", "pm_score": 0, "selected": false, "text": "<p>In case of form submit events, you can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/SubmitEvent/submitter\" rel=\"nofollow noreferrer\"><code>submitter</code></a> property in all modern browser (as of 2022).</p>\n<pre class=\"lang-js prettyprint-override\"><code>let form = document.querySelector(&quot;form&quot;);\nform.addEventListener(&quot;submit&quot;, (event) =&gt; {\n let submitter = event.submitter; //either a form input or a submit button\n});\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25768/" ]
Does anyone know of crossbrowser equivalent of explicitOriginalTarget event parameter? This parameter is Mozilla specific and it gives me the element that caused the blur. Let's say i have a text input and a link on my page. Text input has the focus. If I click on the link, text input's blur event gives me the link element in Firefox via explicitOriginalTarget parameter. I am extending Autocompleter.Base's onBlur method to not hide the search results when search field loses focus to given elements. By default, onBlur method hides if search-field loses focus to any element. ``` Autocompleter.Base.prototype.onBlur = Autocompleter.Base.prototype.onBlur.wrap( function(origfunc, ev) { var newTargetElement = (ev.explicitOriginalTarget.nodeType == 3 ? ev.explicitOriginalTarget.parentNode: ev.explicitOriginalTarget); // FIX: This works only in firefox because of event's explicitOriginalTarget property var callOriginalFunction = true; for (i = 0; i < obj.options.validEventElements.length; i++) { if ($(obj.options.validEventElements[i])) { if (newTargetElement.descendantOf($(obj.options.validEventElements[i])) == true || newTargetElement == $(obj.options.validEventElements[i])) { callOriginalFunction = false; break; } } } if (callOriginalFunction) { return origFunc(ev); } } ); new Ajax.Autocompleter("search-field", "search-results", 'getresults.php', { validEventElements: ['search-field','result-count'] }); ``` Thanks.
There is no equivalent to explicitOriginalTarget in any of the other than Gecko-based browsers. In Gecko this is an internal property and it is not supposed to be used by an application developer (maybe by XBL binding writers).
179,839
<p>Basically, I'm trying to selectively copy a table from one database to another. I have two different [Oracle] databases (e.g., running on different hosts) with the same schema. I'm interested in a efficient way to load Table A in DB1 with the result of running a select on Table A in DB2. I'm using JDBC, if that's relevant.</p>
[ { "answer_id": 179870, "author": "CaptainPicard", "author_id": 15203, "author_profile": "https://Stackoverflow.com/users/15203", "pm_score": 4, "selected": true, "text": "<p>Use a database link, and use create table as select.</p>\n\n<pre><code>create database link other_db connect to remote_user identified by remote_passwd using remote_tnsname;\n\ncreate table a as select * from a@other_db;\n</code></pre>\n" }, { "answer_id": 183526, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If the databases are from the same vendor they usually provide a native way to make a view\nof a table in another database. in which case, a \"select into\" query will do it no problem</p>\n\n<p>Oracle, for example, has the database link which works pretty well.</p>\n\n<p>Outside of that you are going to have to make a connection to each database and read in\nfrom one connection and write out to the other.</p>\n\n<p>There are tools like Oracle's ODI that can do the legwork, but they all use the same\nread in, write out model</p>\n" }, { "answer_id": 1687093, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 0, "selected": false, "text": "<p>You may not even need to move that data. Maybe you can just select across the database link.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25915/" ]
Basically, I'm trying to selectively copy a table from one database to another. I have two different [Oracle] databases (e.g., running on different hosts) with the same schema. I'm interested in a efficient way to load Table A in DB1 with the result of running a select on Table A in DB2. I'm using JDBC, if that's relevant.
Use a database link, and use create table as select. ``` create database link other_db connect to remote_user identified by remote_passwd using remote_tnsname; create table a as select * from a@other_db; ```
179,927
<p>In visual studio, I have an asp.net 3.5 project that is using MS Enterprise Library 4.0 application blocks. </p> <p>When I have my web config file open, my Error list fills up with 99 messages with things like </p> <pre><code>Could not find schema information for the element 'dataConfiguration'. Could not find schema information for the attribute 'defaultDatabase'. Could not find schema information for the element 'loggingConfiguration'. Could not find schema information for the attribute 'tracingEnabled'. Could not find schema information for the attribute 'defaultCategory'. </code></pre> <p>If I close the Web.config file they go away (but they come back as soon as I need to open the file again).</p> <p>After doing some looking, I found that this is becauase there is an XSD or schema file missing that Visual Studio needs in order to properly 'understand' the schema that is in the web.config file and provide intellisense for it. </p> <p>Does anyone know how to either supply VS with the appropriate schema information, or to turn off these messages?</p> <p>@Franci - Thanks for the info, I have tried that tool as well as the MMC snap in (they tend to blow up the formatting in the Web.config) but they still do not resolve the irritating warnings I receive. Thanks for trying. </p>
[ { "answer_id": 179945, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 1, "selected": false, "text": "<p>Have you tried copying the schema file to the XML Schema Caching folder for VS? You can find the location of that folder by looking at VS Tools/Options/Test Editor/XML/Miscellaneous. Unfortunately, i don't know where's the schema file for the MS Enterprise Library 4.0.</p>\n\n<p><strong>Update</strong>: After installing MS Enterprise Library, it seems there's no .xsd file. However, there's a tool for editing the configuration - EntLibConfig.exe, which you can use to edit the configuration files. Also, if you add the proper config sections to your config file, VS should be able to parse the config file properly. (EntLibConfig will add these for you, or you can add them yourself). Here's an example for the loggingConfiguration section:</p>\n\n<pre><code>&lt;configSections&gt;\n &lt;section name=\"loggingConfiguration\" type=\"Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" /&gt;\n&lt;/configSections&gt;\n</code></pre>\n\n<p>You also need to add a reference to the appropriate assembly in your project.</p>\n" }, { "answer_id": 464515, "author": "user57433", "author_id": 57433, "author_profile": "https://Stackoverflow.com/users/57433", "pm_score": 5, "selected": false, "text": "<p>I've created a new scheme based on my current app.config to get the messages to disappear.\nI just used the button in Visual Studio that says \"Create Schema\" and an xsd schema was created for me.</p>\n\n<p>Save the schema in an apropriate place and see the \"Properties\" tab of the app.config file where there is a property named Schemas. If you click the change button there you can select to use both the original dotnetconfig schema and your own newly created one.</p>\n" }, { "answer_id": 464620, "author": "user57433", "author_id": 57433, "author_profile": "https://Stackoverflow.com/users/57433", "pm_score": 5, "selected": true, "text": "<p>I configured the <code>app.config</code> with the tool for EntLib configuration and set up my <code>LoggingConfiguration</code> block. Then I copied this into the <code>DotNetConfig.xsd</code>. Of course, it does not cover all attributes, only the ones I added but it does not display those annoying info messages anymore.</p>\n\n<pre><code>&lt;xs:element name=\"loggingConfiguration\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"listeners\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element maxOccurs=\"unbounded\" name=\"add\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:attribute name=\"fileName\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"footer\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"formatter\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"header\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"rollFileExistsBehavior\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"rollInterval\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"rollSizeKB\" type=\"xs:unsignedByte\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"timeStampPattern\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"listenerDataType\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"traceOutputOptions\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"filter\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"type\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;xs:element name=\"formatters\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"add\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:attribute name=\"template\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"type\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;xs:element name=\"logFilters\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"add\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:attribute name=\"enabled\" type=\"xs:boolean\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"type\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;xs:element name=\"categorySources\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element maxOccurs=\"unbounded\" name=\"add\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"listeners\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"add\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;/xs:sequence&gt;\n &lt;xs:attribute name=\"switchValue\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;xs:element name=\"specialSources\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"allEvents\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:attribute name=\"switchValue\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;xs:element name=\"notProcessed\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:attribute name=\"switchValue\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;xs:element name=\"errors\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"listeners\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"add\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;/xs:sequence&gt;\n &lt;xs:attribute name=\"switchValue\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;/xs:sequence&gt;\n &lt;xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"tracingEnabled\" type=\"xs:boolean\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"defaultCategory\" type=\"xs:string\" use=\"required\" /&gt;\n &lt;xs:attribute name=\"logWarningsWhenNoCategoriesMatch\" type=\"xs:boolean\" use=\"required\" /&gt;\n &lt;/xs:complexType&gt;\n&lt;/xs:element&gt;\n</code></pre>\n" }, { "answer_id": 7517435, "author": "Pressacco", "author_id": 949681, "author_profile": "https://Stackoverflow.com/users/949681", "pm_score": 4, "selected": false, "text": "<p>An XSD is included with EntLib 5, and is installed in the Visual Studio schema directory. In my case, it could be found at:</p>\n<p>&quot;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Xml\\Schemas\\EnterpriseLibrary.Configuration.xsd&quot;</p>\n<h3>CONTEXT</h3>\n<ul>\n<li>Visual Studio 2010</li>\n<li>Enterprise Library 5</li>\n</ul>\n<h3>STEPS TO REMOVE THE WARNINGS</h3>\n<ol>\n<li>open app.config in your Visual Studio project</li>\n<li>right click in the XML Document editor, select &quot;Properties&quot;</li>\n<li>add the fully qualified path to the &quot;EnterpriseLibrary.Configuration.xsd&quot;</li>\n</ol>\n<h3>ASIDE</h3>\n<p>It is worth repeating that these &quot;Error List&quot; &quot;Messages&quot; (&quot;Could not find schema information for the element&quot;) are only visible when you open the app.config file. If you &quot;Close All Documents&quot; and compile... no messages will be reported.</p>\n" }, { "answer_id": 24575462, "author": "darkmatter", "author_id": 2853904, "author_profile": "https://Stackoverflow.com/users/2853904", "pm_score": 0, "selected": false, "text": "<p>Navigate to this : <a href=\"http://nlog-project.org/2010/06/30/intellisense-for-nlog-configuration-files.html\" rel=\"nofollow\">NLog xsd files</a></p>\n\n<p>Download the appropriate xsd for your project and save it along the NLog.config</p>\n\n<p>The first one did the trick for me.</p>\n" }, { "answer_id": 29321444, "author": "Wade Price", "author_id": 4639374, "author_profile": "https://Stackoverflow.com/users/4639374", "pm_score": 1, "selected": false, "text": "<p>What fixed the \"Could not find schema information for the element ...\" for me was</p>\n\n<ul>\n<li>Opening my <code>app.config</code>.</li>\n<li>Right-clicking in the editor window and selecting <code>Properties</code>.</li>\n<li>In the properties box, there is a row called <code>Schemas</code>, I clicked that row and selected the browse <code>...</code> box that appears in the row.</li>\n<li>I simply checked the <code>use</code> box for all the rows that had my project somewhere in them, and also for the current version of .Net I was using. For instance: <code>DotNetConfig30.xsd</code>.</li>\n</ul>\n\n<p>After that everything went to working fine.</p>\n\n<p>How those schema rows with my project got unchecked I'm not sure, but when I made sure they were checked, I was back in business.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16391/" ]
In visual studio, I have an asp.net 3.5 project that is using MS Enterprise Library 4.0 application blocks. When I have my web config file open, my Error list fills up with 99 messages with things like ``` Could not find schema information for the element 'dataConfiguration'. Could not find schema information for the attribute 'defaultDatabase'. Could not find schema information for the element 'loggingConfiguration'. Could not find schema information for the attribute 'tracingEnabled'. Could not find schema information for the attribute 'defaultCategory'. ``` If I close the Web.config file they go away (but they come back as soon as I need to open the file again). After doing some looking, I found that this is becauase there is an XSD or schema file missing that Visual Studio needs in order to properly 'understand' the schema that is in the web.config file and provide intellisense for it. Does anyone know how to either supply VS with the appropriate schema information, or to turn off these messages? @Franci - Thanks for the info, I have tried that tool as well as the MMC snap in (they tend to blow up the formatting in the Web.config) but they still do not resolve the irritating warnings I receive. Thanks for trying.
I configured the `app.config` with the tool for EntLib configuration and set up my `LoggingConfiguration` block. Then I copied this into the `DotNetConfig.xsd`. Of course, it does not cover all attributes, only the ones I added but it does not display those annoying info messages anymore. ``` <xs:element name="loggingConfiguration"> <xs:complexType> <xs:sequence> <xs:element name="listeners"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" name="add"> <xs:complexType> <xs:attribute name="fileName" type="xs:string" use="required" /> <xs:attribute name="footer" type="xs:string" use="required" /> <xs:attribute name="formatter" type="xs:string" use="required" /> <xs:attribute name="header" type="xs:string" use="required" /> <xs:attribute name="rollFileExistsBehavior" type="xs:string" use="required" /> <xs:attribute name="rollInterval" type="xs:string" use="required" /> <xs:attribute name="rollSizeKB" type="xs:unsignedByte" use="required" /> <xs:attribute name="timeStampPattern" type="xs:string" use="required" /> <xs:attribute name="listenerDataType" type="xs:string" use="required" /> <xs:attribute name="traceOutputOptions" type="xs:string" use="required" /> <xs:attribute name="filter" type="xs:string" use="required" /> <xs:attribute name="type" type="xs:string" use="required" /> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="formatters"> <xs:complexType> <xs:sequence> <xs:element name="add"> <xs:complexType> <xs:attribute name="template" type="xs:string" use="required" /> <xs:attribute name="type" type="xs:string" use="required" /> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="logFilters"> <xs:complexType> <xs:sequence> <xs:element name="add"> <xs:complexType> <xs:attribute name="enabled" type="xs:boolean" use="required" /> <xs:attribute name="type" type="xs:string" use="required" /> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="categorySources"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" name="add"> <xs:complexType> <xs:sequence> <xs:element name="listeners"> <xs:complexType> <xs:sequence> <xs:element name="add"> <xs:complexType> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="switchValue" type="xs:string" use="required" /> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="specialSources"> <xs:complexType> <xs:sequence> <xs:element name="allEvents"> <xs:complexType> <xs:attribute name="switchValue" type="xs:string" use="required" /> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> <xs:element name="notProcessed"> <xs:complexType> <xs:attribute name="switchValue" type="xs:string" use="required" /> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> <xs:element name="errors"> <xs:complexType> <xs:sequence> <xs:element name="listeners"> <xs:complexType> <xs:sequence> <xs:element name="add"> <xs:complexType> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="switchValue" type="xs:string" use="required" /> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> <xs:attribute name="tracingEnabled" type="xs:boolean" use="required" /> <xs:attribute name="defaultCategory" type="xs:string" use="required" /> <xs:attribute name="logWarningsWhenNoCategoriesMatch" type="xs:boolean" use="required" /> </xs:complexType> </xs:element> ```
179,934
<p>This is my first time attempting to call an ASP.NET page method from jQuery. I am getting a status 500 error with the responseText message that the web method cannot be found. Here is my jQuery $.ajax call:</p> <pre><code>function callCancelPlan(activePlanId, ntLogin) { var paramList = '{"activePlanId":"' + activePlanId + '","ntLogin":"' + ntLogin + '"}'; $.ajax({ type: "POST", url: "ArpWorkItem.aspx/CancelPlan", data: paramList, contentType: "application/json; charset=utf-8", dataType: "json", success: function() { alert("success"); }, error: function(xml,textStatus,errorThrown) { alert(xml.status + "||" + xml.responseText); } }); } </code></pre> <p>And here is the page method I am trying to call:</p> <pre><code>[WebMethod()] private static void CancelPlan(int activePlanId, string ntLogin) { StrategyRetrievalPresenter presenter = new StrategyRetrievalPresenter(); presenter.CancelExistingPlan(offer, ntLogin); } </code></pre> <p>I have tried this by decorating the Web Method with and without the parens'()'. Anyone have an idea?</p>
[ { "answer_id": 179941, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 8, "selected": true, "text": "<p>Your web method needs to be public and static.</p>\n" }, { "answer_id": 5898609, "author": "Cory House", "author_id": 26180, "author_profile": "https://Stackoverflow.com/users/26180", "pm_score": 4, "selected": false, "text": "<p>Clean the solution and rebuild. I've seen webmethods throw 500's until you do this.</p>\n" }, { "answer_id": 17837848, "author": "Tukaram", "author_id": 2613382, "author_profile": "https://Stackoverflow.com/users/2613382", "pm_score": 2, "selected": false, "text": "<p>Add <code>public static</code> before your method...</p>\n\n<p>ex. </p>\n\n<pre><code>[WebMethod]\npublic static string MethodName() {} \n</code></pre>\n" }, { "answer_id": 66999229, "author": "JustSomeGuyInWorld", "author_id": 11872132, "author_profile": "https://Stackoverflow.com/users/11872132", "pm_score": 1, "selected": false, "text": "<p>For ajax success:</p>\n<p>For me, it was helpful to make:</p>\n<ol>\n<li><p>App_Start\\RouteConfig</p>\n<p>set\nfrom</p>\n</li>\n</ol>\n<pre class=\"lang-cs prettyprint-override\"><code>settings.AutoRedirectMode = RedirectMode.Permanent;\n</code></pre>\n<p>to</p>\n<pre class=\"lang-cs prettyprint-override\"><code>settings.AutoRedirectMode = RedirectMode.Off;\n</code></pre>\n<ol start=\"2\">\n<li>make your using method:</li>\n</ol>\n<pre class=\"lang-cs prettyprint-override\"><code>public\n\nstatic\n</code></pre>\n<ol start=\"3\">\n<li>add:</li>\n</ol>\n<pre class=\"lang-cs prettyprint-override\"><code>using System.Web.Services;\n</code></pre>\n<p>and on top of method using just:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>[WebMethod] \n</code></pre>\n<p>is enough</p>\n" }, { "answer_id": 71754205, "author": "Priyank Raunak", "author_id": 11409162, "author_profile": "https://Stackoverflow.com/users/11409162", "pm_score": 0, "selected": false, "text": "<p>First Of All Don't Forget To Include\nusing System.Web.Services;</p>\n<p>And Make Sure Your Method Should Be Public And Static and avoid adding Multiple Scripts in same Page like jquerymin.js shouldn't be used for every Function/Method in same Page</p>\n<p>[WebMethod]\npublic static sting MethodName(){}</p>\n<p>I Had The Same Issue Which Using Ajax And Jquery To Check Username Exists\nOr Not.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ]
This is my first time attempting to call an ASP.NET page method from jQuery. I am getting a status 500 error with the responseText message that the web method cannot be found. Here is my jQuery $.ajax call: ``` function callCancelPlan(activePlanId, ntLogin) { var paramList = '{"activePlanId":"' + activePlanId + '","ntLogin":"' + ntLogin + '"}'; $.ajax({ type: "POST", url: "ArpWorkItem.aspx/CancelPlan", data: paramList, contentType: "application/json; charset=utf-8", dataType: "json", success: function() { alert("success"); }, error: function(xml,textStatus,errorThrown) { alert(xml.status + "||" + xml.responseText); } }); } ``` And here is the page method I am trying to call: ``` [WebMethod()] private static void CancelPlan(int activePlanId, string ntLogin) { StrategyRetrievalPresenter presenter = new StrategyRetrievalPresenter(); presenter.CancelExistingPlan(offer, ntLogin); } ``` I have tried this by decorating the Web Method with and without the parens'()'. Anyone have an idea?
Your web method needs to be public and static.
179,938
<p>i'm want to have a repeater generate a bunch of checkboxes, e.g.:</p> <pre><code>&lt;tr&gt;&lt;td&gt;&lt;input type="checkbox" name="t" value="11cbf4deb87" /&gt; &lt;input type="checkbox" name="a" value="33cbf4deb87" /&gt;stackoverflow.com&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;input type="checkbox" name="t" value="11cbf4deb88" /&gt; &lt;input type="checkbox" name="a" value="33cbf4deb87" /&gt;microsoft.com&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;input type="checkbox" name="t" value="11cd3f33a89" /&gt; &lt;input type="checkbox" name="a" value="33cbf4deb87" /&gt;gmail.com&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;input type="checkbox" name="t" value="1138fecd337" /&gt; &lt;input type="checkbox" name="a" value="33cbf4deb87" /&gt;youporn.com&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;input type="checkbox" name="t" value="11009efdacc" /&gt; &lt;input type="checkbox" name="a" value="33bf4deb87" /&gt;fantasti.cc&lt;/td&gt;&lt;/tr&gt; </code></pre> <p>Question 1: How do i individually reference each checkbox when the repeater is running so i can set the unique value?</p> <p>Do i data-bind it with something like:</p> <pre><code>&lt;itemtemplate&gt; &lt;tr&gt; &lt;td&gt; &lt;input type="checkbox" name="t" value="&lt;%# ((Item)Container.DataItem).TangoUniquifier %&gt;" /&gt; &lt;input type="checkbox" name="a" value="&lt;%# ((Item)Container.DataItem).AlphaUniquifier %&gt;" /&gt; &lt;%# ((Item)Container.DataItem).SiteName %&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/itemtemplate&gt; </code></pre> <p>Or am i supposed to set it somehow in the OnItemDataBound?</p> <pre><code>&lt;asp:repeater id="ItemsRepeater" OnItemDataBound="ItemsRepeater_OnItemDataBound" runat="server"&gt; ... &lt;itemtemplate&gt; &lt;tr&gt; &lt;td&gt; &lt;input id="chkTango" type="checkbox" name="t" runat="server" /&gt; &lt;input id="chkAlpha" type="checkbox" name="a" runat="server" /&gt; &lt;%# ((Item)Container.DataItem).SiteName %&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/itemtemplate&gt; ... &lt;/asp:repeater&gt; protected void ItemsRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e) { // if the data bound item is an item or alternating item (not the header etc) if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { // get the associated item Item item = (Item)e.Item.DataItem; //??? this.chkTango.Value = item.TangoUniquifier; this.chkAlpha.Value = item.AlphaUniquifier; } } </code></pre> <p>But if i'm supposed to reference it in the code-behind, how do i reference it in the code-behind? Am i supposed to reference it using the (server-side) id property of an <code>&lt;INPUT&gt;</code> control? i realize that the ID of a control on the server-side is not the same as the ID that will be present on the client.</p> <p>Or do i have to do something where i have to find an INPUT control with a name of "t" and another with a name of "a"? And what kind of control is a CheckBox that allows me to set it's input value?</p> <pre><code>protected void ItemsRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e) { // if the data bound item is an item or alternating item (not the header etc) if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { // get the associated item Item item = (Item)e.Item.DataItem; CheckBox chkTango = (CheckBox)e.Item.FindControl("chkTango"); chkTango.Value = item.TangoUniquifier; CheckBox chkAlpha = (CheckBox)e.Item.FindControl("chkAlpha"); chkAlpha.Value = item.AlphaUniquifier; } } </code></pre> <hr> <p>Question 2: When the user later clicks SUBMIT, how do i find all the checked checkboxes, or more specifically their VALUES?</p> <p>Do i have to FindControl?</p> <pre><code>protected void DoStuffWithLinks_Click(object sender, EventArgs e) { // loop through the repeater items foreach (RepeaterItem repeaterItem in actionItemRepeater.Items) { Item item = repeaterItem.DataItem as Item; // grab the checkboxes CheckBox chkAlpha = (CheckBox)repeaterItem.FindControl("chkAlpha"); CheckBox chkTango = (CheckBox)repeaterItem.FindControl("chkTango"); if (chkAlpha.Checked) { item.DoAlphaStuff(chkAlpha.Name); } if (chkTango.Checked) { item.DoTangoStuff(chkTango.Name); } } } </code></pre> <p>Is the repeater items DataItem still there on a click event handler?</p>
[ { "answer_id": 179974, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 2, "selected": false, "text": "<p>You might find it easier to use a CheckBoxList control.</p>\n\n<p>In the simple case, you would set the DataTextVield and the DataValueField to the name and value as pulled from your datasource (assuming you're populating from a datasource) and then bind it to create the items.</p>\n\n<p>Probably less work on your part than creating the checkboxes in a repeater.</p>\n" }, { "answer_id": 180307, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 5, "selected": true, "text": "<p>Use the server control instead of making an input control runat=server</p>\n\n<pre><code> &lt;asp:CheckBox id=\"whatever\" runat=\"Server\" /&gt;\n</code></pre>\n\n<p>When you set the value in your ItemDataBound, you use FindControl</p>\n\n<pre><code>CheckBox checkBox = (CheckBox)e.Item.FindControl(\"whatever\");\ncheckBox.Checked = true;\n</code></pre>\n\n<p>When you get the items, you also use FindControl from the item in a foreach construct. Also, depending on how you databound it, the DataItem may no longer be there after a postback.</p>\n\n<pre><code>foreach (RepeaterItem item in myRepeater.Items)\n{\n if (item.ItemType == ListItemType.Item \n || item.ItemType == ListItemType.AlternatingItem) \n { \n CheckBox checkBox = (CheckBox)item.FindControl(\"whatever\");\n if (checkBox.Checked)\n { /* do something */ }\n }\n}\n</code></pre>\n\n<ul>\n<li>Many people are tempted to 'safe cast' using the <code>as</code> operator with <code>FindControl()</code>. I don't like that because when you change the control name on the form, you can silently ignore a development error and make it harder to track down. I try to only use the <code>as</code> operator if the control isn't guaranteed to be there.</li>\n</ul>\n\n<p>Update for: <em>Which CheckBox is which?</em> In the rendered html you'll end up having all these checkbox name like</p>\n\n<pre><code>ctl00_cph0_ParentContainer_MyRepeater_ctl01_MyCheckbox\nctl00_cph0_ParentContainer_MyRepeater_ctl02_MyCheckbox\nctl00_cph0_ParentContainer_MyRepeater_ctl03_MyCheckbox\n</code></pre>\n\n<p>You don't care what the names are because the foreach item.FindControl() gets them for you, and you shouldn't assume anything about them. However, when you iterate via foreach, you usually need a way to reference that back to something. Most of the time this is done by also having an asp:HiddenField control alongside each CheckBox to hold an identifier to match it back up to the correct entity. </p>\n\n<p><em>Security note</em>: there is a security issue with using hidden fields because a hidden field can be altered in javascript; always be conscious that this value could have been modified by the user before the form was submitted. </p>\n" }, { "answer_id": 1364892, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Here is some specific code for how to handle the hidden field:</p>\n\n<p>MARKUP:</p>\n\n<pre><code>&lt;asp:HiddenField ID=\"repeaterhidden\" Value='&lt;%# DataBinder.Eval(Container.DataItem, \"value\")%&gt;' runat=\"server\" &gt;\n</code></pre>\n\n<p>C#: </p>\n\n<p>{</p>\n\n<pre><code>HiddenField hiddenField = (HiddenField)item.FindControl(repeaterStringhidden);\n\n{ /* do something with hiddenField.Value */\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 9737116, "author": "marquito", "author_id": 461076, "author_profile": "https://Stackoverflow.com/users/461076", "pm_score": 1, "selected": false, "text": "<p>I believe this KB gave me the best answer:</p>\n<p><a href=\"http://msdn.microsoft.com/en-us/library/1d04y8ss.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/1d04y8ss.aspx</a></p>\n<p>to my own lack of luck, this seems to be available for the .net 4.0 version only (and I'm still stuck at 3.5 SP1).</p>\n<p>quoting (bold is mine):</p>\n<blockquote>\n<p>When a control is inside a data-bound control that generates repeated instances of the control, ASP.NET generates <strong>UniqueID and ClientID values for each instance</strong> of the control. The UniqueID value is generated by combining the naming container's UniqueID value, the control's ID value, and a sequential number. This is the case in controls such as the DataList, <strong>Repeater</strong>, GridView, and ListView controls.</p>\n<p>ASP.NET generates ClientID values in a similar manner when the ClientIDMode property is set to AutoID. This can make it difficult to reference the control in client script, because you typically cannot predict the values of the sequential numbers that are used. If you want to access data-bound controls from client script, you can <strong>set the ClientIDMode property to Predictable.</strong> This makes it easier to predict what the ClientID values will be.</p>\n<p>When you set the ClientIDMode to Predictable, you can <strong>also set the ClientIDRowSuffixDataKeys property to the name of a data field that is unique</strong>, such as the primary key in a database table. This causes ASP.NET to generate a client ID that will be easier to predict and reference in client script if you can predict data key values.</p>\n</blockquote>\n<p>So, in version 3.5, I'm doing it using hidden fields:</p>\n<pre><code> foreach (RepeaterItem item in rptClientes.Items)\n {\n Panel pnl = (Panel)item.FindControl(&quot;divCliente&quot;);\n Control c = pnl.FindControl(&quot;hdnID&quot;);\n if (c is HiddenField)\n {\n if (((HiddenField)c).Value == hdnClienteNome.Value)\n pnl.BackColor = System.Drawing.Color.Beige;\n }\n }\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
i'm want to have a repeater generate a bunch of checkboxes, e.g.: ``` <tr><td><input type="checkbox" name="t" value="11cbf4deb87" /> <input type="checkbox" name="a" value="33cbf4deb87" />stackoverflow.com</td></tr> <tr><td><input type="checkbox" name="t" value="11cbf4deb88" /> <input type="checkbox" name="a" value="33cbf4deb87" />microsoft.com</td></tr> <tr><td><input type="checkbox" name="t" value="11cd3f33a89" /> <input type="checkbox" name="a" value="33cbf4deb87" />gmail.com</td></tr> <tr><td><input type="checkbox" name="t" value="1138fecd337" /> <input type="checkbox" name="a" value="33cbf4deb87" />youporn.com</td></tr> <tr><td><input type="checkbox" name="t" value="11009efdacc" /> <input type="checkbox" name="a" value="33bf4deb87" />fantasti.cc</td></tr> ``` Question 1: How do i individually reference each checkbox when the repeater is running so i can set the unique value? Do i data-bind it with something like: ``` <itemtemplate> <tr> <td> <input type="checkbox" name="t" value="<%# ((Item)Container.DataItem).TangoUniquifier %>" /> <input type="checkbox" name="a" value="<%# ((Item)Container.DataItem).AlphaUniquifier %>" /> <%# ((Item)Container.DataItem).SiteName %> </td> </tr> </itemtemplate> ``` Or am i supposed to set it somehow in the OnItemDataBound? ``` <asp:repeater id="ItemsRepeater" OnItemDataBound="ItemsRepeater_OnItemDataBound" runat="server"> ... <itemtemplate> <tr> <td> <input id="chkTango" type="checkbox" name="t" runat="server" /> <input id="chkAlpha" type="checkbox" name="a" runat="server" /> <%# ((Item)Container.DataItem).SiteName %> </td> </tr> </itemtemplate> ... </asp:repeater> protected void ItemsRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e) { // if the data bound item is an item or alternating item (not the header etc) if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { // get the associated item Item item = (Item)e.Item.DataItem; //??? this.chkTango.Value = item.TangoUniquifier; this.chkAlpha.Value = item.AlphaUniquifier; } } ``` But if i'm supposed to reference it in the code-behind, how do i reference it in the code-behind? Am i supposed to reference it using the (server-side) id property of an `<INPUT>` control? i realize that the ID of a control on the server-side is not the same as the ID that will be present on the client. Or do i have to do something where i have to find an INPUT control with a name of "t" and another with a name of "a"? And what kind of control is a CheckBox that allows me to set it's input value? ``` protected void ItemsRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e) { // if the data bound item is an item or alternating item (not the header etc) if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { // get the associated item Item item = (Item)e.Item.DataItem; CheckBox chkTango = (CheckBox)e.Item.FindControl("chkTango"); chkTango.Value = item.TangoUniquifier; CheckBox chkAlpha = (CheckBox)e.Item.FindControl("chkAlpha"); chkAlpha.Value = item.AlphaUniquifier; } } ``` --- Question 2: When the user later clicks SUBMIT, how do i find all the checked checkboxes, or more specifically their VALUES? Do i have to FindControl? ``` protected void DoStuffWithLinks_Click(object sender, EventArgs e) { // loop through the repeater items foreach (RepeaterItem repeaterItem in actionItemRepeater.Items) { Item item = repeaterItem.DataItem as Item; // grab the checkboxes CheckBox chkAlpha = (CheckBox)repeaterItem.FindControl("chkAlpha"); CheckBox chkTango = (CheckBox)repeaterItem.FindControl("chkTango"); if (chkAlpha.Checked) { item.DoAlphaStuff(chkAlpha.Name); } if (chkTango.Checked) { item.DoTangoStuff(chkTango.Name); } } } ``` Is the repeater items DataItem still there on a click event handler?
Use the server control instead of making an input control runat=server ``` <asp:CheckBox id="whatever" runat="Server" /> ``` When you set the value in your ItemDataBound, you use FindControl ``` CheckBox checkBox = (CheckBox)e.Item.FindControl("whatever"); checkBox.Checked = true; ``` When you get the items, you also use FindControl from the item in a foreach construct. Also, depending on how you databound it, the DataItem may no longer be there after a postback. ``` foreach (RepeaterItem item in myRepeater.Items) { if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) { CheckBox checkBox = (CheckBox)item.FindControl("whatever"); if (checkBox.Checked) { /* do something */ } } } ``` * Many people are tempted to 'safe cast' using the `as` operator with `FindControl()`. I don't like that because when you change the control name on the form, you can silently ignore a development error and make it harder to track down. I try to only use the `as` operator if the control isn't guaranteed to be there. Update for: *Which CheckBox is which?* In the rendered html you'll end up having all these checkbox name like ``` ctl00_cph0_ParentContainer_MyRepeater_ctl01_MyCheckbox ctl00_cph0_ParentContainer_MyRepeater_ctl02_MyCheckbox ctl00_cph0_ParentContainer_MyRepeater_ctl03_MyCheckbox ``` You don't care what the names are because the foreach item.FindControl() gets them for you, and you shouldn't assume anything about them. However, when you iterate via foreach, you usually need a way to reference that back to something. Most of the time this is done by also having an asp:HiddenField control alongside each CheckBox to hold an identifier to match it back up to the correct entity. *Security note*: there is a security issue with using hidden fields because a hidden field can be altered in javascript; always be conscious that this value could have been modified by the user before the form was submitted.
179,940
<p>We are developing a C# application for a web-service client. This will run on Windows XP PC's.</p> <p>One of the fields returned by the web service is a DateTime field. The server returns a field in GMT format i.e. with a "Z" at the end.</p> <p>However, we found that .NET seems to do some kind of implicit conversion and the time was always 12 hours out.</p> <p>The following code sample resolves this to some extent in that the 12 hour difference has gone but it makes no allowance for NZ daylight saving.</p> <pre><code>CultureInfo ci = new CultureInfo("en-NZ"); string date = "Web service date".ToString("R", ci); DateTime convertedDate = DateTime.Parse(date); </code></pre> <p>As per <a href="http://www.timeanddate.com/worldclock/city.html?n=22" rel="noreferrer">this date site</a>:</p> <blockquote> <p>UTC/GMT Offset </p> <p>Standard time zone: UTC/GMT +12 hours<br> Daylight saving time: +1 hour<br> Current time zone offset: <strong>UTC/GMT +13 hours</strong> </p> </blockquote> <p>How do we adjust for the extra hour? Can this be done programmatically or is this some kind of setting on the PC's?</p>
[ { "answer_id": 179966, "author": "coder1", "author_id": 3018, "author_profile": "https://Stackoverflow.com/users/3018", "pm_score": 6, "selected": false, "text": "<pre><code>TimeZone.CurrentTimeZone.ToLocalTime(date);\n</code></pre>\n" }, { "answer_id": 180105, "author": "rbrayb", "author_id": 9922, "author_profile": "https://Stackoverflow.com/users/9922", "pm_score": 2, "selected": false, "text": "<p>In answer to Dana's suggestion:</p>\n\n<p>The code sample now looks like:</p>\n\n<pre><code>string date = \"Web service date\"..ToString(\"R\", ci);\nDateTime convertedDate = DateTime.Parse(date); \nDateTime dt = TimeZone.CurrentTimeZone.ToLocalTime(convertedDate);\n</code></pre>\n\n<p>The original date was 20/08/08; the kind was UTC.</p>\n\n<p>Both \"convertedDate\" and \"dt\" are the same:</p>\n\n<p>21/08/08 10:00:26; the kind was local</p>\n" }, { "answer_id": 180126, "author": "Miles", "author_id": 21828, "author_profile": "https://Stackoverflow.com/users/21828", "pm_score": 1, "selected": false, "text": "<p>I had the problem with it being in a data set being pushed across the wire (webservice to client) that it would automatically change because the DataColumn's DateType field was set to local. Make sure you check what the DateType is if your pushing DataSets across.</p>\n\n<p>If you don't want it to change, set it to Unspecified</p>\n" }, { "answer_id": 182453, "author": "Mark T", "author_id": 10722, "author_profile": "https://Stackoverflow.com/users/10722", "pm_score": 4, "selected": false, "text": "<p>I'd just like to add a general note of caution.</p>\n\n<p>If all you are doing is getting the current time from the computer's internal clock to put a date/time on the display or a report, then all is well. But if you are <b>saving</b> the date/time information for later reference or are <b>computing</b> date/times, beware!</p>\n\n<p>Let's say you determine that a cruise ship arrived in Honolulu on 20 Dec 2007 at 15:00 UTC. And you want to know what local time that was.<br>\n<b>1.</b> There are probably at least three 'locals' involved. Local may mean Honolulu, or it may mean where your computer is located, or it may mean the location where your customer is located.<br>\n<b>2.</b> If you use the built-in functions to do the conversion, it will probably be wrong. This is because daylight savings time is (probably) currently in effect on your computer, but was NOT in effect in December. But Windows does not know this... all it has is one flag to determine if daylight savings time is currently in effect. And if it is currently in effect, then it will happily add an hour even to a date in December.<br>\n<b>3.</b> Daylight savings time is implemented differently (or not at all) in various political subdivisions. Don't think that just because your country changes on a specific date, that other countries will too.</p>\n" }, { "answer_id": 182552, "author": "Brendan Kowitz", "author_id": 25767, "author_profile": "https://Stackoverflow.com/users/25767", "pm_score": 3, "selected": false, "text": "<p>Don't forget if you already have a DateTime object and are not sure if it's UTC or Local, it's easy enough to use the methods on the object directly:</p>\n\n<pre><code>DateTime convertedDate = DateTime.Parse(date);\nDateTime localDate = convertedDate.ToLocalTime();\n</code></pre>\n\n<blockquote>\n <p>How do we adjust for the extra hour?</p>\n</blockquote>\n\n<p>Unless specified .net will use the local pc settings. I'd have a read of: <a href=\"http://msdn.microsoft.com/en-us/library/system.globalization.daylighttime.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.globalization.daylighttime.aspx</a></p>\n\n<p>By the looks the code might look something like:</p>\n\n<pre><code>DaylightTime daylight = TimeZone.CurrentTimeZone.GetDaylightChanges( year );\n</code></pre>\n\n<p>And as mentioned above double check what timezone setting your server is on. There are articles on the net for how to safely affect the changes in IIS.</p>\n" }, { "answer_id": 455965, "author": "Daniel Ballinger", "author_id": 54026, "author_profile": "https://Stackoverflow.com/users/54026", "pm_score": 7, "selected": false, "text": "<p>I'd look into using the System.TimeZoneInfo class if you are in .NET 3.5. See <a href=\"http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx</a>. This should take into account the daylight savings changes correctly.</p>\n\n<pre><code>// Coordinated Universal Time string from \n// DateTime.Now.ToUniversalTime().ToString(\"u\");\nstring date = \"2009-02-25 16:13:00Z\"; \n// Local .NET timeZone.\nDateTime localDateTime = DateTime.Parse(date); \nDateTime utcDateTime = localDateTime.ToUniversalTime();\n\n// ID from: \n// \"HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zone\"\n// See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.id.aspx\nstring nzTimeZoneKey = \"New Zealand Standard Time\";\nTimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(nzTimeZoneKey);\nDateTime nzDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, nzTimeZone);\n</code></pre>\n" }, { "answer_id": 963812, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 9, "selected": false, "text": "<p>For strings such as <code>2012-09-19 01:27:30.000</code>, <code>DateTime.Parse</code> cannot tell what time zone the date and time are from.</p>\n\n<p><code>DateTime</code> has a <em>Kind</em> property, which can have one of three time zone options:</p>\n\n<ul>\n<li>Unspecified</li>\n<li>Local</li>\n<li>Utc</li>\n</ul>\n\n<p><strong>NOTE</strong> <em>If you are wishing to represent a date/time other than UTC or your local time zone, then you should use <a href=\"http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx\" rel=\"noreferrer\"><code>DateTimeOffset</code></a>.</em></p>\n\n<hr>\n\n<p>So for the code in your question:</p>\n\n<pre><code>DateTime convertedDate = DateTime.Parse(dateStr);\n\nvar kind = convertedDate.Kind; // will equal DateTimeKind.Unspecified\n</code></pre>\n\n<p>You say you know what kind it is, so tell it.</p>\n\n<pre><code>DateTime convertedDate = DateTime.SpecifyKind(\n DateTime.Parse(dateStr),\n DateTimeKind.Utc);\n\nvar kind = convertedDate.Kind; // will equal DateTimeKind.Utc\n</code></pre>\n\n<p>Now, once the system knows its in UTC time, you can just call <code>ToLocalTime</code>:</p>\n\n<pre><code>DateTime dt = convertedDate.ToLocalTime();\n</code></pre>\n\n<p>This will give you the result you require.</p>\n" }, { "answer_id": 1514136, "author": "DannykPowell", "author_id": 67617, "author_profile": "https://Stackoverflow.com/users/67617", "pm_score": 1, "selected": false, "text": "<p>I came across this question as I was having a problem with the UTC dates you get back through the twitter API (created_at field on a status); I need to convert them to DateTime. None of the answers/ code samples in the answers on this page were sufficient to stop me getting a \"String was not recognized as a valid DateTime\" error (but it's the closest I have got to finding the correct answer on SO)</p>\n\n<p>Posting this link here in case this helps someone else - the answer I needed was found on this blog post: <a href=\"http://www.wduffy.co.uk/blog/parsing-dates-when-aspnets-datetimeparse-doesnt-work/\" rel=\"nofollow noreferrer\">http://www.wduffy.co.uk/blog/parsing-dates-when-aspnets-datetimeparse-doesnt-work/</a> - basically use DateTime.ParseExact with a format string instead of DateTime.Parse</p>\n" }, { "answer_id": 7905548, "author": "David", "author_id": 654199, "author_profile": "https://Stackoverflow.com/users/654199", "pm_score": 4, "selected": false, "text": "<p>I know this is an older question, but I ran into a similar situation, and I wanted to share what I had found for future searchers, possibly including myself :).</p>\n\n<p><code>DateTime.Parse()</code> can be tricky -- see <a href=\"http://blog.aasheim.org/2008/04/dont-use-datetimeparse-use.html\" rel=\"nofollow noreferrer\">here</a> for example.</p>\n\n<p>If the <code>DateTime</code> is coming from a Web service or some other source with a known format, you might want to consider something like </p>\n\n<pre><code>DateTime.ParseExact(dateString, \n \"MM/dd/yyyy HH:mm:ss\", \n CultureInfo.InvariantCulture, \n DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)\n</code></pre>\n\n<p>or, even better,</p>\n\n<pre><code>DateTime.TryParseExact(...)\n</code></pre>\n\n<p>The <code>AssumeUniversal</code> flag tells the parser that the date/time is already UTC; the combination of <code>AssumeUniversal</code> and <code>AdjustToUniversal</code> tells it not to convert the result to \"local\" time, which it will try to do by default. (I personally try to deal exclusively with UTC in the business / application / service layer(s) anyway. But bypassing the conversion to local time also speeds things up -- by 50% or more in my tests, see below.)</p>\n\n<p>Here's what we were doing before: </p>\n\n<pre><code>DateTime.Parse(dateString, new CultureInfo(\"en-US\"))\n</code></pre>\n\n<p>We had profiled the app and found that the DateTime.Parse represented a significant percentage of CPU usage. (Incidentally, the <code>CultureInfo</code> constructor was <em>not</em> a significant contributor to CPU usage.) </p>\n\n<p>So I set up a console app to parse a date/time string 10000 times in a variety of ways. Bottom line:<br>\n<code>Parse()</code> 10 sec<br>\n<code>ParseExact()</code> (converting to local) 20-45 ms<br>\n<code>ParseExact()</code> (not converting to local) 10-15 ms<br>\n... and yes, the results for <code>Parse()</code> are in <em>seconds</em>, whereas the others are in <em>milliseconds</em>.</p>\n" }, { "answer_id": 13410106, "author": "CJ7", "author_id": 327528, "author_profile": "https://Stackoverflow.com/users/327528", "pm_score": 5, "selected": false, "text": "<p><code>DateTime</code> objects have the <code>Kind</code> of <code>Unspecified</code> by default, which for the purposes of <code>ToLocalTime</code> is assumed to be <code>UTC</code>.</p>\n\n<p>To get the local time of an <code>Unspecified</code> <code>DateTime</code> object, you therefore just need to do this:</p>\n\n<pre><code>convertedDate.ToLocalTime();\n</code></pre>\n\n<p>The step of changing the <code>Kind</code> of the <code>DateTime</code> from <code>Unspecified</code> to <code>UTC</code> is unnecessary. <code>Unspecified</code> is assumed to be <code>UTC</code> for the purposes of <code>ToLocalTime</code>: <a href=\"http://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx\">http://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx</a></p>\n" }, { "answer_id": 44225724, "author": "Prince Prasad", "author_id": 2722284, "author_profile": "https://Stackoverflow.com/users/2722284", "pm_score": 3, "selected": false, "text": "<pre><code>@TimeZoneInfo.ConvertTimeFromUtc(timeUtc, TimeZoneInfo.Local)\n</code></pre>\n" }, { "answer_id": 65817420, "author": "David Al-Yakobi", "author_id": 15038341, "author_profile": "https://Stackoverflow.com/users/15038341", "pm_score": 0, "selected": false, "text": "<p>This code block uses universal time to convert current DateTime object then converts it back to local DateTime. Works perfect for me I hope it helps!</p>\n<pre><code>CreatedDate.ToUniversalTime().ToLocalTime();\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9922/" ]
We are developing a C# application for a web-service client. This will run on Windows XP PC's. One of the fields returned by the web service is a DateTime field. The server returns a field in GMT format i.e. with a "Z" at the end. However, we found that .NET seems to do some kind of implicit conversion and the time was always 12 hours out. The following code sample resolves this to some extent in that the 12 hour difference has gone but it makes no allowance for NZ daylight saving. ``` CultureInfo ci = new CultureInfo("en-NZ"); string date = "Web service date".ToString("R", ci); DateTime convertedDate = DateTime.Parse(date); ``` As per [this date site](http://www.timeanddate.com/worldclock/city.html?n=22): > > UTC/GMT Offset > > > Standard time zone: UTC/GMT +12 hours > > Daylight saving time: +1 hour > > Current time zone offset: **UTC/GMT +13 hours** > > > How do we adjust for the extra hour? Can this be done programmatically or is this some kind of setting on the PC's?
For strings such as `2012-09-19 01:27:30.000`, `DateTime.Parse` cannot tell what time zone the date and time are from. `DateTime` has a *Kind* property, which can have one of three time zone options: * Unspecified * Local * Utc **NOTE** *If you are wishing to represent a date/time other than UTC or your local time zone, then you should use [`DateTimeOffset`](http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx).* --- So for the code in your question: ``` DateTime convertedDate = DateTime.Parse(dateStr); var kind = convertedDate.Kind; // will equal DateTimeKind.Unspecified ``` You say you know what kind it is, so tell it. ``` DateTime convertedDate = DateTime.SpecifyKind( DateTime.Parse(dateStr), DateTimeKind.Utc); var kind = convertedDate.Kind; // will equal DateTimeKind.Utc ``` Now, once the system knows its in UTC time, you can just call `ToLocalTime`: ``` DateTime dt = convertedDate.ToLocalTime(); ``` This will give you the result you require.
179,955
<p>Many Java Apps don't use anti-aliased fonts by default, despite the capability of Swing to provide them. How can you coerce an arbitrary java application to use AA fonts? (both for applications I'm running, and applications I'm developing)</p>
[ { "answer_id": 179971, "author": "rcreswick", "author_id": 3446, "author_profile": "https://Stackoverflow.com/users/3446", "pm_score": 7, "selected": true, "text": "<p>If you have access to the source, you can do this in the main method:</p>\n\n<pre><code> // enable anti-aliased text:\n System.setProperty(\"awt.useSystemAAFontSettings\",\"on\");\n</code></pre>\n\n<p>or, (and if you do not have access to the source, or if this is easier) you can simply pass the system properties above into the jvm by adding these options to the command line:</p>\n\n<pre><code>-Dawt.useSystemAAFontSettings=on\n</code></pre>\n" }, { "answer_id": 180027, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<p>thanks for the info. I was wondering about this myself.\nI use SoapUI(www.eviware.com) and it does NOT, by default, use AA text. I added \n-Dawt.useSystemAAFontSettings=on -Dswing.aatext=true to the batch file that launches it BUT that did NOT make a difference. Guess, I have to ask in their forum.</p>\n" }, { "answer_id": 4793618, "author": "Al-Khwarizmi", "author_id": 589004, "author_profile": "https://Stackoverflow.com/users/589004", "pm_score": 3, "selected": false, "text": "<p>For the record, I have found out that in my windows 7 machine,</p>\n\n<ul>\n<li>If I don't use this in my code, I get the nice ClearType subpixel rendering.</li>\n<li>But if I use this, I get the classical black-and-white antialiasing which is much uglier.</li>\n</ul>\n\n<p>So this code should be used carefully. I guess it will stop being needed at all when all Linux users have updated to the versions of OpenJDK that handle aliasing well by default.</p>\n" }, { "answer_id": 11990630, "author": "Luke Usherwood", "author_id": 932359, "author_profile": "https://Stackoverflow.com/users/932359", "pm_score": 3, "selected": false, "text": "<p>Swing controls in the latest versions of Java 6 / 7 should automatically abide by system-wide preferences. (If you're using the Windows L&amp;F on a Windows OS then text should render using ClearType if you have that setting enabled system-wide.) So perhaps one solution could simply be: enable the native Look and Feel?</p>\n\n<p>In applications you're developing, if you render your own text directly, you also need to do something like this (at some point before calling <code>Graphics.drawText</code> or friends):</p>\n\n<pre><code>if (desktopHints == null) { \n Toolkit tk = Toolkit.getDefaultToolkit(); \n desktopHints = (Map) (tk.getDesktopProperty(\"awt.font.desktophints\")); \n}\nif (desktopHints != null) { \n g2d.addRenderingHints(desktopHints); \n} \n</code></pre>\n\n<p>Reference: <a href=\"http://weblogs.java.net/blog/chet/archive/2007/01/font_hints_for.html\">http://weblogs.java.net/blog/chet/archive/2007/01/font_hints_for.html</a></p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3446/" ]
Many Java Apps don't use anti-aliased fonts by default, despite the capability of Swing to provide them. How can you coerce an arbitrary java application to use AA fonts? (both for applications I'm running, and applications I'm developing)
If you have access to the source, you can do this in the main method: ``` // enable anti-aliased text: System.setProperty("awt.useSystemAAFontSettings","on"); ``` or, (and if you do not have access to the source, or if this is easier) you can simply pass the system properties above into the jvm by adding these options to the command line: ``` -Dawt.useSystemAAFontSettings=on ```
179,985
<p>We have a database library in C# that we can use like this:</p> <pre><code>DatabaseConnection conn = DatabaseConnection.FromConnectionString("..."); </code></pre> <p>This library hides many of the differences between different database engines, like SQL function names, parameter names and specifications, etc.</p> <p>Internally, the <code>DatabaseConnection</code> class is an abstract class implementing some of the basic methods, but the <code>FromConnectionString</code> method runs through a list of registered specialized types that handles the actual differences, and constructs an object of the right class. In other words, I don't get a DatabaseConnection object back, I get a MSSQLDatabaseConnection or OracleDatabaseConnection object back instead, which of course inherit from DatabaseConnection.</p> <p>The connection string contains information about what kind of database engine and version this connection is for.</p> <p>I'd like to create a similar library in Python. Is the right approach to make something that can be constructed like this?</p> <pre><code>conn = DatabaseConnection("...") </code></pre> <p>or using a class method?</p> <pre><code>conn = DatabaseConnection.FromConnectionString("...") </code></pre> <p>is the first even possible, that is... constructing an object like this and getting back something else, a specialized object, depending on data in the passed string?</p> <p>Ok, let me ask a different question... What is the <em>pythonic</em> way of doing this?</p> <p>I basically want to have the DatabaseConnection base class in Python as well, implementing the common methods, and specialize in derived classes, and have a method or function somewhere that based on the connection string constructs and returns the right type of object.</p>
[ { "answer_id": 180009, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 4, "selected": true, "text": "<p>This is possible in Python, but is probably not the best way to do it. The class factory pattern is essentially a workaround for languages that don't have first class classes. Since Python does have first class classes, you can store a class in a variable, and use that class directly to create instances. To change what class is created, store a different class in the variable.</p>\n\n<p>For example:</p>\n\n<pre><code>class class1:\n def greet(self):\n print \"hi\"\n\nclass class2:\n def greet(self):\n print \"hello\"\n\nmaker = class1\nobj1 = maker()\n\nmaker = class2\nobj2 = maker()\n\nobj1.greet() # prints \"hi\"\nobj2.greet() # prints \"hello\"\n</code></pre>\n" }, { "answer_id": 180028, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 1, "selected": false, "text": "<p>The first one is absolutely possible, and preferable in my opinion. In python, there's really not a whole lot of magic behind constructors. For all intents and purposes, they're just like any other function. I've used this design pattern a few times to indicate that a class shouldn't be instantiated directly, for example:</p>\n\n<pre><code>def DatabaseConnectionFromString(connection_string)\n return _DatabaseConnection(connection_string)\n\ndef DatabaseConnectionFromSomethingElse(something_else)\n connection_string = convert_something_else_into_string(something_else)\n return _DatabaseConnection(connection_string)\n\nclass _DatabaseConnection(object):\n def __init__(self, connection_string):\n self.connection_string = connection_string\n</code></pre>\n\n<p>Of course, that's a contrived example, but that should give you a general idea.</p>\n\n<p><strong>EDIT:</strong> This is also one of the areas where inheritance isn't quite as frowned upon in python as well. You can also do this:</p>\n\n<pre><code>DatabaseConnection(object):\n def __init__(self, connection_string):\n self.connection_string = connection_string\n\nDatabaseConnectionFromSomethingElse(object)\n def __init__(self, something_else):\n self.connection_string = convert_something_else_into_string(something_else)\n</code></pre>\n\n<p>Sorry that's so verbose, but I wanted to make it clear.</p>\n" }, { "answer_id": 180142, "author": "Sanjaya R", "author_id": 9353, "author_profile": "https://Stackoverflow.com/users/9353", "pm_score": 2, "selected": false, "text": "<p>Python doesn't care why type you return.</p>\n\n<pre><code>def DatabaseConnection( str ): \n if ( IsOracle( str ) ): \n return OracleConnection( str ) \n else: \n return SomeOtherConnection( str )\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
We have a database library in C# that we can use like this: ``` DatabaseConnection conn = DatabaseConnection.FromConnectionString("..."); ``` This library hides many of the differences between different database engines, like SQL function names, parameter names and specifications, etc. Internally, the `DatabaseConnection` class is an abstract class implementing some of the basic methods, but the `FromConnectionString` method runs through a list of registered specialized types that handles the actual differences, and constructs an object of the right class. In other words, I don't get a DatabaseConnection object back, I get a MSSQLDatabaseConnection or OracleDatabaseConnection object back instead, which of course inherit from DatabaseConnection. The connection string contains information about what kind of database engine and version this connection is for. I'd like to create a similar library in Python. Is the right approach to make something that can be constructed like this? ``` conn = DatabaseConnection("...") ``` or using a class method? ``` conn = DatabaseConnection.FromConnectionString("...") ``` is the first even possible, that is... constructing an object like this and getting back something else, a specialized object, depending on data in the passed string? Ok, let me ask a different question... What is the *pythonic* way of doing this? I basically want to have the DatabaseConnection base class in Python as well, implementing the common methods, and specialize in derived classes, and have a method or function somewhere that based on the connection string constructs and returns the right type of object.
This is possible in Python, but is probably not the best way to do it. The class factory pattern is essentially a workaround for languages that don't have first class classes. Since Python does have first class classes, you can store a class in a variable, and use that class directly to create instances. To change what class is created, store a different class in the variable. For example: ``` class class1: def greet(self): print "hi" class class2: def greet(self): print "hello" maker = class1 obj1 = maker() maker = class2 obj2 = maker() obj1.greet() # prints "hi" obj2.greet() # prints "hello" ```
179,987
<p>I am in a situation where I must update an existing database structure from varchar to nvarchar using a script. Since this script is run everytime a configuration application is run, I would rather determine if a column has already been changed to nvarchar and not perform an alter on the table. The databases which I must support are SQL Server 2000, 2005 and 2008. </p>
[ { "answer_id": 180022, "author": "Peter", "author_id": 5189, "author_profile": "https://Stackoverflow.com/users/5189", "pm_score": 3, "selected": true, "text": "<p>The following query should get you what you need:</p>\n\n<pre><code>IF EXISTS \n (SELECT *\n FROM sysobjects syo\n JOIN syscolumns syc ON\n syc.id = syo.id\n JOIN systypes syt ON\n syt.xtype = syc.xtype\n WHERE \n syt.name = 'nvarchar' AND\n syo.name = 'MY TABLE NAME' AND\n syc.name = 'MY COLUMN NAME')\nBEGIN\n ALTER ...\nEND\n</code></pre>\n" }, { "answer_id": 180161, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 5, "selected": false, "text": "<p>You can run the following script which will give you a set of ALTER commands:</p>\n\n<pre><code>SELECT 'ALTER TABLE ' + isnull(schema_name(syo.id), 'dbo') + '.' + syo.name \n + ' ALTER COLUMN ' + syc.name + ' NVARCHAR(' + case syc.length when -1 then 'MAX' \n ELSE convert(nvarchar(10),syc.length) end + ');'\n FROM sysobjects syo\n JOIN syscolumns syc ON\n syc.id = syo.id\n JOIN systypes syt ON\n syt.xtype = syc.xtype\n WHERE \n syt.name = 'varchar' \n and syo.xtype='U'\n</code></pre>\n\n<p>There are, however, a couple of quick <em>caveats</em> for you. </p>\n\n<ol>\n<li>This will only do tables. You'll want to scan all of your sprocs and functions to make sure they are changed to <code>NVARCHAR</code> as well.</li>\n<li>If you have a <code>VARCHAR</code> > 4000 you will need to modify it to be <code>NVARCHAR(MAX)</code></li>\n</ol>\n\n<p>But those should be easily doable with this template.</p>\n\n<p>If you want this to run automagically you can set it in a <code>WHILE</code> clause.</p>\n" }, { "answer_id": 13468461, "author": "Appyks", "author_id": 900087, "author_profile": "https://Stackoverflow.com/users/900087", "pm_score": 2, "selected": false, "text": "<p>Fixed the space issue and added schema</p>\n\n<pre><code>SELECT 'ALTER TABLE [' + isnull(schema_name(syo.object_id), sysc.name) + '].[' + syo.name \n + '] ALTER COLUMN ' + syc.name + ' NVARCHAR(' + case syc.max_length when -1 then 'MAX' \n ELSE convert(nvarchar(10),syc.max_length) end + ');'\n FROM sys.objects syo\n JOIN sys.columns syc ON\n syc.object_id= syo.object_id\n JOIN sys.types syt ON\n syt.system_type_id = syc.system_type_id\n JOIN sys.schemas sysc ON\n syo.schema_id=sysc.schema_id\n WHERE \n syt.name = 'varchar' \n and syo.type='U'\n</code></pre>\n" }, { "answer_id": 31827056, "author": "Nezam", "author_id": 1221203, "author_profile": "https://Stackoverflow.com/users/1221203", "pm_score": 2, "selected": false, "text": "<p>The issue with Josef's answer is that it would change <code>NOT NULL</code> fields to <code>NULL</code> after executing the queries. The following manipulation fixes it:</p>\n\n<pre><code>SELECT cmd = 'alter table [' + c.table_schema + '].[' + c.table_name \n + '] alter column [' + c.column_name + '] nvarchar('\n +CASE WHEN CHARACTER_MAXIMUM_LENGTH&lt;=4000\n THEN CAST(CHARACTER_MAXIMUM_LENGTH as varchar(10)) ELSE 'max' END+')' \n + CASE WHEN IS_NULLABLE='NO' THEN ' NOT NULL' ELSE '' END,*\nFROM information_schema.columns c\nWHERE c.data_type='varchar' \nORDER BY CHARACTER_MAXIMUM_LENGTH desc\n</code></pre>\n\n<blockquote>\n <p><strong>Credits to <a href=\"https://stackoverflow.com/a/31691558/1221203\">Igor's answer</a></strong></p>\n</blockquote>\n" }, { "answer_id": 54932584, "author": "hobwell", "author_id": 1781344, "author_profile": "https://Stackoverflow.com/users/1781344", "pm_score": 0, "selected": false, "text": "<p>Further updated to fix MAX being replaced with -1.</p>\n\n<pre><code>SELECT cmd = 'ALTER TABLE [' + c.table_schema + '].[' + c.table_name \n + '] ALTER COLUMN [' + c.column_name + '] NVARCHAR('\n +CASE WHEN CHARACTER_MAXIMUM_LENGTH&lt;=4000 THEN \n CASE WHEN CHARACTER_MAXIMUM_LENGTH = -1 THEN\n 'MAX' ELSE CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10)) END ELSE 'MAX' END+')' \n + CASE WHEN IS_NULLABLE='NO' THEN ' NOT NULL' ELSE '' END,*\nFROM information_schema.columns c\nWHERE c.data_type='VARCHAR' \nORDER BY CHARACTER_MAXIMUM_LENGTH DESC\n</code></pre>\n\n<p>Credit to <a href=\"https://stackoverflow.com/a/31827056/1781344\">Nezam's Answer</a></p>\n\n<p>And another one to manage default values:</p>\n\n<pre><code>SELECT cmd = \nCASE WHEN name IS NOT NULL THEN\n 'ALTER TABLE ' + c.table_name + ' DROP CONSTRAINT ' + d.name + '; ' +\n 'ALTER TABLE [' + c.table_schema + '].[' + c.table_name + '] ALTER COLUMN [' + c.column_name + '] ' + \n 'NVARCHAR(' +\n CASE WHEN CHARACTER_MAXIMUM_LENGTH &lt;= 4000 THEN \n CASE WHEN CHARACTER_MAXIMUM_LENGTH = -1 THEN\n 'MAX' \n ELSE \n CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10)) \n END \n ELSE \n 'MAX' \n END \n + ')' +\n CASE WHEN IS_NULLABLE='NO' THEN ' NOT NULL' ELSE '' END + '; ' + \n 'ALTER TABLE '+ c.table_name + ' ADD CONSTRAINT ' + d.name +' DEFAULT '+ c.column_default + ' FOR ' + c.column_name + ';'\nELSE\n 'ALTER TABLE [' + c.table_schema + '].[' + c.table_name + '] ALTER COLUMN [' + c.column_name + '] ' +\n 'NVARCHAR(' +\n CASE WHEN CHARACTER_MAXIMUM_LENGTH&lt;=4000 THEN\n CASE WHEN CHARACTER_MAXIMUM_LENGTH = -1 THEN\n 'MAX' \n ELSE \n CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10)) \n END \n ELSE \n 'MAX' \n END\n + ')' +\n CASE WHEN IS_NULLABLE='NO' THEN ' NOT NULL' ELSE '' END \nEND,d.name, c.*\nFROM information_schema.columns c\nLEFT OUTER JOIN sys.default_constraints d ON d.parent_object_id = object_id(c.table_name)\nAND d.parent_column_id = columnproperty(object_id(c.table_name), c.column_name, 'ColumnId')\nWHERE c.data_type='VARCHAR' \nORDER BY CHARACTER_MAXIMUM_LENGTH DESC\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4441/" ]
I am in a situation where I must update an existing database structure from varchar to nvarchar using a script. Since this script is run everytime a configuration application is run, I would rather determine if a column has already been changed to nvarchar and not perform an alter on the table. The databases which I must support are SQL Server 2000, 2005 and 2008.
The following query should get you what you need: ``` IF EXISTS (SELECT * FROM sysobjects syo JOIN syscolumns syc ON syc.id = syo.id JOIN systypes syt ON syt.xtype = syc.xtype WHERE syt.name = 'nvarchar' AND syo.name = 'MY TABLE NAME' AND syc.name = 'MY COLUMN NAME') BEGIN ALTER ... END ```
179,988
<p>Wanted to see peoples thoughts on best way to organize directory and project structure on a project / solution for a winforms C# app. </p> <p>Most people agree its best to seperate view, business logic, data objects, interfaces but wanted to see how different people tackle this. In addition, isolate third party dependencies into implementation projects and then have interface exported projects that consumers reference </p> <p><li>View.csproj <li>BusinessLogic.csproj <li>Data.csproj <li>CalculatorService.Exported.csproj (interfaces) <li>CalculatorService.MyCalcImpl.csproj (one implementation) <li>CalculatorService.MyCalcImpl2.csproj (another implementation)</p> <p>Also, in terms of folder structure, what is better nesting:</p> <p>Interfaces<br> ---IFoo<br> ---IData<br> Impl<br> ---Foo<br> ---Data </p> <p>or </p> <p>Product<br> ---Interfaces/IProduct<br> ---Impl/Product<br> Foo<br> ---Impl/Foo<br> ---Interfaces/IFoo </p> <p>All trying to push for decoupled dependencies on abstractions and quick ability to changed implementations.</p> <p>Thoughts? Best practices?</p>
[ { "answer_id": 180029, "author": "Bill", "author_id": 14547, "author_profile": "https://Stackoverflow.com/users/14547", "pm_score": 0, "selected": false, "text": "<p>We usually keep SourceSafe projects, project names, namespaces and directory structures in sync. </p>\n\n<p>For example, given our company name as XCENT the SourceSafe structure and the corresponding directory structure for App1 looks like:</p>\n\n<pre><code>\\XCENT\n\\XCENT\\App1\n\\XCENT\\App1\\UI\n\\XCENT\\App1\\UI\\Test //test harness for UI\n\\XCENT\\App1\\Data\n\\XCENT\\App1\\Data\\Test //test harnesses for Data\n</code></pre>\n\n<p>etc.</p>\n\n<p>The UI project is named XCENT.App1.UI.cproj, and the classes within that namespace are XCENT.App1.UI</p>\n\n<p>We work for many clients as well so work specifically for them is prefixed with their name. Client1\\App1\\UI, etc.</p>\n\n<p>Everybody in our firm uses the same conventions and it is immediately clear where everything fits.</p>\n\n<p>If it makes sense to segment logical spacing further we do so. Such other segmentation includes .Export, .Import, .Reporting, .Security, etc.</p>\n" }, { "answer_id": 180701, "author": "Odd", "author_id": 11908, "author_profile": "https://Stackoverflow.com/users/11908", "pm_score": 4, "selected": true, "text": "<p>For me it depends on the model I'm following. If I'm using MVC it would be</p>\n\n<pre><code>Project\n-Models\n-Controllers\n-Views\n</code></pre>\n\n<p>Or for MVP it would be</p>\n\n<pre><code>Project\n-Models\n-Presenters\n-Views\n</code></pre>\n\n<p>Under the views I seperate them into namespaces relevant to the controllers, i.e. if I have a controller to handle inventory transactions I might have it as</p>\n\n<pre><code>Project\n-Models\n--Inventory\n-Controllers\n--Inventory\n---TransactionsController.cs\n-Views\n--Inventory\n---Transactions\n----EditTransactionsView.dfm\n</code></pre>\n\n<p>For interfaces I put the interface in the same directory as the implementations.</p>\n" }, { "answer_id": 6209673, "author": "Nick Bedford", "author_id": 151429, "author_profile": "https://Stackoverflow.com/users/151429", "pm_score": 3, "selected": false, "text": "<p>Bit of a late answer but may as well chime in.</p>\n\n<p>I have been personally using folders based on the actual type of item it is. For example:</p>\n\n<pre><code>- Project\n + Forms\n + Classes\n + UserControls\n + Resources\n + Data\n</code></pre>\n\n<p>So I end up with:</p>\n\n<pre><code>new Forms.AboutForm().ShowDialog();\nControls.Add(new Controls.UberTextBox());\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
Wanted to see peoples thoughts on best way to organize directory and project structure on a project / solution for a winforms C# app. Most people agree its best to seperate view, business logic, data objects, interfaces but wanted to see how different people tackle this. In addition, isolate third party dependencies into implementation projects and then have interface exported projects that consumers reference - View.csproj - BusinessLogic.csproj - Data.csproj - CalculatorService.Exported.csproj (interfaces) - CalculatorService.MyCalcImpl.csproj (one implementation) - CalculatorService.MyCalcImpl2.csproj (another implementation) Also, in terms of folder structure, what is better nesting: Interfaces ---IFoo ---IData Impl ---Foo ---Data or Product ---Interfaces/IProduct ---Impl/Product Foo ---Impl/Foo ---Interfaces/IFoo All trying to push for decoupled dependencies on abstractions and quick ability to changed implementations. Thoughts? Best practices?
For me it depends on the model I'm following. If I'm using MVC it would be ``` Project -Models -Controllers -Views ``` Or for MVP it would be ``` Project -Models -Presenters -Views ``` Under the views I seperate them into namespaces relevant to the controllers, i.e. if I have a controller to handle inventory transactions I might have it as ``` Project -Models --Inventory -Controllers --Inventory ---TransactionsController.cs -Views --Inventory ---Transactions ----EditTransactionsView.dfm ``` For interfaces I put the interface in the same directory as the implementations.
180,003
<p>I would like a code sample for a function that takes a tDateTime and an integer as input and sets the system time using setlocaltime after advancing that tDateTime by (int) months. The time should stay the same.</p> <p>pseudo code example</p> <pre><code>SetNewTime(NOW,2); </code></pre> <p>The issues I'm running into are rather frustrating. I cannot use incmonth or similar with a tDateTime, only a tDate, etc.</p>
[ { "answer_id": 180065, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 4, "selected": true, "text": "<p>Below is a complete command-line program that works for me. Tested in Delphi 5 and 2007. Why do you say <a href=\"http://www.delphibasics.co.uk/RTL.asp?Name=IncMonth\" rel=\"nofollow noreferrer\">IncMonth</a> does not work for TDateTime?</p>\n\n<pre><code>program OneMonth;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils,\n Windows,\n Messages;\n\nprocedure SetLocalSystemTime(settotime: TDateTime);\nvar\n SystemTime : TSystemTime;\nbegin\n DateTimeToSystemTime(settotime,SystemTime);\n SetLocalTime(SystemTime);\n //tell windows that the time changed\n PostMessage(HWND_BROADCAST,WM_TIMECHANGE,0,0);\nend;\n\nbegin\n try\n SetLocalSystemTime(IncMonth(Now,1));\n except on E:Exception do\n Writeln(E.Classname, ': ', E.Message);\n end;\nend.\n</code></pre>\n" }, { "answer_id": 180116, "author": "Bruce McGee", "author_id": 19183, "author_profile": "https://Stackoverflow.com/users/19183", "pm_score": 1, "selected": false, "text": "<p>Based on your pseudocode:</p>\n\n<pre><code>procedure SetNewTime(aDateTime: TDateTime; aMonths: Integer);\nvar\n lSystemTime: TSystemTime;\nbegin\n DateTimeToSystemTime(aDateTime, lSystemTime);\n Inc(lSystemTime.wMonth, aMonths);\n setSystemTime(lSystemTime);\nend;\n</code></pre>\n" }, { "answer_id": 180331, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 2, "selected": false, "text": "<p>IncMonth should work with a <a href=\"http://www.delphibasics.co.uk/RTL.asp?Name=IncMonth\" rel=\"nofollow noreferrer\">TDateTime</a>:</p>\n\n<pre><code>function IncMonth ( const StartDate : TDateTime {; NumberOfMonths : Integer = 1} ) : TDateTime;\n</code></pre>\n\n<p>Keep in mind a TDate is really just a TDateTime that by convention your ignore the fraction on.</p>\n" }, { "answer_id": 180718, "author": "Bruce McGee", "author_id": 19183, "author_profile": "https://Stackoverflow.com/users/19183", "pm_score": 1, "selected": false, "text": "<p>setSystemTime uses UTC time, so you have to adjust for your time zone. The bias is the number of minutes your machine's timezone differs from UTC. This adjusts the date properly on my system:</p>\n\n<pre><code>procedure SetNewTime(aDateTime: TDateTime; aMonths: Integer);\nvar\n lSystemTime: TSystemTime;\n lTimeZone: TTimeZoneInformation;\n begin\n GetTimeZoneInformation(lTimeZone);\n aDateTime := aDateTime + (lTimeZone.Bias / 1440);\n DateTimeToSystemTime(aDateTime, lSystemTime);\n Inc(lSystemTime.wMonth, aMonths);\n setSystemTime(lSystemTime);\nend;\n</code></pre>\n" }, { "answer_id": 185518, "author": "user26293", "author_id": 26293, "author_profile": "https://Stackoverflow.com/users/26293", "pm_score": 0, "selected": false, "text": "<p>There isn't enough information to provide a definitive answer to your question. </p>\n\n<p>Consider what you would want to happen if the day of the current month doesn't exist in your future month. Say, January 31 + 1 month. (7 months of the year have 31 days and the rest have fewer.) You have the same problem if you increment the year and the starting date is February 29 on a leap year. So there can't be a universal IncMonth or IncYear function that will work consistantly on all dates. </p>\n\n<p>For anyone interested, I heartily recommend <a href=\"http://www.boyet.com/Articles/PublishedArticles/Calculatingthenumberofmon.html\" rel=\"nofollow noreferrer\">Julian Bucknall's article</a> on the complexities that are inherent in this type of calculation\non how to calculate the number of months and days between two dates.</p>\n\n<p>The following is the only generic date increment functions possible that do not introduce anomolies into generic date math. But it only accomplishes this by shifting the responsibility back onto the programmer who presumably has the exact requirements of the specific application he/she is programming.</p>\n\n<p><a href=\"http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate3/EN/html/delphivclwin32/DateUtils_IncDay.html\" rel=\"nofollow noreferrer\">IncDay</a> - Add a or subtract a number of days.<br>\n<a href=\"http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate3/EN/html/delphivclwin32/DateUtils_IncWeek.html\" rel=\"nofollow noreferrer\">IncWeek</a> - Add or subtract a number of weeks.<br></p>\n\n<p>But if you must use the built in functions then at least be sure that they do what you want them to do. Have a look at the DateUtils and SysUtils units. Having the source code to these functions is one of the coolest aspects of Delphi. Having said that, here is the complete list of built in functions:</p>\n\n<p><a href=\"http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate3/EN/html/delphivclwin32/DateUtils_IncDay.html\" rel=\"nofollow noreferrer\">IncDay</a> - Add a or subtract a number of days.<br>\n<a href=\"http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate3/EN/html/delphivclwin32/DateUtils_IncWeek.html\" rel=\"nofollow noreferrer\">IncWeek</a> - Add or subtract a number of weeks.<br>\n<a href=\"http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate4/EN/html/delphivclwin32/SysUtils_IncMonth.html\" rel=\"nofollow noreferrer\">IncMonth</a> - Add a or subtract a number of months.<br>\n<a href=\"http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate3/EN/html/delphivclwin32/DateUtils_IncYear.html\" rel=\"nofollow noreferrer\">IncYear</a> - Add a or subtract a number of years.</p>\n\n<p>As for the second part of your question, how to set the system date &amp; time using a TDatetime, the following shamelessly stolen code from another post will do the job once you have a TDatetime that has the value you want:</p>\n\n<pre><code>procedure SetSystemDateTime(aDateTime: TDateTime);\nvar\n lSystemTime: TSystemTime;\n lTimeZone: TTimeZoneInformation;\n begin\n GetTimeZoneInformation(lTimeZone);\n aDateTime := aDateTime + (lTimeZone.Bias / 1440);\n DateTimeToSystemTime(aDateTime, lSystemTime);\n setSystemTime(lSystemTime);\nend;\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172/" ]
I would like a code sample for a function that takes a tDateTime and an integer as input and sets the system time using setlocaltime after advancing that tDateTime by (int) months. The time should stay the same. pseudo code example ``` SetNewTime(NOW,2); ``` The issues I'm running into are rather frustrating. I cannot use incmonth or similar with a tDateTime, only a tDate, etc.
Below is a complete command-line program that works for me. Tested in Delphi 5 and 2007. Why do you say [IncMonth](http://www.delphibasics.co.uk/RTL.asp?Name=IncMonth) does not work for TDateTime? ``` program OneMonth; {$APPTYPE CONSOLE} uses SysUtils, Windows, Messages; procedure SetLocalSystemTime(settotime: TDateTime); var SystemTime : TSystemTime; begin DateTimeToSystemTime(settotime,SystemTime); SetLocalTime(SystemTime); //tell windows that the time changed PostMessage(HWND_BROADCAST,WM_TIMECHANGE,0,0); end; begin try SetLocalSystemTime(IncMonth(Now,1)); except on E:Exception do Writeln(E.Classname, ': ', E.Message); end; end. ```
180,005
<p>This Linq to SQL query ...</p> <pre><code> Return (From t In Db.Concessions Where t.Country = "ga" Select t.ConcessionID, t.Title, t.Country) </code></pre> <p>... is generating this SQL:</p> <pre><code>SELECT [t0].[ConcessionID], [t0].[Title], [t0].[Country] FROM [dbo].[Concessions] AS [t0] WHERE [t0].[Country] = ga </code></pre> <p>... when what I want is</p> <pre><code>WHERE [t0].[Country] = 'ga' </code></pre> <p>Any ideas why?</p>
[ { "answer_id": 180035, "author": "Jeff Mc", "author_id": 25521, "author_profile": "https://Stackoverflow.com/users/25521", "pm_score": -1, "selected": false, "text": "<p>the select should be</p>\n\n<pre><code>Select New With {t.ConcessionID, t.Title, t.Country}\n</code></pre>\n\n<p>rather than </p>\n\n<pre><code>Select t.ConcessionID, t.Title, t.Country\n</code></pre>\n\n<p>you need to create a new instance of an anonymous type to contain the fields.</p>\n" }, { "answer_id": 180093, "author": "mspmsp", "author_id": 21724, "author_profile": "https://Stackoverflow.com/users/21724", "pm_score": 1, "selected": false, "text": "<p>Wild guess.... could it be?</p>\n\n<p><code>t.Country = \"ga\"</code></p>\n\n<p>vs.</p>\n\n<p><code>t.Country == \"ga\"</code></p>\n" }, { "answer_id": 180186, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>Actually, it shouldn't be generating either of those. It would convert the constant into a parameter, so it would be:</p>\n\n<pre><code>SELECT [t0].[ConcessionID], [t0].[Title], [t0].[Country]\nFROM [dbo].[Concessions] AS [t0]\nWHERE [t0].[Country] = @p0\n</code></pre>\n\n<p>with @p0 passed as 'ga'.\ncould that be that you are seeing?</p>\n" }, { "answer_id": 180188, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 1, "selected": true, "text": "<h2>Answer</h2>\n\n<p>The Country field was a char(2); I changed it to nvarchar(50), and that fixed the problem. Is this a bug in Linq to SQL?</p>\n" }, { "answer_id": 181489, "author": "Stephen M. Redd", "author_id": 10115, "author_profile": "https://Stackoverflow.com/users/10115", "pm_score": 0, "selected": false, "text": "<p>I cannot be sure about this particular example, but there is a known bug that causes similar problems with nvarchar(1) fields. It may be related. </p>\n\n<p>There is a <a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=337188&amp;wa=wsignin1.0\" rel=\"nofollow noreferrer\">bug report here</a> about it and I also <a href=\"http://reddnet.net/code/linq-to-sql-bug-quot-system-formatexception-string-must-be-exactly-one-character-long-quot/\" rel=\"nofollow noreferrer\">wrote about it</a> on my own site too. </p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
This Linq to SQL query ... ``` Return (From t In Db.Concessions Where t.Country = "ga" Select t.ConcessionID, t.Title, t.Country) ``` ... is generating this SQL: ``` SELECT [t0].[ConcessionID], [t0].[Title], [t0].[Country] FROM [dbo].[Concessions] AS [t0] WHERE [t0].[Country] = ga ``` ... when what I want is ``` WHERE [t0].[Country] = 'ga' ``` Any ideas why?
Answer ------ The Country field was a char(2); I changed it to nvarchar(50), and that fixed the problem. Is this a bug in Linq to SQL?
180,030
<p>In windows XP "FileInfo.LastWriteTime" will return the date a picture is taken - regardless of how many times the file is moved around in the filesystem.</p> <p>In Vista it instead returns the date that the picture is copied from the camera.</p> <p>How can I find out when a picture is taken in Vista? In windows explorer this field is referred to as "Date Taken".</p>
[ { "answer_id": 180055, "author": "DaveK", "author_id": 4244, "author_profile": "https://Stackoverflow.com/users/4244", "pm_score": 3, "selected": false, "text": "<p>With WPF and C# you can get the Date Taken property using the BitmapMetadata class:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapmetadata.aspx\" rel=\"noreferrer\">MSDN - BitmapMetada</a></p>\n\n<p><a href=\"http://blogs.vertigosoftware.com/alanl/archive/category/1039.aspx\" rel=\"noreferrer\">WPF and BitmapMetadata</a></p>\n" }, { "answer_id": 180058, "author": "Miles", "author_id": 21828, "author_profile": "https://Stackoverflow.com/users/21828", "pm_score": 1, "selected": false, "text": "<p>you'll have to check the EXIF information from the picture. I don't think with regular .Net functions you'll know when the picture was taken.</p>\n\n<p>It might get a little complicated...</p>\n" }, { "answer_id": 180067, "author": "Paul Hammond", "author_id": 16280, "author_profile": "https://Stackoverflow.com/users/16280", "pm_score": 1, "selected": false, "text": "<p>There will be EXIF data embedded in the image. There are a ton of examples on the web if you search for EXIF and C#.</p>\n" }, { "answer_id": 180406, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>In windows XP \"FileInfo.LastWriteTime\"\n will return the date a picture is\n taken - regardless of how many times\n the file is moved around in the\n filesystem.</p>\n</blockquote>\n\n<p>I have great doubts XP was actually doing that. More likely the tool you used to copy the image from the camera to you hard disk was reseting the File Modified Date to the image's Date Taken.</p>\n" }, { "answer_id": 180455, "author": "sepang", "author_id": 25930, "author_profile": "https://Stackoverflow.com/users/25930", "pm_score": 4, "selected": false, "text": "<pre><code>Image myImage = Image.FromFile(@\"C:\\temp\\IMG_0325.JPG\");\nPropertyItem propItem = myImage.GetPropertyItem(306);\nDateTime dtaken;\n\n//Convert date taken metadata to a DateTime object\nstring sdate = Encoding.UTF8.GetString(propItem.Value).Trim();\nstring secondhalf = sdate.Substring(sdate.IndexOf(\" \"), (sdate.Length - sdate.IndexOf(\" \")));\nstring firsthalf = sdate.Substring(0, 10);\nfirsthalf = firsthalf.Replace(\":\", \"-\");\nsdate = firsthalf + secondhalf;\ndtaken = DateTime.Parse(sdate);\n</code></pre>\n" }, { "answer_id": 7713780, "author": "kDar", "author_id": 987801, "author_profile": "https://Stackoverflow.com/users/987801", "pm_score": 8, "selected": true, "text": "<p>Here's as fast and clean as you can get it. By using FileStream, you can tell GDI+ not to load the whole image for verification. It runs over 10 × as fast on my machine.</p>\n\n<pre><code>//we init this once so that if the function is repeatedly called\n//it isn't stressing the garbage man\nprivate static Regex r = new Regex(\":\");\n\n//retrieves the datetime WITHOUT loading the whole image\npublic static DateTime GetDateTakenFromImage(string path)\n{\n using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))\n using (Image myImage = Image.FromStream(fs, false, false))\n {\n PropertyItem propItem = myImage.GetPropertyItem(36867);\n string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), \"-\", 2);\n return DateTime.Parse(dateTaken);\n }\n}\n</code></pre>\n\n<p>And yes, the correct id is 36867, not 306.</p>\n\n<p>The other Open Source projects below should take note of this. It is a <em>huge</em> performance hit when processing thousands of files.</p>\n" }, { "answer_id": 35244415, "author": "Peter Redei", "author_id": 5892816, "author_profile": "https://Stackoverflow.com/users/5892816", "pm_score": 0, "selected": false, "text": "<pre><code> //retrieves the datetime WITHOUT loading the whole image\n public static DateTime GetDateTakenFromImage(string path)\n {\n using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))\n using (Image myImage = Image.FromStream(fs, false, false))\n {\n PropertyItem propItem = null;\n try\n {\n propItem = myImage.GetPropertyItem(36867);\n }\n catch { }\n if (propItem != null)\n {\n string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), \"-\", 2);\n return DateTime.Parse(dateTaken);\n }\n else\n return new FileInfo(path).LastWriteTime;\n }\n }\n</code></pre>\n" }, { "answer_id": 39839380, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 4, "selected": false, "text": "<p>I maintained a <a href=\"https://github.com/drewnoakes/metadata-extractor-dotnet\" rel=\"noreferrer\">simple open-source library</a> since 2002 for extracting metadata from image/video files.</p>\n\n<pre><code>// Read all metadata from the image\nvar directories = ImageMetadataReader.ReadMetadata(stream);\n\n// Find the so-called Exif \"SubIFD\" (which may be null)\nvar subIfdDirectory = directories.OfType&lt;ExifSubIfdDirectory&gt;().FirstOrDefault();\n\n// Read the DateTime tag value\nvar dateTime = subIfdDirectory?.GetDateTime(ExifDirectoryBase.TagDateTimeOriginal);\n</code></pre>\n\n<p>In my benchmarks, this code runs over 12 times faster than <code>Image.GetPropertyItem</code>, and around 17 times faster than the WPF <code>JpegBitmapDecoder</code>/<code>BitmapMetadata</code> API.</p>\n\n<p>There's a tonne of extra information available from the library such as camera settings (F-stop, ISO, shutter speed, flash mode, focal length, ...), image properties (dimensions, pixel configurations) and other things such as GPS positions, keywords, copyright info, etc.</p>\n\n<p>If you're only interested in the metadata, then using this library is very fast as it doesn't decode the image (i.e. bitmap). You can scan thousands of images in a few seconds if you have fast enough storage.</p>\n\n<p><code>ImageMetadataReader</code> understands many files types (JPEG, PNG, GIF, BMP, TIFF, PCX, WebP, ICO, ...). If you <em>know</em> that you're dealing with JPEG, and you <em>only</em> want Exif data, then you can make the process even faster with the following:</p>\n\n<pre><code>var directories = JpegMetadataReader.ReadMetadata(stream, new[] { new ExifReader() });\n</code></pre>\n\n<p>The <em>metadata-extractor</em> library is available via <a href=\"https://www.nuget.org/packages/MetadataExtractor/\" rel=\"noreferrer\">NuGet</a> and the <a href=\"https://github.com/drewnoakes/metadata-extractor-dotnet\" rel=\"noreferrer\">code's on GitHub</a>. Thanks to all the amazing contributors who have improved the library and submitted test images over the years.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25930/" ]
In windows XP "FileInfo.LastWriteTime" will return the date a picture is taken - regardless of how many times the file is moved around in the filesystem. In Vista it instead returns the date that the picture is copied from the camera. How can I find out when a picture is taken in Vista? In windows explorer this field is referred to as "Date Taken".
Here's as fast and clean as you can get it. By using FileStream, you can tell GDI+ not to load the whole image for verification. It runs over 10 × as fast on my machine. ``` //we init this once so that if the function is repeatedly called //it isn't stressing the garbage man private static Regex r = new Regex(":"); //retrieves the datetime WITHOUT loading the whole image public static DateTime GetDateTakenFromImage(string path) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (Image myImage = Image.FromStream(fs, false, false)) { PropertyItem propItem = myImage.GetPropertyItem(36867); string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2); return DateTime.Parse(dateTaken); } } ``` And yes, the correct id is 36867, not 306. The other Open Source projects below should take note of this. It is a *huge* performance hit when processing thousands of files.
180,032
<p>Right now, I have a SQL Query like this one:</p> <pre><code>SELECT X, Y FROM POINTS </code></pre> <p>It returns results like so:</p> <pre><code>X Y ---------- 12 3 15 2 18 12 20 29 </code></pre> <p>I'd like to return results all in one row, like this (suitable for using in an HTML &lt;AREA&gt; tag):</p> <pre><code>XYLIST ---------- 12,3,15,2,18,12,20,29 </code></pre> <p>Is there a way to do this using just SQL?</p>
[ { "answer_id": 180053, "author": "Peter", "author_id": 5189, "author_profile": "https://Stackoverflow.com/users/5189", "pm_score": 1, "selected": false, "text": "<pre><code>DECLARE @s VarChar(8000)\nSET @s = ''\n\nSELECT @s = @s + ',' + CAST(X AS VarChar) + ',' + CAST(Y AS VarChar) \nFROM POINTS\n\nSELECT @s \n</code></pre>\n\n<p>Just get rid of the leading comma</p>\n" }, { "answer_id": 180060, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 6, "selected": true, "text": "<pre><code>DECLARE @XYList varchar(MAX)\nSET @XYList = ''\n\nSELECT @XYList = @XYList + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y) + ','\nFROM POINTS\n\n-- Remove last comma\nSELECT LEFT(@XYList, LEN(@XYList) - 1)\n</code></pre>\n" }, { "answer_id": 180375, "author": "Joshua Carmody", "author_id": 8409, "author_profile": "https://Stackoverflow.com/users/8409", "pm_score": 7, "selected": false, "text": "<p>Thanks for the quick and helpful answers guys!</p>\n<p>I just found another fast way to do this too:</p>\n<pre><code>SELECT STUFF(( SELECT ',' + X + ',' + Y\n FROM Points\n FOR\n XML PATH('')\n ), 1, 1, '') AS XYList\n</code></pre>\n<p>Credit goes to this guy:</p>\n<p><a href=\"https://web.archive.org/web/20200217202303/http://geekswithblogs.net:80/mnf/archive/2007/10/02/t-sql-user-defined-function-to-concatenate-column-to-csv-string.aspx\" rel=\"nofollow noreferrer\">Link</a></p>\n" }, { "answer_id": 181249, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 4, "selected": false, "text": "<p>Using the <code>COALESCE</code> trick, you don't have to worry about the trailing comma:</p>\n\n<pre><code>DECLARE @XYList AS varchar(MAX) -- Leave as NULL\n\nSELECT @XYList = COALESCE(@XYList + ',', '') + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y)\nFROM POINTS\n</code></pre>\n" }, { "answer_id": 51291223, "author": "Carter Medlin", "author_id": 324479, "author_profile": "https://Stackoverflow.com/users/324479", "pm_score": 4, "selected": false, "text": "<p>Starting in SQL 2017, you can use <code>STRING_AGG</code></p>\n\n<pre><code>SELECT STRING_AGG (X + ',' + Y, ',') AS XYLIST\nFROM POINTS\n</code></pre>\n\n<p><a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017\" rel=\"noreferrer\">https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017</a></p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8409/" ]
Right now, I have a SQL Query like this one: ``` SELECT X, Y FROM POINTS ``` It returns results like so: ``` X Y ---------- 12 3 15 2 18 12 20 29 ``` I'd like to return results all in one row, like this (suitable for using in an HTML <AREA> tag): ``` XYLIST ---------- 12,3,15,2,18,12,20,29 ``` Is there a way to do this using just SQL?
``` DECLARE @XYList varchar(MAX) SET @XYList = '' SELECT @XYList = @XYList + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y) + ',' FROM POINTS -- Remove last comma SELECT LEFT(@XYList, LEN(@XYList) - 1) ```
180,095
<p>I've written a simple multi-threaded game server in python that creates a new thread for each client connection. I'm finding that every now and then, the server will crash because of a broken-pipe/SIGPIPE error. I'm pretty sure it is happening when the program tries to send a response back to a client that is no longer present.</p> <p>What is a good way to deal with this? My preferred resolution would simply close the server-side connection to the client and move on, rather than exit the entire program.</p> <p>PS: <a href="https://stackoverflow.com/questions/108183/how-to-prevent-sigpipes-or-handle-them-properly">This</a> question/answer deals with the problem in a generic way; how specifically should I solve it?</p>
[ { "answer_id": 180152, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 6, "selected": true, "text": "<p>Read up on the try: statement.</p>\n\n<pre><code>try:\n # do something\nexcept socket.error, e:\n # A socket error\nexcept IOError, e:\n if e.errno == errno.EPIPE:\n # EPIPE error\n else:\n # Other error\n</code></pre>\n" }, { "answer_id": 180378, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 2, "selected": false, "text": "<p><code>SIGPIPE</code> (although I think maybe you mean <code>EPIPE</code>?) occurs on sockets when you shut down a socket and then send data to it. The simple solution is not to shut the socket down before trying to send it data. This can also happen on pipes, but it doesn't sound like that's what you're experiencing, since it's a network server.</p>\n\n<p>You can also just apply the band-aid of catching the exception in some top-level handler in each thread.</p>\n\n<p>Of course, if you used <a href=\"http://twistedmatrix.com/\" rel=\"nofollow noreferrer\">Twisted</a> rather than spawning a new thread for each client connection, you probably wouldn't have this problem. It's really hard (maybe impossible, depending on your application) to get the ordering of close and write operations correct if multiple threads are dealing with the same I/O channel.</p>\n" }, { "answer_id": 180421, "author": "Kirk Strauser", "author_id": 32538, "author_profile": "https://Stackoverflow.com/users/32538", "pm_score": -1, "selected": false, "text": "<p>My answer is very close to S.Lott's, except I'd be even more particular:</p>\n\n<pre><code>try:\n # do something\nexcept IOError, e:\n # ooops, check the attributes of e to see precisely what happened.\n if e.errno != 23:\n # I don't know how to handle this\n raise\n</code></pre>\n\n<p>where \"23\" is the error number you get from EPIPE. This way you won't attempt to handle a permissions error or anything else you're not equipped for.</p>\n" }, { "answer_id": 180922, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 6, "selected": false, "text": "<p>Assuming that you are using the standard socket module, you should be catching the <code>socket.error: (32, 'Broken pipe')</code> exception (not IOError as others have suggested). This will be raised in the case that you've described, i.e. sending/writing to a socket for which the remote side has disconnected.</p>\n\n<pre><code>import socket, errno, time\n\n# setup socket to listen for incoming connections\ns = socket.socket()\ns.bind(('localhost', 1234))\ns.listen(1)\nremote, address = s.accept()\n\nprint \"Got connection from: \", address\n\nwhile 1:\n try:\n remote.send(\"message to peer\\n\")\n time.sleep(1)\n except socket.error, e:\n if isinstance(e.args, tuple):\n print \"errno is %d\" % e[0]\n if e[0] == errno.EPIPE:\n # remote peer disconnected\n print \"Detected remote disconnect\"\n else:\n # determine and handle different error\n pass\n else:\n print \"socket error \", e\n remote.close()\n break\n except IOError, e:\n # Hmmm, Can IOError actually be raised by the socket module?\n print \"Got IOError: \", e\n break\n</code></pre>\n\n<p>Note that this exception will not always be raised on the first write to a closed socket - more usually the second write (unless the number of bytes written in the first write is larger than the socket's buffer size). You need to keep this in mind in case your application thinks that the remote end received the data from the first write when it may have already disconnected.</p>\n\n<p>You can reduce the incidence (but not entirely eliminate) of this by using <code>select.select()</code> (or <code>poll</code>). Check for data ready to read from the peer before attempting a write. If <code>select</code> reports that there is data available to read from the peer socket, read it using <code>socket.recv()</code>. If this returns an empty string, the remote peer has closed the connection. Because there is still a race condition here, you'll still need to catch and handle the exception.</p>\n\n<p>Twisted is great for this sort of thing, however, it sounds like you've already written a fair bit of code.</p>\n" }, { "answer_id": 46946689, "author": "yuan", "author_id": 7832332, "author_profile": "https://Stackoverflow.com/users/7832332", "pm_score": -1, "selected": false, "text": "<p>I face with the same question. But I submit the same code the next time, it just works.\nThe first time it broke:</p>\n\n<pre><code>$ packet_write_wait: Connection to 10.. port 22: Broken pipe\n</code></pre>\n\n<p>The second time it works:</p>\n\n<pre><code>[1] Done nohup python -u add_asc_dec.py &gt; add2.log 2&gt;&amp;1\n</code></pre>\n\n<p>I guess the reason may be about the current server environment.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24208/" ]
I've written a simple multi-threaded game server in python that creates a new thread for each client connection. I'm finding that every now and then, the server will crash because of a broken-pipe/SIGPIPE error. I'm pretty sure it is happening when the program tries to send a response back to a client that is no longer present. What is a good way to deal with this? My preferred resolution would simply close the server-side connection to the client and move on, rather than exit the entire program. PS: [This](https://stackoverflow.com/questions/108183/how-to-prevent-sigpipes-or-handle-them-properly) question/answer deals with the problem in a generic way; how specifically should I solve it?
Read up on the try: statement. ``` try: # do something except socket.error, e: # A socket error except IOError, e: if e.errno == errno.EPIPE: # EPIPE error else: # Other error ```
180,097
<p>I need to make some reflective method calls in Java. Those calls will include methods that have arguments that are primitive types (int, double, etc.). The way to specify such types when looking up the method reflectively is int.class, double.class, etc.</p> <p>The challenge is that I am accepting input from an outside source that will specify the types dynamically. Therefore, I need to come up with these Class references dynamically as well. Imagine a delimited file a list of method names with lists of parameter types:</p> <pre><code>doSomething int double doSomethingElse java.lang.String boolean </code></pre> <p>If the input was something like <code>java.lang.String</code>, I know I could use <code>Class.forName("java.lang.String")</code> to that Class instance back. Is there any way to use that method, or another, to get the primitive type Classes back?</p> <p><strong>Edit:</strong> Thanks to all the respondents. It seems clear that there is no built-in way to cleanly do what I want, so I will settle for reusing the <code>ClassUtils</code> class from the Spring framework. It seems to contain a replacement for Class.forName() that will work with my requirements.</p>
[ { "answer_id": 180139, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 5, "selected": false, "text": "<p>The <code>Class</code> instances for the primitive types are obtainable as you said using e.g. <code>int.class</code>, but it is also possible to get the same values using something like <code>Integer.TYPE</code>. Each primitive wrapper class contains a static field, <code>TYPE</code>, which has the corresponding primitive class instance.</p>\n\n<p>You cannot obtain the primitive class via <code>forName</code>, but you can get it from a class which is readily available. If you absolutely must use reflection, you can try something like this:</p>\n\n<pre><code>Class clazz = Class.forName(\"java.lang.Integer\");\nClass intClass = clazz.getField(\"TYPE\").get(null);\n\nintClass.equals(int.class); // =&gt; true\n</code></pre>\n" }, { "answer_id": 180169, "author": "Synoli", "author_id": 17305, "author_profile": "https://Stackoverflow.com/users/17305", "pm_score": 5, "selected": true, "text": "<p>The Spring framework contains a utility class <a href=\"http://static.springframework.org/spring/docs/1.1.5/api/org/springframework/util/ClassUtils.html\" rel=\"nofollow noreferrer\">ClassUtils</a> which contains the static method forName. This method can be used for the exact purpose you described.</p>\n\n<p>In case you don’t like to have a dependency on Spring: the <a href=\"https://github.com/spring-projects/spring-framework/blob/cc74a2891a4d2a4c7bcec059f20c35aa80bcf668/spring-core/src/main/java/org/springframework/util/ClassUtils.java#L203-L271\" rel=\"nofollow noreferrer\">source code of the method</a> can be found <s>e. g. <a href=\"http://fisheye1.atlassian.com/browse/springframework/spring/src/org/springframework/util/ClassUtils.java?r=1.77\" rel=\"nofollow noreferrer\">here</a></s> on their public repository. The class source code is licensed under the Apache 2.0 model.</p>\n\n<p>Note however that the algorithm uses a hard-coded map of primitive types.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> Thanks to commenters Dávid Horváth and Patrick for pointing out the broken link.</p>\n" }, { "answer_id": 180477, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 4, "selected": false, "text": "<p>Probably you just need to map the primitives and for the rest of the classes perform the &quot;forName&quot; method:</p>\n<p>I would do something like:</p>\n<pre><code>void someWhere(){\n String methodDescription = &quot;doSomething int double java.lang.Integer java.lang.String&quot;\n String [] parts = methodDescription.split();\n String methodName= parts[0]\n Class [] paramsTypes = getParamTypes( parts ); // Well, not all the array, but a, sub array from 1 to arr.length.. \n\n Method m = someObject.class.getMethod( methodName, paramTypes );\n etc. etc etc.\n}\n\npublic Class[] paramTypes( String [] array ){\n List&lt;Class&gt; list = new ArrayList&lt;Class&gt;();\n for( String type : array ) {\n if( builtInMap.contains( type )) {\n list.add( builtInMap.get( type ) );\n }else{\n list.add( Class.forName( type ) );\n }\n }\n return list.toArray();\n} \n\n // That's right.\nMap&lt;String,Class&gt; builtInMap = new HashMap&lt;String,Class&gt;();{\n builtInMap.put(&quot;int&quot;, Integer.TYPE );\n builtInMap.put(&quot;long&quot;, Long.TYPE );\n builtInMap.put(&quot;double&quot;, Double.TYPE );\n builtInMap.put(&quot;float&quot;, Float.TYPE );\n builtInMap.put(&quot;bool&quot;, Boolean.TYPE );\n builtInMap.put(&quot;char&quot;, Character.TYPE );\n builtInMap.put(&quot;byte&quot;, Byte.TYPE );\n builtInMap.put(&quot;void&quot;, Void.TYPE );\n builtInMap.put(&quot;short&quot;, Short.TYPE );\n}\n</code></pre>\n<p>That is, create a map where the primitives types are stored and if the description belong to a primitive then use the mapped class. This map may also be loaded from an external configuration file, to add flexibility so you add String as a built in instead of java.lang.String or potentially have method like this.</p>\n<p>&quot;doSomething string yes|no &quot;</p>\n<p>There are lots of this kind of code in OS projects like Struts, Hibernate, Spring and Apache libs ( just to mention a few ) , so you don't need to start from zero.</p>\n" }, { "answer_id": 646735, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 2, "selected": false, "text": "<p>A number of Class methods don't handle primitives in a consistent fashion unfortunately. A common way around this in forName is to have a table like;</p>\n\n<pre><code>private static final Map&lt;String, Class&gt; BUILT_IN_MAP = \n new ConcurrentHashMap&lt;String, Class&gt;();\n\nstatic {\n for (Class c : new Class[]{void.class, boolean.class, byte.class, char.class, \n short.class, int.class, float.class, double.class, long.class})\n BUILT_IN_MAP.put(c.getName(), c);\n}\n\npublic static Class forName(String name) throws ClassNotFoundException {\n Class c = BUILT_IN_MAP.get(name);\n if (c == null)\n // assumes you have only one class loader!\n BUILT_IN_MAP.put(name, c = Class.forName(name));\n return c;\n}\n</code></pre>\n" }, { "answer_id": 12668403, "author": "Arham", "author_id": 1710942, "author_profile": "https://Stackoverflow.com/users/1710942", "pm_score": 2, "selected": false, "text": "<p>The following code talks about how to get the class of a primitive type who's field name is known, e.g. in this case 'sampleInt'.</p>\n\n<pre><code>public class CheckPrimitve {\n public static void main(String[] args) {\n Sample s = new Sample();\n try {\n System.out.println(s.getClass().getField(\"sampleInt\").getType() == int.class); // returns true\n System.out.println(s.getClass().getField(\"sampleInt\").getType().isPrimitive()); // returns true\n } catch (NoSuchFieldException e) { \n e.printStackTrace();\n } catch (SecurityException e) {\n e.printStackTrace();\n } \n }\n}\n\nclass Sample {\n public int sampleInt;\n public Sample() {\n sampleInt = 10;\n }\n}\n</code></pre>\n\n<p>One can also check whether a given value is primitive or not by getting it's respective wrapper class or it's field value.</p>\n\n<pre><code> public class CheckPrimitve {\n public static void main(String[] args) {\n int i = 3;\n Object o = i;\n System.out.println(o.getClass().getSimpleName().equals(\"Integer\")); // returns true\n Field[] fields = o.getClass().getFields();\n for(Field field:fields) {\n System.out.println(field.getType()); // returns {int, int, class java.lang.Class, int}\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 17292204, "author": "thSoft", "author_id": 90874, "author_profile": "https://Stackoverflow.com/users/90874", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://commons.apache.org/proper/commons-lang/\">Apache Commons Lang</a> has <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ClassUtils.html#getClass%28java.lang.String%29\">ClassUtils.getClass(String)</a>, which supports primitive types.</p>\n" }, { "answer_id": 42673473, "author": "Adrodoc", "author_id": 4149050, "author_profile": "https://Stackoverflow.com/users/4149050", "pm_score": 1, "selected": false, "text": "<p>Google Guava offers <code>com.google.common.primitives.Primitives</code> for this sort of stuff.</p>\n" }, { "answer_id": 59038893, "author": "LSafer", "author_id": 11816777, "author_profile": "https://Stackoverflow.com/users/11816777", "pm_score": 0, "selected": false, "text": "<p>You can use this code :)</p>\n\n<pre><code>/**\n * Get an array class of the given class.\n *\n * @param klass to get an array class of\n * @param &lt;C&gt; the targeted class\n * @return an array class of the given class\n */\npublic static &lt;C&gt; Class&lt;C[]&gt; arrayClass(Class&lt;C&gt; klass) {\n return (Class&lt;C[]&gt;) Array.newInstance(klass, 0).getClass();\n}\n\n/**\n * Get the class that extends {@link Object} that represent the given class.\n *\n * @param klass to get the object class of\n * @return the class that extends Object class and represent the given class\n */\npublic static Class&lt;?&gt; objectiveClass(Class&lt;?&gt; klass) {\n Class&lt;?&gt; component = klass.getComponentType();\n if (component != null) {\n if (component.isPrimitive() || component.isArray())\n return Reflect.arrayClass(Reflect.objectiveClass(component));\n } else if (klass.isPrimitive()) {\n if (klass == char.class)\n return Character.class;\n if (klass == int.class)\n return Integer.class;\n if (klass == boolean.class)\n return Boolean.class;\n if (klass == byte.class)\n return Byte.class;\n if (klass == double.class)\n return Double.class;\n if (klass == float.class)\n return Float.class;\n if (klass == long.class)\n return Long.class;\n if (klass == short.class)\n return Short.class;\n }\n\n return klass;\n}\n\n/**\n * Get the class that don't extends {@link Object} from the given class.\n *\n * @param klass to get the non-object class of\n * @return the non-object class of the given class\n * @throws IllegalArgumentException when the given class don't have a primitive type\n */\npublic static Class&lt;?&gt; primitiveClass(Class&lt;?&gt; klass) {\n if (klass == Character.class)\n return char.class;\n if (klass == Integer.class)\n return int.class;\n if (klass == Boolean.class)\n return boolean.class;\n if (klass == Byte.class)\n return byte.class;\n if (klass == Double.class)\n return double.class;\n if (klass == Float.class)\n return float.class;\n if (klass == Long.class)\n return long.class;\n if (klass == Short.class)\n return short.class;\n\n throw new IllegalArgumentException(klass + \" don't have a primitive type\");\n}\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3005/" ]
I need to make some reflective method calls in Java. Those calls will include methods that have arguments that are primitive types (int, double, etc.). The way to specify such types when looking up the method reflectively is int.class, double.class, etc. The challenge is that I am accepting input from an outside source that will specify the types dynamically. Therefore, I need to come up with these Class references dynamically as well. Imagine a delimited file a list of method names with lists of parameter types: ``` doSomething int double doSomethingElse java.lang.String boolean ``` If the input was something like `java.lang.String`, I know I could use `Class.forName("java.lang.String")` to that Class instance back. Is there any way to use that method, or another, to get the primitive type Classes back? **Edit:** Thanks to all the respondents. It seems clear that there is no built-in way to cleanly do what I want, so I will settle for reusing the `ClassUtils` class from the Spring framework. It seems to contain a replacement for Class.forName() that will work with my requirements.
The Spring framework contains a utility class [ClassUtils](http://static.springframework.org/spring/docs/1.1.5/api/org/springframework/util/ClassUtils.html) which contains the static method forName. This method can be used for the exact purpose you described. In case you don’t like to have a dependency on Spring: the [source code of the method](https://github.com/spring-projects/spring-framework/blob/cc74a2891a4d2a4c7bcec059f20c35aa80bcf668/spring-core/src/main/java/org/springframework/util/ClassUtils.java#L203-L271) can be found ~~e. g. [here](http://fisheye1.atlassian.com/browse/springframework/spring/src/org/springframework/util/ClassUtils.java?r=1.77)~~ on their public repository. The class source code is licensed under the Apache 2.0 model. Note however that the algorithm uses a hard-coded map of primitive types. --- **Edit:** Thanks to commenters Dávid Horváth and Patrick for pointing out the broken link.
180,103
<p>I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document. What is correct way (if any) to set the title of the document?</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function() { // ??? }); &lt;/script&gt; </code></pre>
[ { "answer_id": 180118, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 5, "selected": false, "text": "<p>Like this:</p>\n\n<pre><code>$(document).ready(function ()\n{\n document.title = \"Hello World!\";\n});\n</code></pre>\n\n<p>Be sure to set a default-title if you want your site to be properly indexed by search-engines.</p>\n\n<p>A little tip:</p>\n\n<pre><code>$(function ()\n{\n // this is a shorthand for the whole document-ready thing\n // In my opinion, it's more readable \n});\n</code></pre>\n" }, { "answer_id": 180122, "author": "Atanas Korchev", "author_id": 10141, "author_profile": "https://Stackoverflow.com/users/10141", "pm_score": 4, "selected": false, "text": "<pre><code>&lt;script type=\"text/javascript\"&gt;\n$(document).ready(function() {\n\n $(this).attr(\"title\", \"sometitle\");\n\n});\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 180129, "author": "dpan", "author_id": 8911, "author_profile": "https://Stackoverflow.com/users/8911", "pm_score": 9, "selected": true, "text": "<p>The following should work but it wouldn't be SEO compatible. It's best to put the title in the title tag.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n\n $(document).ready(function() {\n document.title = 'blah';\n });\n\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 188868, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document.</p>\n</blockquote>\n\n<p>The correct way to do this is on the server side.</p>\n\n<p>In your layout, there at some point will be some code which <em>puts the text in the div</em>. Make this code also set some instance variable such as <code>@page_title</code>, and then in your outer layout have it do <code>&lt;%= @page_title || 'Default Title' %&gt;</code></p>\n" }, { "answer_id": 4063283, "author": "vasio", "author_id": 492771, "author_profile": "https://Stackoverflow.com/users/492771", "pm_score": 6, "selected": false, "text": "<p>Do not use <code>$('title').text('hi')</code>, because IE doesn't support it.</p>\n\n<p>It is better to use <code>document.title = 'new title';</code></p>\n" }, { "answer_id": 4989558, "author": "Albert", "author_id": 615824, "author_profile": "https://Stackoverflow.com/users/615824", "pm_score": 6, "selected": false, "text": "<p>This works fine in all browser...</p>\n\n<pre><code>$(document).attr(\"title\", \"New Title\");\n</code></pre>\n\n<p>Works in IE too</p>\n" }, { "answer_id": 8063034, "author": "andreas", "author_id": 1037340, "author_profile": "https://Stackoverflow.com/users/1037340", "pm_score": -1, "selected": false, "text": "<p>If you have got a serverside script get_title.php that echoes the current title session this works fine in jQuery:</p>\n\n<pre><code>$.get('get_title.php',function(*respons*){\n title=*respons* + 'whatever you want' \n $(document).attr('title',title)\n})\n</code></pre>\n" }, { "answer_id": 11171548, "author": "John F", "author_id": 1477123, "author_profile": "https://Stackoverflow.com/users/1477123", "pm_score": 3, "selected": false, "text": "<p>document.title was not working for me.</p>\n\n<p>Here is another way to do it using JQuery</p>\n\n<pre><code>$('html head').find('title').text(\"My New Page Title\");\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18811/" ]
I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document. What is correct way (if any) to set the title of the document? ``` <script type="text/javascript"> $(document).ready(function() { // ??? }); </script> ```
The following should work but it wouldn't be SEO compatible. It's best to put the title in the title tag. ``` <script type="text/javascript"> $(document).ready(function() { document.title = 'blah'; }); </script> ```
180,119
<p>I recently started working on a small game for my own amusement, using Microsoft XNA and C#. My question is in regards to designing a game object and the objects that inherit it. I'm going to define a game object as something that can be rendered on screen. So for this, I decided to make a base class which all other objects that will need to be rendered will inherit, called GameObject. The code below is the class I made:</p> <pre><code>class GameObject { private Model model = null; private float scale = 1f; private Vector3 position = Vector3.Zero; private Vector3 rotation = Vector3.Zero; private Vector3 velocity = Vector3.Zero; private bool alive = false; protected ContentManager content; #region Constructors public GameObject(ContentManager content, string modelResource) { this.content = content; model = content.Load&lt;Model&gt;(modelResource); } public GameObject(ContentManager content, string modelResource, bool alive) : this(content, modelResource) { this.alive = alive; } public GameObject(ContentManager content, string modelResource, bool alive, float scale) : this(content, modelResource, alive) { this.scale = scale; } public GameObject(ContentManager content, string modelResource, bool alive, float scale, Vector3 position) : this(content, modelResource, alive, scale) { this.position = position; } public GameObject(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation) : this(content, modelResource, alive, scale, position) { this.rotation = rotation; } public GameObject(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation, Vector3 velocity) : this(content, modelResource, alive, scale, position, rotation) { this.velocity = velocity; } #endregion } </code></pre> <p>I've left out extra methods that do things such as rotate, move, and draw the object. Now if I wanted to create another object, like a ship, I'd create a Ship class, which would inherit GameObject. Sample code below:</p> <pre><code>class Ship : GameObject { private int num_missiles = 20; // the number of missiles this ship can have alive at any given time private Missile[] missiles; private float max_missile_distance = 3000f; // max distance a missile can be from the ship before it dies #region Constructors public Ship(ContentManager content, string modelResource) : base(content, modelResource) { InitShip(); } public Ship(ContentManager content, string modelResource , bool alive) : base(content, modelResource, alive) { InitShip(); } public Ship(ContentManager content, string modelResource, bool alive, float scale) : base(content, modelResource, alive, scale) { InitShip(); } public Ship(ContentManager content, string modelResource, bool alive, float scale, Vector3 position) : base(content, modelResource, alive, scale, position) { InitShip(); } public Ship(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation) : base(content, modelResource, alive, scale, position, rotation) { InitShip(); } public Ship(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation, Vector3 velocity) : base(content, modelResource, alive, scale, position, rotation, velocity) { InitShip(); } #endregion } </code></pre> <p>Again, I've left out any extra Ship-specific methods, like firing a missile. Do you think that this sort of design is good or should it be improved somehow or changed completely? It seems like the constructors for child classes is messy, but maybe that's the only way to do it. I've never done anything like this and am wondering if I'm way off track.</p> <hr> <p>Thanks to everyone that left an answer. They were all very helpful. There seems to be a general consensus that changing it around to use an MVC pattern would be best. I'm going to look further into exactly how to do that. I'll also be removing most of the constructors and will have just one constructor, because all of the arguments after modelResource aren't necessary to create the object, and they can all be changed later through method calls.</p>
[ { "answer_id": 180146, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 2, "selected": false, "text": "<p>This design doesn't separate the UI parts of an object and the behavior parts of an object, the \"model\" and \"view\" so to speak. This is not necessarily a bad thing, but you might find the following refactorings difficult if you continue with this design:</p>\n\n<ul>\n<li>Re-skinning the game by changing all the art assets</li>\n<li>Changing the behavior of many different in-game objects, for example the rules that determine whether or not an object is alive</li>\n<li>Changing to a different sprite engine. </li>\n</ul>\n\n<p>But if you are OK with these tradeoffs and this design makes sense to you, I see nothing egregiously wrong with it. </p>\n" }, { "answer_id": 180174, "author": "NM.", "author_id": 10347, "author_profile": "https://Stackoverflow.com/users/10347", "pm_score": 3, "selected": false, "text": "<p>Personally I find the sheer number of constructors you have a little offputting, but that's your choice, nothing fundamentally wrong with it :)</p>\n\n<p>With regards to the general strategy of deriving game objects from a common base, that's a pretty common way to do things. Standard, even. I've tended to start using something far more akin to MVC, with incredibly lightweight \"model\" game objects that contain only data.</p>\n\n<p>Other common approaches I've seen in XNA include / things you may want to consider:</p>\n\n<ul>\n<li>Implementation of an IRenderable interface rather than doing any render code in the base or derived classes. For instance, you may want game objects that are never rendered - waypoints or somesuch.</li>\n<li>You could make your base class abstract, you're not likely to want to ever instantiate a GameObject.</li>\n</ul>\n\n<p>Again though, minor points. Your design is fine. </p>\n" }, { "answer_id": 180177, "author": "Davy8", "author_id": 23822, "author_profile": "https://Stackoverflow.com/users/23822", "pm_score": 1, "selected": false, "text": "<p>Depending on how often the constructors would be called, you could consider making all the extra parameters nullable and just passing null to them when they don't have values. Messier creating the objects, fewer constructors</p>\n" }, { "answer_id": 180206, "author": "Bill Reiss", "author_id": 18967, "author_profile": "https://Stackoverflow.com/users/18967", "pm_score": 1, "selected": false, "text": "<p>I went down this path when first creating games in XNA, but next time I would do more of a model/view type of approach. The Model objects would be what you deal with in your Update loop, and your Views would be used in your Draw loop. </p>\n\n<p>I got in trouble with not separating the model from the view when I wanted to use my sprite object to handle both 3D and 2D objects. It got real messy real quick.</p>\n" }, { "answer_id": 180216, "author": "Peter Parker", "author_id": 23264, "author_profile": "https://Stackoverflow.com/users/23264", "pm_score": 2, "selected": false, "text": "<p>I am very interested in your storing method for rotation in a vector. How does this work?\nIf you store the angles of X,Y,Z-axis (so called Euler-angles), you should rethink this idea, if you want to create a 3D game, as you will meet shortly after your first rendering the evil <a href=\"http://en.wikipedia.org/wiki/Gimbal_lock\" rel=\"nofollow noreferrer\"><strong>GIMBAL LOCK</strong></a></p>\n\n<p>Personally I do not like so much constructors there, as you can provide 1 constructor and set all not needed params to null. in this way your interface stays cleaner.</p>\n" }, { "answer_id": 180382, "author": "Parappa", "author_id": 9974, "author_profile": "https://Stackoverflow.com/users/9974", "pm_score": 1, "selected": false, "text": "<p>The people here talking about separating Model from View are correct. To put it in more game developer oriented terms, you should have separate classes for GameObject and RenderObject. Think back to your main game loop:</p>\n\n<pre><code>// main loop\nwhile (true) {\n ProcessInput(); // handle input events\n UpdateGameWorld(); // update game objects\n RenderFrame(); // each render object draws itself\n}\n</code></pre>\n\n<p>You want the process of updating your game world and rendering your current frame to be as separate as possible.</p>\n" }, { "answer_id": 180462, "author": "Ron Warholic", "author_id": 22780, "author_profile": "https://Stackoverflow.com/users/22780", "pm_score": 2, "selected": false, "text": "<p>I also heavily recommend looking into a component based design using composition rather than inheritance. The gist of the idea is to model object based on their underlying properties, and allow the properties to do all of the work for you. </p>\n\n<p>In your case, a GameObject may have properties like being able to move, being renderable, or having some state. These seperate functions (or behaviors) can be modeled as objects and composed in the GameObject to build the functionality you desire.</p>\n\n<p>Honestly though, for a small project you're working on I would focus on making the game functional rather than worry about details like coupling and abstraction.</p>\n" }, { "answer_id": 180466, "author": "Davy8", "author_id": 23822, "author_profile": "https://Stackoverflow.com/users/23822", "pm_score": 1, "selected": false, "text": "<p>Alternatively you can make a struct or helper class to hold all the data and have the many constructors in the struct, that way you only have to have tons constructors in 1 object rather than in every class that inherits from GameObject</p>\n" }, { "answer_id": 180591, "author": "Jeff B", "author_id": 25879, "author_profile": "https://Stackoverflow.com/users/25879", "pm_score": 3, "selected": false, "text": "<p>Not only is the number of constructors a potential issue (especially having to re-define them for each derived class) - but the number of parameters to the constructor can become an issue. Even if you make the optional parameters nullable, it becomes difficult to read and maintain the code later.</p>\n\n<p>If I write:</p>\n\n<pre><code>new Ship(content, \"resource\", true, null, null, null, null);\n</code></pre>\n\n<p>What does the second NULL do?</p>\n\n<p>It makes code more readable (but more verbose) to use a structure to hold your parameters if the parameter list goes beyond four or five parameters:</p>\n\n<pre><code>GameObjectParams params(content, \"resource\");\nparams.IsAlive = true;\nnew Ship(params);\n</code></pre>\n\n<p>There are a lot of ways this can be done.</p>\n" }, { "answer_id": 180611, "author": "Illandril", "author_id": 17887, "author_profile": "https://Stackoverflow.com/users/17887", "pm_score": 1, "selected": false, "text": "<p>First game? Start <strong>simple</strong>. Your base GameObject (which in your case is more appropriately called DrawableGameObject [note the DrawableGameComponent class in XNA]) should only contain the information that belongs to all GameObjects. Your alive and velocity variables don't really belong. As others have mentioned, you probably don't want to ever be mixing your drawing and update logic.</p>\n\n<p>Velocity should be in a Mobile class, which should handle the update logic to change the position of the GameObject. You may also want to consider keeping track of acceleration, and having that steadily increase as the player holds a button down, and steadily decrease after the player releases the button (instead of using a constant acceleration)... but that's more a game design decision than a class organization decision. </p>\n\n<p>What \"alive\" means can be very different based on context. In a simple space shooter, something that isn't alive should probably be destroyed (possibly replaced with a few chunks of space debris?). If it's a player that respawns, you're going to want to make sure the player is separate from the ship. The ship doesn't respawn, the ship is destroyed and the player gets a new ship (recycling the old ship in memory instead of deleting it and creating a new one will use fewer cycles - you can simply either move the ship into no-man's-land or pull it out of your game scene entirely and put it back after respawn).</p>\n\n<p>Another thing that you should be wary of... Do not let your players look directly up or down on your vertical axis, or you'll run into, as Peter Parker mentioned, Gimbal Lock issues (which you do not want to mess with if you're doing game development for fun!). Better yet... start with 2D (or at the very least, limit movement to only 2 dimensions)! It's a lot easier when you're new to game development.</p>\n\n<p>I'd suggest following the <a href=\"http://creators.xna.com/en-US/education/gettingstarted\" rel=\"nofollow noreferrer\">XNA Creators Club Getting Started Guides</a> before doing any more programming, however. You should also consider looking for some other more general game development guides to get a few alternative suggestions.</p>\n" }, { "answer_id": 180668, "author": "mstrobl", "author_id": 25965, "author_profile": "https://Stackoverflow.com/users/25965", "pm_score": 3, "selected": false, "text": "<p>Since you are asking a design-related question, I will try to give some hints on that, rather than on the lots of code you posted, because others have already started on that.</p>\n\n<p>Games lend themselves very much to the <a href=\"http://en.wikipedia.org/wiki/Model_view_controller\" rel=\"noreferrer\">Model-View-Controller pattern</a>. You are explicitly talking about the display part, but <strong>think about it: you have vectors in there, etc., and that usually is part of what you are modelling</strong>. Think of the game world and the objects in there as the models. They have a position, they might have velocity and direction. That's the model part of MVC.</p>\n\n<p>I noticed your wish to have the ship fire. You will probably want the mechanic to make the ship fire in a controller class, something that takes keyboard input, for example. And this <strong>controller class will send messages to the model-part</strong>. A sound and easy think you will probably want is to have some fireAction()-method on the model. On your base-model, that might be an overridable (virtual, abstract) method. On the ship it might add a \"bullet\" to the game world.</p>\n\n<p>Seeing how I wrote about behaviour of your model so much already, here's another thing that has helped me plenty: use the <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"noreferrer\">strategy pattern</a> to make behaviour of classes exchangeable. The <strong>strategy pattern</strong> is also great if you think AI and want <strong>behaviour to change somewhen in the future</strong>. You might not know it now, but in a month you might want ballistic missiles as the default missiles and you can easily change that later if you had used the strategy pattenr.</p>\n\n<p>So eventually you might want to really make something like a display class. It will have primitives like you named: rotate, translate, and so on. And you want to derive from it to add more functionality or change functionality. <strong>But think about it, once you have more than a ship</strong>, a special kind of ship, another special kind of ship, you'll run into derivation hell <strong>and you will replicate a lot of code</strong>. Again, use the strategy pattern. And remember to keep it simple. What does a Displayble class need to have? </p>\n\n<ul>\n<li>Means to know its position relative to the screen. It can, thanks to the model of its in-world object and something like the gameworld's model!</li>\n<li>It must know of a bitmap to display for its model and its dimensions.</li>\n<li>It must know if anything should prevent it from drawing, if that is not handled by the drawing engine (i.e. another object occluding it).</li>\n</ul>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19649/" ]
I recently started working on a small game for my own amusement, using Microsoft XNA and C#. My question is in regards to designing a game object and the objects that inherit it. I'm going to define a game object as something that can be rendered on screen. So for this, I decided to make a base class which all other objects that will need to be rendered will inherit, called GameObject. The code below is the class I made: ``` class GameObject { private Model model = null; private float scale = 1f; private Vector3 position = Vector3.Zero; private Vector3 rotation = Vector3.Zero; private Vector3 velocity = Vector3.Zero; private bool alive = false; protected ContentManager content; #region Constructors public GameObject(ContentManager content, string modelResource) { this.content = content; model = content.Load<Model>(modelResource); } public GameObject(ContentManager content, string modelResource, bool alive) : this(content, modelResource) { this.alive = alive; } public GameObject(ContentManager content, string modelResource, bool alive, float scale) : this(content, modelResource, alive) { this.scale = scale; } public GameObject(ContentManager content, string modelResource, bool alive, float scale, Vector3 position) : this(content, modelResource, alive, scale) { this.position = position; } public GameObject(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation) : this(content, modelResource, alive, scale, position) { this.rotation = rotation; } public GameObject(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation, Vector3 velocity) : this(content, modelResource, alive, scale, position, rotation) { this.velocity = velocity; } #endregion } ``` I've left out extra methods that do things such as rotate, move, and draw the object. Now if I wanted to create another object, like a ship, I'd create a Ship class, which would inherit GameObject. Sample code below: ``` class Ship : GameObject { private int num_missiles = 20; // the number of missiles this ship can have alive at any given time private Missile[] missiles; private float max_missile_distance = 3000f; // max distance a missile can be from the ship before it dies #region Constructors public Ship(ContentManager content, string modelResource) : base(content, modelResource) { InitShip(); } public Ship(ContentManager content, string modelResource , bool alive) : base(content, modelResource, alive) { InitShip(); } public Ship(ContentManager content, string modelResource, bool alive, float scale) : base(content, modelResource, alive, scale) { InitShip(); } public Ship(ContentManager content, string modelResource, bool alive, float scale, Vector3 position) : base(content, modelResource, alive, scale, position) { InitShip(); } public Ship(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation) : base(content, modelResource, alive, scale, position, rotation) { InitShip(); } public Ship(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation, Vector3 velocity) : base(content, modelResource, alive, scale, position, rotation, velocity) { InitShip(); } #endregion } ``` Again, I've left out any extra Ship-specific methods, like firing a missile. Do you think that this sort of design is good or should it be improved somehow or changed completely? It seems like the constructors for child classes is messy, but maybe that's the only way to do it. I've never done anything like this and am wondering if I'm way off track. --- Thanks to everyone that left an answer. They were all very helpful. There seems to be a general consensus that changing it around to use an MVC pattern would be best. I'm going to look further into exactly how to do that. I'll also be removing most of the constructors and will have just one constructor, because all of the arguments after modelResource aren't necessary to create the object, and they can all be changed later through method calls.
Personally I find the sheer number of constructors you have a little offputting, but that's your choice, nothing fundamentally wrong with it :) With regards to the general strategy of deriving game objects from a common base, that's a pretty common way to do things. Standard, even. I've tended to start using something far more akin to MVC, with incredibly lightweight "model" game objects that contain only data. Other common approaches I've seen in XNA include / things you may want to consider: * Implementation of an IRenderable interface rather than doing any render code in the base or derived classes. For instance, you may want game objects that are never rendered - waypoints or somesuch. * You could make your base class abstract, you're not likely to want to ever instantiate a GameObject. Again though, minor points. Your design is fine.
180,158
<ol> <li>How do I get a method's execution time? </li> <li>Is there a <code>Timer</code> utility class for things like timing how long a task takes, etc? </li> </ol> <p>Most of the searches on Google return results for timers that schedule threads and tasks, which is not what I want.</p>
[ { "answer_id": 180171, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 5, "selected": false, "text": "<p>This probably isn't what you wanted me to say, but this is a good use of AOP. Whip an proxy interceptor around your method, and do the timing in there.</p>\n\n<p>The what, why and how of AOP is rather beyond the scope of this answer, sadly, but that's how I'd likely do it. </p>\n\n<p>Edit: <a href=\"http://static.springframework.org/spring/docs/2.5.x/reference/aop.html\" rel=\"noreferrer\">Here's a link</a> to Spring AOP to get you started, if you're keen. This is the most accessible implementation of AOP that Iive come across for java.</p>\n\n<p>Also, given everyone else's very simple suggestions, I should add that AOP is for when you don't want stuff like timing to invade your code. But in many cases, that sort of simple and easy approach is fine.</p>\n" }, { "answer_id": 180179, "author": "MBCook", "author_id": 18189, "author_profile": "https://Stackoverflow.com/users/18189", "pm_score": 8, "selected": false, "text": "<p>I go with the simple answer. Works for me.</p>\n\n<pre><code>long startTime = System.currentTimeMillis();\n\ndoReallyLongThing();\n\nlong endTime = System.currentTimeMillis();\n\nSystem.out.println(\"That took \" + (endTime - startTime) + \" milliseconds\");\n</code></pre>\n\n<p>It works quite well. The resolution is obviously only to the millisecond, you can do better with System.nanoTime(). There are some limitations to both (operating system schedule slices, etc.) but this works pretty well.</p>\n\n<p>Average across a couple of runs (the more the better) and you'll get a decent idea.</p>\n" }, { "answer_id": 180180, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 3, "selected": false, "text": "<p>If you want wall-clock time</p>\n\n<pre><code>long start_time = System.currentTimeMillis();\nobject.method();\nlong end_time = System.currentTimeMillis();\nlong execution_time = end_time - start_time;\n</code></pre>\n" }, { "answer_id": 180191, "author": "Diastrophism", "author_id": 18093, "author_profile": "https://Stackoverflow.com/users/18093", "pm_score": 11, "selected": true, "text": "<p>There is always the old-fashioned way:</p>\n\n<pre><code>long startTime = System.nanoTime();\nmethodToTime();\nlong endTime = System.nanoTime();\n\nlong duration = (endTime - startTime); //divide by 1000000 to get milliseconds.\n</code></pre>\n" }, { "answer_id": 180192, "author": "Ryan Rodemoyer", "author_id": 1444511, "author_profile": "https://Stackoverflow.com/users/1444511", "pm_score": 3, "selected": false, "text": "<pre><code>long startTime = System.currentTimeMillis();\n// code goes here\nlong finishTime = System.currentTimeMillis();\nlong elapsedTime = finishTime - startTime; // elapsed time in milliseconds\n</code></pre>\n" }, { "answer_id": 180200, "author": "luke", "author_id": 25920, "author_profile": "https://Stackoverflow.com/users/25920", "pm_score": 3, "selected": false, "text": "<p>I basically do variations of this, but considering how hotspot compilation works, if you want to get accurate results you need to throw out the first few measurements and make sure you are using the method in a real world (read application specific) application. </p>\n\n<p>If the JIT decides to compile it your numbers will vary heavily. so just be aware</p>\n" }, { "answer_id": 180204, "author": "Horst Gutmann", "author_id": 22312, "author_profile": "https://Stackoverflow.com/users/22312", "pm_score": 3, "selected": false, "text": "<p>There are a couple of ways to do that. I normally fall back to just using something like this: </p>\n\n<pre><code>long start = System.currentTimeMillis();\n// ... do something ...\nlong end = System.currentTimeMillis();\n</code></pre>\n\n<p>or the same thing with System.nanoTime();</p>\n\n<p>For something more on the benchmarking side of things there seems also to be this one: <a href=\"http://jetm.void.fm/\" rel=\"noreferrer\">http://jetm.void.fm/</a> Never tried it though.</p>\n" }, { "answer_id": 180222, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 3, "selected": false, "text": "<p>As \"skaffman\" said, use AOP OR you can use run time bytecode weaving, just like unit test method coverage tools use to transparently add timing info to methods invoked.</p>\n\n<p>You can look at code used by open source tools tools like Emma (<a href=\"http://downloads.sourceforge.net/emma/emma-2.0.5312-src.zip?modtime=1118607545&amp;big_mirror=0\" rel=\"noreferrer\">http://downloads.sourceforge.net/emma/emma-2.0.5312-src.zip?modtime=1118607545&amp;big_mirror=0</a>). The other opensource coverage tool is <a href=\"http://prdownloads.sourceforge.net/cobertura/cobertura-1.9-src.zip?download\" rel=\"noreferrer\">http://prdownloads.sourceforge.net/cobertura/cobertura-1.9-src.zip?download</a>.</p>\n\n<p>If you eventually manage to do what you set out for, pls. share it back with the community here with your ant task/jars.</p>\n" }, { "answer_id": 180543, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 7, "selected": false, "text": "<p>Use a profiler (JProfiler, Netbeans Profiler, Visual VM, Eclipse Profiler, etc). You'll get the most accurate results and is the least intrusive. They use the built-in JVM mechanism for profiling which can also give you extra information like stack traces, execution paths, and more comprehensive results if necessary.</p>\n\n<p>When using a fully integrated profiler, it's faily trivial to profile a method. Right click, Profiler -> Add to Root Methods. Then run the profiler just like you were doing a test run or debugger.</p>\n" }, { "answer_id": 181571, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>We are using AspectJ and Java annotations for this purpose. If we need to know to execution time for a method, we simple annotate it. A more advanced version could use an own log level that can enabled and disabled at runtime.</p>\n\n<pre><code>public @interface Trace {\n boolean showParameters();\n}\n\n@Aspect\npublic class TraceAspect {\n [...]\n @Around(\"tracePointcut() &amp;&amp; @annotation(trace) &amp;&amp; !within(TraceAspect)\")\n public Object traceAdvice ( ProceedingJintPoint jP, Trace trace ) {\n\n Object result;\n // initilize timer\n\n try { \n result = jp.procced();\n } finally { \n // calculate execution time \n }\n\n return result;\n }\n [...]\n}\n</code></pre>\n" }, { "answer_id": 264547, "author": "Hans-Peter Störr", "author_id": 21499, "author_profile": "https://Stackoverflow.com/users/21499", "pm_score": 4, "selected": false, "text": "<p>Just a small twist, if you don't use tooling and want to time methods with low execution time: execute it many times, each time doubling the number of times it is executed until you reach a second, or so. Thus, the time of the Call to System.nanoTime and so forth, nor the accuracy of System.nanoTime does affect the result much.</p>\n\n<pre><code> int runs = 0, runsPerRound = 10;\n long begin = System.nanoTime(), end;\n do {\n for (int i=0; i&lt;runsPerRound; ++i) timedMethod();\n end = System.nanoTime();\n runs += runsPerRound;\n runsPerRound *= 2;\n } while (runs &lt; Integer.MAX_VALUE / 2 &amp;&amp; 1000000000L &gt; end - begin);\n System.out.println(\"Time for timedMethod() is \" + \n 0.000000001 * (end-begin) / runs + \" seconds\");\n</code></pre>\n\n<p>Of course, the caveats about using the wall clock apply: influences of JIT-compilation, multiple threads / processes etc. Thus, you need to first execute the method <em>a lot</em> of times first, such that the JIT compiler does its work, and then repeat this test multiple times and take the lowest execution time.</p>\n" }, { "answer_id": 8365561, "author": "Narayan", "author_id": 1078611, "author_profile": "https://Stackoverflow.com/users/1078611", "pm_score": 4, "selected": false, "text": "<p>Also We can use StopWatch class of Apache commons for measuring the time.</p>\n\n<p>Sample code</p>\n\n<pre><code>org.apache.commons.lang.time.StopWatch sw = new org.apache.commons.lang.time.StopWatch();\n\nSystem.out.println(\"getEventFilterTreeData :: Start Time : \" + sw.getTime());\nsw.start();\n\n// Method execution code\n\nsw.stop();\nSystem.out.println(\"getEventFilterTreeData :: End Time : \" + sw.getTime());\n</code></pre>\n" }, { "answer_id": 9454173, "author": "mergenchik", "author_id": 1233031, "author_profile": "https://Stackoverflow.com/users/1233031", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"https://github.com/perf4j/perf4j\" rel=\"nofollow noreferrer\">Perf4j</a>. Very cool utility. Usage is simple</p>\n\n<pre><code>String watchTag = \"target.SomeMethod\";\nStopWatch stopWatch = new LoggingStopWatch(watchTag);\nResult result = null; // Result is a type of a return value of a method\ntry {\n result = target.SomeMethod();\n stopWatch.stop(watchTag + \".success\");\n} catch (Exception e) {\n stopWatch.stop(watchTag + \".fail\", \"Exception was \" + e);\n throw e; \n}\n</code></pre>\n\n<p><del>More information can be found in <a href=\"http://perf4j.codehaus.org/devguide.html\" rel=\"nofollow noreferrer\">Developer Guide</a></del></p>\n\n<p>Edit: <a href=\"https://github.com/perf4j/perf4j/issues/18\" rel=\"nofollow noreferrer\">Project seems dead</a></p>\n" }, { "answer_id": 11047430, "author": "iceberg", "author_id": 1436703, "author_profile": "https://Stackoverflow.com/users/1436703", "pm_score": 4, "selected": false, "text": "<p>Really good code.</p>\n\n<p><a href=\"http://www.rgagnon.com/javadetails/java-0585.html\" rel=\"noreferrer\">http://www.rgagnon.com/javadetails/java-0585.html</a></p>\n\n<pre><code>import java.util.concurrent.TimeUnit;\n\nlong startTime = System.currentTimeMillis();\n........\n........\n........\nlong finishTime = System.currentTimeMillis();\n\nString diff = millisToShortDHMS(finishTime - startTime);\n\n\n /**\n * converts time (in milliseconds) to human-readable format\n * \"&lt;dd:&gt;hh:mm:ss\"\n */\n public static String millisToShortDHMS(long duration) {\n String res = \"\";\n long days = TimeUnit.MILLISECONDS.toDays(duration);\n long hours = TimeUnit.MILLISECONDS.toHours(duration)\n - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));\n long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)\n - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));\n long seconds = TimeUnit.MILLISECONDS.toSeconds(duration)\n - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));\n if (days == 0) {\n res = String.format(\"%02d:%02d:%02d\", hours, minutes, seconds);\n }\n else {\n res = String.format(\"%dd%02d:%02d:%02d\", days, hours, minutes, seconds);\n }\n return res;\n }\n</code></pre>\n" }, { "answer_id": 14186259, "author": "yegor256", "author_id": 187141, "author_profile": "https://Stackoverflow.com/users/187141", "pm_score": 3, "selected": false, "text": "<p>Using AOP/AspectJ and <a href=\"http://aspects.jcabi.com/apidocs-0.7.6/com/jcabi/aspects/Loggable.html\" rel=\"noreferrer\"><code>@Loggable</code></a> annotation from <a href=\"http://aspects.jcabi.com/\" rel=\"noreferrer\">jcabi-aspects</a> you can do it easy and compact:</p>\n\n<pre><code>@Loggable(Loggable.DEBUG)\npublic String getSomeResult() {\n // return some value\n}\n</code></pre>\n\n<p>Every call to this method will be sent to SLF4J logging facility with <code>DEBUG</code> logging level. And every log message will include execution time.</p>\n" }, { "answer_id": 15395499, "author": "Dmitry Kalashnikov", "author_id": 857165, "author_profile": "https://Stackoverflow.com/users/857165", "pm_score": 8, "selected": false, "text": "<p>Come on guys! Nobody mentioned the <a href=\"http://code.google.com/p/guava-libraries/\" rel=\"noreferrer\">Guava</a> way to do that (which is arguably awesome):</p>\n\n<pre><code>import com.google.common.base.Stopwatch;\n\nStopwatch timer = Stopwatch.createStarted();\n//method invocation\nLOG.info(\"Method took: \" + timer.stop());\n</code></pre>\n\n<p>The nice thing is that Stopwatch.toString() does a good job of selecting time units for the measurement. I.e. if the value is small, it'll output 38 ns, if it's long, it'll show 5m 3s</p>\n\n<p>Even nicer:</p>\n\n<pre><code>Stopwatch timer = Stopwatch.createUnstarted();\nfor (...) {\n timer.start();\n methodToTrackTimeFor();\n timer.stop();\n methodNotToTrackTimeFor();\n}\nLOG.info(\"Method took: \" + timer);\n</code></pre>\n\n<p><em>Note: Google Guava requires Java 1.6+</em></p>\n" }, { "answer_id": 15789819, "author": "Maciek Kreft", "author_id": 203459, "author_profile": "https://Stackoverflow.com/users/203459", "pm_score": 3, "selected": false, "text": "<pre><code>new Timer(\"\"){{\n // code to time \n}}.timeMe();\n\n\n\npublic class Timer {\n\n private final String timerName;\n private long started;\n\n public Timer(String timerName) {\n this.timerName = timerName;\n this.started = System.currentTimeMillis();\n }\n\n public void timeMe() {\n System.out.println(\n String.format(\"Execution of '%s' takes %dms.\", \n timerName, \n started-System.currentTimeMillis()));\n }\n\n}\n</code></pre>\n" }, { "answer_id": 17442594, "author": "hmitcs", "author_id": 2545547, "author_profile": "https://Stackoverflow.com/users/2545547", "pm_score": 1, "selected": false, "text": "<p><code>System.nanoTime()</code> is a pretty precise system utility to measure execution time. But be careful, if you're running on pre-emptive scheduler mode (default), this utility actually measures wall-clock time and not CPU time. Therefore, you may notice different execution time values from run to run, depending on system loads. If you look for CPU time, I think that running your program in real-time mode will do the trick. You have to use RT linux. link: <a href=\"https://stackoverflow.com/questions/10502508/real-time-programming-with-linux\">Real-time programming with Linux</a> </p>\n" }, { "answer_id": 20416934, "author": "gifpif", "author_id": 2093934, "author_profile": "https://Stackoverflow.com/users/2093934", "pm_score": 2, "selected": false, "text": "<p>You can try this way if just want know the time. </p>\n\n<pre><code>long startTime = System.currentTimeMillis();\n//@ Method call\nSystem.out.println(\"Total time [ms]: \" + (System.currentTimeMillis() - startTime)); \n</code></pre>\n" }, { "answer_id": 20803059, "author": "Denis Kutlubaev", "author_id": 751641, "author_profile": "https://Stackoverflow.com/users/751641", "pm_score": 2, "selected": false, "text": "<p>I modified the code from correct answer to get result in seconds: </p>\n\n<pre><code>long startTime = System.nanoTime();\n\nmethodCode ...\n\nlong endTime = System.nanoTime();\ndouble duration = (double)(endTime - startTime) / (Math.pow(10, 9));\nLog.v(TAG, \"MethodName time (s) = \" + duration);\n</code></pre>\n" }, { "answer_id": 22894871, "author": "TondaCZE", "author_id": 2272158, "author_profile": "https://Stackoverflow.com/users/2272158", "pm_score": 6, "selected": false, "text": "<p><code>System.currentTimeMillis();</code> IS NOT a good approach for measuring the performance of your algorithms. It measures the total time you experience as a user watching the computer screen. It includes also time consumed by everything else running on your computer in the background. This could make a huge difference in case you have a lot of programs running on your workstation.</p>\n\n<p>Proper approach is using <code>java.lang.management</code> package.</p>\n\n<p>From <a href=\"http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking\" rel=\"noreferrer\">http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking</a> website (<a href=\"https://web.archive.org/web/20190413083329/http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking\" rel=\"noreferrer\">archive link</a>):</p>\n\n<ul>\n<li>\"User time\" is the time spent running your application's own code.</li>\n<li>\"System time\" is the time spent running OS code on behalf of your application (such as for I/O).</li>\n</ul>\n\n<p><code>getCpuTime()</code> method gives you sum of those:</p>\n\n<pre><code>import java.lang.management.ManagementFactory;\nimport java.lang.management.ThreadMXBean;\n\npublic class CPUUtils {\n\n /** Get CPU time in nanoseconds. */\n public static long getCpuTime( ) {\n ThreadMXBean bean = ManagementFactory.getThreadMXBean( );\n return bean.isCurrentThreadCpuTimeSupported( ) ?\n bean.getCurrentThreadCpuTime( ) : 0L;\n }\n\n /** Get user time in nanoseconds. */\n public static long getUserTime( ) {\n ThreadMXBean bean = ManagementFactory.getThreadMXBean( );\n return bean.isCurrentThreadCpuTimeSupported( ) ?\n bean.getCurrentThreadUserTime( ) : 0L;\n }\n\n /** Get system time in nanoseconds. */\n public static long getSystemTime( ) {\n ThreadMXBean bean = ManagementFactory.getThreadMXBean( );\n return bean.isCurrentThreadCpuTimeSupported( ) ?\n (bean.getCurrentThreadCpuTime( ) - bean.getCurrentThreadUserTime( )) : 0L;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 25884289, "author": "leo", "author_id": 510583, "author_profile": "https://Stackoverflow.com/users/510583", "pm_score": 2, "selected": false, "text": "<p>Performance measurements on my machine</p>\n<ul>\n<li><code>System.nanoTime() : 750ns</code></li>\n<li><code>System.currentTimeMillis() : 18ns</code></li>\n</ul>\n<p>As mentioned, <code>System.nanoTime()</code> is thought to measure elapsed time. Just be aware of the cost if used inside a loop or the like.</p>\n" }, { "answer_id": 27990107, "author": "Alexey Pismenskiy", "author_id": 2495060, "author_profile": "https://Stackoverflow.com/users/2495060", "pm_score": 2, "selected": false, "text": "<p>It would be nice if java had a better functional support, so that the action, that needs to be measured, could be wrapped into a block: </p>\n\n<pre><code>measure {\n // your operation here\n}\n</code></pre>\n\n<p>In java this could be done by anonymous functions, that look too verbose</p>\n\n<pre><code>public interface Timer {\n void wrap();\n}\n\n\npublic class Logger {\n\n public static void logTime(Timer timer) {\n long start = System.currentTimeMillis();\n timer.wrap();\n System.out.println(\"\" + (System.currentTimeMillis() - start) + \"ms\");\n }\n\n public static void main(String a[]) {\n Logger.logTime(new Timer() {\n public void wrap() {\n // Your method here\n timeConsumingOperation();\n }\n });\n\n }\n\n public static void timeConsumingOperation() {\n for (int i = 0; i&lt;=10000; i++) {\n System.out.println(\"i=\" +i);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 28177737, "author": "msysmilu", "author_id": 2251011, "author_profile": "https://Stackoverflow.com/users/2251011", "pm_score": 2, "selected": false, "text": "<p>Ok, this is a simple class to be used for simple simple timing of your functions. There is an example below it.</p>\n\n<pre><code>public class Stopwatch {\n static long startTime;\n static long splitTime;\n static long endTime;\n\n public Stopwatch() {\n start();\n }\n\n public void start() {\n startTime = System.currentTimeMillis();\n splitTime = System.currentTimeMillis();\n endTime = System.currentTimeMillis();\n }\n\n public void split() {\n split(\"\");\n }\n\n public void split(String tag) {\n endTime = System.currentTimeMillis();\n System.out.println(\"Split time for [\" + tag + \"]: \" + (endTime - splitTime) + \" ms\");\n splitTime = endTime;\n }\n\n public void end() {\n end(\"\");\n }\n public void end(String tag) {\n endTime = System.currentTimeMillis();\n System.out.println(\"Final time for [\" + tag + \"]: \" + (endTime - startTime) + \" ms\");\n }\n}\n</code></pre>\n\n<p>Sample of use:</p>\n\n<pre><code>public static Schedule getSchedule(Activity activity_context) {\n String scheduleJson = null;\n Schedule schedule = null;\n/*-&gt;*/ Stopwatch stopwatch = new Stopwatch();\n\n InputStream scheduleJsonInputStream = activity_context.getResources().openRawResource(R.raw.skating_times);\n/*-&gt;*/ stopwatch.split(\"open raw resource\");\n\n scheduleJson = FileToString.convertStreamToString(scheduleJsonInputStream);\n/*-&gt;*/ stopwatch.split(\"file to string\");\n\n schedule = new Gson().fromJson(scheduleJson, Schedule.class);\n/*-&gt;*/ stopwatch.split(\"parse Json\");\n/*-&gt;*/ stopwatch.end(\"Method getSchedule\"); \n return schedule;\n}\n</code></pre>\n\n<p>Sample of console output:</p>\n\n<pre><code>Split time for [file to string]: 672 ms\nSplit time for [parse Json]: 893 ms\nFinal time for [get Schedule]: 1565 ms\n</code></pre>\n" }, { "answer_id": 28274381, "author": "Sufiyan Ghori", "author_id": 1149423, "author_profile": "https://Stackoverflow.com/users/1149423", "pm_score": 7, "selected": false, "text": "<p>Using <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html\">Instant</a> and <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html\">Duration</a> from Java 8's new API,</p>\n\n<pre><code>Instant start = Instant.now();\nThread.sleep(5000);\nInstant end = Instant.now();\nSystem.out.println(Duration.between(start, end));\n</code></pre>\n\n<p>outputs,</p>\n\n<pre><code>PT5S\n</code></pre>\n" }, { "answer_id": 30975902, "author": "akhil_mittal", "author_id": 1216775, "author_profile": "https://Stackoverflow.com/users/1216775", "pm_score": 2, "selected": false, "text": "<p>In Java 8 a new class named <code>Instant</code> is introduced. As per doc:</p>\n\n<blockquote>\n <p>Instant represents the start of a nanosecond on the time line. This\n class is useful for generating a time stamp to represent machine time.\n The range of an instant requires the storage of a number larger than a\n long. To achieve this, the class stores a long representing\n epoch-seconds and an int representing nanosecond-of-second, which will\n always be between 0 and 999,999,999. The epoch-seconds are measured\n from the standard Java epoch of 1970-01-01T00:00:00Z where instants\n after the epoch have positive values, and earlier instants have\n negative values. For both the epoch-second and nanosecond parts, a\n larger value is always later on the time-line than a smaller value.</p>\n</blockquote>\n\n<p>This can be used as:</p>\n\n<pre><code>Instant start = Instant.now();\ntry {\n Thread.sleep(7000);\n} catch (InterruptedException e) {\n e.printStackTrace();\n}\nInstant end = Instant.now();\nSystem.out.println(Duration.between(start, end));\n</code></pre>\n\n<p>It prints <code>PT7.001S</code>.</p>\n" }, { "answer_id": 31853341, "author": "Sunil Manheri", "author_id": 300538, "author_profile": "https://Stackoverflow.com/users/300538", "pm_score": 4, "selected": false, "text": "<p>Spring provides a utility class <a href=\"https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/StopWatch.html\" rel=\"noreferrer\">org.springframework.util.StopWatch</a>, as per JavaDoc:</p>\n\n<blockquote>\n <p>Simple stop watch, allowing for timing of a number of tasks, exposing\n total running time and running time for each named task.</p>\n</blockquote>\n\n<p>Usage:</p>\n\n<pre><code>StopWatch stopWatch = new StopWatch(\"Performance Test Result\");\n\nstopWatch.start(\"Method 1\");\ndoSomething1();//method to test\nstopWatch.stop();\n\nstopWatch.start(\"Method 2\");\ndoSomething2();//method to test\nstopWatch.stop();\n\nSystem.out.println(stopWatch.prettyPrint());\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>StopWatch 'Performance Test Result': running time (millis) = 12829\n-----------------------------------------\nms % Task name\n-----------------------------------------\n11907 036% Method 1\n00922 064% Method 2\n</code></pre>\n\n<p><strong>With Aspects:</strong></p>\n\n<pre><code>@Around(\"execution(* my.package..*.*(..))\")\npublic Object logTime(ProceedingJoinPoint joinPoint) throws Throwable {\n StopWatch stopWatch = new StopWatch();\n stopWatch.start();\n Object retVal = joinPoint.proceed();\n stopWatch.stop();\n log.info(\" execution time: \" + stopWatch.getTotalTimeMillis() + \" ms\");\n return retVal;\n}\n</code></pre>\n" }, { "answer_id": 32697799, "author": "dingjsh", "author_id": 3103993, "author_profile": "https://Stackoverflow.com/users/3103993", "pm_score": 2, "selected": false, "text": "<p>You can use <strong>javaagent</strong> to modify the java class bytes ,add the monitor codes dynamically.there is some open source tools on the github that can do this for you.<br>\nIf you want to do it by yourself, just implements the <strong>javaagent</strong>,use <strong>javassist</strong> to modify the methods you want to monitor,and the monitor code before your method return.it's clean and you can monitor systems that you even don't have source code.</p>\n" }, { "answer_id": 33927764, "author": "Stefan", "author_id": 3226909, "author_profile": "https://Stackoverflow.com/users/3226909", "pm_score": 5, "selected": false, "text": "<p>With Java 8 you can do also something like this with every normal <strong>methods</strong>:</p>\n\n<pre><code>Object returnValue = TimeIt.printTime(() -&gt; methodeWithReturnValue());\n//do stuff with your returnValue\n</code></pre>\n\n<p>with TimeIt like:</p>\n\n<pre><code>public class TimeIt {\n\npublic static &lt;T&gt; T printTime(Callable&lt;T&gt; task) {\n T call = null;\n try {\n long startTime = System.currentTimeMillis();\n call = task.call();\n System.out.print((System.currentTimeMillis() - startTime) / 1000d + \"s\");\n } catch (Exception e) {\n //...\n }\n return call;\n}\n}\n</code></pre>\n\n<p>With this methode you can make easy time measurement anywhere in your code without breaking it. In this simple example i just print the time. May you add a Switch for TimeIt, e.g. to only print the time in DebugMode or something.</p>\n\n<p>If you are working with <strong>Function</strong> you can do somthing like this:</p>\n\n<pre><code>Function&lt;Integer, Integer&gt; yourFunction= (n) -&gt; {\n return IntStream.range(0, n).reduce(0, (a, b) -&gt; a + b);\n };\n\nInteger returnValue = TimeIt.printTime2(yourFunction).apply(10000);\n//do stuff with your returnValue\n\npublic static &lt;T, R&gt; Function&lt;T, R&gt; printTime2(Function&lt;T, R&gt; task) {\n return (t) -&gt; {\n long startTime = System.currentTimeMillis();\n R apply = task.apply(t);\n System.out.print((System.currentTimeMillis() - startTime) / 1000d\n + \"s\");\n return apply;\n };\n}\n</code></pre>\n" }, { "answer_id": 34086460, "author": "Yash", "author_id": 5081877, "author_profile": "https://Stackoverflow.com/users/5081877", "pm_score": 7, "selected": false, "text": "<p><em>Gathered all possible ways together into one place.</em></p>\n\n<p><strong><a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Date.html\" rel=\"noreferrer\">Date</a></strong></p>\n\n<pre><code>Date startDate = Calendar.getInstance().getTime();\nlong d_StartTime = new Date().getTime();\nThread.sleep(1000 * 4);\nDate endDate = Calendar.getInstance().getTime();\nlong d_endTime = new Date().getTime();\nSystem.out.format(\"StartDate : %s, EndDate : %s \\n\", startDate, endDate);\nSystem.out.format(\"Milli = %s, ( D_Start : %s, D_End : %s ) \\n\", (d_endTime - d_StartTime),d_StartTime, d_endTime);\n</code></pre>\n\n<p><strong>System.<a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#currentTimeMillis()\" rel=\"noreferrer\">currentTimeMillis()</a></strong></p>\n\n<pre><code>long startTime = System.currentTimeMillis();\nThread.sleep(1000 * 4);\nlong endTime = System.currentTimeMillis();\nlong duration = (endTime - startTime); \nSystem.out.format(\"Milli = %s, ( S_Start : %s, S_End : %s ) \\n\", duration, startTime, endTime );\nSystem.out.println(\"Human-Readable format : \"+millisToShortDHMS( duration ) );\n</code></pre>\n\n<p><strong>Human Readable <a href=\"http://www.rgagnon.com/javadetails/java-0585.html\" rel=\"noreferrer\">Format</a></strong></p>\n\n<pre><code>public static String millisToShortDHMS(long duration) {\n String res = \"\"; // java.util.concurrent.TimeUnit;\n long days = TimeUnit.MILLISECONDS.toDays(duration);\n long hours = TimeUnit.MILLISECONDS.toHours(duration) -\n TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));\n long minutes = TimeUnit.MILLISECONDS.toMinutes(duration) -\n TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));\n long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) -\n TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));\n long millis = TimeUnit.MILLISECONDS.toMillis(duration) - \n TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(duration));\n\n if (days == 0) res = String.format(\"%02d:%02d:%02d.%04d\", hours, minutes, seconds, millis);\n else res = String.format(\"%dd %02d:%02d:%02d.%04d\", days, hours, minutes, seconds, millis);\n return res;\n}\n</code></pre>\n\n<p><strong>Guava: Google</strong> <a href=\"https://google.github.io/guava/releases/24.0-jre/api/docs/com/google/common/base/Stopwatch.html\" rel=\"noreferrer\"><strong>Stopwatch</strong></a><sup><a href=\"http://mvnrepository.com/artifact/com.google.guava/guava/24.1-jre\" rel=\"noreferrer\">JAR</a></sup> « An object of Stopwatch is to measures elapsed time in nanoseconds.</p>\n\n<pre><code>com.google.common.base.Stopwatch g_SW = Stopwatch.createUnstarted();\ng_SW.start();\nThread.sleep(1000 * 4);\ng_SW.stop();\nSystem.out.println(\"Google StopWatch : \"+g_SW);\n</code></pre>\n\n<p><strong>Apache Commons Lang<sup><a href=\"http://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4\" rel=\"noreferrer\">JAR</a></sup>\n « <a href=\"https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/StopWatch.html\" rel=\"noreferrer\">StopWatch</a></strong> provides a convenient API for timings.</p>\n\n<pre><code>org.apache.commons.lang3.time.StopWatch sw = new StopWatch();\nsw.start(); \nThread.sleep(1000 * 4); \nsw.stop();\nSystem.out.println(\"Apache StopWatch : \"+ millisToShortDHMS(sw.getTime()) );\n</code></pre>\n\n<p><strong><a href=\"http://mvnrepository.com/artifact/joda-time/joda-time\" rel=\"noreferrer\">JODA</a>-TIME</strong></p>\n\n<pre><code>public static void jodaTime() throws InterruptedException, ParseException{\n java.text.SimpleDateFormat ms_SDF = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss.SSS\");\n String start = ms_SDF.format( new Date() ); // java.util.Date\n\n Thread.sleep(10000);\n\n String end = ms_SDF.format( new Date() ); \n System.out.println(\"Start:\"+start+\"\\t Stop:\"+end);\n\n Date date_1 = ms_SDF.parse(start);\n Date date_2 = ms_SDF.parse(end); \n Interval interval = new org.joda.time.Interval( date_1.getTime(), date_2.getTime() );\n Period period = interval.toPeriod(); //org.joda.time.Period\n\n System.out.format(\"%dY/%dM/%dD, %02d:%02d:%02d.%04d \\n\", \n period.getYears(), period.getMonths(), period.getDays(),\n period.getHours(), period.getMinutes(), period.getSeconds(), period.getMillis());\n}\n</code></pre>\n\n<p><strong>Java date time API from Java 8</strong> « A <a href=\"https://docs.oracle.com/javase/tutorial/datetime/iso/period.html\" rel=\"noreferrer\">Duration</a> object represents a period of time between two <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html\" rel=\"noreferrer\">Instant</a> objects.</p>\n\n<pre><code>Instant start = java.time.Instant.now();\n Thread.sleep(1000);\nInstant end = java.time.Instant.now();\nDuration between = java.time.Duration.between(start, end);\nSystem.out.println( between ); // PT1.001S\nSystem.out.format(\"%dD, %02d:%02d:%02d.%04d \\n\", between.toDays(),\n between.toHours(), between.toMinutes(), between.getSeconds(), between.toMillis()); // 0D, 00:00:01.1001 \n</code></pre>\n\n<hr>\n\n<p><a href=\"https://spring.io/\" rel=\"noreferrer\"><strong>Spring Framework</strong></a> provides <a href=\"https://docs.spring.io/spring/docs/2.0.x/javadoc-api/org/springframework/util/StopWatch.html\" rel=\"noreferrer\">StopWatch</a> utility class to measure elapsed time in Java.</p>\n\n\n\n<pre class=\"lang-java prettyprint-override\"><code>StopWatch sw = new org.springframework.util.StopWatch();\nsw.start(\"Method-1\"); // Start a named task\n Thread.sleep(500);\nsw.stop();\n\nsw.start(\"Method-2\");\n Thread.sleep(300);\nsw.stop();\n\nsw.start(\"Method-3\");\n Thread.sleep(200);\nsw.stop();\n\nSystem.out.println(\"Total time in milliseconds for all tasks :\\n\"+sw.getTotalTimeMillis());\nSystem.out.println(\"Table describing all tasks performed :\\n\"+sw.prettyPrint());\n\nSystem.out.format(\"Time taken by the last task : [%s]:[%d]\", \n sw.getLastTaskName(),sw.getLastTaskTimeMillis());\n\nSystem.out.println(\"\\n Array of the data for tasks performed « Task Name: Time Taken\");\nTaskInfo[] listofTasks = sw.getTaskInfo();\nfor (TaskInfo task : listofTasks) {\n System.out.format(\"[%s]:[%d]\\n\", \n task.getTaskName(), task.getTimeMillis());\n}\n</code></pre>\n\n\n\n<p>OutPut:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Total time in milliseconds for all tasks :\n999\nTable describing all tasks performed :\nStopWatch '': running time (millis) = 999\n-----------------------------------------\nms % Task name\n-----------------------------------------\n00500 050% Method-1\n00299 030% Method-2\n00200 020% Method-3\n\nTime taken by the last task : [Method-3]:[200]\n Array of the data for tasks performed « Task Name: Time Taken\n[Method-1]:[500]\n[Method-2]:[299]\n[Method-3]:[200]\n</code></pre>\n" }, { "answer_id": 38154825, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 4, "selected": false, "text": "<h1>JEP 230: Microbenchmark Suite</h1>\n\n<p>FYI, <a href=\"http://openjdk.java.net/jeps/230\" rel=\"noreferrer\">JEP 230: Microbenchmark Suite</a> is an <a href=\"http://openjdk.java.net/\" rel=\"noreferrer\">OpenJDK</a> project to:</p>\n\n<blockquote>\n <p>Add a basic suite of microbenchmarks to the JDK source code, and make it easy for developers to run existing microbenchmarks and create new ones.</p>\n</blockquote>\n\n<p>This feature arrived in <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_12\" rel=\"noreferrer\">Java 12</a>.</p>\n\n<h1>Java Microbenchmark Harness (JMH)</h1>\n\n<p>For earlier versions of Java, take a look at the <a href=\"http://openjdk.java.net/projects/code-tools/jmh\" rel=\"noreferrer\">Java Microbenchmark Harness (JMH)</a> project on which JEP 230 is based.</p>\n" }, { "answer_id": 41160571, "author": "timxor", "author_id": 1482105, "author_profile": "https://Stackoverflow.com/users/1482105", "pm_score": 2, "selected": false, "text": "<p>Here is pretty printed string ready formated seconds elapsed similar to google search time took to search:</p>\n\n<pre><code> long startTime = System.nanoTime();\n // ... methodToTime();\n long endTime = System.nanoTime();\n long duration = (endTime - startTime);\n long seconds = (duration / 1000) % 60;\n // formatedSeconds = (0.xy seconds)\n String formatedSeconds = String.format(\"(0.%d seconds)\", seconds);\n System.out.println(\"formatedSeconds = \"+ formatedSeconds);\n // i.e actual formatedSeconds = (0.52 seconds)\n</code></pre>\n" }, { "answer_id": 41376436, "author": "StationaryTraveller", "author_id": 2204803, "author_profile": "https://Stackoverflow.com/users/2204803", "pm_score": 2, "selected": false, "text": "<p>I implemented a simple timer, And I think it's really useful:</p>\n\n<pre><code>public class Timer{\n private static long start_time;\n\n public static double tic(){\n return start_time = System.nanoTime();\n }\n\n public static double toc(){\n return (System.nanoTime()-start_time)/1000000000.0;\n }\n\n}\n</code></pre>\n\n<p>That way you can time one or more actions:</p>\n\n<pre><code>Timer.tic();\n// Code 1\nSystem.out.println(\"Code 1 runtime: \"+Timer.toc()+\" seconds.\");\n// Code 2\nSystem.out.println(\"(Code 1 + Code 2) runtime: \"+Timer.toc()+\"seconds\");\nTimer.tic();\n// Code 3\nSystem.out.println(\"Code 3 runtime: \"+Timer.toc()+\" seconds.\");\n</code></pre>\n" }, { "answer_id": 44949335, "author": "Maciel Escudero Bombonato", "author_id": 1096326, "author_profile": "https://Stackoverflow.com/users/1096326", "pm_score": 1, "selected": false, "text": "<p>A strategy that works to me in java ee was:</p>\n\n<ol>\n<li><p>Create a class with a method annotated with <code>@AroundInvoke</code>;</p>\n\n<pre><code>@Singleton\npublic class TimedInterceptor implements Serializable {\n\n @AroundInvoke\n public Object logMethod(InvocationContext ic) throws Exception {\n Date start = new Date();\n Object result = ic.proceed();\n Date end = new Date();\n System.out.println(\"time: \" + (end.getTime - start.getTime()));\n return result;\n }\n}\n</code></pre></li>\n<li><p>Annotate the method that you want to monitoring:</p>\n\n<pre><code>@Interceptors(TimedInterceptor.class)\npublic void onMessage(final Message message) { ... \n</code></pre></li>\n</ol>\n\n<p>I hope this can help.</p>\n" }, { "answer_id": 45413916, "author": "Justinas Jakavonis", "author_id": 5962766, "author_profile": "https://Stackoverflow.com/users/5962766", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"http://metrics.dropwizard.io/3.2.3/getting-started.html\" rel=\"noreferrer\">Metrics</a> library which provides various measuring instruments. Add dependency:</p>\n\n<pre><code>&lt;dependencies&gt;\n &lt;dependency&gt;\n &lt;groupId&gt;io.dropwizard.metrics&lt;/groupId&gt;\n &lt;artifactId&gt;metrics-core&lt;/artifactId&gt;\n &lt;version&gt;${metrics.version}&lt;/version&gt;\n &lt;/dependency&gt;\n&lt;/dependencies&gt;\n</code></pre>\n\n<p>And configure it for your environment. </p>\n\n<p>Methods can be annotated with <a href=\"http://metrics.dropwizard.io/3.1.0/apidocs/com/codahale/metrics/annotation/Timed.html\" rel=\"noreferrer\">@Timed</a>:</p>\n\n<pre><code>@Timed\npublic void exampleMethod(){\n // some code\n}\n</code></pre>\n\n<p>or piece of code wrapped with <a href=\"http://metrics.dropwizard.io/3.1.0/manual/core/#timers\" rel=\"noreferrer\">Timer</a>:</p>\n\n<pre><code>final Timer timer = metricsRegistry.timer(\"some_name\");\nfinal Timer.Context context = timer.time();\n// timed code\ncontext.stop();\n</code></pre>\n\n<p>Aggregated metrics can exported to console, JMX, CSV or other.</p>\n\n<p><code>@Timed</code> metrics output example:</p>\n\n<pre><code>com.example.ExampleService.exampleMethod\n count = 2\n mean rate = 3.11 calls/minute\n 1-minute rate = 0.96 calls/minute\n 5-minute rate = 0.20 calls/minute\n 15-minute rate = 0.07 calls/minute\n min = 17.01 milliseconds\n max = 1006.68 milliseconds\n mean = 511.84 milliseconds\n stddev = 699.80 milliseconds\n median = 511.84 milliseconds\n 75% &lt;= 1006.68 milliseconds\n 95% &lt;= 1006.68 milliseconds\n 98% &lt;= 1006.68 milliseconds\n 99% &lt;= 1006.68 milliseconds\n 99.9% &lt;= 1006.68 milliseconds\n</code></pre>\n" }, { "answer_id": 49168439, "author": "praveen jain", "author_id": 1993534, "author_profile": "https://Stackoverflow.com/users/1993534", "pm_score": 2, "selected": false, "text": "<p>You can use stopwatch class from spring core project: </p>\n\n<p>Code:</p>\n\n<pre><code>StopWatch stopWatch = new StopWatch()\nstopWatch.start(); //start stopwatch\n// write your function or line of code.\nstopWatch.stop(); //stop stopwatch\nstopWatch.getTotalTimeMillis() ; ///get total time\n</code></pre>\n\n<p>Documentation for Stopwatch:\n<strong>Simple stop watch, allowing for timing of a number of tasks, exposing total running time and running time for each named task. \nConceals use of System.currentTimeMillis(), improving the readability of application code and reducing the likelihood of calculation errors. \nNote that this object is not designed to be thread-safe and does not use synchronization. \nThis class is normally used to verify performance during proof-of-concepts and in development, rather than as part of production applications.</strong></p>\n" }, { "answer_id": 53052361, "author": "Pratik Patil", "author_id": 4773290, "author_profile": "https://Stackoverflow.com/users/4773290", "pm_score": 3, "selected": false, "text": "<p>I have written a method to print the method execution time in a much readable form.\nFor example, to calculate the factorial of 1 Million, it takes approximately 9 minutes. So the execution time get printed as:</p>\n\n<pre><code>Execution Time: 9 Minutes, 36 Seconds, 237 MicroSeconds, 806193 NanoSeconds\n</code></pre>\n\n<p>The code is here:</p>\n\n<pre><code>public class series\n{\n public static void main(String[] args)\n {\n long startTime = System.nanoTime();\n\n long n = 10_00_000;\n printFactorial(n);\n\n long endTime = System.nanoTime();\n printExecutionTime(startTime, endTime);\n\n }\n\n public static void printExecutionTime(long startTime, long endTime)\n {\n long time_ns = endTime - startTime;\n long time_ms = TimeUnit.NANOSECONDS.toMillis(time_ns);\n long time_sec = TimeUnit.NANOSECONDS.toSeconds(time_ns);\n long time_min = TimeUnit.NANOSECONDS.toMinutes(time_ns);\n long time_hour = TimeUnit.NANOSECONDS.toHours(time_ns);\n\n System.out.print(\"\\nExecution Time: \");\n if(time_hour &gt; 0)\n System.out.print(time_hour + \" Hours, \");\n if(time_min &gt; 0)\n System.out.print(time_min % 60 + \" Minutes, \");\n if(time_sec &gt; 0)\n System.out.print(time_sec % 60 + \" Seconds, \");\n if(time_ms &gt; 0)\n System.out.print(time_ms % 1E+3 + \" MicroSeconds, \");\n if(time_ns &gt; 0)\n System.out.print(time_ns % 1E+6 + \" NanoSeconds\");\n }\n}\n</code></pre>\n" }, { "answer_id": 58167003, "author": "Aska Fed", "author_id": 5922688, "author_profile": "https://Stackoverflow.com/users/5922688", "pm_score": 1, "selected": false, "text": "<p>For java 8+, another possible solution (more general, func-style and without aspects) could be to create some utility method accepting code as a parameter </p>\n\n<pre><code>public static &lt;T&gt; T timed (String description, Consumer&lt;String&gt; out, Supplier&lt;T&gt; code) {\n final LocalDateTime start = LocalDateTime.now ();\n T res = code.get ();\n final long execTime = Duration.between (start, LocalDateTime.now ()).toMillis ();\n out.accept (String.format (\"%s: %d ms\", description, execTime));\n return res;\n}\n</code></pre>\n\n<p>And the calling code could be smth like that:</p>\n\n<pre><code>public static void main (String[] args) throws InterruptedException {\n timed (\"Simple example\", System.out::println, Timing::myCode);\n}\n\npublic static Object myCode () {\n try {\n Thread.sleep (1500);\n } catch (InterruptedException e) {\n e.printStackTrace ();\n }\n return null;\n}\n</code></pre>\n" }, { "answer_id": 61475752, "author": "Ahmad Hoghooghi", "author_id": 2246238, "author_profile": "https://Stackoverflow.com/users/2246238", "pm_score": -1, "selected": false, "text": "<p><strong>Pure Java SE code</strong>, no need for adding dependency, using <code>TimeTracedExecuter</code> :</p>\n\n<pre><code>public static void main(String[] args) {\n\n Integer square = new TimeTracedExecutor&lt;&gt;(Main::calculateSquare)\n .executeWithInput(\"calculate square of num\",5,logger);\n\n}\npublic static int calculateSquare(int num){\n return num*num;\n}\n</code></pre>\n\n<p>Will produce result like this:</p>\n\n<p><code>INFO: It took 3 milliseconds to calculate square of num</code></p>\n\n<p>Custom reusable class: <strong>TimeTracedExecutor</strong></p>\n\n<pre><code>import java.text.NumberFormat;\nimport java.time.Duration;\nimport java.time.Instant;\nimport java.util.function.Function;\nimport java.util.logging.Logger;\n\npublic class TimeTracedExecutor&lt;T,R&gt; {\n Function&lt;T,R&gt; methodToExecute;\n\n public TimeTracedExecutor(Function&lt;T, R&gt; methodToExecute) {\n this.methodToExecute = methodToExecute;\n }\n\n public R executeWithInput(String taskDescription, T t, Logger logger){\n Instant start = Instant.now();\n R r= methodToExecute.apply(t);\n Instant finish = Instant.now();\n String format = \"It took %s milliseconds to \"+taskDescription;\n String elapsedTime = NumberFormat.getNumberInstance().format(Duration.between(start, finish).toMillis());\n logger.info(String.format(format, elapsedTime));\n return r;\n }\n}\n</code></pre>\n" }, { "answer_id": 61832131, "author": "Bhaskara Arani", "author_id": 4838509, "author_profile": "https://Stackoverflow.com/users/4838509", "pm_score": 3, "selected": false, "text": "<p>In Spring framework we have a call called StopWatch (org.springframework.util.StopWatch)</p>\n<pre><code>//measuring elapsed time using Spring StopWatch\n StopWatch watch = new StopWatch();\n watch.start();\n for(int i=0; i&lt; 1000; i++){\n Object obj = new Object();\n }\n watch.stop();\n System.out.println(&quot;Total execution time to create 1000 objects in Java using StopWatch in millis: &quot;\n + watch.getTotalTimeMillis());\n</code></pre>\n" }, { "answer_id": 69223408, "author": "jhenya-d", "author_id": 2054164, "author_profile": "https://Stackoverflow.com/users/2054164", "pm_score": 0, "selected": false, "text": "<p>Also could be implemented <code>Timer</code> interface and executed on any method of your class</p>\n<pre><code>import java.util.function.*;\n\npublic interface Timer {\n\n default void timeIt(Runnable r) {\n timeIt(() -&gt; { r.run(); return 0;});\n }\n\n default &lt;S,T&gt; T timeIt(Function&lt;S,T&gt; fun, S arg) {\n long start = System.nanoTime();\n T result = fun.apply(arg);\n long stop = System.nanoTime();\n System.out.println(&quot;Time: &quot; + (stop-start)/1000000.0 + &quot; msec&quot;);\n return result;\n }\n\n default &lt;T&gt; T timeIt(Supplier&lt;T&gt; s) {\n return timeIt(obj -&gt; s.get(), null);\n }\n}\n</code></pre>\n<p>Usage:</p>\n<pre><code>class MyClass implements Timer ..\n\ntimeIt(this::myFunction); \n</code></pre>\n" }, { "answer_id": 70313074, "author": "Brett Ryan", "author_id": 140037, "author_profile": "https://Stackoverflow.com/users/140037", "pm_score": 0, "selected": false, "text": "<p>There's a lot of valid answers here, all of which are implemented within the method. To make a general purpose method for timing I generally have a <code>Timing</code> class consisting of the following.</p>\n<pre><code>public record TimedResult&lt;T&gt;(T result, Duration duration) {}\n\npublic static Duration time(Runnable r) {\n var s = Instant.now();\n r.run();\n var dur = Duration.between(s, Instant.now());\n return dur;\n}\n\npublic static &lt;T&gt; TimedResult&lt;T&gt; time(Callable&lt;T&gt; r) throws Exception {\n var s = Instant.now();\n T res = r.call();\n var dur = Duration.between(s, Instant.now());\n return new TimedResult&lt;&gt;(res, dur);\n}\n</code></pre>\n<p>This is general enough to pass a <a href=\"https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Runnable.html\" rel=\"nofollow noreferrer\">Runnable</a> or <a href=\"https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/Callable.html\" rel=\"nofollow noreferrer\">Callable</a>.</p>\n<pre><code>Duration result = Timing.time(() -&gt; {\n // do some work.\n});\n\nTimedResult&lt;String&gt; result = Timing.time(() -&gt; {\n // do some work.\n return &quot;answer&quot;;\n});\n\nDuration timeTaken = result.duration();\nString answer = result.result();\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13140/" ]
1. How do I get a method's execution time? 2. Is there a `Timer` utility class for things like timing how long a task takes, etc? Most of the searches on Google return results for timers that schedule threads and tasks, which is not what I want.
There is always the old-fashioned way: ``` long startTime = System.nanoTime(); methodToTime(); long endTime = System.nanoTime(); long duration = (endTime - startTime); //divide by 1000000 to get milliseconds. ```
180,172
<p>Is there any good reason that an empty set of round brackets (parentheses) isn't valid for calling the default constructor in C++?</p> <pre><code>MyObject object; // ok - default ctor MyObject object(blah); // ok MyObject object(); // error </code></pre> <p>I seem to type "()" automatically everytime. Is there a good reason this isn't allowed?</p>
[ { "answer_id": 180185, "author": "Nemanja Trifunovic", "author_id": 8899, "author_profile": "https://Stackoverflow.com/users/8899", "pm_score": 6, "selected": false, "text": "<p>The same syntax is used for function declaration - e.g. the function <code>object</code>, taking no parameters and returning <code>MyObject</code></p>\n" }, { "answer_id": 180187, "author": "Fred Larson", "author_id": 10077, "author_profile": "https://Stackoverflow.com/users/10077", "pm_score": 4, "selected": false, "text": "<p>Because the compiler thinks it is a declaration of a function that takes no arguments and returns a MyObject instance.</p>\n" }, { "answer_id": 180189, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 7, "selected": false, "text": "<p>Because it is treated as the declaration for a function:</p>\n\n<pre><code>int MyFunction(); // clearly a function\nMyObject object(); // also a function declaration\n</code></pre>\n" }, { "answer_id": 180196, "author": "Black", "author_id": 25234, "author_profile": "https://Stackoverflow.com/users/25234", "pm_score": 3, "selected": false, "text": "<p>I guess, the compiler would not know if this statement:</p>\n\n<blockquote>\n <p>MyObject object(); </p>\n</blockquote>\n\n<p>is a constructor call or a function prototype declaring a function named <em>object</em> with return type <em>MyObject</em> and no parameters.</p>\n" }, { "answer_id": 180536, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "<p>As mentioned many times, it's a declaration. It's that way for backward compatibility. One of the many areas of C++ that are goofy/inconsistent/painful/bogus because of its legacy. </p>\n" }, { "answer_id": 181463, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 9, "selected": true, "text": "<p><strong>Most vexing parse</strong></p>\n\n<p>This is related to what is known as \"C++'s most vexing parse\". Basically, anything that can be interpreted by the compiler as a function declaration will be interpreted as a function declaration.</p>\n\n<p>Another instance of the same problem:</p>\n\n<pre><code>std::ifstream ifs(\"file.txt\");\nstd::vector&lt;T&gt; v(std::istream_iterator&lt;T&gt;(ifs), std::istream_iterator&lt;T&gt;());\n</code></pre>\n\n<p><code>v</code> is interpreted as a declaration of function with 2 parameters.</p>\n\n<p>The workaround is to add another pair of parentheses:</p>\n\n<pre><code>std::vector&lt;T&gt; v((std::istream_iterator&lt;T&gt;(ifs)), std::istream_iterator&lt;T&gt;());\n</code></pre>\n\n<p>Or, if you have C++11 and list-initialization (also known as uniform initialization) available:</p>\n\n<pre><code>std::vector&lt;T&gt; v{std::istream_iterator&lt;T&gt;{ifs}, std::istream_iterator&lt;T&gt;{}};\n</code></pre>\n\n<p>With this, there is no way it could be interpreted as a function declaration.</p>\n" }, { "answer_id": 181772, "author": "dalle", "author_id": 19100, "author_profile": "https://Stackoverflow.com/users/19100", "pm_score": 3, "selected": false, "text": "<p>You could also use the more verbose way of construction:</p>\n\n<pre><code>MyObject object1 = MyObject();\nMyObject object2 = MyObject(object1);\n</code></pre>\n\n<p>In C++0x this also allows for <code>auto</code>:</p>\n\n<pre><code>auto object1 = MyObject();\nauto object2 = MyObject(object1);\n</code></pre>\n" }, { "answer_id": 31093033, "author": "Andreas DM", "author_id": 3677097, "author_profile": "https://Stackoverflow.com/users/3677097", "pm_score": 3, "selected": false, "text": "<p>From n4296 [dcl.init]:</p>\n\n<blockquote>\n <p>[ Note:<br> Since <code>()</code> is not permitted by the syntax for <em>initializer</em>, \n <code>X a();</code> is not the declaration of an <em>object</em> of class X, but the\n declaration of a <em>function</em> taking no argument and returning an X. The\n form () is permitted in certain other initialization contexts (5.3.4,\n 5.2.3, 12.6.2). \n <br>—end note ]</p>\n</blockquote>\n\n<p><a href=\"https://timsong-cpp.github.io/cppwp/n3337/dcl.init#10\" rel=\"nofollow noreferrer\">C++11 Link</a><br>\n<a href=\"https://timsong-cpp.github.io/cppwp/n4140/dcl.init#11\" rel=\"nofollow noreferrer\">C++14 Link</a></p>\n" }, { "answer_id": 46824436, "author": "Hitokage", "author_id": 3027604, "author_profile": "https://Stackoverflow.com/users/3027604", "pm_score": 2, "selected": false, "text": "<p>As the others said, it is a function declaration. Since C++11 you can use brace initialization if you need to see the empty <em>something</em> that explicitly tells you that a default constructor is used.</p>\n\n<pre><code>Jedi luke{}; //default constructor\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10897/" ]
Is there any good reason that an empty set of round brackets (parentheses) isn't valid for calling the default constructor in C++? ``` MyObject object; // ok - default ctor MyObject object(blah); // ok MyObject object(); // error ``` I seem to type "()" automatically everytime. Is there a good reason this isn't allowed?
**Most vexing parse** This is related to what is known as "C++'s most vexing parse". Basically, anything that can be interpreted by the compiler as a function declaration will be interpreted as a function declaration. Another instance of the same problem: ``` std::ifstream ifs("file.txt"); std::vector<T> v(std::istream_iterator<T>(ifs), std::istream_iterator<T>()); ``` `v` is interpreted as a declaration of function with 2 parameters. The workaround is to add another pair of parentheses: ``` std::vector<T> v((std::istream_iterator<T>(ifs)), std::istream_iterator<T>()); ``` Or, if you have C++11 and list-initialization (also known as uniform initialization) available: ``` std::vector<T> v{std::istream_iterator<T>{ifs}, std::istream_iterator<T>{}}; ``` With this, there is no way it could be interpreted as a function declaration.
180,211
<p>To make click-able divs, I do:</p> <pre><code>&lt;div class="clickable" url="http://google.com"&gt; blah blah &lt;/div&gt; </code></pre> <p>and then </p> <pre><code>$("div.clickable").click( function() { window.location = $(this).attr("url"); }); </code></pre> <p>I don't know if this is the best way, but it works perfectly with me, except for one issue: If the div contains a click-able element, such as &lt;a href="..."&gt;, and the user clicks on the hyperlink, both the hyperlink and div's-clickable are called</p> <p>This is especially a problem when the anchor tag is referring to a javascript AJAX function, which executes the AJAX function <em>AND</em> follows the link in the 'url' attribute of the div.</p> <p>Anyway around this?</p>
[ { "answer_id": 180246, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 3, "selected": false, "text": "<p><code>\n$(\"div.clickable\").click(\nfunction(event)\n{\n window.location = $(this).attr(\"url\");\n event.preventDefault();\n});\n</code></p>\n" }, { "answer_id": 180247, "author": "Leanan", "author_id": 22390, "author_profile": "https://Stackoverflow.com/users/22390", "pm_score": 2, "selected": false, "text": "<p>I know that if you were to change that to an href you'd do:</p>\n\n<pre>\n$(\"a#link1\").click(function(event) {\n event.preventDefault();\n $('div.link1').show();\n //whatever else you want to do\n});\n</pre>\n\n<p>so if you want to keep it with the div, I'd try </p>\n\n<pre>\n$(\"div.clickable\").click(function(event) {\n event.preventDefault();\n window.location = $(this).attr(\"url\");\n});\n</pre>\n" }, { "answer_id": 180278, "author": "Parand", "author_id": 13055, "author_profile": "https://Stackoverflow.com/users/13055", "pm_score": 6, "selected": true, "text": "<p>If you return \"false\" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click).</p>\n\n<pre><code>$(\"div.clickable\").click(\nfunction()\n{\n window.location = $(this).attr(\"url\");\n return false;\n});\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/questions/1357118/javascript-event-preventdefault-vs-return-false\">event.preventDefault() vs. return false</a> for details on return false vs. preventDefault.</p>\n" }, { "answer_id": 2195216, "author": "Sander Aarts", "author_id": 265623, "author_profile": "https://Stackoverflow.com/users/265623", "pm_score": 3, "selected": false, "text": "<p>Using a custom url attribute makes the HTML invalid. Although that may not be a huge problem, the given examples are neither accessible. Not for keyboard navigation and not in cases when JavaScript is turned off (or blocked by some other script). Even Google will not find the page located at the specified url, not via this route at least.</p>\n\n<p>It's quite easy to make this accessible though. Just make sure there's a regular link inside the div that points to the url. Using JavaScript/jQuery you add an onclick to the div that redirects to the location specified by the link's href attribute. Now, when JavaScript doesn't work, the link still does and it can even catch the focus when using the keyboard to navigate (and you don't need custom attributes, so your HTML can be valid).</p>\n\n<hr>\n\n<p>I wrote a jQuery plugin some time ago that does this. It also adds classNames to the div (or any other element you want to make clickable) and the link so you can alter their looks with CSS when the div is indeed clickable. It even adds classNames that you can use to specify hover and focus styles.</p>\n\n<p>All you need to do is specify the element(s) you want to make clickable and call their clickable() method: in your case that would be <code>$(\"div.clickable).clickable();</code></p>\n\n<p>For downloading + documentation see the plugin's page: <a href=\"http://jlix.net/extensions/jquery/clickable\" rel=\"nofollow noreferrer\">jQuery: clickable &mdash; jLix</a></p>\n" }, { "answer_id": 54482019, "author": "Adem Ozturk", "author_id": 5389509, "author_profile": "https://Stackoverflow.com/users/5389509", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;div class=\"info\"&gt;\n &lt;h2&gt;Takvim&lt;/h2&gt;\n &lt;a href=\"item-list.php\"&gt; Click Me !&lt;/a&gt;\n&lt;/div&gt;\n\n\n$(document).delegate(\"div.info\", \"click\", function() {\n window.location = $(this).find(\"a\").attr(\"href\");\n});\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2721/" ]
To make click-able divs, I do: ``` <div class="clickable" url="http://google.com"> blah blah </div> ``` and then ``` $("div.clickable").click( function() { window.location = $(this).attr("url"); }); ``` I don't know if this is the best way, but it works perfectly with me, except for one issue: If the div contains a click-able element, such as <a href="...">, and the user clicks on the hyperlink, both the hyperlink and div's-clickable are called This is especially a problem when the anchor tag is referring to a javascript AJAX function, which executes the AJAX function *AND* follows the link in the 'url' attribute of the div. Anyway around this?
If you return "false" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click). ``` $("div.clickable").click( function() { window.location = $(this).attr("url"); return false; }); ``` See [event.preventDefault() vs. return false](https://stackoverflow.com/questions/1357118/javascript-event-preventdefault-vs-return-false) for details on return false vs. preventDefault.
180,242
<p>We are making a Ruby On Rails webapp where every customer gets their own database.<br> The database needs to be created after they fill out a form on our website.</p> <p>We have a template database that has all of the tables and columns that we need to copy. How can I do this in programatically from ruby on rails?</p>
[ { "answer_id": 180282, "author": "Tilendor", "author_id": 1470, "author_profile": "https://Stackoverflow.com/users/1470", "pm_score": 4, "selected": true, "text": "<p>From any controller, you can define the following method.</p>\n\n<pre><code> def copy_template_database\n template_name = \"customerdb1\" # Database to copy from\n new_name = \"temp\" #database to create &amp; copy to\n\n #connect to template database to copy. Note that this will override any previous\n #connections for all Models that inherit from ActiveRecord::Base\n ActiveRecord::Base.establish_connection({:adapter =&gt; \"mysql\", :database =&gt; template_name, :host =&gt; \"olddev\",\n :username =&gt; \"root\", :password =&gt; \"password\" })\n\n sql_connection = ActiveRecord::Base.connection \n sql_connection.execute(\"CREATE DATABASE #{new_name} CHARACTER SET latin1 COLLATE latin1_general_ci\")\n tables = sql_connection.select_all(\"Show Tables\")\n #the results are an array of hashes, ie:\n # [{\"table_from_customerdb1\" =&gt; \"customers\"},{\"table_from_customerdb1\" =&gt; \"employees},...]\n table_names = Array.new\n tables.each { |hash| hash.each_value { |name| table_names &lt;&lt; name }}\n\n table_names.each { |name| \n sql_connection.execute(\"CREATE TABLE #{new_name}.#{name} LIKE #{template_name}.#{name}\")\n sql_connection.execute(\"INSERT INTO #{new_name}.#{name} SELECT * FROM #{template_name}.#{name}\")\n }\n #This statement is optional. It connects ActiveRecord to the new database\n ActiveRecord::Base.establish_connection({:adapter =&gt; \"mysql\", :database =&gt; new_name, :host =&gt; \"olddev\",\n :username =&gt; \"root\", :password =&gt; \"password\" })\n end\n</code></pre>\n\n<p>Note that I do not know for sure if this will keep foriegn key integrity. I think it depends a lot on how the template Database is created.</p>\n" }, { "answer_id": 181183, "author": "ninesided", "author_id": 1030, "author_profile": "https://Stackoverflow.com/users/1030", "pm_score": 0, "selected": false, "text": "<p>You could put your template schema creation code into a script which contains all of the required table/index/view/procedure creation statements, call it \"template_schema.sql\" or whatever and then just run the script on the database of your choice (from Ruby, if that's what you're after) and you're done.</p>\n\n<p>The best approach is probably to have each database object in a separate file under source control (to make it easy to track changes on individual objects) and then have them merged into a single file as part of the deployment.</p>\n" }, { "answer_id": 182589, "author": "abarax", "author_id": 24390, "author_profile": "https://Stackoverflow.com/users/24390", "pm_score": 3, "selected": false, "text": "<p>I'm not sure what you mean but you can use ruby's command line functionality to dump the template database, create a new database and re-import it using the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/mysqldump.html\" rel=\"noreferrer\">mysqldump</a> program:</p>\n\n<pre><code>&gt; mysqldump -uroot -proot templateDB &gt; dump.sql\n&gt; mysql -uroot -proot --execute=\"CREATE DATABASE newDB\"\n&gt; mysql -uroot -proot newDB &lt; dump.sql\n</code></pre>\n\n<p><a href=\"http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html\" rel=\"noreferrer\">Here</a> is a good description of invoking command line options from Ruby.</p>\n" }, { "answer_id": 1632815, "author": "Kodak", "author_id": 197559, "author_profile": "https://Stackoverflow.com/users/197559", "pm_score": 1, "selected": false, "text": "<p>By using <a href=\"http://github.com/adamwiggins/yaml_db\" rel=\"nofollow noreferrer\">yaml_db</a></p>\n<p>You need to install plugin, dump any rails database (including mysql) into data.yml file using rake task, change connection string to point to new database and then finaly load data.yml into any new database (including mysql) using another rake task. Very straightforward.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1470/" ]
We are making a Ruby On Rails webapp where every customer gets their own database. The database needs to be created after they fill out a form on our website. We have a template database that has all of the tables and columns that we need to copy. How can I do this in programatically from ruby on rails?
From any controller, you can define the following method. ``` def copy_template_database template_name = "customerdb1" # Database to copy from new_name = "temp" #database to create & copy to #connect to template database to copy. Note that this will override any previous #connections for all Models that inherit from ActiveRecord::Base ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => template_name, :host => "olddev", :username => "root", :password => "password" }) sql_connection = ActiveRecord::Base.connection sql_connection.execute("CREATE DATABASE #{new_name} CHARACTER SET latin1 COLLATE latin1_general_ci") tables = sql_connection.select_all("Show Tables") #the results are an array of hashes, ie: # [{"table_from_customerdb1" => "customers"},{"table_from_customerdb1" => "employees},...] table_names = Array.new tables.each { |hash| hash.each_value { |name| table_names << name }} table_names.each { |name| sql_connection.execute("CREATE TABLE #{new_name}.#{name} LIKE #{template_name}.#{name}") sql_connection.execute("INSERT INTO #{new_name}.#{name} SELECT * FROM #{template_name}.#{name}") } #This statement is optional. It connects ActiveRecord to the new database ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => new_name, :host => "olddev", :username => "root", :password => "password" }) end ``` Note that I do not know for sure if this will keep foriegn key integrity. I think it depends a lot on how the template Database is created.
180,245
<p>I have this CheckBoxList on a page:</p> <pre><code>&lt;asp:checkboxlist runat="server" id="Locations" datasourceid="LocationsDatasource" datatextfield="CountryName" datavaluefield="CountryCode" /&gt; </code></pre> <p>I'd like to loop through the checkbox elements on the client using Javascript and grab the value of each checked checkbox, but the values don't appear to be available on the client side. The HTML output looks like this:</p> <pre><code>&lt;table id="ctl00_Content_Locations" class="SearchFilterCheckboxlist" cellspacing="0" cellpadding="0" border="0" style="width:235px;border-collapse:collapse;"&gt; &lt;tr&gt; &lt;td&gt;&lt;input id="ctl00_Content_Locations_0" type="checkbox" name="ctl00$Content$Locations$0" /&gt;&lt;label for="ctl00_Content_Locations_0"&gt;Democratic Republic of the Congo&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;&lt;input id="ctl00_Content_Locations_1" type="checkbox" name="ctl00$Content$Locations$1" /&gt;&lt;label for="ctl00_Content_Locations_1"&gt;Central African Republic&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;&lt;input id="ctl00_Content_Locations_2" type="checkbox" name="ctl00$Content$Locations$2" /&gt;&lt;label for="ctl00_Content_Locations_2"&gt;Congo&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;&lt;input id="ctl00_Content_Locations_3" type="checkbox" name="ctl00$Content$Locations$3" /&gt;&lt;label for="ctl00_Content_Locations_3"&gt;Cameroon&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;&lt;input id="ctl00_Content_Locations_4" type="checkbox" name="ctl00$Content$Locations$4" /&gt;&lt;label for="ctl00_Content_Locations_4"&gt;Gabon&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;&lt;input id="ctl00_Content_Locations_5" type="checkbox" name="ctl00$Content$Locations$5" /&gt;&lt;label for="ctl00_Content_Locations_5"&gt;Equatorial Guinea&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre> <p></p> <p>The values ("cd", "cg", "ga", etc.) are nowhere to be found. Where are they? Is it even possible to access them on the client, or do I need to build this checkboxlist myself using a repeater or something?</p>
[ { "answer_id": 180253, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 3, "selected": true, "text": "<p>Stored in ViewState, you cannot access them on the client without <a href=\"http://www.daveparslow.com/2007/08/assigning-value-to-aspnet-checkbox.html\" rel=\"nofollow noreferrer\"><strong>some hacking</strong></a>.</p>\n" }, { "answer_id": 222147, "author": "rjarmstrong", "author_id": 25809, "author_profile": "https://Stackoverflow.com/users/25809", "pm_score": 2, "selected": false, "text": "<p>To avoid hacking the checkbox list just use a repeater as such:</p>\n\n<pre><code>&lt;asp:Repeater ID=\"rptItems\" runat=\"server\" DataSourceID=\"odsDataSource\"&gt;\n&lt;ItemTemplate&gt;\n&lt;input id=\"iptCheckBox\" type=\"checkbox\" runat=\"server\" value='&lt;%# Eval(\"Key\") %&gt;'&gt;&lt;%# Eval(\"Value\") %&gt;&lt;/input&gt;\n&lt;/ItemTemplate&gt;\n&lt;/asp:Repeater&gt;\n</code></pre>\n" }, { "answer_id": 1878966, "author": "Swapna", "author_id": 228546, "author_profile": "https://Stackoverflow.com/users/228546", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;body&gt;\n &lt;form id=\"form1\" runat=\"server\"&gt;\n &lt;div&gt;\n &lt;asp:CheckBoxList ID=\"CheckBoxList1\" runat=\"server\" DataTextField=\"tx\" DataValueField=\"vl\"&gt;\n &lt;/asp:CheckBoxList&gt;\n &lt;/div&gt;\n &lt;input id=\"Button1\" type=\"button\" value=\"button\" onclick=\"return Button1_onclick()\" /&gt; \n &lt;/form&gt;\n&lt;/body&gt;\n&lt;script type=\"text/javascript\"&gt;\n\nfunction Button1_onclick() \n{\nvar itemarr = document.getElementById(\"CheckBoxList1\").getElementsByTagName(\"span\");\nvar itemlen = itemarr.length;\n for(i = 0; i &lt;itemlen;i++)\n {\n alert(itemarr[i].getAttribute(\"dvalue\"));\n }\nreturn false;\n}\n\n\n&lt;/script&gt;\n</code></pre>\n\n<p>Code</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n if (!IsPostBack)\n {\n DataTable dt = new DataTable();\n dt.Columns.Add(\"tx\");\n dt.Columns.Add(\"vl\");\n DataRow dr = dt.NewRow();\n dr[0] = \"asdas\";\n dr[1] = \"1\";\n dt.Rows.Add(dr);\n dr = dt.NewRow();\n dr[0] = \"456456\";\n dr[1] = \"2\";\n dt.Rows.Add(dr);\n dr = dt.NewRow();\n dr[0] = \"yjryut\";\n dr[1] = \"3\";\n dt.Rows.Add(dr);\n dr = dt.NewRow();\n dr[0] = \"yjrfdgdfgyut\";\n dr[1] = \"3\";\n dt.Rows.Add(dr);\n dr = dt.NewRow();\n dr[0] = \"34534\";\n dr[1] = \"3\";\n dt.Rows.Add(dr);\n CheckBoxList1.DataSource = dt;\n CheckBoxList1.DataBind();\n foreach (ListItem li in CheckBoxList1.Items)\n {\n li.Attributes.Add(\"dvalue\", li.Value);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 3549453, "author": "user428602", "author_id": 428602, "author_profile": "https://Stackoverflow.com/users/428602", "pm_score": 0, "selected": false, "text": "<p>Swapna, Your answer absolutely works. So in order to check if the check box in the ASP.Net Checkboxlist is checked and then accumulate the list as a comma-delimited string, you can do as</p>\n\n<p>C# Code-behind</p>\n\n<pre><code>ChkboxList1.DataSource = dsData;\nChkboxList1.DataTextField = \"your-display-column-name\";\nChkboxList1.DataValueField = \"your-identifier-column-name\";\nChkboxList1.DataBind();\n\nforeach (ListItem li in ChkboxList1.Items)\n{\n li.Attributes.Add(\"DataValue\", li.Value); \n}\n</code></pre>\n\n<p>Then in Javascript do</p>\n\n<pre><code>var selValues = \"\";\nvar ChkboxList1Ctl = document.getElementById(\"ChkboxList1\");\nvar ChkboxList1Arr = null;\nvar ChkboxList1Attr= null;\n\nif (ChkboxList1Ctl != null)\n{\n ChkboxList1Arr = ChkboxList1Ctl.getElementsByTagName(\"INPUT\");\n ChkboxList1Attr = ChkboxList1Ctl.getElementByTagName(\"span\");\n}\nif (ChkboxList1Arr != null)\n{\n for (var i = 0; i &lt; ChkboxList1Arr.length; i++)\n {\n if (ChkboxList1Arr[i].checked)\n selValues += ChkboxList1Attr[i].getAttribute(\"DataValue\") + \",\";\n }\n if (selValues.length &gt; 0)\n selValues = selValues.substr(0, selValues.length - 1);\n}\n</code></pre>\n" }, { "answer_id": 10301643, "author": "danyim", "author_id": 350951, "author_profile": "https://Stackoverflow.com/users/350951", "pm_score": 2, "selected": false, "text": "<p>Had to do something really nasty in order to get this to work..</p>\n\n<pre><code> &lt;asp:Repeater ID=\"rptItems\" runat=\"server\"&gt;\n &lt;ItemTemplate&gt;\n &lt;input ID=\"iptCheckBox\" type=\"checkbox\" runat=\"server\" value='&lt;%# Eval(\"your_data_value\") %&gt;' /&gt;\n &lt;label ID=\"iptLabel\" runat=\"server\"&gt;&lt;%# Eval(\"your_data_field\") %&gt;&lt;/label&gt;\n &lt;br /&gt;\n &lt;/ItemTemplate&gt;\n &lt;/asp:Repeater&gt;\n</code></pre>\n\n<hr>\n\n<p>Codebehind:</p>\n\n<pre><code>Private Sub rptItems_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptItems.ItemDataBound\n Dim checkBox As HtmlInputCheckBox = DirectCast(e.Item.FindControl(\"iptCheckBox\"), HtmlInputCheckBox)\n Dim label As HtmlControl = DirectCast(e.Item.FindControl(\"iptLabel\"), HtmlControl)\n\n label.Attributes.Add(\"for\", checkBox.ClientID)\nEnd Sub\n</code></pre>\n" }, { "answer_id": 15030781, "author": "AdamE", "author_id": 796858, "author_profile": "https://Stackoverflow.com/users/796858", "pm_score": 4, "selected": false, "text": "<p>I finally have the answer I've been looking for!</p>\n\n<p>The asp.net CheckboxList control <em>does</em> in fact render the value attribute to HTML - it has been working for me in a Production site for over a year now! (We ALWAYS have EnableViewState turned off for all our sites and it still works, without any tweaks or hacks)</p>\n\n<p>However, all of a sudden, it stopped working one day, and our CheckboxList checkboxes no longer were rendering their value attribute in HTML! WTF you say? So did we! It took a while to figure this out, but since it had been working before, we knew there had to be a reason. The reason was an accidental change to our web.config!</p>\n\n<pre><code>&lt;pages controlRenderingCompatibilityVersion=\"3.5\"&gt;\n</code></pre>\n\n<p>We removed this attribute from the pages configuration section and that did the trick!</p>\n\n<p>Why is this so? We reflected the code for the CheckboxList control and found this in the RenderItem method:</p>\n\n<pre><code>if (this.RenderingCompatibility &gt;= VersionUtil.Framework40)\n{\n this._controlToRepeat.InputAttributes.Add(\"value\", item.Value);\n}\n</code></pre>\n\n<p>Dearest dev brothers and sisters do not despair! ALL the answers I searched for here on Stackexchange and the rest of the web gave erroneous information! As of .Net 4.0 asp.net renders the value attribute of the checkboxes of a CheckboxList:</p>\n\n<pre><code>&lt;input type=\"checkbox\" value=\"myvalue1\" id=\"someid\" /&gt;\n</code></pre>\n\n<p>Perhaps not practically useful, Microsoft gave you the ability to add a \"controlRenderingCompatibilityVersion\" to your web.config to turn this off by setting to a version lower than 4, which for our purposes is completely unnecessary and in fact harmful, since javascript code relied on the value attribute...</p>\n\n<p>We were getting chk.val() equal to \"on\" for all our checkboxes, which is what originally alerted us to this problem in the first place (using jquery.val() which gets the value of the checkbox. Turns out \"on\" is the value of a checkbox that is checked... Learn something every day).</p>\n" }, { "answer_id": 35276896, "author": "David Sherret", "author_id": 188246, "author_profile": "https://Stackoverflow.com/users/188246", "pm_score": 0, "selected": false, "text": "<p>Removing <code>&lt;pages controlRenderingCompatibilityVersion=\"3.5\"&gt;</code> caused an issue in some old code I was working on. I was getting <a href=\"https://stackoverflow.com/questions/778952/the-controls-collection-cannot-be-modified-because-the-control-contains-code-bl\">this error</a>. Once I got that error I realized it was too risky of a change.</p>\n\n<p>To fix this, I ended up extending <code>CheckBoxList</code> and overriding the <code>Render</code> method to add an additional attribute containing the value to each list item:</p>\n\n<pre><code>public class CheckBoxListExt : CheckBoxList\n{\n protected override void Render(HtmlTextWriter writer)\n {\n foreach (ListItem item in this.Items)\n {\n item.Attributes.Add(\"data-value\", item.Value);\n }\n\n base.Render(writer);\n }\n}\n</code></pre>\n\n<p>This will render the <code>data-value</code> attribute on the outer <code>span</code> tag.</p>\n" }, { "answer_id": 44547137, "author": "Jigs17", "author_id": 8018680, "author_profile": "https://Stackoverflow.com/users/8018680", "pm_score": 0, "selected": false, "text": "<pre><code>Easy Way I Do It.\n\n//First create query directly From Database that contains hidden field code format (i do it in stored procedure)\n\nSELECT Id,Name + '&lt;input id=\"hf_Id\" name=\"hf_Id\" value=\"'+convert(nvarchar(100),Id)+'\" type=\"hidden\"&gt;' as Name FROM User\n\n//Then bind checkbox list as normally(i bind it from dataview).\n\ncbl.DataSource = dv;\ncbl.DataTextField = \"Name\";\ncbl.DataValueField = \"Id\";\ncbl.DataBind();\n\n//Then finally it represent code as follow.\n\n&lt;table id=\"cbl_Position\" border=\"0\"&gt;\n&lt;tbody&gt;\n&lt;tr&gt;\n&lt;td&gt;\n&lt;input id=\"cbl_0\" name=\"cbl$0\" type=\"checkbox\"&gt;\n&lt;label for=\"cbl_0\"&gt;\nABC\n&lt;input id=\"hf_Id\" name=\"hf_Id\" value=\"1\" type=\"hidden\"&gt;\n&lt;/label&gt;\n&lt;/td&gt;\n&lt;/tr&gt;\n&lt;/table&gt;\n\nThis way you can get DataValueField as inside hiddenfield and also can get it value from client side using javascript.\n</code></pre>\n" }, { "answer_id": 63115878, "author": "Muhammad Awais", "author_id": 3901944, "author_profile": "https://Stackoverflow.com/users/3901944", "pm_score": 0, "selected": false, "text": "<p>I tried the following and its working for me:</p>\n<pre><code>&lt;asp:CheckBoxList ID=&quot;chkAttachments&quot; runat=&quot;server&quot;&gt;&lt;/asp:CheckBoxList&gt;\n</code></pre>\n<p>Server side binding:</p>\n<pre><code>private void LoadCheckBoxData()\n {\n\n var docList = new List&lt;Documents&gt;(); // need to get the list data from database\n chkAttachments.Items.Clear();\n\n ListItem item = new ListItem();\n \n foreach (var doc in docList )\n {\n item = new ListItem();\n item.Value = doc.Id.ToString();\n item.Text = doc.doc_name;\n chkAttachments.Items.Add(item);\n }\n }\n \n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
I have this CheckBoxList on a page: ``` <asp:checkboxlist runat="server" id="Locations" datasourceid="LocationsDatasource" datatextfield="CountryName" datavaluefield="CountryCode" /> ``` I'd like to loop through the checkbox elements on the client using Javascript and grab the value of each checked checkbox, but the values don't appear to be available on the client side. The HTML output looks like this: ``` <table id="ctl00_Content_Locations" class="SearchFilterCheckboxlist" cellspacing="0" cellpadding="0" border="0" style="width:235px;border-collapse:collapse;"> <tr> <td><input id="ctl00_Content_Locations_0" type="checkbox" name="ctl00$Content$Locations$0" /><label for="ctl00_Content_Locations_0">Democratic Republic of the Congo</label></td> </tr><tr> <td><input id="ctl00_Content_Locations_1" type="checkbox" name="ctl00$Content$Locations$1" /><label for="ctl00_Content_Locations_1">Central African Republic</label></td> </tr><tr> <td><input id="ctl00_Content_Locations_2" type="checkbox" name="ctl00$Content$Locations$2" /><label for="ctl00_Content_Locations_2">Congo</label></td> </tr><tr> <td><input id="ctl00_Content_Locations_3" type="checkbox" name="ctl00$Content$Locations$3" /><label for="ctl00_Content_Locations_3">Cameroon</label></td> </tr><tr> <td><input id="ctl00_Content_Locations_4" type="checkbox" name="ctl00$Content$Locations$4" /><label for="ctl00_Content_Locations_4">Gabon</label></td> </tr><tr> <td><input id="ctl00_Content_Locations_5" type="checkbox" name="ctl00$Content$Locations$5" /><label for="ctl00_Content_Locations_5">Equatorial Guinea</label></td> </tr> ``` The values ("cd", "cg", "ga", etc.) are nowhere to be found. Where are they? Is it even possible to access them on the client, or do I need to build this checkboxlist myself using a repeater or something?
Stored in ViewState, you cannot access them on the client without [**some hacking**](http://www.daveparslow.com/2007/08/assigning-value-to-aspnet-checkbox.html).
180,266
<p>How do you think, is it a good idea to have such an enum:</p> <pre><code>enum AvailableSpace { Percent10, Percent20, SqF500, SqF600 } </code></pre> <p>The question is about the semantics of the values names, i.e. both percentage and square feet. I really believe that it's not a good idea, but I could not find and guidelines, etc. in support of this.</p> <p>EDIT: This will be used to determine a state of an entity - i.e. as a read only property to describe a state of an object. If we know the total space (i.e. the object itself knows it), we have the option to convert internally, so we either have only percentage, or square feet, or both. The argument is, that "both" is not a good idea.</p> <p>The above is an example of course, but the real problem is that some data providers send us totals (sq.f.), and others percentage, and my goal is to unify the UI. I'm free to make some approximations, so the exact values will be adapted based on how accurate we want to present the information.</p> <p>The question is only about the semantics of the value names, not the content - i.e. if it is a good idea to put percentage in an (potential) int enum.</p>
[ { "answer_id": 180284, "author": "Chris Wenham", "author_id": 5548, "author_profile": "https://Stackoverflow.com/users/5548", "pm_score": 3, "selected": false, "text": "<p>If at all possible, I'd rather break your example into two values, where your enum is \"Percent\" and \"SquareFeet\" and the second value is the quantifier. Tie these together in a struct.</p>\n\n<p>If the context allows for it, it may be even better to create two wrapper types \"Percent\" and \"SquareFeet\" and then create some operator overloads, so you can do things like \"new SquareFeet(500) + new Percent(20);\" and eliminate the use of enums.</p>\n\n<p><em>Update:</em> Your naming scheme would be appropriate if the values were industry recognized terms, almost to the point of being symbols. For example, it's safe to have an enum that contains values such as \"ISO9001\" rather than two values (an enum containing \"ISO\" and an int of 9001). It'd also be appropriate to have an enum like below:</p>\n\n<pre><code>public enum OperatingSystem\n{\n Windows95,\n Windows98,\n Windows2000,\n WindowsXP,\n WindowsVista,\n MacOSClassic,\n MacOSXTiger,\n MacOSXLeopard\n}\n</code></pre>\n\n<p>If the terms \"Percentage10\" and \"Sqf500\" are not terms of art or well defined in a spec, data dictionary, etc. then it's inappropriate to use them as values in an enum.</p>\n" }, { "answer_id": 180296, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 4, "selected": true, "text": "<p><strong>The answer</strong>: No, it is not a good idea to use enums for representing values. Especially values in two semantically distinct scales. You should not use enums for values.</p>\n\n<p><strong>The reason</strong>: What's the relation between the enum values from the two scales, like Percent10 and SqF600? How do you expand the list of values you can represent within your code? How do you do comparison and arithmetic operations on these values?</p>\n\n<p><strong>The suggestion (not asked for, but nevertheless here it is. :-))</strong>: The semantic of what you are trying to do would be better reflected by a struct that contains two fields - one for absolute area and one for percentage available of that absolute area. With such structure you can represent anything you can represent with the enums above. For example, data providers that give you absolute area, are represented with a struct with the area and 100% available. Data providers that give you percentage, are represented with a struct with the percentage they set and the absolute area such that the percentage of that area is the actual available area the data provider wants to report. You get \"normalized\" representation of the data from both type of providers and you can add couple of operators to enable comparison and arithmetic calculations with instances.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8220/" ]
How do you think, is it a good idea to have such an enum: ``` enum AvailableSpace { Percent10, Percent20, SqF500, SqF600 } ``` The question is about the semantics of the values names, i.e. both percentage and square feet. I really believe that it's not a good idea, but I could not find and guidelines, etc. in support of this. EDIT: This will be used to determine a state of an entity - i.e. as a read only property to describe a state of an object. If we know the total space (i.e. the object itself knows it), we have the option to convert internally, so we either have only percentage, or square feet, or both. The argument is, that "both" is not a good idea. The above is an example of course, but the real problem is that some data providers send us totals (sq.f.), and others percentage, and my goal is to unify the UI. I'm free to make some approximations, so the exact values will be adapted based on how accurate we want to present the information. The question is only about the semantics of the value names, not the content - i.e. if it is a good idea to put percentage in an (potential) int enum.
**The answer**: No, it is not a good idea to use enums for representing values. Especially values in two semantically distinct scales. You should not use enums for values. **The reason**: What's the relation between the enum values from the two scales, like Percent10 and SqF600? How do you expand the list of values you can represent within your code? How do you do comparison and arithmetic operations on these values? **The suggestion (not asked for, but nevertheless here it is. :-))**: The semantic of what you are trying to do would be better reflected by a struct that contains two fields - one for absolute area and one for percentage available of that absolute area. With such structure you can represent anything you can represent with the enums above. For example, data providers that give you absolute area, are represented with a struct with the area and 100% available. Data providers that give you percentage, are represented with a struct with the percentage they set and the absolute area such that the percentage of that area is the actual available area the data provider wants to report. You get "normalized" representation of the data from both type of providers and you can add couple of operators to enable comparison and arithmetic calculations with instances.
180,272
<p>Is it even possible?</p> <p>Basically, there's a remote repository from which I pull using just:</p> <pre><code>git pull </code></pre> <p>Now, I'd like to preview what this pull would change (a diff) without touching anything on my side. The reason is that thing I'm pulling might not be "good" and I want someone else to fix it before making my repository "dirty".</p>
[ { "answer_id": 180329, "author": "Brian Gianforcaro", "author_id": 3415, "author_profile": "https://Stackoverflow.com/users/3415", "pm_score": 6, "selected": false, "text": "<p>I think <strong>git fetch</strong> is what your looking for. </p>\n\n<p>It will pull the changes and objects without committing them to your local repo's index. </p>\n\n<p>They can be merged later with <strong>git merge</strong>. </p>\n\n<p><a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-fetch.html\" rel=\"noreferrer\">Man Page</a></p>\n\n<p>Edit: Further Explination</p>\n\n<p>Straight from the <strong>Git- SVN Crash Course</strong> <a href=\"http://git.or.cz/course/svn.html\" rel=\"noreferrer\">link</a></p>\n\n<blockquote>\n <p>Now, how do you get any new changes from a remote repository? You fetch them: </p>\n\n<pre><code>git fetch http://host.xz/path/to/repo.git/ \n</code></pre>\n \n <p>At this point they are in your repository and you can examine them using:</p>\n\n<pre><code>git log origin \n</code></pre>\n \n <p>You can also diff the changes. You can also use <strong>git log HEAD..origin</strong> to see just the changes you don't have in your branch. Then if would like to merge them - just do:</p>\n\n<pre><code>git merge origin\n</code></pre>\n \n <p>Note that if you don't specify a branch to fetch, it will conveniently default to the tracking remote.</p>\n</blockquote>\n\n<p>Reading the man page is honestly going to give you the best understanding of options and how to use it. </p>\n\n<p>I'm just trying to do this by examples and memory, I don't currently have a box to test out on. You should look at:</p>\n\n<pre><code>git log -p //log with diff\n</code></pre>\n\n<p>A fetch can be undone with <strong>git reset --hard</strong> (<a href=\"http://git-scm.com/docs/git-reset\" rel=\"noreferrer\">link</a>) , however all uncommitted changes in your tree will be lost as well as the changes you've fetched.</p>\n" }, { "answer_id": 180368, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 9, "selected": true, "text": "<p>After doing a <code>git fetch</code>, do a <code>git log HEAD..origin/master</code> to show the log entries between your last common commit and the origin's master branch. To show the diffs, use either <code>git log -p HEAD..origin/master</code> to show each patch, or <code>git diff HEAD...origin/master</code> (three dots not two) to show a single diff.</p>\n\n<p>There normally isn't any need to undo a fetch, because doing a fetch only updates the <em>remote</em> branches and none of <em>your</em> branches. If you're not prepared to do a pull and merge in all the remote commits, you can use <code>git cherry-pick</code> to accept only the specific remote commits you want. Later, when you're ready to get everything, a <code>git pull</code> will merge in the rest of the commits.</p>\n\n<p>Update: I'm not entirely sure why you want to avoid the use of git fetch. All git fetch does is update your local copy of the remote branches. This local copy doesn't have anything to do with any of your branches, and it doesn't have anything to do with uncommitted local changes. I have heard of people who run git fetch in a cron job because it's so safe. (I wouldn't normally recommend doing that, though.)</p>\n" }, { "answer_id": 5376713, "author": "Antonio Bardazzi", "author_id": 614407, "author_profile": "https://Stackoverflow.com/users/614407", "pm_score": 5, "selected": false, "text": "<p>You can fetch from a remote repo, see the differences and then pull or merge.</p>\n\n<p>This is an example for a remote repo called <code>origin</code> and a branch called <code>master</code> tracking the remote branch <code>origin/master</code>:</p>\n\n<pre><code>git checkout master \ngit fetch \ngit diff origin/master\ngit pull --rebase origin master\n</code></pre>\n" }, { "answer_id": 7103880, "author": "Matthias", "author_id": 127013, "author_profile": "https://Stackoverflow.com/users/127013", "pm_score": 4, "selected": false, "text": "<p>I created a custom git alias to do that for me:</p>\n\n<pre><code>alias.changes=!git log --name-status HEAD..\n</code></pre>\n\n<p>with that you can do this:</p>\n\n<pre><code>$git fetch\n$git changes origin\n</code></pre>\n\n<p>This will get you a nice and easy way to preview changes before doing a <code>merge</code>.</p>\n" }, { "answer_id": 44633884, "author": "Ed Greenberg", "author_id": 226493, "author_profile": "https://Stackoverflow.com/users/226493", "pm_score": -1, "selected": false, "text": "<p>What about cloning the repo elsewhere, and doing git log on both the real checkout and the fresh clone to see if you got the same thing. </p>\n" }, { "answer_id": 48784435, "author": "Andy P", "author_id": 2115610, "author_profile": "https://Stackoverflow.com/users/2115610", "pm_score": 2, "selected": false, "text": "<p>I may be late to the party, but this is something which bugged me for too long. \nIn my experience, I would rather want to see which changes are pending than update my working copy and deal with those changes.</p>\n\n<p>This goes in the <code>~/.gitconfig</code> file:</p>\n\n<pre><code>[alias]\n diffpull=!git fetch &amp;&amp; git diff HEAD..@{u}\n</code></pre>\n\n<p>It fetches the current branch, then does a diff between the working copy and this fetched branch. So you should only see the changes that would come with <code>git pull</code>.</p>\n" }, { "answer_id": 48800580, "author": "cowboycb", "author_id": 9137976, "author_profile": "https://Stackoverflow.com/users/9137976", "pm_score": 2, "selected": false, "text": "<p>I use these two commands and I can see the files to change.</p>\n\n<ol>\n<li><p>First executing <strong>git fetch</strong>, it gives output like this (part of output):</p>\n\n<pre>...\n72f8433..c8af041 develop -> origin/develop\n...</pre></li>\n</ol>\n\n<p>This operation gives us two commit IDs, first is the old one, and second will be the new.</p>\n\n<ol start=\"2\">\n<li><p>Then compare these two commits using <strong>git diff</strong> </p>\n\n<pre>git diff 72f8433..c8af041 | grep \"diff --git\"</pre></li>\n</ol>\n\n<p>This command will list the files that will be updated:</p>\n\n<pre><code>diff --git a/app/controller/xxxx.php b/app/controller/xxxx.php\ndiff --git a/app/view/yyyy.php b/app/view/yyyy.php\n</code></pre>\n\n<p>For example <em>app/controller/xxxx.php</em> and <em>app/view/yyyy.php</em> will be updated.</p>\n\n<p>Comparing two commits using <strong>git diff</strong> prints all updated files with\nchanged lines, but with <strong>grep</strong> it searches and gets only the lines\ncontains <strong>diff --git</strong> from output.</p>\n" }, { "answer_id": 59737915, "author": "AXE Labs", "author_id": 632827, "author_profile": "https://Stackoverflow.com/users/632827", "pm_score": 0, "selected": false, "text": "<p>If you don't want <a href=\"https://git-scm.com/docs/git-fetch\" rel=\"nofollow noreferrer\">git-fetch</a> to update your local .git, just copy your local repo to a temp dir and do a pull there. Here is a shor-hand:</p>\n\n<pre><code>$ alias gtp=\"tar -c . | (cd /tmp &amp;&amp; mkdir tp &amp;&amp; cd tp &amp;&amp; tar -x &amp;&amp; git pull; rm -rf /tmp/tp)\"\n</code></pre>\n\n<p>Ex.:</p>\n\n<pre><code>$ git status\n# On branch master\nnothing to commit (working directory clean)\n\n$ gtp\nremote: Finding sources: 100% (25/25)\nremote: Total 25 (delta 10), reused 25 (delta 10)\nUnpacking objects: 100% (25/25), done.\nFrom ssh://my.git.domain/reapO\n 32d61dc..05287d6 master -&gt; origin/master\nUpdating 32d61dc..05287d6\nFast-forward\n subdir/some.file | 2 +-\n .../somepath/by.tes | 3 ++-\n .../somepath/data | 11 +++++++++++\n 3 files changed, 14 insertions(+), 2 deletions(-)\n\n$ git status\n# On branch master\nnothing to commit (working directory clean)\n\n$ git fetch\nremote: Finding sources: 100% (25/25)\nremote: Total 25 (delta 10), reused 25 (delta 10)\nUnpacking objects: 100% (25/25), done.\nFrom ssh://my.git.domain/reapO\n 32d61dc..05287d6 master -&gt; origin/master\n\n$ git status\n# On branch master\n# Your branch is behind 'origin/master' by 3 commits, and can be fast-forwarded.\n#\nnothing to commit (working directory clean)\n</code></pre>\n" }, { "answer_id": 67351884, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "<p>13 years later, you now have With a <strong><code>prefetch</code></strong> task in &quot;<a href=\"https://github.com/git/git/blob/d250f903596ee149dffcd65e3794dbd00b62f97e/Documentation/git-maintenance.txt\" rel=\"nofollow noreferrer\"><code>git maintenance</code></a>&quot;<sup>(<a href=\"https://git-scm.com/docs/git-maintenance\" rel=\"nofollow noreferrer\">man</a>)</sup></p>\n<blockquote>\n<p>The prefetch task updates the object directory with the latest objects from all registered remotes.</p>\n<p>For each remote, a <code>git fetch</code> command is run.<br />\nThe refmap is custom to avoid updating local or remote branches (those in <code>refs/heads</code> or <code>refs/remotes</code>).<br />\nInstead, the remote refs are stored in <strong><code>refs/prefetch/&lt;remote&gt;/</code></strong>.<br />\nAlso, tags are not updated.</p>\n<p><strong>This is done to avoid disrupting the remote-tracking branches</strong>.<br />\nThe end users expect these refs to stay unmoved unless they initiate a fetch.</p>\n<p>With prefetch task, however, the objects necessary to complete a later real fetch would already be obtained, so the real fetch would go faster.<br />\nIn the ideal case, it will just become an update to a bunch of remote-tracking branches without any object transfer.</p>\n</blockquote>\n<p>And you can also do, since Git 2.32 (Q2 2021) a <code>git fetch --prefetch</code>, again without modifying your last fetch state.</p>\n<p>See <a href=\"https://github.com/git/git/commit/32f67888d85bd0af30b857a29ca25a55999b6d01\" rel=\"nofollow noreferrer\">commit 32f6788</a>, <a href=\"https://github.com/git/git/commit/cfd781ea22e0f334d3c0104e1f34c47327934314\" rel=\"nofollow noreferrer\">commit cfd781e</a>, <a href=\"https://github.com/git/git/commit/2e03115d0c253843953ef9d113c72e0375892df4\" rel=\"nofollow noreferrer\">commit 2e03115</a> (16 Apr 2021), and <a href=\"https://github.com/git/git/commit/a039a1fcf987de3a8209cc5229324d37d9ead16e\" rel=\"nofollow noreferrer\">commit a039a1f</a> (06 Apr 2021) by <a href=\"https://github.com/derrickstolee\" rel=\"nofollow noreferrer\">Derrick Stolee (<code>derrickstolee</code>)</a>.<br />\n<sup>(Merged by <a href=\"https://github.com/gitster\" rel=\"nofollow noreferrer\">Junio C Hamano -- <code>gitster</code> --</a> in <a href=\"https://github.com/git/git/commit/d250f903596ee149dffcd65e3794dbd00b62f97e\" rel=\"nofollow noreferrer\">commit d250f90</a>, 30 Apr 2021)</sup></p>\n<blockquote>\n<h2><a href=\"https://github.com/git/git/commit/2e03115d0c253843953ef9d113c72e0375892df4\" rel=\"nofollow noreferrer\"><code>fetch</code></a>: add <code>--prefetch</code> option</h2>\n<p><sup>Helped-by: Tom Saeger</sup><br />\n<sup>Helped-by: Ramsay Jones</sup><br />\n<sup>Signed-off-by: Derrick Stolee</sup></p>\n</blockquote>\n<blockquote>\n<p>The <code>--prefetch</code> option will be used by the 'prefetch' maintenance task instead of sending refspecs explicitly across the command-line.<br />\nThe intention is to modify the refspec to place all results in <code>refs/prefetch/</code> instead of anywhere else.</p>\n<p>Create helper method <code>filter_prefetch_refspec()</code> to modify a given refspec to fit the rules expected of the prefetch task:</p>\n<ul>\n<li>Negative refspecs are preserved.</li>\n<li>Refspecs without a destination are removed.</li>\n<li>Refspecs whose source starts with &quot;<code>refs/tags/</code>&quot; are removed.</li>\n<li>Other refspecs are placed within &quot;<code>refs/prefetch/</code>&quot;.</li>\n</ul>\n<p>Finally, we add the '<code>force</code>' option to ensure that prefetch refs are replaced as necessary.</p>\n<p>There are some interesting cases that are worth testing.</p>\n<p>An earlier version of this change dropped the &quot;<code>i--</code>&quot; from the loop that deletes a refspec item and shifts the remaining entries down.<br />\nThis allowed some refspecs to not be modified.<br />\nThe subtle part about the first <code>--prefetch</code> test is that the <code>refs/tags/*</code> refspec appears directly before the refs/heads/bogus/* refspec.<br />\nWithout that &quot;<code>i--</code>&quot;, this ordering would remove the &quot;<code>refs/tags/*</code>&quot; refspec and leave the last one unmodified, placing the result in &quot;<code>refs/heads/*</code>&quot;.</p>\n<p>It is possible to have an empty refspec.<br />\nThis is typically the case for remotes other than the origin, where users want to fetch a specific tag or branch.<br />\nTo correctly test this case, we need to further remove the upstream remote for the local branch.<br />\nThus, we are testing a refspec that will be deleted, leaving nothing to fetch.</p>\n</blockquote>\n<p><code>fetch-options</code> now includes in its <a href=\"https://github.com/git/git/blob/2e03115d0c253843953ef9d113c72e0375892df4/Documentation/fetch-options.txt#L113-L117\" rel=\"nofollow noreferrer\">man page</a>:</p>\n<blockquote>\n<h2><code>--prefetch</code></h2>\n<p>Modify the configured refspec to place all refs into the\n<code>refs/prefetch/</code> namespace.</p>\n</blockquote>\n" }, { "answer_id": 68115220, "author": "SuperNova", "author_id": 3464971, "author_profile": "https://Stackoverflow.com/users/3464971", "pm_score": 1, "selected": false, "text": "<p>This useful commands below I picked from this link <a href=\"https://gist.github.com/jtdp/5443297\" rel=\"nofollow noreferrer\">https://gist.github.com/jtdp/5443297</a>. Thanks to <a href=\"https://gist.github.com/jtdp\" rel=\"nofollow noreferrer\">https://gist.github.com/jtdp</a></p>\n<pre><code>git fetch origin\n\n# show commit logs of changes\ngit log master..origin/master\n\n# show diffs of changes\ngit diff master..origin/master\n\n# apply the changes by merge..\ngit merge origin/master\n\n# .. or just pull the changes\ngit pull\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14690/" ]
Is it even possible? Basically, there's a remote repository from which I pull using just: ``` git pull ``` Now, I'd like to preview what this pull would change (a diff) without touching anything on my side. The reason is that thing I'm pulling might not be "good" and I want someone else to fix it before making my repository "dirty".
After doing a `git fetch`, do a `git log HEAD..origin/master` to show the log entries between your last common commit and the origin's master branch. To show the diffs, use either `git log -p HEAD..origin/master` to show each patch, or `git diff HEAD...origin/master` (three dots not two) to show a single diff. There normally isn't any need to undo a fetch, because doing a fetch only updates the *remote* branches and none of *your* branches. If you're not prepared to do a pull and merge in all the remote commits, you can use `git cherry-pick` to accept only the specific remote commits you want. Later, when you're ready to get everything, a `git pull` will merge in the rest of the commits. Update: I'm not entirely sure why you want to avoid the use of git fetch. All git fetch does is update your local copy of the remote branches. This local copy doesn't have anything to do with any of your branches, and it doesn't have anything to do with uncommitted local changes. I have heard of people who run git fetch in a cron job because it's so safe. (I wouldn't normally recommend doing that, though.)
180,327
<p>I need to solve a few mathematical equations in my application. Here's a typical example of such an equation:</p> <pre><code>a + b * c - d / e = a </code></pre> <p>Additional rules:</p> <ul> <li>b % 10 = 0</li> <li>b >= 0</li> <li>b &lt;= 100</li> <li>Each number must be integer</li> <li>...</li> </ul> <p>I would like to get the possible solution sets for a, b, c, d and e.</p> <p>Are there <strong>any libraries out there</strong>, either open source or commercial, <strong>which I can use to solve such an equation</strong>? If yes, what kind of result do they provide?</p>
[ { "answer_id": 180360, "author": "Simon", "author_id": 24039, "author_profile": "https://Stackoverflow.com/users/24039", "pm_score": 0, "selected": false, "text": "<p>Pretty sure <a href=\"http://www.nr.com/\" rel=\"nofollow noreferrer\">Numerical Recipes</a> will have something</p>\n" }, { "answer_id": 180362, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 1, "selected": false, "text": "<p>You want a computer algebra system.</p>\n\n<p>See <A href=\"https://stackoverflow.com/questions/160911/symbolic-math-lib\"><a href=\"https://stackoverflow.com/questions/160911/symbolic-math-lib\">https://stackoverflow.com/questions/160911/symbolic-math-lib</a></A>, the answers to which are mostly as relevant to c++ as to c.</p>\n" }, { "answer_id": 180367, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 0, "selected": false, "text": "<p>You're looking for a computer algebra system, and that's not a trivial thing.</p>\n\n<p>Lot's of them are available, though, try this list at Wikipedia:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Comparison_of_computer_algebra_systems\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Comparison_of_computer_algebra_systems</a></p>\n\n<p>-Adam</p>\n" }, { "answer_id": 180374, "author": "andreas buykx", "author_id": 19863, "author_profile": "https://Stackoverflow.com/users/19863", "pm_score": 0, "selected": false, "text": "<p>This looks like linear programming. Does <a href=\"http://en.wikipedia.org/wiki/Linear_programming#Solvers_and_Scripting_.28Programming.29_Languages\" rel=\"nofollow noreferrer\">this</a> list help?</p>\n" }, { "answer_id": 180380, "author": "I GIVE CRAP ANSWERS", "author_id": 25083, "author_profile": "https://Stackoverflow.com/users/25083", "pm_score": 0, "selected": false, "text": "<p>In addition to the other posts. Your constraint sets make this reminiscent of an <strong>integer programming problem</strong>, so you might want to check that kind of thing out as well. Perhaps your problem can be (re-)stated as one.</p>\n\n<p>You must know, however that the integer programming problems tends to be one of the harder computational problems so you might end up using many clock cycles to crack it.</p>\n" }, { "answer_id": 180381, "author": "simon", "author_id": 14143, "author_profile": "https://Stackoverflow.com/users/14143", "pm_score": 2, "selected": false, "text": "<p>You're venturing into the world of numerical analysis, and here be dragons. Seemingly small differences in specification can make a huge difference in what is the right approach.</p>\n\n<p>I hesitate to make specific suggestions without a fairly precise description of the problem domain. It sounds superficiall like you are solving constrained linear problems that are simple enough that there are a lot of ways to do it but \"...\" could be a problem.</p>\n\n<p>A good resource for general solvers etc. would be <a href=\"http://gams.nist.gov/\" rel=\"nofollow noreferrer\">GAMS</a>. Much of the software there may be a bit heavy weight for what you are asking.</p>\n" }, { "answer_id": 180432, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 1, "selected": false, "text": "<p>I know it is not your real question, but you can simplify the given equation to:</p>\n\n<p>d = b * c * e with e != 0</p>\n" }, { "answer_id": 180845, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 3, "selected": true, "text": "<p>Solving <a href=\"http://en.wikipedia.org/wiki/Linear_systems\" rel=\"nofollow noreferrer\">linear systems</a> can <em>generally</em> be solved using linear programming. I'd recommend taking a look at <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/numeric/ublas/doc/index.htm\" rel=\"nofollow noreferrer\">Boost uBLAS</a> for starters - it has a simple triangular solver. Then you might checkout libraries targeting more domain specific approaches, perhaps <a href=\"http://www2.isye.gatech.edu/~wcook/qsopt/\" rel=\"nofollow noreferrer\">QSopt</a>. </p>\n" }, { "answer_id": 201679, "author": "Joe Pineda", "author_id": 21258, "author_profile": "https://Stackoverflow.com/users/21258", "pm_score": 0, "selected": false, "text": "<p>Looking only at the \"additional rules\" part it does look like linear programming, in which case LINDO or a similar program implementing the simplex algorithm should be fine.</p>\n\n<p>However, if the first equation is really <em>typical</em> it shows yours is NOT a linear algebra problem - no 2 variables multiplying or dividing each other should appear on a linear equation!</p>\n\n<p>So I'd say you definitely need either a computer algebra system or solve the problem using a genetic algorithm.</p>\n\n<p>Since you have restrictions similar to those found in linear programming though you're not quite there, if you just want a solution to your specific problem I'd say pick up any of the libraries mentioned at the end of <a href=\"http://en.wikipedia.org/wiki/Genetic_algorithm\" rel=\"nofollow noreferrer\">Wikipedia's article on genetic algorithms</a> and develop an app to give you the result. If you want a more generalist approach, then you've got to simulate algebraic manipulations on your computer, no other way around.</p>\n" }, { "answer_id": 1701109, "author": "Jason", "author_id": 206908, "author_profile": "https://Stackoverflow.com/users/206908", "pm_score": 0, "selected": false, "text": "<p>The TI-89 Calculator has a 'solver' application. \nIt was built to solve problems like the one in your example.\nI know its not a library. But there are several TI-89 emulators out there.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15288/" ]
I need to solve a few mathematical equations in my application. Here's a typical example of such an equation: ``` a + b * c - d / e = a ``` Additional rules: * b % 10 = 0 * b >= 0 * b <= 100 * Each number must be integer * ... I would like to get the possible solution sets for a, b, c, d and e. Are there **any libraries out there**, either open source or commercial, **which I can use to solve such an equation**? If yes, what kind of result do they provide?
Solving [linear systems](http://en.wikipedia.org/wiki/Linear_systems) can *generally* be solved using linear programming. I'd recommend taking a look at [Boost uBLAS](http://www.boost.org/doc/libs/1_36_0/libs/numeric/ublas/doc/index.htm) for starters - it has a simple triangular solver. Then you might checkout libraries targeting more domain specific approaches, perhaps [QSopt](http://www2.isye.gatech.edu/~wcook/qsopt/).
180,328
<p>So lets say I have a dataset based on:</p> <pre><code>SELECT TopicLink.*, Topic.Name AS FromTopicName, Topic_1.Name AS ToTopicName FROM TopicLink INNER JOIN Topic ON TopicLink.FromTopicId = Topic.TopicId INNER JOIN Topic AS Topic_1 ON TopicLink.ToTopicId = Topic_1.TopicId </code></pre> <p>With old school ADO, using a Recordset, I could modify columns in table TopicLink and the invoke Save() on the recordset and it would make it back into the database. Is this functionality in no way possible anymore in ADO.Net, presumably with a CommandBuilder? Or is there a workaround?</p> <p>(Yes I know I could "simply" write a stored procedure...but I am looking for a quick and easy solution, basically the equivalent functionality we had in old ADO, or MS Access, where you can do a query with multiple joins, bind it to a grid on a form, and the user can update and save data, with no code required whatsoever)</p> <p>Key point here: I do not want to manually write the INSERT, UPDATE, and DELETE statements. </p>
[ { "answer_id": 180344, "author": "Vijesh VP", "author_id": 22016, "author_profile": "https://Stackoverflow.com/users/22016", "pm_score": 2, "selected": true, "text": "<p>I think you can achive this by providing your own update command for the ADO.net DataAdaptor. Check out the sample provided <a href=\"http://www.ondotnet.com/pub/a/dotnet/excerpt/progvisbasic_ch08-2/index.html?page=4\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 441125, "author": "SqlRyan", "author_id": 8114, "author_profile": "https://Stackoverflow.com/users/8114", "pm_score": 0, "selected": false, "text": "<p>It's my understanding that as long as you've selected the entire primary key from every table you'll be updating, you should be fine, since ADO.NET will know what to do with the updated data automatically. If your returned data doesn't have the primary keys in it, though, ADO.NET won't know which rows in the tables it needs to update, and so will be unable to help you unless you specify you own UPDATE statement (as the other answerer suggested).</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8678/" ]
So lets say I have a dataset based on: ``` SELECT TopicLink.*, Topic.Name AS FromTopicName, Topic_1.Name AS ToTopicName FROM TopicLink INNER JOIN Topic ON TopicLink.FromTopicId = Topic.TopicId INNER JOIN Topic AS Topic_1 ON TopicLink.ToTopicId = Topic_1.TopicId ``` With old school ADO, using a Recordset, I could modify columns in table TopicLink and the invoke Save() on the recordset and it would make it back into the database. Is this functionality in no way possible anymore in ADO.Net, presumably with a CommandBuilder? Or is there a workaround? (Yes I know I could "simply" write a stored procedure...but I am looking for a quick and easy solution, basically the equivalent functionality we had in old ADO, or MS Access, where you can do a query with multiple joins, bind it to a grid on a form, and the user can update and save data, with no code required whatsoever) Key point here: I do not want to manually write the INSERT, UPDATE, and DELETE statements.
I think you can achive this by providing your own update command for the ADO.net DataAdaptor. Check out the sample provided [here](http://www.ondotnet.com/pub/a/dotnet/excerpt/progvisbasic_ch08-2/index.html?page=4).
180,330
<p>I've got a save dialog box which pops up when i press a button. However i dont want to save a file at that point, i want to take the name and place it in the text box next to the button, for the name to be used later. </p> <p>Can anybody tell me how to obtain the file path from the save dialog box to use it later?</p>
[ { "answer_id": 180332, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 7, "selected": true, "text": "<p>Here is a sample code I just wrote very fast... instead of Console.Write you can simply store the path in a variable and use it later.</p>\n\n<pre><code>SaveFileDialog saveFileDialog1 = new SaveFileDialog(); \nsaveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments); \nsaveFileDialog1.Filter = \"Your extension here (*.EXT)|*.ext|All Files (*.*)|*.*\" ; \nsaveFileDialog1.FilterIndex = 1; \n\nif(saveFileDialog1.ShowDialog() == DialogResult.OK) \n{ \n Console.WriteLine(saveFileDialog1.FileName);//Do what you want here\n} \n</code></pre>\n" }, { "answer_id": 180359, "author": "Inisheer", "author_id": 2982, "author_profile": "https://Stackoverflow.com/users/2982", "pm_score": 2, "selected": false, "text": "<p>Addressing the textbox...</p>\n\n<pre><code>if (saveFileDialog.ShowDialog() == DialogResult.OK)\n{\n this.textBox1.Text = saveFileDialog.FileName;\n}\n</code></pre>\n" }, { "answer_id": 4721043, "author": "Nidz", "author_id": 579496, "author_profile": "https://Stackoverflow.com/users/579496", "pm_score": 2, "selected": false, "text": "<pre><code>private void mnuFileSave_Click(object sender, EventArgs e)\n{\n dlgFileSave.Filter = \"RTF Files|*.rtf|\"+\"Text files (*.txt)|*.txt|All files (*.*)|*.*\";\n dlgFileSave.FilterIndex = 1;\n if (dlgFileSave.ShowDialog() == System.Windows.Forms.DialogResult.OK &amp;&amp; dlgFileSave.FileName.Length &gt; 0)\n {\n foreach (string strFile in dlgFileSave.FileNames)\n {\n SingleDocument document = new SingleDocument();\n document.rtbNotice.SaveFile(strFile, RichTextBoxStreamType.RichText);\n document.MdiParent = this;\n document.Show();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 26754513, "author": "user4218087", "author_id": 4218087, "author_profile": "https://Stackoverflow.com/users/4218087", "pm_score": -1, "selected": false, "text": "<p>Try below code.</p>\n\n<pre><code>saveFileDialog1.ShowDialog();\nrichTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14441/" ]
I've got a save dialog box which pops up when i press a button. However i dont want to save a file at that point, i want to take the name and place it in the text box next to the button, for the name to be used later. Can anybody tell me how to obtain the file path from the save dialog box to use it later?
Here is a sample code I just wrote very fast... instead of Console.Write you can simply store the path in a variable and use it later. ``` SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments); saveFileDialog1.Filter = "Your extension here (*.EXT)|*.ext|All Files (*.*)|*.*" ; saveFileDialog1.FilterIndex = 1; if(saveFileDialog1.ShowDialog() == DialogResult.OK) { Console.WriteLine(saveFileDialog1.FileName);//Do what you want here } ```
180,349
<p>In our program, each customer gets their own database. We e-mail them a link that connects them to their database. The link contains a GUID that lets the program know which database to connect to.</p> <p>How do I dynamically and programatically connect ActiveRecord to the right db?</p>
[ { "answer_id": 180355, "author": "Tilendor", "author_id": 1470, "author_profile": "https://Stackoverflow.com/users/1470", "pm_score": 4, "selected": false, "text": "<p>you can change the connection to ActiveRecord at any time by calling ActiveRecord::Base.establish_connection(...)</p>\n\n<p>IE:</p>\n\n<pre><code> ActiveRecord::Base.establish_connection({:adapter =&gt; \"mysql\", :database =&gt; new_name, :host =&gt; \"olddev\",\n :username =&gt; \"root\", :password =&gt; \"password\" })\n</code></pre>\n" }, { "answer_id": 180391, "author": "Jim Puls", "author_id": 6010, "author_profile": "https://Stackoverflow.com/users/6010", "pm_score": 6, "selected": true, "text": "<p>You can also do this easily without hardcoding anything and run migrations automatically:</p>\n\n<pre><code>customer = CustomerModel.find(id)\nspec = CustomerModel.configurations[RAILS_ENV]\nnew_spec = spec.clone\nnew_spec[\"database\"] = customer.database_name\nActiveRecord::Base.establish_connection(new_spec)\nActiveRecord::Migrator.migrate(\"db/migrate_data/\", nil)\n</code></pre>\n\n<p>I find it useful to re-establish the old connection on a particular model afterwards:</p>\n\n<pre><code>CustomerModel.establish_connection(spec)\n</code></pre>\n" }, { "answer_id": 30492099, "author": "Andre Figueiredo", "author_id": 986862, "author_profile": "https://Stackoverflow.com/users/986862", "pm_score": 4, "selected": false, "text": "<p>It's been a while since this question has been created, but I have to say that there is another way too:</p>\n\n<pre><code>conn_config = ActiveRecord::Base.connection_config\nconn_config[:database] = new_database\nActiveRecord::Base.establish_connection conn_config\n</code></pre>\n" }, { "answer_id": 44147811, "author": "Dorian", "author_id": 407213, "author_profile": "https://Stackoverflow.com/users/407213", "pm_score": 2, "selected": false, "text": "<pre><code>class Database\n def self.development!\n ActiveRecord::Base.establish_connection(:development)\n end\n\n def self.production!\n ActiveRecord::Base.establish_connection(ENV['PRODUCTION_DATABASE'])\n end\n\n def self.staging!\n ActiveRecord::Base.establish_connection(ENV['STAGING_DATABASE'])\n end\nend\n</code></pre>\n\n<p>And in <code>.env</code> (with <code>dotenv-rails</code> gem for instance):</p>\n\n<pre><code>PRODUCTION_DATABASE=postgres://...\nSTAGING_DATABASE=postgres://...\n</code></pre>\n\n<p>And now you can:</p>\n\n<pre><code>Database.development!\nUser.count\nDatabase.production!\nUser.count\nDatabase.staging!\nUser.count\n# etc.\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1470/" ]
In our program, each customer gets their own database. We e-mail them a link that connects them to their database. The link contains a GUID that lets the program know which database to connect to. How do I dynamically and programatically connect ActiveRecord to the right db?
You can also do this easily without hardcoding anything and run migrations automatically: ``` customer = CustomerModel.find(id) spec = CustomerModel.configurations[RAILS_ENV] new_spec = spec.clone new_spec["database"] = customer.database_name ActiveRecord::Base.establish_connection(new_spec) ActiveRecord::Migrator.migrate("db/migrate_data/", nil) ``` I find it useful to re-establish the old connection on a particular model afterwards: ``` CustomerModel.establish_connection(spec) ```
180,366
<p>I have a Page that has a single instance of a UserControl that itself has a single UpdatePanel. Inside the UpdatePanel are several Button controls. The Click event for these controls are wired up in the code-behind, in the Init event of the UserControl.</p> <p>I get the Click event for the first button I push, every time, no problem. After that, I only get Click events for one button (SearchButton) - the rest are ignored. I have included the code for the control below - for sake of brevity, I have excluded the click event handler methods, but they are all of the standard "void Button_Click(object sender, EventArgs e)" variety. Any ideas?</p> <pre><code>&lt;asp:UpdatePanel ID="PickerUpdatePanel" runat="server" UpdateMode="Conditional"&gt; &lt;ContentTemplate&gt; &lt;asp:Panel ID="Container" runat="server"&gt; &lt;div&gt; &lt;asp:TextBox ID="PickerResults" runat="server" style="margin-right: 3px;" SkinID="Plain" /&gt; &lt;asp:Image ID="LaunchPopup" runat="server" ImageUrl="~/images/icons/user_manage.png" ImageAlign="Top" BorderColor="#294254" BorderStyle="Dotted" BorderWidth="1px" Height="20px" Width="20px" style="cursor: pointer;" /&gt; &lt;/div&gt; &lt;asp:Panel ID="PickerPanel" runat="server" DefaultButton="OKButton" CssClass="popupDialog" style="height: 227px; width: 400px; padding: 5px; display: none;"&gt; &lt;asp:Panel runat="server" id="ContactPickerSearchParams" style="margin-bottom: 3px;" DefaultButton="SearchButton"&gt; Search: &lt;asp:TextBox ID="SearchTerms" runat="server" style="margin-right: 3px;" Width="266px" SkinID="Plain" /&gt; &lt;asp:Button ID="SearchButton" runat="server" Text="Go" Width="60px" SkinID="Plain" /&gt; &lt;/asp:Panel&gt; &lt;asp:ListBox ID="SearchResults" runat="server" Height="150px" Width="100%" SelectionMode="Multiple" style="margin-bottom: 3px;" /&gt; &lt;asp:Button ID="AddButton" runat="server" Text="Add &gt;&gt;" style="margin-right: 3px;" Width="60px" SkinID="Plain" /&gt; &lt;asp:TextBox ID="ChosenPeople" runat="server" Width="325px" SkinID="Plain" /&gt; &lt;div style="float: left;"&gt; &lt;asp:Button ID="AddNewContact" runat="server" SkinID="Plain" Width="150px" Text="New Contact" /&gt; &lt;/div&gt; &lt;div style="text-align: right;"&gt; &lt;asp:Button ID="OKButton" runat="server" Text="Ok" SkinID="Plain" Width="100px" /&gt; &lt;/div&gt; &lt;input id="SelectedContacts" runat="server" visible="false" /&gt; &lt;/asp:Panel&gt; &lt;ajax:PopupControlExtender ID="PickerPopEx" runat="server" PopupControlID="PickerPanel" TargetControlID="LaunchPopup" Position="Bottom" /&gt; &lt;/asp:Panel&gt; &lt;/ContentTemplate&gt; &lt;Triggers&gt; &lt;asp:AsyncPostBackTrigger ControlID="AddButton" EventName="Click" /&gt; &lt;asp:AsyncPostBackTrigger ControlID="SearchButton" EventName="Click" /&gt; &lt;asp:AsyncPostBackTrigger ControlID="AddNewContact" EventName="Click" /&gt; &lt;/Triggers&gt; &lt;/asp:UpdatePanel&gt; public partial class ContactPicker : System.Web.UI.UserControl { protected void Page_Init(object sender, EventArgs e) { SearchButton.Click += new EventHandler(SearchButton_Click); AddButton.Click += new EventHandler(AddButton_Click); OKButton.Click += new EventHandler(OKButton_Click); } // Other code left out } </code></pre>
[ { "answer_id": 180641, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 3, "selected": true, "text": "<p>It seems that adding UseSubmitBehavior=\"false\" to the button definitions has solved my problem. Still don't know why that first button click worked at all.</p>\n" }, { "answer_id": 305111, "author": "Blatfrig", "author_id": 39241, "author_profile": "https://Stackoverflow.com/users/39241", "pm_score": 1, "selected": false, "text": "<p>The most likely reason for this would be the client IDs that .Net generates for its controls changing. These are dynamically assigned and could change between postbacks / partial postbacks.</p>\n\n<p>If controls are being added to the panel dynamically, the ID of your button could be different between postbacks causing .Net to be unable to tie the click event to the correct event handler in your code.</p>\n" }, { "answer_id": 4248741, "author": "Orson", "author_id": 207756, "author_profile": "https://Stackoverflow.com/users/207756", "pm_score": 0, "selected": false, "text": "<p>In my case, i had a <code>LinkButton</code> within a <code>dgPatients_ItemDataBound</code> event handler that used the <code>PostBackUrl</code> property.</p>\n\n<p>The moment i changed the <code>LinkButton</code> to a <code>HyperLink</code>, the problem went away.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35/" ]
I have a Page that has a single instance of a UserControl that itself has a single UpdatePanel. Inside the UpdatePanel are several Button controls. The Click event for these controls are wired up in the code-behind, in the Init event of the UserControl. I get the Click event for the first button I push, every time, no problem. After that, I only get Click events for one button (SearchButton) - the rest are ignored. I have included the code for the control below - for sake of brevity, I have excluded the click event handler methods, but they are all of the standard "void Button\_Click(object sender, EventArgs e)" variety. Any ideas? ``` <asp:UpdatePanel ID="PickerUpdatePanel" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:Panel ID="Container" runat="server"> <div> <asp:TextBox ID="PickerResults" runat="server" style="margin-right: 3px;" SkinID="Plain" /> <asp:Image ID="LaunchPopup" runat="server" ImageUrl="~/images/icons/user_manage.png" ImageAlign="Top" BorderColor="#294254" BorderStyle="Dotted" BorderWidth="1px" Height="20px" Width="20px" style="cursor: pointer;" /> </div> <asp:Panel ID="PickerPanel" runat="server" DefaultButton="OKButton" CssClass="popupDialog" style="height: 227px; width: 400px; padding: 5px; display: none;"> <asp:Panel runat="server" id="ContactPickerSearchParams" style="margin-bottom: 3px;" DefaultButton="SearchButton"> Search: <asp:TextBox ID="SearchTerms" runat="server" style="margin-right: 3px;" Width="266px" SkinID="Plain" /> <asp:Button ID="SearchButton" runat="server" Text="Go" Width="60px" SkinID="Plain" /> </asp:Panel> <asp:ListBox ID="SearchResults" runat="server" Height="150px" Width="100%" SelectionMode="Multiple" style="margin-bottom: 3px;" /> <asp:Button ID="AddButton" runat="server" Text="Add >>" style="margin-right: 3px;" Width="60px" SkinID="Plain" /> <asp:TextBox ID="ChosenPeople" runat="server" Width="325px" SkinID="Plain" /> <div style="float: left;"> <asp:Button ID="AddNewContact" runat="server" SkinID="Plain" Width="150px" Text="New Contact" /> </div> <div style="text-align: right;"> <asp:Button ID="OKButton" runat="server" Text="Ok" SkinID="Plain" Width="100px" /> </div> <input id="SelectedContacts" runat="server" visible="false" /> </asp:Panel> <ajax:PopupControlExtender ID="PickerPopEx" runat="server" PopupControlID="PickerPanel" TargetControlID="LaunchPopup" Position="Bottom" /> </asp:Panel> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="AddButton" EventName="Click" /> <asp:AsyncPostBackTrigger ControlID="SearchButton" EventName="Click" /> <asp:AsyncPostBackTrigger ControlID="AddNewContact" EventName="Click" /> </Triggers> </asp:UpdatePanel> public partial class ContactPicker : System.Web.UI.UserControl { protected void Page_Init(object sender, EventArgs e) { SearchButton.Click += new EventHandler(SearchButton_Click); AddButton.Click += new EventHandler(AddButton_Click); OKButton.Click += new EventHandler(OKButton_Click); } // Other code left out } ```
It seems that adding UseSubmitBehavior="false" to the button definitions has solved my problem. Still don't know why that first button click worked at all.
180,370
<p>I am aware of the <a href="http://msdn.microsoft.com/en-us/library/system.timezone(VS.80).aspx" rel="noreferrer">System.TimeZone</a> class as well as the many uses of the <a href="http://msdn.microsoft.com/en-us/library/system.datetime.tostring(VS.80).aspx" rel="noreferrer">DateTime.ToString()</a> method. What I haven't been able to find is a way to convert a DateTime to a string that, in addition to the time and date info, contains the three-letter Time Zone abbreviation (in fact, much the same way StackOverflow's tooltips for relative time display works).</p> <p>To make an example easy for everyone to follow as well as consume, let's continue with the StackOverflow example. If you look at the tooltip that displays on relative times, it displays with the full date, the time including seconds in twelve-hour format, an AM/PM designation, and then the three-letter Time Zone abbreviation (in their case, Coordinated Universal Time). I realize I could easily get GMT or UTC by using the built-in methods, but what I really want is the time as it is locally &mdash; in this case, on a web server.</p> <p>If our web server is running Windows Server 2k3 and has it's time zone set to CST (or, until <a href="http://en.wikipedia.org/wiki/Daylight_saving_time#Terminology" rel="noreferrer">daylight saving</a> switches back, CDT is it?), I'd like our ASP.NET web app to display DateTimes relative to that time zone as well as formatted to display a "CST" on the end. I realize I could easily hard-code this, but in the interest of robustness, I'd really prefer a solution based on the server running the code's OS environment settings.</p> <p>Right now, I have everything but the time zone abbreviation using the following code:</p> <pre><code>myDateTime.ToString("MM/dd/yyyy hh:mm:ss tt") </code></pre> <p>Which displays:</p> <p>10/07/2008 03:40:31 PM</p> <p>All I want (and it's not much, promise!) is for it to say:</p> <p>10/07/2008 03:40:31 PM CDT</p> <p>I can use System.TimeZone.CurrentTimeZone and use it to correctly display "Central Daylight Time" but... that's a bit too long for brevity's sake. Am I then stuck writing a string manipulation routine to strip out white-space and any non-uppercase letters? While that might work, that seems incredibly hack to me...</p> <p><a href="http://www.google.com/search?hl=en&amp;safe=off&amp;q=C%23+time+zone+abbreviation&amp;btnG=Search" rel="noreferrer">Googling</a> and looking around on here did not produce anything applicable to my specific question.</p>
[ { "answer_id": 180559, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 0, "selected": false, "text": "<p>It depends on the level of robustness that you need.</p>\n\n<p>You'll probably need some kind of hack either way. An easy way would be to split the string by spaces and then concatenate the first letter of each word. i.e.</p>\n\n<pre><code>string[] words = tzname.Split(\" \".ToCharArray());\nstring tzabbr = \"\";\nforeach (string word in words)\n tzabbr += word[0];\n</code></pre>\n\n<p>That won't work for every time zone on the planet, but it will work for most of them. If you need it more robust then you'll probably need to create a map that maps time zone names to their abbreviations.</p>\n" }, { "answer_id": 181131, "author": "Pavel Chuchuva", "author_id": 14131, "author_profile": "https://Stackoverflow.com/users/14131", "pm_score": 1, "selected": false, "text": "<p>I would create a lookup table that converts time zone name to its abbreviation. If the match is not found you could return full zone name.</p>\n\n<p>See <a href=\"http://www.timeanddate.com/library/abbreviations/timezones/\" rel=\"nofollow noreferrer\">time zone abbreviations</a>.</p>\n" }, { "answer_id": 181253, "author": "Dave Moore", "author_id": 6996, "author_profile": "https://Stackoverflow.com/users/6996", "pm_score": 3, "selected": false, "text": "<p>There is a freely available library, <a href=\"http://www.babiej.demon.nl/Tz4Net/main.htm\" rel=\"noreferrer\">TZ4NET</a>, which has these abbreviations available. Prior to .NET 3.5, this was one of the only alternatives for converting between timezones as well.</p>\n\n<p>If you don't want a seperate library, you could certainly generate a map of reasonable abbreviations using the TimeZoneInfo classes, and then just supply those to your user.</p>\n" }, { "answer_id": 794958, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 4, "selected": false, "text": "<p>Here's my quick hack method I just made to work around this.</p>\n\n<pre><code>public static String TimeZoneName(DateTime dt)\n{\n String sName = TimeZone.CurrentTimeZone.IsDaylightSavingTime(dt) \n ? TimeZone.CurrentTimeZone.DaylightName \n : TimeZone.CurrentTimeZone.StandardName;\n\n String sNewName = \"\";\n String[] sSplit = sName.Split(new char[]{' '});\n foreach (String s in sSplit)\n if (s.Length &gt;= 1)\n sNewName += s.Substring(0, 1);\n\n return sNewName;\n}\n</code></pre>\n" }, { "answer_id": 7600922, "author": "Bob Houghton", "author_id": 971645, "author_profile": "https://Stackoverflow.com/users/971645", "pm_score": 1, "selected": false, "text": "<p>If pulling the abbreviation from the DaylightName/StandardName, you're going to be better off building the string using a StringBuilder, for strings are immutable.</p>\n\n<pre><code> public static string ToCurrentTimeZoneString(this DateTime date)\n {\n string name = TimeZone.CurrentTimeZone.IsDaylightSavingTime(date) ?\n TimeZone.CurrentTimeZone.DaylightName :\n TimeZone.CurrentTimeZone.StandardName;\n return name;\n }\n\n public static string ToCurrentTimeZoneShortString(this DateTime date)\n {\n StringBuilder result = new StringBuilder();\n\n foreach (string value in date.ToCurrentTimeZoneString().Split(' '))\n {\n if (value.IsNotNullOrEmptyWithTrim())\n {\n result.Append(char.ToUpper(value[0]));\n }\n }\n\n return result.ToString();\n }\n</code></pre>\n\n<p>Of course, an array containing KeyValuePair's is probably best for a multinational company. If you want to shave a few minutes off of a tight deadline, and you are at a US company, this works. </p>\n" }, { "answer_id": 12860785, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": -1, "selected": false, "text": "<p>Ok, It's been 4 years (and almost a week), it's time we brought LINQ into the discussion...</p>\n\n<p>Putting together Criag's and Bob's ideas...</p>\n\n<pre><code>public static String TimeZoneName2(DateTime dt)\n{\n var return ToCurrentTimeZoneShortString(dt)\n .Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);\n return sSplit.Aggregate(\"\", (st,w)=&gt; st +=w[0]);\n}\n</code></pre>\n\n<p>Unless you can trust TimeZone to never return a string with two consecutive spaces:</p>\n\n<pre><code>public static String TimeZoneName3(DateTime dt)\n{\n return ToCurrentTimeZoneShortString(dt).Split(' ')\n .Aggregate(\"\", (st,w)=&gt; st +=w[0]);\n}\n</code></pre>\n" }, { "answer_id": 26580626, "author": "ComeIn", "author_id": 909122, "author_profile": "https://Stackoverflow.com/users/909122", "pm_score": -1, "selected": false, "text": "<p>If you are using &lt;= .Net 3.0 then download TZ4Net and use OlsonTimeZone.CurrentTimeZone.StandardAbbreviation for > .Net 3.0 use NodaTime or other. The timezones names do not conform to any convention where you can rely on simple string manipulation to construct the abbreviation from an acronym. Wrong 5% of the time is still wrong. </p>\n" }, { "answer_id": 27451460, "author": "kaptan", "author_id": 266659, "author_profile": "https://Stackoverflow.com/users/266659", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"http://nodatime.org/\" rel=\"nofollow\">nodatime</a>.</p>\n\n<p>The following function takes a <code>DateTime</code> in UTC time and formats it with abbreviated local system timezone. Use <code>x</code> in format string for abbreviated timezone. Look for custom formatting <a href=\"http://nodatime.org/unstable/userguide/zoneddatetime-patterns.html\" rel=\"nofollow\">here</a>.</p>\n\n<pre><code> public static string ConvertToFormattedLocalTimeWithTimezone(DateTime dateTimeUtc)\n {\n var tz = DateTimeZoneProviders.Tzdb.GetSystemDefault(); // Get the system's time zone\n var zdt = new ZonedDateTime(Instant.FromDateTimeUtc(dateTimeUtc), tz);\n return zdt.ToString(\"MM'/'dd'/'yyyy' 'hh':'mm':'ss' 'tt' 'x\", CultureInfo.InvariantCulture);\n }\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7290/" ]
I am aware of the [System.TimeZone](http://msdn.microsoft.com/en-us/library/system.timezone(VS.80).aspx) class as well as the many uses of the [DateTime.ToString()](http://msdn.microsoft.com/en-us/library/system.datetime.tostring(VS.80).aspx) method. What I haven't been able to find is a way to convert a DateTime to a string that, in addition to the time and date info, contains the three-letter Time Zone abbreviation (in fact, much the same way StackOverflow's tooltips for relative time display works). To make an example easy for everyone to follow as well as consume, let's continue with the StackOverflow example. If you look at the tooltip that displays on relative times, it displays with the full date, the time including seconds in twelve-hour format, an AM/PM designation, and then the three-letter Time Zone abbreviation (in their case, Coordinated Universal Time). I realize I could easily get GMT or UTC by using the built-in methods, but what I really want is the time as it is locally — in this case, on a web server. If our web server is running Windows Server 2k3 and has it's time zone set to CST (or, until [daylight saving](http://en.wikipedia.org/wiki/Daylight_saving_time#Terminology) switches back, CDT is it?), I'd like our ASP.NET web app to display DateTimes relative to that time zone as well as formatted to display a "CST" on the end. I realize I could easily hard-code this, but in the interest of robustness, I'd really prefer a solution based on the server running the code's OS environment settings. Right now, I have everything but the time zone abbreviation using the following code: ``` myDateTime.ToString("MM/dd/yyyy hh:mm:ss tt") ``` Which displays: 10/07/2008 03:40:31 PM All I want (and it's not much, promise!) is for it to say: 10/07/2008 03:40:31 PM CDT I can use System.TimeZone.CurrentTimeZone and use it to correctly display "Central Daylight Time" but... that's a bit too long for brevity's sake. Am I then stuck writing a string manipulation routine to strip out white-space and any non-uppercase letters? While that might work, that seems incredibly hack to me... [Googling](http://www.google.com/search?hl=en&safe=off&q=C%23+time+zone+abbreviation&btnG=Search) and looking around on here did not produce anything applicable to my specific question.
Here's my quick hack method I just made to work around this. ``` public static String TimeZoneName(DateTime dt) { String sName = TimeZone.CurrentTimeZone.IsDaylightSavingTime(dt) ? TimeZone.CurrentTimeZone.DaylightName : TimeZone.CurrentTimeZone.StandardName; String sNewName = ""; String[] sSplit = sName.Split(new char[]{' '}); foreach (String s in sSplit) if (s.Length >= 1) sNewName += s.Substring(0, 1); return sNewName; } ```
180,371
<p>When extending classes, I find it very descriptive to use the <code>base</code> (<code>MyBase</code> in VB) keyword when accessing methods in the base-class. And the <code>this</code> (<code>Me</code> in VB) keyword when accessing functions in the class extending the base-class. That goes for a "flat" structure with no inheritance as well.</p> <p>I find it easier to read this:</p> <pre><code>public class World { public String baseName = "World"; } public class Hello : World { public String thisName = "Hello"; public String GetNames() { return this.thisName + " " + base.baseName; } } </code></pre> <p>Than this:</p> <pre><code>... public String GetNames() { return thisName + " " + baseName; } ... </code></pre> <p>Now, my question is: is it possible to enforce the use of <code>this</code> and <code>base</code> at compile-time in Visual Studio/C#, so that the compiler throws an error or a warning if you do not use these keywords in your code?</p>
[ { "answer_id": 180379, "author": "JohnC", "author_id": 25088, "author_profile": "https://Stackoverflow.com/users/25088", "pm_score": 3, "selected": true, "text": "<p>Have a look at StyleCop.</p>\n\n<p><a href=\"http://code.msdn.microsoft.com/sourceanalysis\" rel=\"nofollow noreferrer\">http://code.msdn.microsoft.com/sourceanalysis</a></p>\n\n<p>There are some rules in there that should do what you want.\nYou can configure it to show any style violations as warnings or errors.</p>\n" }, { "answer_id": 180688, "author": "Odd", "author_id": 11908, "author_profile": "https://Stackoverflow.com/users/11908", "pm_score": 0, "selected": false, "text": "<p>You may also want to check out <a href=\"http://www.ssw.com.au/ssw/CodeAuditor/\" rel=\"nofollow noreferrer\">SSW's code auditor</a></p>\n\n<p>Unfortunately there is no way that I'm aware of to enforce this in the compiler.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20946/" ]
When extending classes, I find it very descriptive to use the `base` (`MyBase` in VB) keyword when accessing methods in the base-class. And the `this` (`Me` in VB) keyword when accessing functions in the class extending the base-class. That goes for a "flat" structure with no inheritance as well. I find it easier to read this: ``` public class World { public String baseName = "World"; } public class Hello : World { public String thisName = "Hello"; public String GetNames() { return this.thisName + " " + base.baseName; } } ``` Than this: ``` ... public String GetNames() { return thisName + " " + baseName; } ... ``` Now, my question is: is it possible to enforce the use of `this` and `base` at compile-time in Visual Studio/C#, so that the compiler throws an error or a warning if you do not use these keywords in your code?
Have a look at StyleCop. <http://code.msdn.microsoft.com/sourceanalysis> There are some rules in there that should do what you want. You can configure it to show any style violations as warnings or errors.
180,401
<p>I've recently decided that I just have to finally learn C/C++, and there is one thing I do not really understand about pointers or more precisely, their definition.</p> <p>How about these examples:</p> <ol> <li><code>int* test;</code></li> <li><code>int *test;</code></li> <li><code>int * test;</code></li> <li><code>int* test,test2;</code></li> <li><code>int *test,test2;</code></li> <li><code>int * test,test2;</code></li> </ol> <p>Now, to my understanding, the first three cases are all doing the same: Test is not an int, but a pointer to one.</p> <p>The second set of examples is a bit more tricky. In case 4, both test and test2 will be pointers to an int, whereas in case 5, only test is a pointer, whereas test2 is a "real" int. What about case 6? Same as case 5?</p>
[ { "answer_id": 180409, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 8, "selected": true, "text": "<p>4, 5, and 6 are the same thing, only <em>test</em> is a pointer. If you want two pointers, you should use:</p>\n\n<pre><code>int *test, *test2;\n</code></pre>\n\n<p>Or, even better (to make everything clear):</p>\n\n<pre><code>int* test;\nint* test2;\n</code></pre>\n" }, { "answer_id": 180417, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 3, "selected": false, "text": "<p>In 4, 5 and 6, <code>test</code> is always a pointer and <code>test2</code> is not a pointer. White space is (almost) never significant in C++.</p>\n" }, { "answer_id": 180420, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 6, "selected": false, "text": "<p>White space around asterisks have no significance. All three mean the same thing:</p>\n\n<pre><code>int* test;\nint *test;\nint * test;\n</code></pre>\n\n<p>The \"<code>int *var1, var2</code>\" is an evil syntax that is just meant to confuse people and should be avoided. It expands to:</p>\n\n<pre><code>int *var1;\nint var2;\n</code></pre>\n" }, { "answer_id": 180431, "author": "Ron Warholic", "author_id": 22780, "author_profile": "https://Stackoverflow.com/users/22780", "pm_score": 1, "selected": false, "text": "<p>The pointer is a modifier to the type. It's best to read them right to left in order to better understand how the asterisk modifies the type. 'int *' can be read as \"pointer to int'. In multiple declarations you must specify that each variable is a pointer or it will be created as a standard variable.</p>\n\n<p>1,2 and 3) Test is of type (int *). Whitespace doesn't matter.</p>\n\n<p>4,5 and 6) Test is of type (int *). Test2 is of type int. Again whitespace is inconsequential.</p>\n" }, { "answer_id": 180457, "author": "Scott Langham", "author_id": 11898, "author_profile": "https://Stackoverflow.com/users/11898", "pm_score": 5, "selected": false, "text": "<p>Many coding guidelines recommend that you only declare <strong>one variable per line</strong>. This avoids any confusion of the sort you had before asking this question. Most C++ programmers I've worked with seem to stick to this.</p>\n\n<hr>\n\n<p>A bit of an aside I know, but something I found useful is to read declarations backwards.</p>\n\n<pre><code>int* test; // test is a pointer to an int\n</code></pre>\n\n<p>This starts to work very well, especially when you start declaring const pointers and it gets tricky to know whether it's the pointer that's const, or whether its the thing the pointer is pointing at that is const.</p>\n\n<pre><code>int* const test; // test is a const pointer to an int\n\nint const * test; // test is a pointer to a const int ... but many people write this as \nconst int * test; // test is a pointer to an int that's const\n</code></pre>\n" }, { "answer_id": 180509, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": false, "text": "<p>Use the <a href=\"http://c-faq.com/decl/spiral.anderson.html\" rel=\"noreferrer\">\"Clockwise Spiral Rule\"</a> to help parse C/C++ declarations; </p>\n\n<blockquote>\n <p>There are three simple steps to follow:</p>\n \n <ol>\n <li><p>Starting with the unknown element, move in a spiral/clockwise\n direction; when encountering the following elements replace them with\n the corresponding english statements: </p>\n \n <p><code>[X]</code> or <code>[]</code>: Array X size of... or Array undefined size of... </p>\n \n <p><code>(type1, type2)</code>: function passing type1 and type2 returning...</p>\n \n <p><code>*</code>: pointer(s) to...</p></li>\n <li>Keep doing this in a spiral/clockwise direction until all tokens have been covered. </li>\n <li>Always resolve anything in parenthesis first!</li>\n </ol>\n</blockquote>\n\n<p>Also, declarations should be in separate statements when possible (which is true the vast majority of times).</p>\n" }, { "answer_id": 180602, "author": "mstrobl", "author_id": 25965, "author_profile": "https://Stackoverflow.com/users/25965", "pm_score": -1, "selected": false, "text": "<p>A good rule of thumb, a lot of people seem to grasp these concepts by: In C++ a lot of semantic meaning is derived by the left-binding of keywords or identifiers.</p>\n\n<p>Take for example:</p>\n\n<pre><code>int const bla;\n</code></pre>\n\n<p>The const applies to the \"int\" word. The same is with pointers' asterisks, they apply to the keyword left of them. And the actual variable name? Yup, that's declared by what's left of it.</p>\n" }, { "answer_id": 8685467, "author": "huskerchad", "author_id": 1109067, "author_profile": "https://Stackoverflow.com/users/1109067", "pm_score": 4, "selected": false, "text": "<p>As others mentioned, 4, 5, and 6 are the same. Often, people use these examples to make the argument that the <code>*</code> belongs with the variable instead of the type. While it's an issue of style, there is some debate as to whether you should think of and write it this way:</p>\n\n<pre><code>int* x; // \"x is a pointer to int\"\n</code></pre>\n\n<p>or this way:</p>\n\n<pre><code>int *x; // \"*x is an int\"\n</code></pre>\n\n<p>FWIW I'm in the first camp, but the reason others make the argument for the second form is that it (mostly) solves this particular problem:</p>\n\n<pre><code>int* x,y; // \"x is a pointer to int, y is an int\"\n</code></pre>\n\n<p>which is potentially misleading; instead you would write either</p>\n\n<pre><code>int *x,y; // it's a little clearer what is going on here\n</code></pre>\n\n<p>or if you really want two pointers,</p>\n\n<pre><code>int *x, *y; // two pointers\n</code></pre>\n\n<p>Personally, I say keep it to one variable per line, then it doesn't matter which style you prefer.</p>\n" }, { "answer_id": 12439110, "author": "fredoverflow", "author_id": 252000, "author_profile": "https://Stackoverflow.com/users/252000", "pm_score": 4, "selected": false, "text": "<pre><code>#include &lt;type_traits&gt;\n\nstd::add_pointer&lt;int&gt;::type test, test2;\n</code></pre>\n" }, { "answer_id": 34559760, "author": "Michel Billaud", "author_id": 4744142, "author_profile": "https://Stackoverflow.com/users/4744142", "pm_score": 2, "selected": false, "text": "<p>The rationale in C is that you declare the variables the way you use them. For example</p>\n\n<pre><code>char *a[100];\n</code></pre>\n\n<p>says that <code>*a[42]</code> will be a <code>char</code>. And <code>a[42]</code> a char pointer. And thus <code>a</code> is an array of char pointers.</p>\n\n<p>This because the original compiler writers wanted to use the same parser for expressions and declarations. (Not a very sensible reason for a langage design choice)</p>\n" }, { "answer_id": 46464876, "author": "TheDrev", "author_id": 2323803, "author_profile": "https://Stackoverflow.com/users/2323803", "pm_score": 2, "selected": false, "text": "<p>I would say that the initial convention was to put the star on the pointer name side (right side of the declaration</p>\n\n<ul>\n<li><p>in <em>the c programming language</em> by Dennis M. Ritchie the stars are on the right side of the declaration. </p></li>\n<li><p>by looking at the linux source code at <a href=\"https://github.com/torvalds/linux/blob/master/init/main.c\" rel=\"nofollow noreferrer\">https://github.com/torvalds/linux/blob/master/init/main.c</a>\nwe can see that the star is also on the right side. </p></li>\n</ul>\n\n<p>You can follow the same rules, but it's not a big deal if you put stars on the type side.\nRemember that <strong>consistency</strong> is important, so always but the star on the same side regardless of which side you have choose. </p>\n" }, { "answer_id": 55958119, "author": "deLock", "author_id": 8588773, "author_profile": "https://Stackoverflow.com/users/8588773", "pm_score": 2, "selected": false, "text": "<p>In my opinion, the answer is BOTH, depending on the situation. \nGenerally, IMO, it is better to put the asterisk next to the pointer name, rather than the type. Compare e.g.:</p>\n\n<pre><code>int *pointer1, *pointer2; // Fully consistent, two pointers\nint* pointer1, pointer2; // Inconsistent -- because only the first one is a pointer, the second one is an int variable\n// The second case is unexpected, and thus prone to errors\n</code></pre>\n\n<p>Why is the second case inconsistent? Because e.g. <code>int x,y;</code> declares two variables of the same type but the type is mentioned only once in the declaration. This creates a precedent and expected behavior. And <code>int* pointer1, pointer2;</code> is inconsistent with that because it declares <code>pointer1</code> as a pointer, but <code>pointer2</code> is an integer variable. Clearly prone to errors and, thus, should be avoided (by putting the asterisk next to the pointer name, rather than the type).</p>\n\n<p><strong>However</strong>, there are some <strong>exceptions</strong> where you might not be able to put the asterisk next to an object name (and where it matters where you put it) without getting undesired outcome — for example: </p>\n\n<p><code>MyClass *volatile MyObjName</code></p>\n\n<p><code>void test (const char *const p) // const value pointed to by a const pointer</code></p>\n\n<p>Finally, in some cases, it might be arguably <em>clearer</em> to put the asterisk next to the <em>type</em> name, e.g.:</p>\n\n<p><code>void* ClassName::getItemPtr () {return &amp;item;} // Clear at first sight</code></p>\n" }, { "answer_id": 64339233, "author": "John Bode", "author_id": 134554, "author_profile": "https://Stackoverflow.com/users/134554", "pm_score": 4, "selected": false, "text": "<p>There are three pieces to this puzzle.</p>\n<p>The first piece is that whitespace in C and C++ is normally not significant beyond separating adjacent tokens that are otherwise indistinguishable.</p>\n<p>During the preprocessing stage, the source text is broken up into a sequence of <em>tokens</em> - identifiers, punctuators, numeric literals, string literals, etc. That sequence of tokens is later analyzed for syntax and meaning. The tokenizer is &quot;greedy&quot; and will build the longest valid token that's possible. If you write something like</p>\n<pre><code>inttest;\n</code></pre>\n<p>the tokenizer only sees two tokens - the identifier <code>inttest</code> followed by the punctuator <code>;</code>. It doesn't recognize <code>int</code> as a separate keyword at this stage (that happens later in the process). So, for the line to be read as a declaration of an integer named <code>test</code>, we have to use whitespace to separate the identifier tokens:</p>\n<pre><code>int test;\n</code></pre>\n<p>The <code>*</code> character is not part of any identifier; it's a separate token (punctuator) on its own. So if you write</p>\n<pre><code>int*test;\n</code></pre>\n<p>the compiler sees 4 separate tokens - <code>int</code>, <code>*</code>, <code>test</code>, and <code>;</code>. Thus, whitespace is not significant in pointer declarations, and all of</p>\n<pre><code>int *test;\nint* test;\nint*test;\nint * test;\n</code></pre>\n<p>are interpreted the same way.</p>\n<hr>\n<p>The second piece to the puzzle is how declarations actually work in C and C++<sup>1</sup>. Declarations are broken up into two main pieces - a sequence of <em>declaration specifiers</em> (storage class specifiers, type specifiers, type qualifiers, etc.) followed by a comma-separated list of (possibly initialized) <em>declarators</em>. In the declaration</p>\n<pre><code>unsigned long int a[10]={0}, *p=NULL, f(void);\n</code></pre>\n<p>the declaration specifiers are <code>unsigned long int</code> and the declarators are <code>a[10]={0}</code>, <code>*p=NULL</code>, and <code>f(void)</code>. The declarator introduces the name of the thing being declared (<code>a</code>, <code>p</code>, and <code>f</code>) along with information about that thing's array-ness, pointer-ness, and function-ness. A declarator may also have an associated initializer.</p>\n<p>The type of <code>a</code> is &quot;10-element array of <code>unsigned long int</code>&quot;. That type is fully specified by the <em>combination</em> of the declaration specifiers and the declarator, and the initial value is specified with the initializer <code>={0}</code>. Similarly, the type of <code>p</code> is &quot;pointer to <code>unsigned long int</code>&quot;, and again that type is specified by the combination of the declaration specifiers and the declarator, and is initialized to <code>NULL</code>. And the type of <code>f</code> is &quot;function returning <code>unsigned long int</code>&quot; by the same reasoning.</p>\n<p>This is key - there is no &quot;pointer-to&quot; <em>type specifier</em>, just like there is no &quot;array-of&quot; type specifier, just like there is no &quot;function-returning&quot; type specifier. We can't declare an array as</p>\n<pre><code>int[10] a;\n</code></pre>\n<p>because the operand of the <code>[]</code> operator is <code>a</code>, not <code>int</code>. Similarly, in the declaration</p>\n<pre><code>int* p;\n</code></pre>\n<p>the operand of <code>*</code> is <code>p</code>, not <code>int</code>. But because the indirection operator is unary and whitespace is not significant, the compiler won't complain if we write it this way. However, it is <em>always</em> interpreted as <code>int (*p);</code>.</p>\n<p>Therefore, if you write</p>\n<pre><code>int* p, q;\n</code></pre>\n<p>the operand of <code>*</code> is <code>p</code>, so it will be interpreted as</p>\n<pre><code>int (*p), q;\n</code></pre>\n<p>Thus, all of</p>\n<pre><code>int *test1, test2;\nint* test1, test2;\nint * test1, test2;\n</code></pre>\n<p>do the same thing - in all three cases, <code>test1</code> is the operand of <code>*</code> and thus has type &quot;pointer to <code>int</code>&quot;, while <code>test2</code> has type <code>int</code>.</p>\n<p>Declarators can get arbitrarily complex. You can have arrays of pointers:</p>\n<pre><code>T *a[N];\n</code></pre>\n<p>you can have pointers to arrays:</p>\n<pre><code>T (*a)[N];\n</code></pre>\n<p>you can have functions returning pointers:</p>\n<pre><code>T *f(void);\n</code></pre>\n<p>you can have pointers to functions:</p>\n<pre><code>T (*f)(void);\n</code></pre>\n<p>you can have arrays of pointers to functions:</p>\n<pre><code>T (*a[N])(void);\n</code></pre>\n<p>you can have functions returning pointers to arrays:</p>\n<pre><code>T (*f(void))[N];\n</code></pre>\n<p>you can have functions returning pointers to arrays of pointers to functions returning pointers to <code>T</code>:</p>\n<pre><code>T *(*(*f(void))[N])(void); // yes, it's eye-stabby. Welcome to C and C++.\n</code></pre>\n<p>and then you have <code>signal</code>:</p>\n<pre><code>void (*signal(int, void (*)(int)))(int);\n</code></pre>\n<p>which reads as</p>\n<pre><code> signal -- signal\n signal( ) -- is a function taking\n signal( ) -- unnamed parameter\n signal(int ) -- is an int\n signal(int, ) -- unnamed parameter\n signal(int, (*) ) -- is a pointer to\n signal(int, (*)( )) -- a function taking\n signal(int, (*)( )) -- unnamed parameter\n signal(int, (*)(int)) -- is an int\n signal(int, void (*)(int)) -- returning void\n (*signal(int, void (*)(int))) -- returning a pointer to\n (*signal(int, void (*)(int)))( ) -- a function taking\n (*signal(int, void (*)(int)))( ) -- unnamed parameter\n (*signal(int, void (*)(int)))(int) -- is an int\nvoid (*signal(int, void (*)(int)))(int); -- returning void\n \n</code></pre>\n<p>and this just barely scratches the surface of what's possible. But notice that array-ness, pointer-ness, and function-ness are always part of the declarator, not the type specifier.</p>\n<p>One thing to watch out for - <code>const</code> can modify both the pointer type and the pointed-to type:</p>\n<pre><code>const int *p; \nint const *p;\n</code></pre>\n<p>Both of the above declare <code>p</code> as a pointer to a <code>const int</code> object. You can write a new value to <code>p</code> setting it to point to a different object:</p>\n<pre><code>const int x = 1;\nconst int y = 2;\n\nconst int *p = &amp;x;\np = &amp;y;\n</code></pre>\n<p>but you cannot write to the pointed-to object:</p>\n<pre><code>*p = 3; // constraint violation, the pointed-to object is const\n</code></pre>\n<p>However,</p>\n<pre><code>int * const p;\n</code></pre>\n<p>declares <code>p</code> as a <code>const</code> pointer to a non-const <code>int</code>; you can write to the thing <code>p</code> points to</p>\n<pre><code>int x = 1;\nint y = 2;\nint * const p = &amp;x;\n\n*p = 3;\n</code></pre>\n<p>but you can't set <code>p</code> to point to a different object:</p>\n<pre><code>p = &amp;y; // constraint violation, p is const\n</code></pre>\n<hr>\n<p>Which brings us to the third piece of the puzzle - why declarations are structured this way.</p>\n<p>The intent is that the structure of a declaration should closely mirror the structure of an expression in the code (&quot;declaration mimics use&quot;). For example, let's suppose we have an array of pointers to <code>int</code> named <code>ap</code>, and we want to access the <code>int</code> value pointed to by the <code>i</code>'th element. We would access that value as follows:</p>\n<pre><code>printf( &quot;%d&quot;, *ap[i] );\n</code></pre>\n<p>The <em>expression</em> <code>*ap[i]</code> has type <code>int</code>; thus, the declaration of <code>ap</code> is written as</p>\n<pre><code>int *ap[N]; // ap is an array of pointer to int, fully specified by the combination\n // of the type specifier and declarator\n</code></pre>\n<p>The declarator <code>*ap[N]</code> has the same structure as the expression <code>*ap[i]</code>. The operators <code>*</code> and <code>[]</code> behave the same way in a declaration that they do in an expression - <code>[]</code> has higher precedence than unary <code>*</code>, so the operand of <code>*</code> is <code>ap[N]</code> (it's parsed as <code>*(ap[N])</code>).</p>\n<p>As another example, suppose we have a pointer to an array of <code>int</code> named <code>pa</code> and we want to access the value of the <code>i</code>'th element. We'd write that as</p>\n<pre><code>printf( &quot;%d&quot;, (*pa)[i] );\n</code></pre>\n<p>The type of the expression <code>(*pa)[i]</code> is <code>int</code>, so the declaration is written as</p>\n<pre><code>int (*pa)[N];\n</code></pre>\n<p>Again, the same rules of precedence and associativity apply. In this case, we don't want to dereference the <code>i</code>'th element of <code>pa</code>, we want to access the <code>i</code>'th element of what <code>pa</code> <em>points to</em>, so we have to explicitly group the <code>*</code> operator with <code>pa</code>.</p>\n<p>The <code>*</code>, <code>[]</code> and <code>()</code> operators are all part of the <em>expression</em> in the code, so they are all part of the <em>declarator</em> in the declaration. The declarator tells you how to use the object in an expression. If you have a declaration like <code>int *p;</code>, that tells you that the expression <code>*p</code> in your code will yield an <code>int</code> value. By extension, it tells you that the expression <code>p</code> yields a value of type &quot;pointer to <code>int</code>&quot;, or <code>int *</code>.</p>\n<hr>\n<p>So, what about things like cast and <code>sizeof</code> expressions, where we use things like <code>(int *)</code> or <code>sizeof (int [10])</code> or things like that? How do I read something like</p>\n<pre><code>void foo( int *, int (*)[10] );\n</code></pre>\n<p>There's no declarator, aren't the <code>*</code> and <code>[]</code> operators modifying the type directly?</p>\n<p>Well, no - there is still a declarator, just with an empty identifier (known as an <em>abstract declarator</em>). If we represent an empty identifier with the symbol λ, then we can read those things as <code>(int *λ)</code>, <code>sizeof (int λ[10])</code>, and</p>\n<pre><code>void foo( int *&lambda;, int (*&lambda;)[10] );</code></pre>\n<p>and they behave exactly like any other declaration. <code>int *[10]</code> represents an array of 10 pointers, while <code>int (*)[10]</code> represents a pointer to an array.</p>\n<hr>\n<p>And now the opinionated portion of this answer. I am not fond of the C++ convention of declaring simple pointers as</p>\n<pre><code>T* p;\n</code></pre>\n<p>and consider it <em>bad practice</em> for the following reasons:</p>\n<ol>\n<li>It's not consistent with the syntax;</li>\n<li>It introduces confusion (as evidenced by this question, all the duplicates to this question, questions about the meaning of <code>T* p, q;</code>, all the duplicates to <em>those</em> questions, etc.);</li>\n<li>It's not internally consistent - declaring an array of pointers as <code>T* a[N]</code> is asymmetrical with use (unless you're in the habit of writing <code>* a[i]</code>);</li>\n<li>It cannot be applied to pointer-to-array or pointer-to-function types (unless you create a typedef just so you can apply the <code>T* p</code> convention cleanly, which...<em>no</em>);</li>\n<li>The reason for doing so - &quot;it emphasizes the pointer-ness of the object&quot; - is spurious. It cannot be applied to array or function types, and I would think those qualities are just as important to emphasize.</li>\n</ol>\n<p>In the end, it just indicates confused thinking about how the two languages' type systems work.</p>\n<p>There are good reasons to declare items separately; working around a bad practice (<code>T* p, q;</code>) isn't one of them. If you write your declarators <em>correctly</em> (<code>T *p, q;</code>) you are less likely to cause confusion.</p>\n<p>I consider it akin to deliberately writing all your simple <code>for</code> loops as</p>\n<pre><code>i = 0;\nfor( ; i &lt; N; ) \n{ \n ... \n i++; \n}\n</code></pre>\n<p>Syntactically valid, but confusing, and the intent is likely to be misinterpreted. However, the <code>T* p;</code> convention is entrenched in the C++ community, and I use it in my own C++ code because consistency across the code base is a good thing, but it makes me itch every time I do it.</p>\n<hr>\n<sup>\n<ol>\n<li>I will be using C terminology - the C++ terminology is a little different, but the concepts are largely the same.\n</ol>\n</sup>\n" }, { "answer_id": 71562364, "author": "TallChuck", "author_id": 6284025, "author_profile": "https://Stackoverflow.com/users/6284025", "pm_score": 0, "selected": false, "text": "<p>I have always preferred to declare pointers like this:</p>\n<pre><code>int* i;\n</code></pre>\n<p>I read this to say &quot;<code>i</code> is of type int-pointer&quot;. You can get away with this interpretation if you only declare one variable per declaration.</p>\n<p>It is an uncomfortable truth, however, that this reading is <em>wrong</em>. <em>The C Programming Language, 2nd Ed.</em> (p. 94) explains the opposite paradigm, which is the one used in the C standards:</p>\n<blockquote>\n<p>The declaration of the pointer <code>ip</code>,</p>\n<pre><code>int *ip;\n</code></pre>\n<p>is intended as a mnemonic; it says that the expression <code>*ip</code> is an\n<code>int</code>. The syntax of the declaration for a variable mimics the syntax\nof expressions in which the variable might appear. This reasoning\napplies to function declarations as well. For example,</p>\n<pre><code>double *dp, atof(char *);\n</code></pre>\n<p>says that in an expression <code>*dp</code> and <code>atof(s)</code> have values of type\n<code>double</code>, and that the argument of <code>atof</code> is a pointer to <code>char</code>.</p>\n</blockquote>\n<p>So, by the reasoning of the C language, when you declare</p>\n<pre><code>int* test, test2;\n</code></pre>\n<p>you are not declaring two variables of type <code>int*</code>, you are introducing two expressions that evaluate to an <code>int</code> type, with no attachment to the allocation of an <code>int</code> in memory.</p>\n<p>A compiler is perfectly happy to accept the following:</p>\n<pre><code>int *ip, i;\ni = *ip;\n</code></pre>\n<p>because in the C paradigm, the compiler is only expected to keep track of the <em>type</em> of <code>*ip</code> and <code>i</code>. The programmer is expected to keep track of the <em>meaning</em> of <code>*ip</code> and <code>i</code>. In this case, <code>ip</code> is uninitialized, so it is the programmer's responsibility to point it at something meaningful before dereferencing it.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
I've recently decided that I just have to finally learn C/C++, and there is one thing I do not really understand about pointers or more precisely, their definition. How about these examples: 1. `int* test;` 2. `int *test;` 3. `int * test;` 4. `int* test,test2;` 5. `int *test,test2;` 6. `int * test,test2;` Now, to my understanding, the first three cases are all doing the same: Test is not an int, but a pointer to one. The second set of examples is a bit more tricky. In case 4, both test and test2 will be pointers to an int, whereas in case 5, only test is a pointer, whereas test2 is a "real" int. What about case 6? Same as case 5?
4, 5, and 6 are the same thing, only *test* is a pointer. If you want two pointers, you should use: ``` int *test, *test2; ``` Or, even better (to make everything clear): ``` int* test; int* test2; ```
180,405
<p>I've got a User table with a bitmask that contains the user's roles. The linq query below returns all the users whose roles include 1, 4 or 16. </p> <pre><code>var users = from u in dc.Users where ((u.UserRolesBitmask &amp; 1) == 1) || ((u.UserRolesBitmask &amp; 4) == 4) || ((u.UserRolesBitmask &amp; 16) == 16) select u; </code></pre> <p>I'd like to rewrite this into the method below to returns all the users from the given roles so I can reuse it:</p> <pre><code>private List&lt;User&gt; GetUsersFromRoles(uint[] UserRoles) {} </code></pre> <p>Any pointers on how to dynamically build my query? Thanks</p>
[ { "answer_id": 180447, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 2, "selected": false, "text": "<p>Assuming your UserRoles values are themselves bitmasks, would something like this work?</p>\n\n<pre><code>private List&lt;User&gt; GetUsersFromRoles(uint[] UserRoles) {\n uint roleMask = 0;\n for (var i = 0; i &lt; UserRoles.Length;i++) roleMask= roleMask| UserRoles[i];\n // roleMasknow contains the OR'ed bitfields of the roles we're looking for\n\n return (from u in dc.Users where (u.UserRolesBitmask &amp; roleMask) &gt; 0) select u);\n}\n</code></pre>\n\n<p>There's probably a nice LINQ syntax that'll work in place of the loops, but the concept should be the same.</p>\n" }, { "answer_id": 180465, "author": "Carlton Jenke", "author_id": 1215, "author_profile": "https://Stackoverflow.com/users/1215", "pm_score": 1, "selected": false, "text": "<p>How's this? It is not dynamic linq, but accomplishes the goal.</p>\n\n<pre><code>private List&lt;User&gt; GetUsersFromRoles(uint[] userRoles) \n{\n List&lt;User&gt; users = new List&lt;User&gt;();\n\n foreach(uint userRole in UserRoles)\n {\n List&lt;User&gt; usersInRole = GetUsersFromRole(userRole);\n foreach(User user in usersInRole )\n {\n users.Add(user);\n }\n }\n return users;\n} \n\nprivate List&lt;User&gt; GetUsersFromRole(uint userRole) \n{\n var users = from u in dc.Users\n where ((u.UserRolesBitmask &amp; UserRole) == UserRole)\n select u;\n\n return users; \n}\n</code></pre>\n" }, { "answer_id": 180468, "author": "alexmac", "author_id": 23066, "author_profile": "https://Stackoverflow.com/users/23066", "pm_score": 2, "selected": false, "text": "<p>There are a couple of ways you can do this:</p>\n\n<p>LINQ Dynamic query libraries:\n<a href=\"http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx</a></p>\n\n<p>Expression Trees &amp; Lamda expressions:\n<a href=\"http://msdn.microsoft.com/en-us/library/bb882637.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb882637.aspx</a></p>\n" }, { "answer_id": 180469, "author": "Michael Damatov", "author_id": 23372, "author_profile": "https://Stackoverflow.com/users/23372", "pm_score": 0, "selected": false, "text": "<pre><code>private List&lt;User&gt; GetUsersFromRoles(uint UserRoles) {\n return from u in dc.Users \n where (u.UserRolesBitmask &amp; UserRoles) != 0\n select u;\n}\n</code></pre>\n\n<p>UserRoles parameter should be provided, however, as a bit mask, instead of array.</p>\n" }, { "answer_id": 180475, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 6, "selected": true, "text": "<p>You can use the <a href=\"http://www.albahari.com/nutshell/predicatebuilder.aspx\" rel=\"noreferrer\">PredicateBuilder</a> class.</p>\n\n<p>PredicateBuilder has been released in the <a href=\"https://www.nuget.org/packages/LinqKit/\" rel=\"noreferrer\">LINQKit NuGet package</a></p>\n\n<blockquote>\n <p>LINQKit is a free set of extensions for LINQ to SQL and Entity Framework power users.</p>\n</blockquote>\n" }, { "answer_id": 180488, "author": "Lucas", "author_id": 24231, "author_profile": "https://Stackoverflow.com/users/24231", "pm_score": 2, "selected": false, "text": "<p>Here's one way of adding a variable number of <em>where</em> clauses to your LINQ query.\nNote that I haven't touched your bitmask logic, I just focused on the multiple <em>where</em>s.</p>\n\n<pre><code>// C#\nprivate List&lt;User&gt; GetUsersFromRoles(uint[] UserRoles)\n{\n var users = dc.Users;\n\n foreach (uint role in UserRoles)\n {\n users = users.Where(u =&gt; (u.UserRolesBitmask &amp; role) == role);\n }\n\n return users.ToList();\n}\n</code></pre>\n\n<hr>\n\n<p>EDIT: Actually, this will <strong>AND</strong> the <em>where</em> clauses and you wanted to <strong>OR</strong> them. The following approach (a inner join) works in LINQ to Objects but can not be translated to SQL with LINQ to SQL:</p>\n\n<pre><code>var result = from user in Users\n from role in UserRoles\n where (user.UserRolesBitmask &amp; role) == role\n select user;\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14072/" ]
I've got a User table with a bitmask that contains the user's roles. The linq query below returns all the users whose roles include 1, 4 or 16. ``` var users = from u in dc.Users where ((u.UserRolesBitmask & 1) == 1) || ((u.UserRolesBitmask & 4) == 4) || ((u.UserRolesBitmask & 16) == 16) select u; ``` I'd like to rewrite this into the method below to returns all the users from the given roles so I can reuse it: ``` private List<User> GetUsersFromRoles(uint[] UserRoles) {} ``` Any pointers on how to dynamically build my query? Thanks
You can use the [PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx) class. PredicateBuilder has been released in the [LINQKit NuGet package](https://www.nuget.org/packages/LinqKit/) > > LINQKit is a free set of extensions for LINQ to SQL and Entity Framework power users. > > >
180,422
<p>I'm trying to determine which records to delete from a database when a user submits a form. The page has two CheckBoxList one representing the records before modification and one after.</p> <p>I can easily get the selected values that need to be deleted like this...</p> <pre><code>//get the items not selected that were selected before var oldSelectedItems = from oItem in oldChklSpecialNeeds.Items.Cast&lt;ListItem&gt;() where !(from nItem in newChklSpecialNeeds.Items.Cast&lt;ListItem&gt;() where nItem.Selected select nItem.Value).Contains(oItem.Value) &amp;&amp; oItem.Selected select oItem.Value; </code></pre> <p>now I am trying to do something like this but it isn't allowing it...</p> <pre><code>var itemsToDelete = from specialNeed in db.SpecialNeeds join oldSelectedItem in oldSelectedItems on specialNeed.SpecialNeedsTypeCd equals oldSelectedItem.Value where specialNeed.CustomerId == customerId </code></pre> <p>I can easily just use a foreach loop and a .DeleteOnSubmit() for each item but I'm thinking there is a way use functionality of LINQ and pass the whole query result of an inner join to .DeleteAllOnSubmit() </p> <pre><code>//like so db.SpecialNeeds.DeleteAllOnSubmit(itemsToDelete); </code></pre> <p>Any ideas?</p>
[ { "answer_id": 180524, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>What is the error you are getting? Is it a type mismatch between SpecialNeedsTypeCd and oldSelectedItem.Value? Have you just omitted the select in the second Linq statement in this post or is that the problem?</p>\n" }, { "answer_id": 180706, "author": "Lucas", "author_id": 24231, "author_profile": "https://Stackoverflow.com/users/24231", "pm_score": 3, "selected": true, "text": "<p>Local collections can be used in LINQ to SQL with the Contains() method. You can try changing the <em>join</em> clause into a <em>where</em> with Contains():</p>\n\n<pre><code>var itemsToDelete = from specialNeed in db.SpecialNeeds\n where oldSelectedItems.Contains(specialNeed.SpecialNeedsTypeCd)\n &amp;&amp; specialNeed.CustomerId == customerId\n select ...;\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6161/" ]
I'm trying to determine which records to delete from a database when a user submits a form. The page has two CheckBoxList one representing the records before modification and one after. I can easily get the selected values that need to be deleted like this... ``` //get the items not selected that were selected before var oldSelectedItems = from oItem in oldChklSpecialNeeds.Items.Cast<ListItem>() where !(from nItem in newChklSpecialNeeds.Items.Cast<ListItem>() where nItem.Selected select nItem.Value).Contains(oItem.Value) && oItem.Selected select oItem.Value; ``` now I am trying to do something like this but it isn't allowing it... ``` var itemsToDelete = from specialNeed in db.SpecialNeeds join oldSelectedItem in oldSelectedItems on specialNeed.SpecialNeedsTypeCd equals oldSelectedItem.Value where specialNeed.CustomerId == customerId ``` I can easily just use a foreach loop and a .DeleteOnSubmit() for each item but I'm thinking there is a way use functionality of LINQ and pass the whole query result of an inner join to .DeleteAllOnSubmit() ``` //like so db.SpecialNeeds.DeleteAllOnSubmit(itemsToDelete); ``` Any ideas?
Local collections can be used in LINQ to SQL with the Contains() method. You can try changing the *join* clause into a *where* with Contains(): ``` var itemsToDelete = from specialNeed in db.SpecialNeeds where oldSelectedItems.Contains(specialNeed.SpecialNeedsTypeCd) && specialNeed.CustomerId == customerId select ...; ```
180,428
<pre><code>Option Explicit On Option Strict On Public Class Class1 Dim l As List(Of A) Public Sub New() l = New List(Of B) End Sub End Class Public Class A End Class Public Class B Inherits A End Class&lt;p&gt; </code></pre> <p>I've run into this problem.<br> I have a list declared of a Generic Type 'A'<br> I want to define the list as a Generic Type 'B', which is a subclass of 'A'.<p> Why can't this be done, and how can the same effect be achieved?</p>
[ { "answer_id": 180442, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": true, "text": "<p>It's a matter of variance, which C# doesn't support for generics. See <a href=\"http://blogs.msdn.com/rmbyers/archive/2005/02/16/375079.aspx\" rel=\"nofollow noreferrer\">Rick Byer's post on the subject</a>.</p>\n" }, { "answer_id": 180460, "author": "Oliver Hallam", "author_id": 19995, "author_profile": "https://Stackoverflow.com/users/19995", "pm_score": 0, "selected": false, "text": "<p>If you could cast a list of As as a list of Bs, then what would happen if you added an A?</p>\n" }, { "answer_id": 245173, "author": "Oliver Hallam", "author_id": 19995, "author_profile": "https://Stackoverflow.com/users/19995", "pm_score": 0, "selected": false, "text": "<p>In C# 4.0 (as announced yesterday) we are <a href=\"http://blogs.msdn.com/charlie/archive/2008/10/28/linq-farm-covariance-and-contravariance-in-visual-studio-2010.aspx\" rel=\"nofollow noreferrer\">half way there</a>.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24804/" ]
``` Option Explicit On Option Strict On Public Class Class1 Dim l As List(Of A) Public Sub New() l = New List(Of B) End Sub End Class Public Class A End Class Public Class B Inherits A End Class<p> ``` I've run into this problem. I have a list declared of a Generic Type 'A' I want to define the list as a Generic Type 'B', which is a subclass of 'A'. Why can't this be done, and how can the same effect be achieved?
It's a matter of variance, which C# doesn't support for generics. See [Rick Byer's post on the subject](http://blogs.msdn.com/rmbyers/archive/2005/02/16/375079.aspx).
180,430
<p>I'm refactoring some PHP code and discovered that certain nested combinations of </p> <pre><code>if () : </code></pre> <p>and </p> <pre><code>if () { </code></pre> <p>generate syntax errors. Not that I would normally mix the two, but I like to do frequent syntax checks as I'm writing code and I kept getting a syntax error because of this.</p> <p>Example - generates syntax error:</p> <pre><code>if ( $test == 1 ) : if ( $test2 == 'a' ) { if ( $test3 == 'A' ) { } else { } } else : echo 'test2'; endif; </code></pre> <p>Example - does NOT generate syntax error:</p> <pre><code>if ( $test == 1 ) : if ( $test2 == 'a' ) : if ( $test3 == 'A' ) : else : endif; endif; else : echo 'test2'; endif; </code></pre> <p>Could someone please explain to me why the first block of code is generating an error? </p>
[ { "answer_id": 180507, "author": "I GIVE CRAP ANSWERS", "author_id": 25083, "author_profile": "https://Stackoverflow.com/users/25083", "pm_score": 3, "selected": true, "text": "<p>This is a wild guess since I am not familiar with the grammar of PHP. But here goes:</p>\n\n<p>The problem is the second <code>else</code>. The parser can't see if this <code>else</code> is belonging to the first or the second if (counting from the beginning). In your second example there is an <code>endif</code> making the second <code>if</code>-block be terminated so there it can do the parse. Perhaps this is the famous 'dangling-else' problem in disguise?</p>\n" }, { "answer_id": 180552, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "<p>i don't know the exact reason why. here's a related <a href=\"http://bugs.php.net/bug.php?id=18413\" rel=\"nofollow noreferrer\">PHP bug post</a> in which a dev basically says, \"just don't do it\" :). i haven't poured through the PHP source code lately, but if i had to hazard a guess, it's due to not checking for alternative syntax while recursively going through if statements.</p>\n" }, { "answer_id": 180953, "author": "Alex Weinstein", "author_id": 16668, "author_profile": "https://Stackoverflow.com/users/16668", "pm_score": 0, "selected": false, "text": "<p>The only thing I can say here is that the code is completely unreadable. Avoid : like plague. Use familiar, C-style curly brace syntax. </p>\n\n<p>The quality of the code is very much driven by its readability, so do make an effort to clean this up, you'll save yourself a bunch of surprising bugs. </p>\n" }, { "answer_id": 180995, "author": "dmazzoni", "author_id": 7193, "author_profile": "https://Stackoverflow.com/users/7193", "pm_score": 1, "selected": false, "text": "<p>It works fine if you put a semicolon after the last curly-brace:</p>\n\n<pre><code>if ( $test == 1 ) :\n if ( $test2 == 'a' ) {\n if ( $test3 == 'A' ) {\n } else {\n }\n };\nelse :\n echo 'test2';\nendif;\n</code></pre>\n" }, { "answer_id": 181247, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 1, "selected": false, "text": "<p>Indentation be damned, it's interpreting the first example as being an if using braces matched up with an else using the alternate syntax.</p>\n\n<p>Consistency is the rule of thumb here and the interpretation is ambiguous to any reader anyway, so either put in the semicolon as suggested in the other answers, or better yet... clean up the code. That's horrible!</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24190/" ]
I'm refactoring some PHP code and discovered that certain nested combinations of ``` if () : ``` and ``` if () { ``` generate syntax errors. Not that I would normally mix the two, but I like to do frequent syntax checks as I'm writing code and I kept getting a syntax error because of this. Example - generates syntax error: ``` if ( $test == 1 ) : if ( $test2 == 'a' ) { if ( $test3 == 'A' ) { } else { } } else : echo 'test2'; endif; ``` Example - does NOT generate syntax error: ``` if ( $test == 1 ) : if ( $test2 == 'a' ) : if ( $test3 == 'A' ) : else : endif; endif; else : echo 'test2'; endif; ``` Could someone please explain to me why the first block of code is generating an error?
This is a wild guess since I am not familiar with the grammar of PHP. But here goes: The problem is the second `else`. The parser can't see if this `else` is belonging to the first or the second if (counting from the beginning). In your second example there is an `endif` making the second `if`-block be terminated so there it can do the parse. Perhaps this is the famous 'dangling-else' problem in disguise?
180,451
<p>Using answers to <a href="https://stackoverflow.com/questions/57522/javascript-array-with-a-mix-of-literals-and-arrays">this question</a>, I have been able to populate a select box based on the selection of another select box. ( <a href="https://stackoverflow.com/questions/57522/javascript-array-with-a-mix-of-literals-and-arrays#58062">I posted my answer here</a>) Pulling the data from an array structure built server-side, stored in a .js file and referenced in the html page.</p> <p>Now I would like to add a third select box. If I had 3 sets of data (model, make, options) something like this (pseudo code):</p> <pre><code>cars : [Honda[Accord[Lx, Dx]], [Civic[2dr, Hatchback]], [Toyota[Camry[Blk, Red]], [Prius[2dr,4dr]] </code></pre> <p>Ex: If Honda were selected, the next select box would have [Accord Civic] and if Accord were selected the next select box would have [Lx Dx]</p> <p>How can I</p> <p>1) create an array structure to hold the data? such that</p> <p>2) I can use the value from one select box to reference the needed values for the next select box</p> <p>Thanks</p> <p><strong>EDIT</strong></p> <p>I can create the following, but can't figure out the references in a way that would help populate a select box</p> <pre><code>var cars = [ {"makes" : "Honda", "models" : [ {'Accord' : ["2dr","4dr"]} , {'CRV' : ["2dr","Hatchback"]} , {'Pilot': ["base","superDuper"] } ] }, {"makes" :"Toyota", "models" : [ {'Prius' : ["green","reallyGreen"]} , {'Camry' : ["sporty","square"]} , {'Corolla' : ["cheap","superFly"] } ] } ] ; alert(cars[0].models[0].Accord[0]); ---&gt; 2dr </code></pre>
[ { "answer_id": 180593, "author": "Ionuț Staicu", "author_id": 23810, "author_profile": "https://Stackoverflow.com/users/23810", "pm_score": 1, "selected": false, "text": "<p>You should take a look <a href=\"http://www.texotela.co.uk/code/jquery/select/\" rel=\"nofollow noreferrer\">here</a> for select box manipulation.\nFor what you want, i think <a href=\"http://json.org/\" rel=\"nofollow noreferrer\">JSON</a> will do the right job for you.\nAnyhow, if i were you, i will do this way: \nWhen I change first select, i do an ajax request. With ajax response, i will populate the second box. Same for second box and there you have the third box populated with right data.</p>\n" }, { "answer_id": 180926, "author": "Marko Dumic", "author_id": 5817, "author_profile": "https://Stackoverflow.com/users/5817", "pm_score": 7, "selected": true, "text": "<p>I prefer data structure like this:</p>\n\n<pre><code>var carMakers = [\n { name: 'Honda', models: [\n { name: 'Accord', features: ['2dr', '4dr'] },\n { name: 'CRV', features: ['2dr', 'Hatchback'] },\n { name: 'Pilot', features: ['base', 'superDuper'] }\n ]},\n\n { name: 'Toyota', models: [\n { name: 'Prius', features: ['green', 'superGreen'] },\n { name: 'Camry', features: ['sporty', 'square'] },\n { name: 'Corolla', features: ['cheap', 'superFly'] }\n ]}\n];\n</code></pre>\n\n<p>Given the three select lists with id's: 'maker', 'model' and 'features' you can manipulate them with this (I believe this is pretty self explanatory):</p>\n\n<pre><code>// returns array of elements whose 'prop' property is 'value'\nfunction filterByProperty(arr, prop, value) {\n return $.grep(arr, function (item) { return item[prop] == value });\n}\n\n// populates select list from array of items given as objects: { name: 'text', value: 'value' }\nfunction populateSelect(el, items) {\n el.options.length = 0;\n if (items.length &gt; 0)\n el.options[0] = new Option('please select', '');\n\n $.each(items, function () {\n el.options[el.options.length] = new Option(this.name, this.value);\n });\n}\n\n// initialization\n$(document).ready(function () {\n // populating 1st select list\n populateSelect($('#maker').get(0), $.map(carMakers, function(maker) { return { name: maker.name, value: maker.name} }));\n\n // populating 2nd select list\n $('#maker').bind('change', function() {\n var makerName = this.value,\n carMaker = filterByProperty(carMakers, 'name', makerName),\n models = [];\n\n if (carMaker.length &gt; 0)\n models = $.map(carMaker[0].models, function(model) { return { name: model.name, value: makerName + '.' + model.name} });\n\n populateSelect($('#model').get(0), models);\n $('#model').trigger('change');\n });\n\n // populating 3rd select list\n $('#model').bind('change', function () {\n var nameAndModel = this.value.split('.'),\n features = [];\n\n if (2 == nameAndModel.length) {\n var makerName = nameAndModel[0], \n carModel = nameAndModel[1],\n carMaker = filterByProperty(carMakers, 'name', makerName);\n\n if (carMaker.length &gt; 0) {\n var model = filterByProperty(carMaker[0].models, 'name', carModel)\n\n if (model.length &gt; 0)\n features = $.map(model[0].features, function(feature) { return { name: feature, value: makerName + '.' + carModel + '.' + feature} })\n }\n }\n\n populateSelect($('#feature').get(0), features);\n })\n\n // alerting value on 3rd select list change\n $('#feature').bind('change', function () { \n if (this.value.length &gt; 0)\n alert(this.value);\n })\n});\n</code></pre>\n" }, { "answer_id": 187865, "author": "Jay Corbett", "author_id": 2755, "author_profile": "https://Stackoverflow.com/users/2755", "pm_score": 2, "selected": false, "text": "<p>Thanks to the answer from @Marko Dunic, I was able to build an array (data) structure that can be referenced to populate 3 select boxes. I didn't use the implementation code only because I didn't completely understand it...it works as posted. I will come back to this code later as I learn jQuery.\nMy code is posted below (obviously, your reference to jQuery may be different)</p>\n\n<pre><code>&lt;html&gt;&lt;head&gt;\n&lt;script language=\"Javascript\" src=\"javascript/jquery-1.2.6.min.js\"&gt;&lt;/script&gt;\n&lt;script type=\"text/JavaScript\"&gt;\nvar cars = [\n{ name: 'Honda', models: [\n{ name: 'Accord', features: ['2dr', '4dr'] },\n{ name: 'CRV', features: ['2dr', 'Hatchback'] },\n{ name: 'Pilot', features: ['base', 'superDuper'] }\n ]},\n{ name: 'Toyota', models: [\n{ name: 'Prius', features: ['green', 'superGreen'] },\n{ name: 'Camry', features: ['sporty', 'square'] },\n{ name: 'Corolla', features: ['cheap', 'superFly'] }\n ]\n }\n];\n$(function() {\nvar options = '' ;\nfor (var i = 0; i &lt; cars.length; i++) {\n var opt = cars[i].name ;\n if (i == 0){ options += '&lt;option selected value=\"' + opt + '\"&gt;' + opt + '&lt;/option&gt;'; }\n else {options += '&lt;option value=\"' + opt + '\"&gt;' + opt + '&lt;/option&gt;'; } \n}\n$(\"#maker\").html(options); // populate select box with array\n\nvar options = '' ;\nfor (var i=0; i &lt; cars[0].models.length; i++) { \n var opt = cars[0].models[0].name ;\n if (i==0){options += '&lt;option selected value=\"' + opt + '\"&gt;' + opt + '&lt;/option&gt;';}\n else {options += '&lt;option value=\"' + opt + '\"&gt;' + opt + '&lt;/option&gt;';} \n}\n$(\"#model\").html(options); // populate select box with array\n\nvar options = '' ;\nfor (var i=0; i &lt; cars[0].models[0].features.length; i++) { \n var opt = cars[0].models[0].features[i] ;\n if (i==0){options += '&lt;option selected value=\"' + opt + '\"&gt;' + opt + '&lt;/option&gt;';}\n else {options += '&lt;option value=\"' + opt + '\"&gt;' + opt + '&lt;/option&gt;';}\n}\n$(\"#feature\").html(options); // populate select box with array\n\n$(\"#maker\").bind(\"click\",\n function() {\n $(\"#model\").children().remove() ; // clear select box\n for(var i=0; i&lt;cars.length; i++) {\n if (cars[i].name == this.value) {\n var options = '' ;\n for (var j=0; j &lt; cars[i].models.length; j++) { \n var opt= cars[i].models[j].name ;\n if (j==0) {options += '&lt;option selected value=\"' + opt + '\"&gt;' + opt + '&lt;/option&gt;';}\n else {options += '&lt;option value=\"' + opt + '\"&gt;' + opt + '&lt;/option&gt;';} \n }\n break;\n }\n }\n $(\"#model\").html(options); // populate select box with array\n\n $(\"#feature\").children().remove() ; // clear select box\n for(var i=0; i&lt;cars.length; i++) {\n for(var j=0; j&lt;cars[i].models.length; j++) {\n if(cars[i].models[j].name == $(\"#model\").val()) {\n var options = '' ;\n for (var k=0; k &lt; cars[i].models[j].features.length; k++) { \n var opt = cars[i].models[j].features[k] ;\n if (k==0){options += '&lt;option selected value=\"' + opt + '\"&gt;' + opt + '&lt;/option&gt;';}\n else {options += '&lt;option value=\"' + opt + '\"&gt;' + opt + '&lt;/option&gt;';}\n }\n break;\n }\n }\n }\n $(\"#feature\").html(options); // populate select box with array\n });\n\n $(\"#model\").bind(\"click\",\n function() {\n $(\"#feature\").children().remove() ; // clear select box\n for(var i=0; i&lt;cars.length; i++) {\n for(var j=0; j&lt;cars[i].models.length; j++) {\n if(cars[i].models[j].name == this.value) {\n var options = '' ;\n for (var k=0; k &lt; cars[i].models[j].features.length; k++) { \n var opt = cars[i].models[j].features[k] ;\n if (k==0){options += '&lt;option selected value=\"' + opt + '\"&gt;' + opt + '&lt;/option&gt;';}\n else {options += '&lt;option value=\"' + opt + '\"&gt;' + opt + '&lt;/option&gt;';}\n }\n break ;\n }\n }\n }\n $(\"#feature\").html(options); // populate select box with array\n });\n});\n&lt;/script&gt;\n&lt;/head&gt; &lt;body&gt;\n&lt;div id=\"selection\"&gt;\n&lt;select id=\"maker\"size=\"10\" style=\"{width=75px}\"&gt;&lt;/select&gt;\n&lt;select id=\"model\" size=\"10\" style=\"{width=75px}\"&gt;&lt;/select&gt;\n&lt;select id=\"feature\" size=\"10\"style=\"{width=75px}\"&gt;&lt;/select&gt;\n&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 7883989, "author": "DoctorJava", "author_id": 1011927, "author_profile": "https://Stackoverflow.com/users/1011927", "pm_score": 2, "selected": false, "text": "<p>I really liked the solution by @Marko Dunic, but it didn't meet my needs for attaching IDs to the options. Once I attached the IDs, I realized that I could make the JS code even smaller and simpler. My solution is designed for when the data comes from a relational database, and the JSON input data retains the relational structure with Primary/Foreign Keys. Here is the JSON data:</p>\n\n<pre><code>&lt;html lang=\"en\"&gt;\n &lt;head&gt;\n &lt;title&gt;Populate a select dropdown list with jQuery - WebDev Ingredients&lt;/title&gt;\n &lt;script type=\"text/javascript\" src=\"js/jquery-1.4.2.js\"&gt;&lt;/script&gt;\n &lt;script type=\"text/javascript\"&gt;\n var types = [ \n { typeID: 1, name: 'Domestic'},\n { typeID: 2, name: 'Import'},\n { typeID: 3, name: 'Boat'}\n ]\n var makes = [ \n { typeID: 1, makeID: 1, name: 'Chevy'}, \n { typeID: 1, makeID: 2, name: 'Ford'}, \n { typeID: 1, makeID: 3, name: 'Delorean'}, \n { typeID: 2, makeID: 4, name: 'Honda'}, \n { typeID: 2, makeID: 5, name: 'Toyota'}, \n { typeID: 2, makeID: 6, name: 'Saab'} \n ] \n var model = [ \n { makeID: 1, modelID: 1, name: 'Camaro'}, \n { makeID: 1, modelID: 2, name: 'Chevelle'}, \n { makeID: 1, modelID: 3, name: 'Nova'}, \n { makeID: 2, modelID: 4, name: 'Focus'}, \n { makeID: 2, modelID: 5, name: 'Galaxie'}, \n { makeID: 2, modelID: 6, name: 'Mustang'}, \n { makeID: 4, modelID: 7, name: 'Accord'},\n { makeID: 4, modelID: 8, name: 'Civic'}, \n { makeID: 4, modelID: 9, name: 'Odyssey'}, \n { makeID: 5, modelID: 10, name: 'Camry'}, \n { makeID: 5, modelID: 11, name: 'Corolla'}\n ]\n // \n // Put this in a stand alone .js file\n //\n // returns array of elements whose 'prop' property is 'value' \n function filterByProperty(arr, prop, value) { \n return $.grep(arr, function (item) { return item[prop] == value }); \n } \n // populates select list from array of items given as objects: { name: 'text', value: 'value' } \n function populateSelect(el, items) { \n el.options.length = 0; \n if (items.length &gt; 0) \n el.options[0] = new Option('please select', ''); \n $.each(items, function () { \n el.options[el.options.length] = new Option(this.name, this.value); \n }); \n } \n // initialization \n $(document).ready(function () { \n // populating 1st select list \n populateSelect($('#sType').get(0), $.map(types, function(type) { return { name: type.name, value: type.typeID} })); \n // populating 2nd select list \n $('#sType').bind('change', function() { \n var theModels = filterByProperty(makes, 'typeID', this.value);\n populateSelect($('#sMake').get(0), $.map(theModels, function(make) { return { name: make.name, value: make.makeID} })); \n $('#sMake').trigger('change'); \n }); \n // populating 3nd select list \n $('#sMake').bind('change', function() { \n var theSeries = filterByProperty(model, 'makeID', this.value); \n populateSelect($('#sModel').get(0), $.map(theSeries, function(model) { return { name: model.name, value: model.modelID} })); \n }); \n });\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n Enter values, click submit, and look at the post parameters\n &lt;form method=\"get\" action=\"index.php\"&gt;\n &lt;div id=\"selection\"&gt; \n &lt;select id=\"sType\" name=\"type_id\" style=\"{width=75px}\"&gt;&lt;/select&gt; \n &lt;select id=\"sMake\" name=\"make_id\" style=\"{width=75px}\"&gt;&lt;/select&gt; \n &lt;select id=\"sModel\" name=\"model_id\" style=\"{width=75px}\"&gt;&lt;/select&gt; \n &lt;/div&gt;\n &lt;input type=\"submit\"&gt;\n &lt;/form&gt;\n &lt;/body&gt;\n&lt;/html&gt; \n</code></pre>\n\n<p>Notice that my solution shifts the functionality so that Make-Model are the 2nd and 3rd text boxes, and Type ( domestic, import, boat, etc. ) are the 1st level. I got the boilerplate JS down to 23 lines (less comments) while retaining good formatting. </p>\n\n<p>The JSON data is very easy to render from SQL queries, which are cached in java Lists on init because the Type-Make-Model rarely change. I don't use any dynamic AJAX because that complicates the architecture, and I have a relatively small list of available values, so I just send it at the page request.</p>\n\n<p>\"Solutions should be a simple as possible, but no simpler\" - A. Einstein </p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
Using answers to [this question](https://stackoverflow.com/questions/57522/javascript-array-with-a-mix-of-literals-and-arrays), I have been able to populate a select box based on the selection of another select box. ( [I posted my answer here](https://stackoverflow.com/questions/57522/javascript-array-with-a-mix-of-literals-and-arrays#58062)) Pulling the data from an array structure built server-side, stored in a .js file and referenced in the html page. Now I would like to add a third select box. If I had 3 sets of data (model, make, options) something like this (pseudo code): ``` cars : [Honda[Accord[Lx, Dx]], [Civic[2dr, Hatchback]], [Toyota[Camry[Blk, Red]], [Prius[2dr,4dr]] ``` Ex: If Honda were selected, the next select box would have [Accord Civic] and if Accord were selected the next select box would have [Lx Dx] How can I 1) create an array structure to hold the data? such that 2) I can use the value from one select box to reference the needed values for the next select box Thanks **EDIT** I can create the following, but can't figure out the references in a way that would help populate a select box ``` var cars = [ {"makes" : "Honda", "models" : [ {'Accord' : ["2dr","4dr"]} , {'CRV' : ["2dr","Hatchback"]} , {'Pilot': ["base","superDuper"] } ] }, {"makes" :"Toyota", "models" : [ {'Prius' : ["green","reallyGreen"]} , {'Camry' : ["sporty","square"]} , {'Corolla' : ["cheap","superFly"] } ] } ] ; alert(cars[0].models[0].Accord[0]); ---> 2dr ```
I prefer data structure like this: ``` var carMakers = [ { name: 'Honda', models: [ { name: 'Accord', features: ['2dr', '4dr'] }, { name: 'CRV', features: ['2dr', 'Hatchback'] }, { name: 'Pilot', features: ['base', 'superDuper'] } ]}, { name: 'Toyota', models: [ { name: 'Prius', features: ['green', 'superGreen'] }, { name: 'Camry', features: ['sporty', 'square'] }, { name: 'Corolla', features: ['cheap', 'superFly'] } ]} ]; ``` Given the three select lists with id's: 'maker', 'model' and 'features' you can manipulate them with this (I believe this is pretty self explanatory): ``` // returns array of elements whose 'prop' property is 'value' function filterByProperty(arr, prop, value) { return $.grep(arr, function (item) { return item[prop] == value }); } // populates select list from array of items given as objects: { name: 'text', value: 'value' } function populateSelect(el, items) { el.options.length = 0; if (items.length > 0) el.options[0] = new Option('please select', ''); $.each(items, function () { el.options[el.options.length] = new Option(this.name, this.value); }); } // initialization $(document).ready(function () { // populating 1st select list populateSelect($('#maker').get(0), $.map(carMakers, function(maker) { return { name: maker.name, value: maker.name} })); // populating 2nd select list $('#maker').bind('change', function() { var makerName = this.value, carMaker = filterByProperty(carMakers, 'name', makerName), models = []; if (carMaker.length > 0) models = $.map(carMaker[0].models, function(model) { return { name: model.name, value: makerName + '.' + model.name} }); populateSelect($('#model').get(0), models); $('#model').trigger('change'); }); // populating 3rd select list $('#model').bind('change', function () { var nameAndModel = this.value.split('.'), features = []; if (2 == nameAndModel.length) { var makerName = nameAndModel[0], carModel = nameAndModel[1], carMaker = filterByProperty(carMakers, 'name', makerName); if (carMaker.length > 0) { var model = filterByProperty(carMaker[0].models, 'name', carModel) if (model.length > 0) features = $.map(model[0].features, function(feature) { return { name: feature, value: makerName + '.' + carModel + '.' + feature} }) } } populateSelect($('#feature').get(0), features); }) // alerting value on 3rd select list change $('#feature').bind('change', function () { if (this.value.length > 0) alert(this.value); }) }); ```
180,452
<p>I have a c# form (let's call it MainForm) with a number of custom controls on it. I'd like to have the MainForm.OnClick() method fire anytime someone clicks on the form regardless of whether the click happened on the form or if the click was on one of the custom controls. I'm looking for behavior similar to the KeyPreview feature of forms except for mouse clicks rather than key presses.</p>
[ { "answer_id": 180476, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>Catching a click on an open space on the form is easy, but to get a click that's actually on a control, you'll need the cooperation of that control to send it to the form.</p>\n\n<p>One possibility is to place a transparent control over the entire form, and accept clicks onto that, deal with them, and then pass them onto the proper control underneath.</p>\n" }, { "answer_id": 180530, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 0, "selected": false, "text": "<p>This is a common pattern in development, its called the Observer pattern. There are lots of examples of Observer patterns and c# here is 1 example <a href=\"http://msdn.microsoft.com/en-us/library/ms954621.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms954621.aspx</a> but have a good google around.</p>\n" }, { "answer_id": 180555, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 1, "selected": false, "text": "<p>The only way I've ever managed to do this is to handle the [c]Click[/c] event of every control. I don't believe the event is raised before the control processes it.</p>\n\n<p>In WPF, there are \"tunneling\" preview events that provide this functionality, but that doesn't really help you in WinForms.</p>\n" }, { "answer_id": 180558, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>In the form's ControlAdded event, add a MouseClick handler to the control, with the Address of the form's click event. I haven't tested this, but it might work.</p>\n\n<pre><code>Private Sub Example_ControlAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.ControlEventArgs) Handles Me.ControlAdded\n\n AddHandler e.Control.MouseClick, AddressOf Example_MouseClick\nEnd Sub\n\nPrivate Sub Example_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick\n MessageBox.Show(\"Click\")\nEnd Sub\n</code></pre>\n" }, { "answer_id": 180621, "author": "Andrew", "author_id": 15127, "author_profile": "https://Stackoverflow.com/users/15127", "pm_score": 1, "selected": false, "text": "<p>You can hook all the control's events, if you like, and then monitor that way. I assume there is some uber fancy Win32 api way to trap them all, but that is beyond me at the moment.</p>\n\n<pre><code> public Form1()\n {\n InitializeComponent();\n HookEvents();\n }\n\n private void HookEvents() {\n foreach (Control ctl in this.Controls) {\n ctl.MouseClick += new MouseEventHandler(Form1_MouseClick);\n }\n } \n\n void Form1_MouseClick(object sender, MouseEventArgs e)\n {\n LogEvent(sender, \"MouseClick\");\n }\n\n // and then this just logs to a multiline textbox you have somwhere on the form\n private void LogEvent(object sender, string msg) {\n this.textBox1.Text = string.Format(\"{0} {1} ({2}) \\n {3}\",\n DateTime.Now.TimeOfDay.ToString(),\n msg,\n sender.GetType().Name,\n textBox1.Text\n );\n }\n</code></pre>\n\n<p>The output is something like this, showing all the events and who \"sent\" them up:</p>\n\n<pre><code>14:51:42.3381985 MouseClick (Form1) \n14:51:40.6194485 MouseClick (RichTextBox) \n14:51:40.0100735 MouseClick (TextBox) \n14:51:39.6194485 MouseClick (Form1) \n14:51:39.2131985 MouseClick (RichTextBox) \n14:51:38.8694485 MouseClick (Button) \n</code></pre>\n\n<p>HTH.</p>\n" }, { "answer_id": 11990432, "author": "ChéDon", "author_id": 1329654, "author_profile": "https://Stackoverflow.com/users/1329654", "pm_score": 3, "selected": false, "text": "<p>I recommend creating a base form for the other forms in your application to inherit. Add this code to your base form to create a new event called GlobalMouseClickEventHandler:</p>\n\n<pre><code>namespace Temp\n{\n public delegate void GlobalMouseClickEventHander(object sender, MouseEventArgs e);\n\n public partial class TestForm : Form\n {\n [Category(\"Action\")]\n [Description(\"Fires when any control on the form is clicked.\")]\n public event GlobalMouseClickEventHander GlobalMouseClick;\n\n public TestForm()\n {\n InitializeComponent();\n BindControlMouseClicks(this);\n }\n\n private void BindControlMouseClicks(Control con)\n {\n con.MouseClick += delegate(object sender, MouseEventArgs e)\n {\n TriggerMouseClicked(sender, e);\n };\n // bind to controls already added\n foreach (Control i in con.Controls)\n {\n BindControlMouseClicks(i);\n }\n // bind to controls added in the future\n con.ControlAdded += delegate(object sender, ControlEventArgs e)\n {\n BindControlMouseClicks(e.Control);\n }; \n }\n\n private void TriggerMouseClicked(object sender, MouseEventArgs e)\n {\n if (GlobalMouseClick != null)\n {\n GlobalMouseClick(sender, e);\n }\n }\n }\n}\n</code></pre>\n\n<p>This solution will work not only for top-level controls, but also nested controls such as controls placed inside of panels.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2191/" ]
I have a c# form (let's call it MainForm) with a number of custom controls on it. I'd like to have the MainForm.OnClick() method fire anytime someone clicks on the form regardless of whether the click happened on the form or if the click was on one of the custom controls. I'm looking for behavior similar to the KeyPreview feature of forms except for mouse clicks rather than key presses.
In the form's ControlAdded event, add a MouseClick handler to the control, with the Address of the form's click event. I haven't tested this, but it might work. ``` Private Sub Example_ControlAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.ControlEventArgs) Handles Me.ControlAdded AddHandler e.Control.MouseClick, AddressOf Example_MouseClick End Sub Private Sub Example_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick MessageBox.Show("Click") End Sub ```
180,464
<p>I'm running PHP on Windows/IIS.</p> <p>My session variables don't seem to be preserved from page-to-page.</p> <p>This code&hellip;</p> <pre><code>//echos out the session variables in a nice format for inspection echo "&lt;p&gt;&lt;pre&gt;"; print_r($_SESSION); echo "&lt;/pre&gt;&lt;/p&gt;"; </code></pre> <p>&hellip;outputs blank values, like this&hellip;</p> <pre> Array ( [s_firstvar] => [s_var2] => [s_third] => [s_numberfour] => [s_youget] => [s_thepoint] => [] => ) </pre> <p>I found suggestions on a forum&hellip;</p> <blockquote> <p>I had a similar problem recently (Win2000, IIS), and it turned out that PHP did not have write-access to whatever directory that the session data was stored in. You may want to look into this.</p> </blockquote> <p>and</p> <blockquote> <p>have you set session.save_path?</p> </blockquote> <p>What's the proper use of php.ini's session.save_path? And, is that my problem?</p>
[ { "answer_id": 180486, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": false, "text": "<p>can you post a bit more of your session code? some basics:</p>\n\n<ul>\n<li>did you start your session? (<a href=\"http://php.net/session_start\" rel=\"nofollow noreferrer\"><code>session_start()</code></a> )</li>\n<li>did you check whether your save path has proper permissions (not mentioned in OP)</li>\n<li>session.save_path is really just the directory sessions will be saved into. if you are on a shared service, it may be better to set it to a different directory than the default temporary directory (as your sessions would be intermingled with other app's sessions as well, and could potentially lead to a greater chance of session collision)</li>\n<li>if you are altering session configurations (like <code>save_path</code>, these must be set previous to calling <code>session_start()</code>.</li>\n</ul>\n" }, { "answer_id": 180495, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 1, "selected": true, "text": "<p>Oops. I found that I was not using the correct syntax when assigning values:</p>\n\n<p>Does not work:</p>\n\n<pre><code>$_SESSION['$s_firstvar'] = 3;\n</code></pre>\n\n<p>Does work:</p>\n\n<pre><code>$_SESSION['s_firstvar'] = 3;\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
I'm running PHP on Windows/IIS. My session variables don't seem to be preserved from page-to-page. This code… ``` //echos out the session variables in a nice format for inspection echo "<p><pre>"; print_r($_SESSION); echo "</pre></p>"; ``` …outputs blank values, like this… ``` Array ( [s_firstvar] => [s_var2] => [s_third] => [s_numberfour] => [s_youget] => [s_thepoint] => [] => ) ``` I found suggestions on a forum… > > I had a similar problem recently (Win2000, IIS), and it turned out that PHP > did not have write-access to whatever directory that the session data was > stored in. You may want to look into this. > > > and > > have you set session.save\_path? > > > What's the proper use of php.ini's session.save\_path? And, is that my problem?
Oops. I found that I was not using the correct syntax when assigning values: Does not work: ``` $_SESSION['$s_firstvar'] = 3; ``` Does work: ``` $_SESSION['s_firstvar'] = 3; ```
180,516
<p>I have roughly the following code. Could this be made nicer or more efficient? Perhaps using <code>std::remove_if</code>? Can you remove items from the map while traversing it? Can we avoid using the temporary map?</p> <pre><code>typedef std::map&lt;Action, What&gt; Actions; static Actions _actions; bool expired(const Actions::value_type &amp;action) { return &lt;something&gt;; } void bar(const Actions::value_type &amp;action) { // do some stuff } void foo() { // loop the actions finding expired items Actions actions; BOOST_FOREACH(Actions::value_type &amp;action, _actions) { if (expired(action)) bar(action); else actions[action.first]=action.second; } } actions.swap(_actions); } </code></pre>
[ { "answer_id": 180532, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 1, "selected": false, "text": "<p>If the idea is to remove expired items, why not use <a href=\"http://www.cplusplus.com/reference/stl/map/erase.html\" rel=\"nofollow noreferrer\">map::erase</a>? This way you only have to remove elements you don't need anymore, not rebuild an entire copy with all the elements that you want to keep.</p>\n\n<p>The way you would do this is to save off the iterators pointing to the elements you want to erase, then erase them all after the iteration is over.</p>\n\n<p>Or, you can save off the element that you visited, move to the next element, and then erase the temporary. The loop bounds get messed up in your case though, so you have to fine tune the iteration yourself.</p>\n\n<p>Depending on how expired() is implemented, there may be other better ways. For example if you are keeping track of a timestamp as the key to the map (as expired() implies?), you can do upper_bound on the current timestamp, and all elements in the range [ begin(), upper_bound() ) need to be processed and erased.</p>\n" }, { "answer_id": 180616, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 6, "selected": true, "text": "<p>You could use erase(), but I don't know how BOOST_FOREACH will handle the invalidated iterator. The <a href=\"http://en.cppreference.com/w/cpp/container/map/erase\" rel=\"noreferrer\">documentation for map::erase</a> states that only the erased iterator will be invalidated, the others should be OK. Here's how I would restructure the inner loop:</p>\n\n<pre><code>Actions::iterator it = _actions.begin();\nwhile (it != _actions.end())\n{\n if (expired(*it))\n {\n bar(*it);\n Actions::iterator toerase = it;\n ++it;\n _actions.erase(toerase);\n }\n else\n ++it;\n}\n</code></pre>\n" }, { "answer_id": 180679, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 2, "selected": false, "text": "<p>Something that no one ever seems to know is that erase returns a new, guaranteed-to-be-valid iterator, when used on any container.</p>\n\n<pre><code>Actions::iterator it = _actions.begin();\nwhile (it != _actions.end())\n{\n if (expired(*it))\n {\n bar(*it);\n it = _actions::erase(it);\n }\n else\n ++it;\n}\n</code></pre>\n\n<p>Storing actions.end() is probably not a good plan in this case since iterator stability is not guaranteed, I believe.</p>\n" }, { "answer_id": 180772, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 6, "selected": false, "text": "<p>A variation of Mark Ransom algorithm but without the need for a temporary.</p>\n\n<pre><code>for(Actions::iterator it = _actions.begin();it != _actions.end();)\n{\n if (expired(*it))\n {\n bar(*it);\n _actions.erase(it++); // Note the post increment here.\n // This increments 'it' and returns a copy of\n // the original 'it' to be used by erase()\n }\n else\n {\n ++it; // Use Pre-Increment here as it is more effecient\n // Because no copy of it is required.\n }\n}\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
I have roughly the following code. Could this be made nicer or more efficient? Perhaps using `std::remove_if`? Can you remove items from the map while traversing it? Can we avoid using the temporary map? ``` typedef std::map<Action, What> Actions; static Actions _actions; bool expired(const Actions::value_type &action) { return <something>; } void bar(const Actions::value_type &action) { // do some stuff } void foo() { // loop the actions finding expired items Actions actions; BOOST_FOREACH(Actions::value_type &action, _actions) { if (expired(action)) bar(action); else actions[action.first]=action.second; } } actions.swap(_actions); } ```
You could use erase(), but I don't know how BOOST\_FOREACH will handle the invalidated iterator. The [documentation for map::erase](http://en.cppreference.com/w/cpp/container/map/erase) states that only the erased iterator will be invalidated, the others should be OK. Here's how I would restructure the inner loop: ``` Actions::iterator it = _actions.begin(); while (it != _actions.end()) { if (expired(*it)) { bar(*it); Actions::iterator toerase = it; ++it; _actions.erase(toerase); } else ++it; } ```
180,518
<p>I've just discovered that Oracle lets you do the following:</p> <pre><code>SELECT foo.a, (SELECT c FROM bar WHERE foo.a = bar.a) from foo </code></pre> <p>As long as only one row in bar matches any row in foo.</p> <p>The explain plan I get from PL/SQL developer is this:</p> <pre><code>SELECT STATEMENT, GOAL = ALL_ROWS TABLE ACCESS FULL BAR TABLE ACCESS FULL FOO </code></pre> <p>This doesn't actually specify how the tables are joined. A colleague asserted that this is more efficient than doing a regular join. Is that true? What is the join strategy on such a select statement, and why doesn't it show up in the explain plan?</p> <p>Thanks.</p>
[ { "answer_id": 180588, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 3, "selected": true, "text": "<p>The plan you have there does not provide much information at all. </p>\n\n<p>Use SQL*Plus and use dbms_xplan to get a more detailed plan. Look for a script called utlxpls.sql.</p>\n\n<p>This gives a bit more information:-</p>\n\n<pre><code>--------------------------------------------------------------------------\n| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |\n--------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 1837 | 23881 | 3 (0)| 00:00:01 |\n|* 1 | TABLE ACCESS FULL| BAR | 18 | 468 | 2 (0)| 00:00:01 |\n| 2 | TABLE ACCESS FULL| FOO | 1837 | 23881 | 3 (0)| 00:00:01 |\n--------------------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n\n 1 - filter(\"BAR\".\"A\"=:B1)\n\nNote\n-----\n - dynamic sampling used for this statement\n\n18 rows selected.\n</code></pre>\n\n<p>I didn't create any indexes or foreign keys or collect statistics on the tables, which would change the plan and the join mechanism choosen. Oracle is actually doing a NESTED LOOPS type join here. Step 1, your inline sub-select, is performed for every row returned from FOO.</p>\n\n<p>This way of performing a SELECT is not quicker. It could be the same or slower. In general try and join everything in the main WHERE clause unless it becomes horribly unreadable.</p>\n" }, { "answer_id": 180913, "author": "Andrew not the Saint", "author_id": 23670, "author_profile": "https://Stackoverflow.com/users/23670", "pm_score": 2, "selected": false, "text": "<p>If you create a normal index on bar(a) the CBO should be able to use, but I'm pretty sure that it won't be able to do hash joins. These kind of queries only make sense if you're using an aggregate function and you got multiple single-row subqueries in your top SELECT. Even so, you can always rewrite the query as:</p>\n\n<pre><code>SELECT foo.a, bar1.c, pub1.d\nFROM foo\nJOIN (SELECT a, MIN(c) as c\n FROM bar\n GROUP BY a) bar1\n ON foo.a = bar1.a\nJOIN (SELECT a, MAX(d) as d\n FROM pub\n GROUP BY a) pub1\n ON foo.a = pub1.a\n</code></pre>\n\n<p>This would enable the CBO to use more options, while at the same time it would enable you to easily retrieve multiple columns from the child tables without having to scan the same tables multiple times.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15962/" ]
I've just discovered that Oracle lets you do the following: ``` SELECT foo.a, (SELECT c FROM bar WHERE foo.a = bar.a) from foo ``` As long as only one row in bar matches any row in foo. The explain plan I get from PL/SQL developer is this: ``` SELECT STATEMENT, GOAL = ALL_ROWS TABLE ACCESS FULL BAR TABLE ACCESS FULL FOO ``` This doesn't actually specify how the tables are joined. A colleague asserted that this is more efficient than doing a regular join. Is that true? What is the join strategy on such a select statement, and why doesn't it show up in the explain plan? Thanks.
The plan you have there does not provide much information at all. Use SQL\*Plus and use dbms\_xplan to get a more detailed plan. Look for a script called utlxpls.sql. This gives a bit more information:- ``` -------------------------------------------------------------------------- | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | -------------------------------------------------------------------------- | 0 | SELECT STATEMENT | | 1837 | 23881 | 3 (0)| 00:00:01 | |* 1 | TABLE ACCESS FULL| BAR | 18 | 468 | 2 (0)| 00:00:01 | | 2 | TABLE ACCESS FULL| FOO | 1837 | 23881 | 3 (0)| 00:00:01 | -------------------------------------------------------------------------- Predicate Information (identified by operation id): --------------------------------------------------- 1 - filter("BAR"."A"=:B1) Note ----- - dynamic sampling used for this statement 18 rows selected. ``` I didn't create any indexes or foreign keys or collect statistics on the tables, which would change the plan and the join mechanism choosen. Oracle is actually doing a NESTED LOOPS type join here. Step 1, your inline sub-select, is performed for every row returned from FOO. This way of performing a SELECT is not quicker. It could be the same or slower. In general try and join everything in the main WHERE clause unless it becomes horribly unreadable.
180,563
<p>I'd like to bold the text for a tab page under certain conditions (not, necessarily, GotFocus). Is it true the only 'er easiest way to do this is by overriding the DrawItem event for the tab control?</p> <p><a href="http://www.vbforums.com/showthread.php?t=355093" rel="noreferrer">http://www.vbforums.com/showthread.php?t=355093</a></p> <p>It seems like there should be an easier way. </p> <p>Like ...</p> <p><code> tabControl.TabPages(index).Font = New Font(Me.Font, FontStyle.Bold) </code></p> <p>That doesn't work, obviously.</p>
[ { "answer_id": 180637, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 3, "selected": false, "text": "<p>When you set the Font property on a TabPage, you are setting the default font for all controls on that tab page. You are not setting it for the header, however.</p>\n\n<p>When you execute the following code:</p>\n\n<pre><code>tabControl.TabPages(index).Font = New Font(Me.Font, FontStyle.Bold)\n</code></pre>\n\n<p>Any controls on that page will now be bold by default, which is not (I'm assuming) what you want.</p>\n\n<p>The header's font (that is, the tab itself) is controlled by the TabControl's Font property. If you were to change your code to:</p>\n\n<pre><code>tabControl.Font = New Font(Me.Font, FontStyle.Bold)\n</code></pre>\n\n<p>You will see that in action. However, it changes the font for <strong>all</strong> the tabs on display, which is also not, I'm assuming, what you want.</p>\n\n<p>So, using the default WinForms tab control, you are (I believe) limited to the technique in the link you've posted. Alternatively, you can begin looking at 3rd-party controls, such as those discussed in <a href=\"https://stackoverflow.com/questions/162413/what-is-the-best-commercial-3rd-party-control-library-out-right-now#162463\">these</a> <a href=\"https://stackoverflow.com/questions/178661/recommended-c-winform-controls-packs#178671\">questions</a> on <a href=\"https://stackoverflow.com/questions/169357/net-usercontrols-telerik-devexpress-infragistics-componentone-whos-best#170227\">StackOverflow</a>.</p>\n" }, { "answer_id": 184122, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>An easy way to give tab controls different labels depending on a field value is to change the caption itself:</p>\n\n<p>For example:</p>\n\n<pre><code>Private Sub Form_Current()\n If IsNull(Me.Subform.Form.Field_Name) Then\n Me.Tab_Name.Caption = \"Tab One\"\n Else\n Me.Tab_Name.Caption = \"Tab One +++\"\n End If\nEnd Sub\n</code></pre>\n" }, { "answer_id": 4945845, "author": "aceregid", "author_id": 609849, "author_profile": "https://Stackoverflow.com/users/609849", "pm_score": 1, "selected": false, "text": "<pre class=\"lang-cs prettyprint-override\"><code>private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)\n{\n Font BoldFont = new Font(tabControl1.Font, FontStyle.Bold);\n e.Graphics.DrawString(tabControl1.TabPages[e.Index].Text, BoldFont, Brushes.Black, e.Bounds);\n}\n\nprivate void Form1_Paint(object sender, PaintEventArgs e)\n{\n tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed;\n}\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81/" ]
I'd like to bold the text for a tab page under certain conditions (not, necessarily, GotFocus). Is it true the only 'er easiest way to do this is by overriding the DrawItem event for the tab control? <http://www.vbforums.com/showthread.php?t=355093> It seems like there should be an easier way. Like ... `tabControl.TabPages(index).Font = New Font(Me.Font, FontStyle.Bold)` That doesn't work, obviously.
When you set the Font property on a TabPage, you are setting the default font for all controls on that tab page. You are not setting it for the header, however. When you execute the following code: ``` tabControl.TabPages(index).Font = New Font(Me.Font, FontStyle.Bold) ``` Any controls on that page will now be bold by default, which is not (I'm assuming) what you want. The header's font (that is, the tab itself) is controlled by the TabControl's Font property. If you were to change your code to: ``` tabControl.Font = New Font(Me.Font, FontStyle.Bold) ``` You will see that in action. However, it changes the font for **all** the tabs on display, which is also not, I'm assuming, what you want. So, using the default WinForms tab control, you are (I believe) limited to the technique in the link you've posted. Alternatively, you can begin looking at 3rd-party controls, such as those discussed in [these](https://stackoverflow.com/questions/162413/what-is-the-best-commercial-3rd-party-control-library-out-right-now#162463) [questions](https://stackoverflow.com/questions/178661/recommended-c-winform-controls-packs#178671) on [StackOverflow](https://stackoverflow.com/questions/169357/net-usercontrols-telerik-devexpress-infragistics-componentone-whos-best#170227).
180,572
<p>My situation is as follows:</p> <p>I have a normalized database, in which I hold geographic information about airports. The structure is:</p> <pre><code>airport --is in--&gt; city --is in--&gt; country --is in--&gt; continent </code></pre> <p>Now I want to let users administrate this data, without giving them direct access to the database. We need to offer this administration interface via a web service.</p> <p>Now, when it comes to designing the service, we ran into the discussion about how to define the operations. We came up with different solutions:</p> <p><strong>Solution A: specific operations</strong></p> <p>For each of the four tables (airport, city, country, continent) we define 3 operations:</p> <ul> <li>insert</li> <li>get</li> <li>update</li> </ul> <p>This would lead to 12 operations with 2 request/response objects = 24 objects</p> <p>To create an all new airport with all dependencies, at least 4 requests would be necessary.</p> <p><strong>Solution B: generic</strong></p> <p>There is only one operation, which is controlled via parameters. This operation is capable of creating everything needed to administer the database.</p> <p>The operation would decide what needs to be done and executes it. If an error occures, it will roll back everything.</p> <p>==> 1 Operation = 2 highly complex request/response-objects</p> <p><strong>Solution C: Meet in the middle 1</strong></p> <p>One generic operation per table, which is capable of executing get, insert, update, just like solution B, but focused on one table each.</p> <p>==> 4 operations = 8 complex request/response-objects</p> <p><strong>Solution D: Meet in the middle 2</strong></p> <p>One generic operation per action (get, insert, delete), which can work on each table and resolve dependencies.</p> <p>==> 3 operations = 6 slightly more complex request/response-objects</p> <p><strong>Example</strong></p> <p>Since this was rather abstract, hier a simplified example for request-objects for creating (JFK/New York/USA/North America):</p> <p><strong>Solution A:</strong></p> <p>Request 1/4:</p> <pre><code>&lt;insertContinent&gt;North America&lt;/insertContinent&gt; </code></pre> <p>Request 2/4:</p> <pre><code>&lt;insertCountry continent="North America"&gt;USA&lt;/insertCountry&gt; </code></pre> <p>Request 3/4:</p> <pre><code>&lt;insertCity country="USA"&gt;New York&lt;/insertCity&gt; </code></pre> <p>Request 4/4:</p> <pre><code>&lt;insertAirport city="New York"&gt;JFK&lt;/insertAirport&gt; </code></pre> <p><strong>Solution B:</strong></p> <p>Request 1/1:</p> <pre><code>&lt;action type="insertCountry" parent="North America"&gt;USA&lt;/action&gt; &lt;action type="insertAirport" parent="New York"&gt;JFK&lt;/action&gt; &lt;action type="insertContinent" parent=""&gt;North America&lt;/action&gt; &lt;action type="insertCity" parent="USA"&gt;New York&lt;/action&gt; </code></pre> <p><strong>Solution C:</strong></p> <p>Request 1/4:</p> <pre><code>&lt;countryAction type="insert" parent="North America"&gt;USA&lt;/countryAction&gt; </code></pre> <p>Request 2/4:</p> <pre><code>&lt;airportAction type="insert" parent="New York"&gt;JFK&lt;/airportAction&gt; </code></pre> <p>Request 3/4:</p> <pre><code>&lt;continentAction type="insert" parent=""&gt;North America&lt;/continentAction &gt; </code></pre> <p>Request 4/4:</p> <pre><code>&lt;cityAction type="insert" parent="USA"&gt;New York&lt;/cityAction &gt; </code></pre> <p><strong>Solution D:</strong> Request 1/1:</p> <pre><code>&lt;insert airport="JFK" city="New York" country="USA" continent="North America" /&gt; </code></pre> <p>Solution D seems rather elegant for me, therefore I tried to put this in XSD:</p> <p>Code:</p> <pre><code>&lt;complexType name="NewContinent"&gt; &lt;sequence&gt; &lt;element name="NAME" type="string"&gt;&lt;/element&gt; &lt;/sequence&gt; &lt;/complexType&gt; &lt;complexType name="NewCountry"&gt; &lt;sequence&gt; &lt;element name="ISOCODE" type="string"&gt;&lt;/element&gt; &lt;element name="NAME" type="string"&gt;&lt;/element&gt; &lt;choice&gt; &lt;element name="newCONTINENT" type="tns:NewContinent"&gt;&lt;/element&gt; &lt;element name="CONTINENT" type="string"&gt;&lt;/element&gt; &lt;/choice&gt; &lt;/sequence&gt; &lt;/complexType&gt; &lt;complexType name="NewCity"&gt; &lt;sequence&gt; &lt;element name="IATA" type="string"&gt;&lt;/element&gt; &lt;element name="NAME" type="string"&gt;&lt;/element&gt; &lt;choice&gt; &lt;element name="COUNTRY" type="string"&gt;&lt;/element&gt; &lt;element name="newCOUNTRY" type="tns:NewCountry"&gt;&lt;/element&gt; &lt;/choice&gt; &lt;/sequence&gt; &lt;/complexType&gt; &lt;complexType name="NewAirport"&gt; &lt;sequence&gt; &lt;element name="IATA" type="string"&gt;&lt;/element&gt; &lt;element name="NAME" type="string"&gt;&lt;/element&gt; &lt;choice&gt; &lt;element name="CITY" type="string"&gt;&lt;/element&gt; &lt;element name="newCITY" type="tns:NewCity"&gt;&lt;/element&gt; &lt;/choice&gt; &lt;/sequence&gt; &lt;/complexType&gt; </code></pre> <p>A corresponding request would then look like follows:</p> <pre><code>&lt;complexType name="Request"&gt; &lt;choice&gt; &lt;element name="AIRPORT" type="tns:NewAirport"&gt;&lt;/element&gt; &lt;element name="CITY" type="tns:NewCity"&gt;&lt;/element&gt; &lt;element name="COUNTRY" type="tns:NewCountry"&gt;&lt;/element&gt; &lt;element name="CONTINENT" type="tns:NewContinent"&gt;&lt;/element&gt; &lt;/choice&gt; &lt;/complexType&gt; </code></pre> <p>Now my question: <strong>Is this really the best solution available? Is the XSD enough to understand, what is going on?</strong></p>
[ { "answer_id": 184512, "author": "Ed Greaves", "author_id": 26262, "author_profile": "https://Stackoverflow.com/users/26262", "pm_score": 4, "selected": true, "text": "<p>Presumably you are writing a protocol layer that will understand your different message types. You will also need an application layer to parse the contents of the message. The different approaches you mention will shift the burden of parsing between these two layers. So for example:</p>\n\n<p><strong>Solution A</strong>: The protocol layer does all the parsing and returns the data and command. The application layer can just use the data. This is also known as the RPC pattern.</p>\n\n<p>Pros: You can validate your messages. You can map messages directly to application calls.</p>\n\n<p>Cons: If you need to make a change to the interface, your protocol changes.</p>\n\n<p><strong>Solution B</strong>: The protocol layer returns two values and a command. The application layer must use the command to parse the values into types.</p>\n\n<p>Pros: The protocol never changes.</p>\n\n<p>Cons: You can't validate messages. Your application code is more complicated.</p>\n\n<p><strong>Solution C</strong>: The protocol layer returns two known types and an command that must be parsed. The application layer can just parse the command and use the data.</p>\n\n<p>Pros: I can't think of any, seems like not a very good compromise.</p>\n\n<p>Cons: Leaves the parsing only partially done.</p>\n\n<p><strong>Solution D</strong>: The protocol layer returns known types (the way you implemented it) and a generic command. The application layer must look at the data it receives and convert the generic command into a specific command. This is similar to the REST architecture.</p>\n\n<p>Pros: Calls are distinct operations so that you could for example cache get responses.</p>\n\n<p>Cons: Complexity in the application layer</p>\n\n<p>The REST model is usually implemented differently than you have outlined. It uses HTTP GET, POST, PUT, DELETE messages to communicate arbitrary documents. Parameters are given as part of the URL. So for example:</p>\n\n<pre><code>&lt;insert airport=\"JFK\" city=\"New York\" country=\"USA\" continent=\"North America\" /&gt;\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>&lt;insert URL=\"airport?city=Chicago\"&gt;ORD&lt;/insert&gt;\n</code></pre>\n\n<p>Or if you are using HTTP it becomes a POST request to an airport URL with a param of the city with the contents being information about the airport. Note that some of this becomes clearer with more compliated data where you have multiple elements and mixed types. For example if you wanted to send the airport abbreviation, long name, and altitude.</p>\n\n<p>I think the REST architecture could work quite well for the interface you describe. As long as all you need to do is support the CRUD operations. The are many sites that will give you the pros and cons of the REST architectural style.</p>\n\n<p>Personally I prefer the RPC style (Solution A) with some REST-ful attributes. I want the protocol to do the parsing work and validate the messages. This is typically how people implement SOAP web service interfaces.</p>\n\n<p>Your interface may look simple today but tomorrow one of your customers is going to ask you for a new call that doesn't fit the REST model so well and you'll find yourself wedging it into the existing four messages.</p>\n" }, { "answer_id": 3272477, "author": "DougWebb", "author_id": 73475, "author_profile": "https://Stackoverflow.com/users/73475", "pm_score": 1, "selected": false, "text": "<p>This is an old question, and I'm sure the service has been written a long time ago, but I wanted to contribute an answer anyway.</p>\n\n<p>The RESTful approach would be to define an airport resource, such as this:</p>\n\n<pre><code>&lt;airport href=\"/airports/JFK\"&gt;\n &lt;name&gt;JFK&lt;/name&gt;\n &lt;city&gt;New York&lt;/city&gt;\n &lt;country&gt;USA&lt;/country&gt;\n &lt;continent&gt;North America&lt;/continent&gt;\n&lt;/airport&gt;\n</code></pre>\n\n<p>Or, if you want to use a browser-compatible microformat:</p>\n\n<pre><code>&lt;div class=\"object airport\" href=\"/airports/JFK\"&gt;\n &lt;ul class=\"attributes\"&gt; \n &lt;li class=\"name\"&gt;JFK&lt;/li&gt;\n &lt;li class=\"city\"&gt;New York&lt;/li&gt;\n &lt;li class=\"country\"&gt;USA&lt;/li&gt;\n &lt;li class=\"continent\"&gt;North America&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>This resource would be located at a URI like <code>/airports/JFK</code>, which would be retrieved with a <code>GET</code> method, updated with a <code>PUT</code> method, and deleted with a <code>DELETE</code> method.</p>\n\n<p>In a design like this, the URI <code>/airports/</code> would represent a container resource for all of the airports in the database, and URIs like <code>/airports/?city=New+York</code> and <code>/airports/?country=USA</code> would be filters on the container to return a subset of the airports. Both of these would be <code>GET</code> methods, and the resources would contain a list of airport resources as defined above, either in full (since they're small) or with a few useful attributes and the <code>href</code> that points to the full resource for each airport.</p>\n\n<p>Finally, adding a new resource could either be a <code>PUT</code> method on the airport's full URI, or a <code>POST</code> method on <code>/airports/</code>. In both cases the body of the request is the airport resource as shown above. The difference between the methods is who gets to decide the final URI for the airport: the client decides for <code>PUT</code> and the service decides for <code>POST</code>. Which one you use depends upon whether or not your clients can reasonably determine the right URI. Usually the service decides because the URIs contain a numeric unique identifier and the service has to choose that.</p>\n\n<p>Now of course your original question was about SOAP, not REST. I would go ahead and set up a RESTful design as I've described, then describe my resources as complex types using XSD and a SOAP service with actions that duplicate the <code>GET</code>, <code>PUT</code>, <code>DELETE</code>, and <code>POST</code> operations of the RESTful service. This will give you the RPC equivalent of:</p>\n\n<pre><code>class Airport\n has String name\n has String city\n has String country\n has String continent\n method void update(name, city, country, continent)\n method void delete()\n\nclass AirportList\n method Airport[] get(opt name, opt city, opt country, opt continent)\n method void add(name, city, country, continent)\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25253/" ]
My situation is as follows: I have a normalized database, in which I hold geographic information about airports. The structure is: ``` airport --is in--> city --is in--> country --is in--> continent ``` Now I want to let users administrate this data, without giving them direct access to the database. We need to offer this administration interface via a web service. Now, when it comes to designing the service, we ran into the discussion about how to define the operations. We came up with different solutions: **Solution A: specific operations** For each of the four tables (airport, city, country, continent) we define 3 operations: * insert * get * update This would lead to 12 operations with 2 request/response objects = 24 objects To create an all new airport with all dependencies, at least 4 requests would be necessary. **Solution B: generic** There is only one operation, which is controlled via parameters. This operation is capable of creating everything needed to administer the database. The operation would decide what needs to be done and executes it. If an error occures, it will roll back everything. ==> 1 Operation = 2 highly complex request/response-objects **Solution C: Meet in the middle 1** One generic operation per table, which is capable of executing get, insert, update, just like solution B, but focused on one table each. ==> 4 operations = 8 complex request/response-objects **Solution D: Meet in the middle 2** One generic operation per action (get, insert, delete), which can work on each table and resolve dependencies. ==> 3 operations = 6 slightly more complex request/response-objects **Example** Since this was rather abstract, hier a simplified example for request-objects for creating (JFK/New York/USA/North America): **Solution A:** Request 1/4: ``` <insertContinent>North America</insertContinent> ``` Request 2/4: ``` <insertCountry continent="North America">USA</insertCountry> ``` Request 3/4: ``` <insertCity country="USA">New York</insertCity> ``` Request 4/4: ``` <insertAirport city="New York">JFK</insertAirport> ``` **Solution B:** Request 1/1: ``` <action type="insertCountry" parent="North America">USA</action> <action type="insertAirport" parent="New York">JFK</action> <action type="insertContinent" parent="">North America</action> <action type="insertCity" parent="USA">New York</action> ``` **Solution C:** Request 1/4: ``` <countryAction type="insert" parent="North America">USA</countryAction> ``` Request 2/4: ``` <airportAction type="insert" parent="New York">JFK</airportAction> ``` Request 3/4: ``` <continentAction type="insert" parent="">North America</continentAction > ``` Request 4/4: ``` <cityAction type="insert" parent="USA">New York</cityAction > ``` **Solution D:** Request 1/1: ``` <insert airport="JFK" city="New York" country="USA" continent="North America" /> ``` Solution D seems rather elegant for me, therefore I tried to put this in XSD: Code: ``` <complexType name="NewContinent"> <sequence> <element name="NAME" type="string"></element> </sequence> </complexType> <complexType name="NewCountry"> <sequence> <element name="ISOCODE" type="string"></element> <element name="NAME" type="string"></element> <choice> <element name="newCONTINENT" type="tns:NewContinent"></element> <element name="CONTINENT" type="string"></element> </choice> </sequence> </complexType> <complexType name="NewCity"> <sequence> <element name="IATA" type="string"></element> <element name="NAME" type="string"></element> <choice> <element name="COUNTRY" type="string"></element> <element name="newCOUNTRY" type="tns:NewCountry"></element> </choice> </sequence> </complexType> <complexType name="NewAirport"> <sequence> <element name="IATA" type="string"></element> <element name="NAME" type="string"></element> <choice> <element name="CITY" type="string"></element> <element name="newCITY" type="tns:NewCity"></element> </choice> </sequence> </complexType> ``` A corresponding request would then look like follows: ``` <complexType name="Request"> <choice> <element name="AIRPORT" type="tns:NewAirport"></element> <element name="CITY" type="tns:NewCity"></element> <element name="COUNTRY" type="tns:NewCountry"></element> <element name="CONTINENT" type="tns:NewContinent"></element> </choice> </complexType> ``` Now my question: **Is this really the best solution available? Is the XSD enough to understand, what is going on?**
Presumably you are writing a protocol layer that will understand your different message types. You will also need an application layer to parse the contents of the message. The different approaches you mention will shift the burden of parsing between these two layers. So for example: **Solution A**: The protocol layer does all the parsing and returns the data and command. The application layer can just use the data. This is also known as the RPC pattern. Pros: You can validate your messages. You can map messages directly to application calls. Cons: If you need to make a change to the interface, your protocol changes. **Solution B**: The protocol layer returns two values and a command. The application layer must use the command to parse the values into types. Pros: The protocol never changes. Cons: You can't validate messages. Your application code is more complicated. **Solution C**: The protocol layer returns two known types and an command that must be parsed. The application layer can just parse the command and use the data. Pros: I can't think of any, seems like not a very good compromise. Cons: Leaves the parsing only partially done. **Solution D**: The protocol layer returns known types (the way you implemented it) and a generic command. The application layer must look at the data it receives and convert the generic command into a specific command. This is similar to the REST architecture. Pros: Calls are distinct operations so that you could for example cache get responses. Cons: Complexity in the application layer The REST model is usually implemented differently than you have outlined. It uses HTTP GET, POST, PUT, DELETE messages to communicate arbitrary documents. Parameters are given as part of the URL. So for example: ``` <insert airport="JFK" city="New York" country="USA" continent="North America" /> ``` becomes ``` <insert URL="airport?city=Chicago">ORD</insert> ``` Or if you are using HTTP it becomes a POST request to an airport URL with a param of the city with the contents being information about the airport. Note that some of this becomes clearer with more compliated data where you have multiple elements and mixed types. For example if you wanted to send the airport abbreviation, long name, and altitude. I think the REST architecture could work quite well for the interface you describe. As long as all you need to do is support the CRUD operations. The are many sites that will give you the pros and cons of the REST architectural style. Personally I prefer the RPC style (Solution A) with some REST-ful attributes. I want the protocol to do the parsing work and validate the messages. This is typically how people implement SOAP web service interfaces. Your interface may look simple today but tomorrow one of your customers is going to ask you for a new call that doesn't fit the REST model so well and you'll find yourself wedging it into the existing four messages.
180,601
<p>My style of coding includes the following idiom:</p> <pre><code>class Derived : public Base { public : typedef Base super; // note that it could be hidden in // protected/private section, instead // Etc. } ; </code></pre> <p>This enables me to use &quot;super&quot; as an alias to Base, for example, in constructors:</p> <pre><code>Derived(int i, int j) : super(i), J(j) { } </code></pre> <p>Or even when calling the method from the base class inside its overridden version:</p> <pre><code>void Derived::foo() { super::foo() ; // ... And then, do something else } </code></pre> <p>It can even be chained (I have still to find the use for that, though):</p> <pre><code>class DerivedDerived : public Derived { public : typedef Derived super; // note that it could be hidden in // protected/private section, instead // Etc. } ; void DerivedDerived::bar() { super::bar() ; // will call Derived::bar super::super::bar ; // will call Base::bar // ... And then, do something else } </code></pre> <p>Anyway, I find the use of &quot;typedef super&quot; very useful, for example, when Base is either verbose and/or templated.</p> <p>The fact is that super is implemented in Java, as well as in C# (where it is called &quot;base&quot;, unless I'm wrong). But C++ lacks this keyword.</p> <p>So, my questions:</p> <ul> <li>is this use of typedef super common/rare/never seen in the code you work with?</li> <li>is this use of typedef super Ok (i.e. do you see strong or not so strong reasons to not use it)?</li> <li>should &quot;super&quot; be a good thing, should it be somewhat standardized in C++, or is this use through a typedef enough already?</li> </ul> <p><b>Edit:</b> Roddy mentionned the fact the typedef should be private. This would mean any derived class would not be able to use it without redeclaring it. But I guess it would also prevent the super::super chaining (but who's gonna cry for that?).</p> <p><b>Edit 2:</b> Now, some months after massively using &quot;super&quot;, I wholeheartedly agree with Roddy's viewpoint: &quot;super&quot; should be private.</p>
[ { "answer_id": 180613, "author": "James Hopkin", "author_id": 11828, "author_profile": "https://Stackoverflow.com/users/11828", "pm_score": 2, "selected": false, "text": "<p>I've quite often seen it used, sometimes as super_t, when the base is a complex template type (<code>boost::iterator_adaptor</code> does this, for example)</p>\n" }, { "answer_id": 180614, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 4, "selected": false, "text": "<p>I don't recall seeing this before, but at first glance I like it. As <a href=\"https://stackoverflow.com/questions/180601/using-super-in-c#180607\">Ferruccio</a> notes, it doesn't work well in the face of MI, but MI is more the exception than the rule and there's nothing that says something needs to be usable everywhere to be useful.</p>\n" }, { "answer_id": 180618, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 1, "selected": false, "text": "<p>I don't know whether it's rare or not, but I've certainly done the same thing.</p>\n\n<p>As has been pointed out, the difficulty with making this part of the language itself is when a class makes use of multiple inheritance.</p>\n" }, { "answer_id": 180620, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>After migrating from Turbo Pascal to C++ back in the day, I used to do this in order to have an equivalent for the Turbo Pascal \"inherited\" keyword, which works the same way. However, after programming in C++ for a few years I stopped doing it. I found I just didn't need it very much.</p>\n" }, { "answer_id": 180623, "author": "Scott Langham", "author_id": 11898, "author_profile": "https://Stackoverflow.com/users/11898", "pm_score": 1, "selected": false, "text": "<p>I use this from time to time. Just when I find myself typing out the base class type a couple of times, I'll replace it with a typedef similar to yours.</p>\n\n<p>I think it can be a good use. As you say, if your base class is a template it can save typing. Also, template classes may take arguments that act as policies for how the template should work. You're free to change the base type without having to fix up all your references to it as long as the interface of the base remains compatible.</p>\n\n<p>I think the use through the typedef is enough already. I can't see how it would be built into the language anyway because multiple inheritence means there can be many base classes, so you can typedef it as you see fit for the class you logically feel is the most important base class.</p>\n" }, { "answer_id": 180627, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 5, "selected": false, "text": "<p>One problem with this is that if you forget to (re-)define super for derived classes, then any call to super::something will compile fine but will probably not call the desired function.</p>\n\n<p>For example:</p>\n\n<pre><code>class Base\n{\npublic: virtual void foo() { ... }\n};\n\nclass Derived: public Base\n{\npublic:\n typedef Base super;\n virtual void foo()\n {\n super::foo(); // call superclass implementation\n\n // do other stuff\n ...\n }\n};\n\nclass DerivedAgain: public Derived\n{\npublic:\n virtual void foo()\n {\n // Call superclass function\n super::foo(); // oops, calls Base::foo() rather than Derived::foo()\n\n ...\n }\n};\n</code></pre>\n\n<p>(As pointed out by Martin York in the comments to this answer, this problem can be eliminated by making the typedef private rather than public or protected.)</p>\n" }, { "answer_id": 180628, "author": "Toji", "author_id": 25968, "author_profile": "https://Stackoverflow.com/users/25968", "pm_score": 2, "selected": false, "text": "<p><em>is this use of typedef super common/rare/never seen in the code you work with?</em></p>\n\n<p>I have never seen this particular pattern in the C++ code I work with, but that doesn't mean it's not out there.</p>\n\n<p><em>is this use of typedef super Ok (i.e. do you see strong or not so strong reasons to not use it)?</em></p>\n\n<p>It doesn't allow for multiple inheritance (cleanly, anyway).</p>\n\n<p><em>should \"super\" be a good thing, should it be somewhat standardized in C++, or is this use through a typedef enough already?</em></p>\n\n<p>For the above cited reason (multiple inheritance), no. The reason why you see \"super\" in the other languages you listed is that they only support single inheritance, so there is no confusion as to what \"super\" is referring to. Granted, in those languages it IS useful but it doesn't really have a place in the C++ data model.</p>\n\n<p>Oh, and FYI: C++/CLI supports this concept in the form of the \"__super\" keyword. Please note, though, that C++/CLI doesn't support multiple inheritance either.</p>\n" }, { "answer_id": 180633, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 8, "selected": true, "text": "<p>Bjarne Stroustrup mentions in <em>Design and Evolution of C++</em> that <code>super</code> as a keyword was considered by the ISO C++ Standards committee the first time C++ was standardized.</p>\n\n<p>Dag Bruck proposed this extension, calling the base class \"inherited.\" The proposal mentioned the multiple inheritance issue, and would have flagged ambiguous uses. Even Stroustrup was convinced.</p>\n\n<p>After discussion, Dag Bruck (yes, the same person making the proposal) wrote that the proposal was implementable, technically sound, and free of major flaws, and handled multiple inheritance. On the other hand, there wasn't enough bang for the buck, and the committee should handle a thornier problem.</p>\n\n<p>Michael Tiemann arrived late, and then showed that a typedef'ed super would work just fine, using the same technique that was asked about in this post.</p>\n\n<p>So, no, this will probably never get standardized.</p>\n\n<p>If you don't have a copy, <em>Design and Evolution</em> is well worth the cover price. Used copies can be had for about $10.</p>\n" }, { "answer_id": 180634, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 7, "selected": false, "text": "<p>I've always used \"inherited\" rather than super. (Probably due to a Delphi background), and I always make it <strong>private</strong>, to avoid the problem when the 'inherited' is erroneously omitted from a class but a subclass tries to use it.</p>\n\n<pre><code>class MyClass : public MyBase\n{\nprivate: // Prevents erroneous use by other classes.\n typedef MyBase inherited;\n...\n</code></pre>\n\n<p>My standard 'code template' for creating new classes includes the typedef, so I have little opportunity to accidentally omit it.</p>\n\n<p>I don't think the chained \"super::super\" suggestion is a good idea- If you're doing that, you're probably tied in very hard to a particular hierarchy, and changing it will likely break stuff badly.</p>\n" }, { "answer_id": 180635, "author": "Colin Jensen", "author_id": 9884, "author_profile": "https://Stackoverflow.com/users/9884", "pm_score": 4, "selected": false, "text": "<p>Super (or inherited) is Very Good Thing because if you need to stick another inheritance layer in between Base and Derived, you only have to change two things: 1. the \"class Base: foo\" and 2. the typedef</p>\n\n<p>If I recall correctly, the C++ Standards committee was considering adding a keyword for this... until Michael Tiemann pointed out that this typedef trick works.</p>\n\n<p>As for multiple inheritance, since it's under programmer control you can do whatever you want: maybe super1 and super2, or whatever.</p>\n" }, { "answer_id": 180685, "author": "jdkoftinoff", "author_id": 32198, "author_profile": "https://Stackoverflow.com/users/32198", "pm_score": 2, "selected": false, "text": "<p>One additional reason to use a typedef for the superclass is when you are using complex templates in the object's inheritance.</p>\n\n<p>For instance:</p>\n\n<pre><code>template &lt;typename T, size_t C, typename U&gt;\nclass A\n{ ... };\n\ntemplate &lt;typename T&gt;\nclass B : public A&lt;T,99,T&gt;\n{ ... };\n</code></pre>\n\n<p>In class B it would be ideal to have a typedef for A otherwise you would be stuck repeating it everywhere you wanted to reference A's members.</p>\n\n<p>In these cases it can work with multiple inheritance too, but you wouldn't have a typedef named 'super', it would be called 'base_A_t' or something like that.</p>\n\n<p>--jeffk++</p>\n" }, { "answer_id": 180747, "author": "krujos", "author_id": 511, "author_profile": "https://Stackoverflow.com/users/511", "pm_score": 5, "selected": false, "text": "<p>FWIW Microsoft has added an extension for <a href=\"http://msdn.microsoft.com/en-us/library/94dw1w7x(VS.80).aspx\" rel=\"noreferrer\">__super</a> in their compiler. </p>\n" }, { "answer_id": 181911, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 1, "selected": false, "text": "<p>I use the __super keyword. But it's Microsoft specific:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/94dw1w7x.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/94dw1w7x.aspx</a></p>\n" }, { "answer_id": 181917, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<p>I've seen this idiom employed in many code bases and I'm pretty sure I've even seen it somewhere in Boost's libraries. However, as far as I remember the most common name is <code>base</code> (or <code>Base</code>) instead of <code>super</code>.</p>\n<p>This idiom is especially useful if working with class templates. As an example, consider the following class (from a <a href=\"http://www.seqan.de/\" rel=\"nofollow noreferrer\">real project</a>):</p>\n<pre><code>template &lt;typename TText, typename TSpec&gt;\nclass Finder&lt;Index&lt;TText, PizzaChili&lt;TSpec&gt;&gt;, MyFinderType&gt;\n : public Finder&lt;Index&lt;TText, MyFinderImpl&lt;TSpec&gt;&gt;, Default&gt;\n{\n using TBase = Finder&lt;Index&lt;TText, MyFinderImpl&lt;TSpec&gt;&gt;, Default&gt;;\n // …\n}\n</code></pre>\n<p>The inheritance chain uses type arguments to achieve compile-time polymorphism. Unfortunately, the nesting level of these templates gets quite high. Therefore, meaningful abbreviations for the full type names are crucial for readability and maintainability.</p>\n" }, { "answer_id": 5622694, "author": "paperjam", "author_id": 674683, "author_profile": "https://Stackoverflow.com/users/674683", "pm_score": 4, "selected": false, "text": "<p>I just found an alternate workaround. I have a big problem with the typedef approach which bit me today:</p>\n\n<ul>\n<li>The typedef requires an exact copy of the class name. If someone changes the class name but doesn't change the typedef then you will run into problems.</li>\n</ul>\n\n<p>So I came up with a better solution using a very simple template.</p>\n\n<pre><code>template &lt;class C&gt;\nstruct MakeAlias : C\n{ \n typedef C BaseAlias;\n};\n</code></pre>\n\n<p>So now, instead of</p>\n\n<pre><code>class Derived : public Base\n{\nprivate:\n typedef Base Super;\n};\n</code></pre>\n\n<p>you have</p>\n\n<pre><code>class Derived : public MakeAlias&lt;Base&gt;\n{\n // Can refer to Base as BaseAlias here\n};\n</code></pre>\n\n<p>In this case, <code>BaseAlias</code> is not private and I've tried to guard against careless usage by selecting an type name that should alert other developers.</p>\n" }, { "answer_id": 31618380, "author": "Kevin", "author_id": 2972004, "author_profile": "https://Stackoverflow.com/users/2972004", "pm_score": 2, "selected": false, "text": "<p>I was trying to solve this exact same problem; I threw around a few ideas, such as using variadic templates and pack expansion to allow for an arbitrary number of parents, but I realized that would result in an implementation like 'super0' and 'super1'. I trashed it because that would be barely more useful than not having it to begin with.</p>\n\n<p>My Solution involves a helper class <code>PrimaryParent</code> and is implemented as so:</p>\n\n<pre><code>template&lt;typename BaseClass&gt;\nclass PrimaryParent : virtual public BaseClass\n{\nprotected:\n using super = BaseClass;\npublic:\n template&lt;typename ...ArgTypes&gt;\n PrimaryParent&lt;BaseClass&gt;(ArgTypes... args) : BaseClass(args...){}\n}\n</code></pre>\n\n<p>Then which ever class you want to use would be declared as such:</p>\n\n<pre><code>class MyObject : public PrimaryParent&lt;SomeBaseClass&gt;\n{\npublic:\n MyObject() : PrimaryParent&lt;SomeBaseClass&gt;(SomeParams) {}\n}\n</code></pre>\n\n<p>To avoid the need to use virtual inheritance in <code>PrimaryParent</code>on <code>BaseClass</code>, a constructor taking a variable number of arguments is used to allow construction of <code>BaseClass</code>.</p>\n\n<p>The reason behind the <code>public</code> inheritance of <code>BaseClass</code> into <code>PrimaryParent</code> is to let <code>MyObject</code> have full control over over the inheritance of <code>BaseClass</code> despite having a helper class between them.</p>\n\n<p>This does mean that every class you want to have <code>super</code> must use the <code>PrimaryParent</code> helper class, and each child may only inherit from one class using <code>PrimaryParent</code> (hence the name).</p>\n\n<p>Another restriction for this method, is <code>MyObject</code> can inherit only one class which inherits from <code>PrimaryParent</code>, and that one must be inherited using <code>PrimaryParent</code>. Here is what I mean:</p>\n\n<pre><code>class SomeOtherBase : public PrimaryParent&lt;Ancestor&gt;{}\n\nclass MixinClass {}\n\n//Good\nclass BaseClass : public PrimaryParent&lt;SomeOtherBase&gt;, public MixinClass\n{}\n\n\n//Not Good (now 'super' is ambiguous)\nclass MyObject : public PrimaryParent&lt;BaseClass&gt;, public SomeOtherBase{}\n\n//Also Not Good ('super' is again ambiguous)\nclass MyObject : public PrimaryParent&lt;BaseClass&gt;, public PrimaryParent&lt;SomeOtherBase&gt;{}\n</code></pre>\n\n<p>Before you discard this as an option because of the seeming number of restrictions and the fact there is a middle-man class between every inheritance, these things are not bad.</p>\n\n<p>Multiple inheritance is a strong tool, but in most circumstances, there will be only one primary parent, and if there are other parents, they likely will be Mixin classes, or classes which don't inherit from <code>PrimaryParent</code> anyways. If multiple inheritance is still necessary (though many situations would benefit to use composition to define an object instead of inheritance), than just explicitly define <code>super</code> in that class and don't inherit from <code>PrimaryParent</code>.</p>\n\n<p>The idea of having to define <code>super</code> in every class is not very appealing to me, using <code>PrimaryParent</code> allows for <code>super</code>, clearly an inheritence based alias, to stay in the class definition line instead of the class body where the data should go.</p>\n\n<p>That might just be me though.</p>\n\n<p>Of course every situation is different, but consider these things i have said when deciding which option to use.</p>\n" }, { "answer_id": 35420894, "author": "Zhro", "author_id": 1762276, "author_profile": "https://Stackoverflow.com/users/1762276", "pm_score": 0, "selected": false, "text": "<p>This is a method I use which uses macros instead of a typedef. I know that this is not the C++ way of doing things but it can be convenient when chaining iterators together through inheritance when only the base class furthest down the hierarchy is acting upon an inherited offset.</p>\n\n<p>For example:</p>\n\n<pre><code>// some header.h\n\n#define CLASS some_iterator\n#define SUPER_CLASS some_const_iterator\n#define SUPER static_cast&lt;SUPER_CLASS&amp;&gt;(*this)\n\ntemplate&lt;typename T&gt;\nclass CLASS : SUPER_CLASS {\n typedef CLASS&lt;T&gt; class_type;\n\n class_type&amp; operator++();\n};\n\ntemplate&lt;typename T&gt;\ntypename CLASS&lt;T&gt;::class_type CLASS&lt;T&gt;::operator++(\n int)\n{\n class_type copy = *this;\n\n // Macro\n ++SUPER;\n\n // vs\n\n // Typedef\n // super::operator++();\n\n return copy;\n}\n\n#undef CLASS\n#undef SUPER_CLASS\n#undef SUPER\n</code></pre>\n\n<p>The generic setup I use makes it very easy to read and copy/paste between the inheritance tree which have duplicate code but must be overridden because the return type has to match the current class.</p>\n\n<p>One could use a lower-case <code>super</code> to replicate the behavior seen in Java but my coding style is to use all upper-case letters for macros.</p>\n" }, { "answer_id": 61619711, "author": "metablaster", "author_id": 12091999, "author_profile": "https://Stackoverflow.com/users/12091999", "pm_score": 1, "selected": false, "text": "<p>I won't say much except present code with comments that demonstrates that super doesn't mean calling base!</p>\n\n<p><code>super != base.</code></p>\n\n<p>In short, what is \"super\" supposed to mean anyway? and then what is \"base\" supposed to mean?</p>\n\n<ol>\n<li>super means, calling the last implementor of a method (not base method)</li>\n<li>base means, choosing which class is default base in multiple inheritance.</li>\n</ol>\n\n<p>This 2 rules apply to in class typedefs.</p>\n\n<p>Consider library implementor and library user, who is super and who is base?</p>\n\n<p>for more info here is working code for copy paste into your IDE:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\n// Library defiens 4 classes in typical library class hierarchy\nclass Abstract\n{\npublic:\n virtual void f() = 0;\n};\n\nclass LibraryBase1 :\n virtual public Abstract\n{\npublic:\n void f() override\n {\n std::cout &lt;&lt; \"Base1\" &lt;&lt; std::endl;\n }\n};\n\nclass LibraryBase2 :\n virtual public Abstract\n{\npublic:\n void f() override\n {\n std::cout &lt;&lt; \"Base2\" &lt;&lt; std::endl;\n }\n};\n\nclass LibraryDerivate :\n public LibraryBase1,\n public LibraryBase2\n{\n // base is meaningfull only for this class,\n // this class decides who is my base in multiple inheritance\nprivate:\n using base = LibraryBase1;\n\nprotected:\n // this is super! base is not super but base!\n using super = LibraryDerivate;\n\npublic:\n void f() override\n {\n std::cout &lt;&lt; \"I'm super not my Base\" &lt;&lt; std::endl;\n std::cout &lt;&lt; \"Calling my *default* base: \" &lt;&lt; std::endl;\n base::f();\n }\n};\n\n// Library user\nstruct UserBase :\n public LibraryDerivate\n{\nprotected:\n // NOTE: If user overrides f() he must update who is super, in one class before base!\n using super = UserBase; // this typedef is needed only so that most derived version\n // is called, which calls next super in hierarchy.\n // it's not needed here, just saying how to chain \"super\" calls if needed\n\n // NOTE: User can't call base, base is a concept private to each class, super is not.\nprivate:\n using base = LibraryDerivate; // example of typedefing base.\n\n};\n\nstruct UserDerived :\n public UserBase\n{\n // NOTE: to typedef who is super here we would need to specify full name\n // when calling super method, but in this sample is it's not needed.\n\n // Good super is called, example of good super is last implementor of f()\n // example of bad super is calling base (but which base??)\n void f() override\n {\n super::f();\n }\n};\n\nint main()\n{\n UserDerived derived;\n // derived calls super implementation because that's what\n // \"super\" is supposed to mean! super != base\n derived.f();\n\n // Yes it work with polymorphism!\n Abstract* pUser = new LibraryDerivate;\n pUser-&gt;f();\n\n Abstract* pUserBase = new UserBase;\n pUserBase-&gt;f();\n}\n</code></pre>\n\n<p>Another important point here is this:</p>\n\n<ol>\n<li>polymorphic call: calls downward</li>\n<li>super call: calls upwards</li>\n</ol>\n\n<p>inside <code>main()</code> we use polymorphic call downards that super calls upwards, not really useful in real life, but it demonstrates the difference.</p>\n" }, { "answer_id": 70501970, "author": "I am not englishman", "author_id": 8208357, "author_profile": "https://Stackoverflow.com/users/8208357", "pm_score": 1, "selected": false, "text": "<p>The simple answer why c++ doesn't support &quot;super&quot; keyword is.</p>\n<p>DDD(Deadly Diamond of Death) problem.</p>\n<p>in multiple inheritance. Compiler will confuse which is superclass.</p>\n<p><a href=\"https://i.stack.imgur.com/IvleG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IvleG.png\" alt=\"enter image description here\" /></a></p>\n<p>So which superclass is &quot;D&quot;'s superclass?? &quot;Both&quot; cannot be solution because &quot;super&quot; keyword is pointer.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14089/" ]
My style of coding includes the following idiom: ``` class Derived : public Base { public : typedef Base super; // note that it could be hidden in // protected/private section, instead // Etc. } ; ``` This enables me to use "super" as an alias to Base, for example, in constructors: ``` Derived(int i, int j) : super(i), J(j) { } ``` Or even when calling the method from the base class inside its overridden version: ``` void Derived::foo() { super::foo() ; // ... And then, do something else } ``` It can even be chained (I have still to find the use for that, though): ``` class DerivedDerived : public Derived { public : typedef Derived super; // note that it could be hidden in // protected/private section, instead // Etc. } ; void DerivedDerived::bar() { super::bar() ; // will call Derived::bar super::super::bar ; // will call Base::bar // ... And then, do something else } ``` Anyway, I find the use of "typedef super" very useful, for example, when Base is either verbose and/or templated. The fact is that super is implemented in Java, as well as in C# (where it is called "base", unless I'm wrong). But C++ lacks this keyword. So, my questions: * is this use of typedef super common/rare/never seen in the code you work with? * is this use of typedef super Ok (i.e. do you see strong or not so strong reasons to not use it)? * should "super" be a good thing, should it be somewhat standardized in C++, or is this use through a typedef enough already? **Edit:** Roddy mentionned the fact the typedef should be private. This would mean any derived class would not be able to use it without redeclaring it. But I guess it would also prevent the super::super chaining (but who's gonna cry for that?). **Edit 2:** Now, some months after massively using "super", I wholeheartedly agree with Roddy's viewpoint: "super" should be private.
Bjarne Stroustrup mentions in *Design and Evolution of C++* that `super` as a keyword was considered by the ISO C++ Standards committee the first time C++ was standardized. Dag Bruck proposed this extension, calling the base class "inherited." The proposal mentioned the multiple inheritance issue, and would have flagged ambiguous uses. Even Stroustrup was convinced. After discussion, Dag Bruck (yes, the same person making the proposal) wrote that the proposal was implementable, technically sound, and free of major flaws, and handled multiple inheritance. On the other hand, there wasn't enough bang for the buck, and the committee should handle a thornier problem. Michael Tiemann arrived late, and then showed that a typedef'ed super would work just fine, using the same technique that was asked about in this post. So, no, this will probably never get standardized. If you don't have a copy, *Design and Evolution* is well worth the cover price. Used copies can be had for about $10.
180,606
<p>I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?</p>
[ { "answer_id": 180615, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 8, "selected": true, "text": "<p>You are probably looking for 'chr()':</p>\n\n<pre><code>&gt;&gt;&gt; L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]\n&gt;&gt;&gt; ''.join(chr(i) for i in L)\n'hello, world'\n</code></pre>\n" }, { "answer_id": 180617, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 3, "selected": false, "text": "<pre><code>l = [83, 84, 65, 67, 75]\n\ns = \"\".join([chr(c) for c in l])\n\nprint s\n</code></pre>\n" }, { "answer_id": 181057, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Same basic solution as others, but I personally prefer to use map instead of the list comprehension:</p>\n\n<pre><code>\n>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]\n>>> ''.join(map(chr,L))\n'hello, world'\n</code></pre>\n" }, { "answer_id": 184708, "author": "Toni Ruža", "author_id": 6267, "author_profile": "https://Stackoverflow.com/users/6267", "pm_score": 4, "selected": false, "text": "<pre><code>import array\ndef f7(list):\n return array.array('B', list).tostring()\n</code></pre>\n\n<p>from <a href=\"http://www.python.org/doc/essays/list2str.html\" rel=\"noreferrer\">Python Patterns - An Optimization Anecdote</a></p>\n" }, { "answer_id": 31800289, "author": "ptsivakumar", "author_id": 878403, "author_profile": "https://Stackoverflow.com/users/878403", "pm_score": 2, "selected": false, "text": "<pre><code>def working_ascii():\n \"\"\"\n G r e e t i n g s !\n 71, 114, 101, 101, 116, 105, 110, 103, 115, 33\n \"\"\"\n\n hello = [71, 114, 101, 101, 116, 105, 110, 103, 115, 33]\n pmsg = ''.join(chr(i) for i in hello)\n print(pmsg)\n\n for i in range(33, 256):\n print(\" ascii: {0} char: {1}\".format(i, chr(i)))\n\nworking_ascii()\n</code></pre>\n" }, { "answer_id": 34246694, "author": "David White", "author_id": 5396645, "author_profile": "https://Stackoverflow.com/users/5396645", "pm_score": 3, "selected": false, "text": "<p>Perhaps not as Pyhtonic a solution, but easier to read for noobs like me:</p>\n\n<pre><code>charlist = [34, 38, 49, 67, 89, 45, 103, 105, 119, 125]\nmystring = \"\"\nfor char in charlist:\n mystring = mystring + chr(char)\nprint mystring\n</code></pre>\n" }, { "answer_id": 53691464, "author": "Idan Rakovsky", "author_id": 10766457, "author_profile": "https://Stackoverflow.com/users/10766457", "pm_score": 0, "selected": false, "text": "<pre><code>Question = [67, 121, 98, 101, 114, 71, 105, 114, 108, 122]\nprint(''.join(chr(number) for number in Question))\n</code></pre>\n" }, { "answer_id": 55509509, "author": "Timo Herngreen", "author_id": 8810830, "author_profile": "https://Stackoverflow.com/users/8810830", "pm_score": 3, "selected": false, "text": "<p>You can use <code>bytes(list).decode()</code> to do this - and <code>list(string.encode())</code> to get the values back.</p>\n" }, { "answer_id": 61790880, "author": "user13528444", "author_id": 13528444, "author_profile": "https://Stackoverflow.com/users/13528444", "pm_score": 1, "selected": false, "text": "<p>I've timed the existing answers. Code to reproduce is below. TLDR is that <code>bytes(seq).decode()</code> is by far the fastest. Results here:</p>\n\n<pre><code> test_bytes_decode : 12.8046 μs/rep\n test_join_map : 62.1697 μs/rep\ntest_array_library : 63.7088 μs/rep\n test_join_list : 112.021 μs/rep\ntest_join_iterator : 171.331 μs/rep\n test_naive_add : 286.632 μs/rep\n</code></pre>\n\n<p>Setup was CPython 3.8.2 (32-bit), Windows 10, i7-2600 3.4GHz</p>\n\n<p>Interesting observations:</p>\n\n<ul>\n<li>The \"official\" fastest answer (as reposted by Toni Ruža) is now out of date for Python 3, but once fixed is still basically tied for second place</li>\n<li>Joining a mapped sequence is almost twice as fast as a list comprehension</li>\n<li>The list comprehension is faster than its non-list counterpart</li>\n</ul>\n\n<p>Code to reproduce is here:</p>\n\n<pre><code>import array, string, timeit, random\nfrom collections import namedtuple\n\n# Thomas Wouters (https://stackoverflow.com/a/180615/13528444)\ndef test_join_iterator(seq):\n return ''.join(chr(c) for c in seq)\n\n# community wiki (https://stackoverflow.com/a/181057/13528444)\ndef test_join_map(seq):\n return ''.join(map(chr, seq))\n\n# Thomas Vander Stichele (https://stackoverflow.com/a/180617/13528444)\ndef test_join_list(seq):\n return ''.join([chr(c) for c in seq])\n\n# Toni Ruža (https://stackoverflow.com/a/184708/13528444)\n# Also from https://www.python.org/doc/essays/list2str/\ndef test_array_library(seq):\n return array.array('b', seq).tobytes().decode() # Updated from tostring() for Python 3\n\n# David White (https://stackoverflow.com/a/34246694/13528444)\ndef test_naive_add(seq):\n output = ''\n for c in seq:\n output += chr(c)\n return output\n\n# Timo Herngreen (https://stackoverflow.com/a/55509509/13528444)\ndef test_bytes_decode(seq):\n return bytes(seq).decode()\n\nRESULT = ''.join(random.choices(string.printable, None, k=1000))\nINT_SEQ = [ord(c) for c in RESULT]\nREPS=10000\n\nif __name__ == '__main__':\n tests = {\n name: test\n for (name, test) in globals().items()\n if name.startswith('test_')\n }\n\n Result = namedtuple('Result', ['name', 'passed', 'time', 'reps'])\n results = [\n Result(\n name=name,\n passed=test(INT_SEQ) == RESULT,\n time=timeit.Timer(\n stmt=f'{name}(INT_SEQ)',\n setup=f'from __main__ import INT_SEQ, {name}'\n ).timeit(REPS) / REPS,\n reps=REPS)\n for name, test in tests.items()\n ]\n results.sort(key=lambda r: r.time if r.passed else float('inf'))\n\n def seconds_per_rep(secs):\n (unit, amount) = (\n ('s', secs) if secs &gt; 1\n else ('ms', secs * 10 ** 3) if secs &gt; (10 ** -3)\n else ('μs', secs * 10 ** 6) if secs &gt; (10 ** -6)\n else ('ns', secs * 10 ** 9))\n return f'{amount:.6} {unit}/rep'\n\n max_name_length = max(len(name) for name in tests)\n for r in results:\n print(\n r.name.rjust(max_name_length),\n ':',\n 'failed' if not r.passed else seconds_per_rep(r.time))\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ]
I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?
You are probably looking for 'chr()': ``` >>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100] >>> ''.join(chr(i) for i in L) 'hello, world' ```
180,624
<p>I'm developing a solution which uses an ActiveX control (a commercial one which we bought and that I did not develop). I need to develop the proper installation pages to simulate what happens when a user who has never visited the site and does not have the add-on installed comes to the page.</p> <p>I've found the "Manage Add-Ons" bit in Internet Options and I'm not having any luck.</p> <p>In IE7, I see an ability to enable or disable any control and a "Delete ActiveX" option, but it's disabled for this particular control.</p> <p>In IE8 Beta 2, the "Manage Add-Ons" bit has been completely reworked and I no longer see an option to delete the control. Each control has a "Properties" dialog and I can "Remove" it, but the button doesn't appear to do anything (could be related to how "Delete ActiveX" doesn't work for this on in IE7).</p> <p>It looks like maybe this control is installed in such a way that merely deleting it from IE won't work or isn't allowed, but it's not a control with its own entry on the Add/Remove Programs menu in XP, so I can't uninstall it that way either.</p> <p>How can I delete/remove (not disable) this ActiveX control in IE so that I can simulate what happens when people come to the site and the ActiveX control hasn't been installed yet? I figure there must be a way to "purge" IE of it.</p>
[ { "answer_id": 180640, "author": "dummy", "author_id": 6297, "author_profile": "https://Stackoverflow.com/users/6297", "pm_score": 4, "selected": true, "text": "<p>You could unregister the control with</p>\n\n<pre><code>regsvr32 /u badboy.ocx\n</code></pre>\n\n<p>at the command line. Though i would suggest testing these things in a vmware.</p>\n" }, { "answer_id": 1670996, "author": "naedyr", "author_id": 202212, "author_profile": "https://Stackoverflow.com/users/202212", "pm_score": -1, "selected": false, "text": "<p>Tools > Manage Add-ons, right click \"Name\" header and enable the \"In Folder\" section. go to the directory for the plugin you're interested in. Right click the plugin file, and click \"remove\".</p>\n" }, { "answer_id": 1671007, "author": "Gabriel Magana", "author_id": 99455, "author_profile": "https://Stackoverflow.com/users/99455", "pm_score": 0, "selected": false, "text": "<p>Use a virtual machine. Start fresh as often as you want, and stop doing these hacks that may or may not simulate a clean machine.</p>\n\n<p>Seriously, use VMWare or VirtualPC.</p>\n" }, { "answer_id": 3672392, "author": "user442893", "author_id": 442893, "author_profile": "https://Stackoverflow.com/users/442893", "pm_score": 3, "selected": false, "text": "<p>Internet options-->General Tab-->browsing History section.... click settings and then click \"View objects\". A list of your active X add on's are displayed in the windows folder that they are stored in. You can manipulate these files as you would any others. Simply delete the ones you want to uninstall and restart IE.</p>\n" }, { "answer_id": 6219480, "author": "CKYHC", "author_id": 781749, "author_profile": "https://Stackoverflow.com/users/781749", "pm_score": 1, "selected": false, "text": "<p>Actually the \"Remote\" option in Configuration Menu for Plug-In works by me (Win7 64, ie8 with all updates), however:</p>\n\n<ol>\n<li>You need administrator rights</li>\n<li>The plug-in should be disabled before pressing the remove button</li>\n<li>You need restart internet-explorer to see the changes.</li>\n</ol>\n\n<p>Also the previous comment about browsing-history->view objects was also useful if plug-in was installed right now.</p>\n\n<p>Regards!</p>\n" }, { "answer_id": 6303168, "author": "Prasi", "author_id": 792300, "author_profile": "https://Stackoverflow.com/users/792300", "pm_score": -1, "selected": false, "text": "<p>You can go to <code>IE Tools -&gt; Internet options -&gt; Advanced Tab</code>. Under Advanced, check for security and put a check on the 1st 2 options which says,\"Allow active content from CDs to run on My Computer* and Allow active content to run in files on My Computer*\"</p>\n\n<p>Restart your browser and the ActiveX scripts will not be shown.</p>\n" }, { "answer_id": 10216271, "author": "Warren Rox", "author_id": 1130151, "author_profile": "https://Stackoverflow.com/users/1130151", "pm_score": 3, "selected": false, "text": "<p>Close all browsers and tabs to ensure that the ActiveX control is not reside in memory. Open a fresh IE9 browser. Select Tools->Manage Add-ons. Change the drop down to \"All add-ons\" since the default only shows ones that are loaded.</p>\n\n<p>Now select the add-on you wish to remove. There will be a link displayed on the lower left that says \"More information\". Click it.</p>\n\n<p>This opens a further dialog that allows you to safely un-install the ActiveX control.</p>\n\n<p>If you follow the direction of manually running the 'regsvr32' to remove the OCX it is not sufficient. ActiveX controls are wrapped up as signed CAB files and they extract to multiple DLLs and OCXs potentially. You wish to use IE to safely and correctly unregister every COM DLL and OCX.</p>\n\n<p>There you have it! The problem is that in IE 9 it is somewhat hidden since you have to click the \"More information\" whereas IE8 you could do it from the same UI.</p>\n" }, { "answer_id": 16472089, "author": "functionoid", "author_id": 1827461, "author_profile": "https://Stackoverflow.com/users/1827461", "pm_score": 1, "selected": false, "text": "<p>Start -> Control Panel -> Programs and Features, search for the Add-ons you would like to uninstall and click on particular one to uninstall.</p>\n\n<p>Yes, I tried uninstalling from IE, Tools -> Manage Add-ons and then click \"More Information\" link at the bottom, however the \"Remove\" button was disabled. This didn't work.</p>\n\n<p>Above mentioned solution for uninstalling from \"Programs and Features\" works.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ]
I'm developing a solution which uses an ActiveX control (a commercial one which we bought and that I did not develop). I need to develop the proper installation pages to simulate what happens when a user who has never visited the site and does not have the add-on installed comes to the page. I've found the "Manage Add-Ons" bit in Internet Options and I'm not having any luck. In IE7, I see an ability to enable or disable any control and a "Delete ActiveX" option, but it's disabled for this particular control. In IE8 Beta 2, the "Manage Add-Ons" bit has been completely reworked and I no longer see an option to delete the control. Each control has a "Properties" dialog and I can "Remove" it, but the button doesn't appear to do anything (could be related to how "Delete ActiveX" doesn't work for this on in IE7). It looks like maybe this control is installed in such a way that merely deleting it from IE won't work or isn't allowed, but it's not a control with its own entry on the Add/Remove Programs menu in XP, so I can't uninstall it that way either. How can I delete/remove (not disable) this ActiveX control in IE so that I can simulate what happens when people come to the site and the ActiveX control hasn't been installed yet? I figure there must be a way to "purge" IE of it.
You could unregister the control with ``` regsvr32 /u badboy.ocx ``` at the command line. Though i would suggest testing these things in a vmware.
180,626
<p>I am hosting a service within a Windows Service. </p> <p>The following snippet instantiates the ServiceHost object:</p> <pre><code>Host = new ServiceHost(typeof(Services.DocumentInfoService)); </code></pre> <p>The DocumentInfoService class implements a contract interface that has methods that invoke business objects requiring initialization (actually a connection string). Ideally, I'd like the hosting process to get the connection string from the config file and pass it to a constructor for my service object, DocumentInfoService, which would hold onto it and use it to pass to business objects as needed.</p> <p>However, the ServiceHost constructor takes a System.Type object -- so instances of DocumentInfoService are created via the default constructor. I did note that there is another constructor method for ServiceHost that takes an object instance -- but the docs indicate that is for use with singletons.</p> <p>Is there a way for me to get to my object after it is constructed so that I can pass it some initialization data?</p>
[ { "answer_id": 180645, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>Implement your own <code>ServiceHost</code>. See also <a href=\"http://hyperthink.net/blog/servicehostfactory-vs-servicehostfactorybase/\" rel=\"nofollow noreferrer\">http://hyperthink.net/blog/servicehostfactory-vs-servicehostfactorybase/</a></p>\n" }, { "answer_id": 180739, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 3, "selected": true, "text": "<p>ServiceHost will create the service instances based on the binding and behaviors configured for the endpoint. There's no particular point in time, where you can rely there is a service instance. Hence, ServiceHost does not expose the service instances.</p>\n\n<p>What you could do is add code to your service object constructor to read the relevant configuration values itself through the <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx\" rel=\"nofollow noreferrer\">ConfigurationManager</a> class.</p>\n\n<p>Of course, if you don't keep your configuration in the app.config, that won't work for you. Alternative approach would be to have a well-known singleton object that the service instances access when created to get the necessary configuration.</p>\n\n<p>And there's also the option of creating your own ServiceHost or your own ServiceHostFactory to control the service instantiation explicitly. This would give you acess to the new service instances at the moment of creation. I would stay away from that option though. It's not worth the effort for your scenario.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7961/" ]
I am hosting a service within a Windows Service. The following snippet instantiates the ServiceHost object: ``` Host = new ServiceHost(typeof(Services.DocumentInfoService)); ``` The DocumentInfoService class implements a contract interface that has methods that invoke business objects requiring initialization (actually a connection string). Ideally, I'd like the hosting process to get the connection string from the config file and pass it to a constructor for my service object, DocumentInfoService, which would hold onto it and use it to pass to business objects as needed. However, the ServiceHost constructor takes a System.Type object -- so instances of DocumentInfoService are created via the default constructor. I did note that there is another constructor method for ServiceHost that takes an object instance -- but the docs indicate that is for use with singletons. Is there a way for me to get to my object after it is constructed so that I can pass it some initialization data?
ServiceHost will create the service instances based on the binding and behaviors configured for the endpoint. There's no particular point in time, where you can rely there is a service instance. Hence, ServiceHost does not expose the service instances. What you could do is add code to your service object constructor to read the relevant configuration values itself through the [ConfigurationManager](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx) class. Of course, if you don't keep your configuration in the app.config, that won't work for you. Alternative approach would be to have a well-known singleton object that the service instances access when created to get the necessary configuration. And there's also the option of creating your own ServiceHost or your own ServiceHostFactory to control the service instantiation explicitly. This would give you acess to the new service instances at the moment of creation. I would stay away from that option though. It's not worth the effort for your scenario.
180,647
<p>I am hoping to find a resource for lining up input elements in a HTML page. I find it difficult to get a select element and a text box to be the same width even when using the width style attribute, and it is even more difficult across browsers. Finally, file inputs seem impossible to get to the same width cross browser. Are there any good guides or tips for accomplishing this? Perhaps there are some default CSS attributes I should be setting.</p>
[ { "answer_id": 180656, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 4, "selected": false, "text": "<p>I usually put them inside a div or table cell (horrors! I know) of the width I want, then set the select and input style:width to 100% so they fill the div / cell they are in.</p>\n" }, { "answer_id": 180659, "author": "Dave Rutledge", "author_id": 2486915, "author_profile": "https://Stackoverflow.com/users/2486915", "pm_score": 0, "selected": false, "text": "<p>Do you start your CSS files with some base settings? It may be useful to turn padding and margin off on all elements. I haven't tested to see if this could be affecting select / input elements.</p>\n\n<p>Here's an example CSS Reset from Eric Meyer:</p>\n\n<p><a href=\"http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/\" rel=\"nofollow noreferrer\">http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/</a></p>\n" }, { "answer_id": 180660, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 1, "selected": false, "text": "<p>Other than width, I'd be setting border and margin too, these may or may not influence your controls. Something like this may help:</p>\n\n<pre><code>input, select {\n width: 100px;\n margin: 0px;\n border: 1px solid;\n}\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/180647/how-to-line-up-html-input-elements#180656\">Ron</a> has a good idea too.</p>\n" }, { "answer_id": 180879, "author": "mmacaulay", "author_id": 22152, "author_profile": "https://Stackoverflow.com/users/22152", "pm_score": 0, "selected": false, "text": "<p>File inputs can be fundamentally different across browsers and definitely don't allow much in the way of customization, which can be annoying, but I also understand why that is from a security perspective. For example, try changing the text of the \"browse\" button that appears on most browsers, or compare the file input on Safari to other browsers...</p>\n" }, { "answer_id": 181523, "author": "cowgod", "author_id": 6406, "author_profile": "https://Stackoverflow.com/users/6406", "pm_score": 5, "selected": true, "text": "<p>I tested this out in Internet Explorer 7, Firefox 3 and Safari/Google Chrome. I definitely see the problem with <code>&lt;select&gt;</code> and <code>&lt;input type=\"file\"&gt;</code>. My findings showed that if you styled all the inputs at the same width, the <code>&lt;select&gt;</code> would be about 5 pixels shorter in all browsers.</p>\n\n<p>Using the <a href=\"http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/\" rel=\"nofollow noreferrer\">Eric Meyer CSS reset script</a> does not help this issue, however if you simply make your <code>&lt;select&gt;</code> inputs 5 pixels wider you'll get very good (albeit not perfect) alignment in the major browsers. The only one that differs is Safari/Google Chrome, and it appears to be 1 or 2 pixels wider than all the other browsers.</p>\n\n<p>As far as the <code>&lt;input type=\"file\"&gt;</code> is concerned, you don't have much flexibility with styling there. If JavaScript is an option for you, you can implement the method <a href=\"http://www.quirksmode.org/dom/inputfile.html\" rel=\"nofollow noreferrer\">shown on quirksmode</a> to achieve greater control over the styling of the file upload control.</p>\n\n<p>See my full working example below in XHTML 1.0 Strict for a typical form with consistent input widths. Note that this does not use the 100% width trick pointed out by others here because it has the same problem with inconsistent widths. Additionally there are no tables used to render the form as tables should only be used for tabular data and not layout.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\r\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"&gt;\r\n\r\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\r\n\r\n&lt;head&gt;\r\n &lt;title&gt;Example Form&lt;/title&gt;\r\n &lt;style type=\"text/css\"&gt;\r\n label,\r\n input,\r\n select,\r\n textarea {\r\n display: block;\r\n width: 200px;\r\n float: left;\r\n margin-bottom: 1em;\r\n }\r\n \r\n select {\r\n width: 205px;\r\n }\r\n \r\n label {\r\n text-align: right;\r\n width: 100px;\r\n padding-right: 2em;\r\n }\r\n \r\n .clear {\r\n clear: both;\r\n }\r\n &lt;/style&gt;\r\n&lt;/head&gt;\r\n\r\n&lt;body&gt;\r\n &lt;form action=\"#\"&gt;\r\n &lt;fieldset&gt;\r\n &lt;legend&gt;User Profile&lt;/legend&gt;\r\n &lt;label for=\"fname\"&gt;First Name&lt;/label&gt;\r\n &lt;input id=\"fname\" name=\"fname\" type=\"text\" /&gt;\r\n &lt;br class=\"clear\" /&gt;\r\n\r\n &lt;label for=\"lname\"&gt;Last Name&lt;/label&gt;\r\n &lt;input id=\"lname\" name=\"lname\" type=\"text\" /&gt;\r\n &lt;br class=\"clear\" /&gt;\r\n\r\n &lt;label for=\"fav_lang\"&gt;Favorite Language&lt;/label&gt;\r\n &lt;select id=\"fav_lang\" name=\"fav_lang\"&gt;\r\n &lt;option value=\"c#\"&gt;C#&lt;/option&gt;\r\n &lt;option value=\"java\"&gt;Java&lt;/option&gt;\r\n &lt;option value=\"ruby\"&gt;Ruby&lt;/option&gt;\r\n &lt;option value=\"python\"&gt;Python&lt;/option&gt;\r\n &lt;option value=\"perl\"&gt;Perl&lt;/option&gt;\r\n &lt;/select&gt;\r\n &lt;br class=\"clear\" /&gt;\r\n\r\n &lt;label for=\"bio\"&gt;Biography&lt;/label&gt;\r\n &lt;textarea id=\"bio\" name=\"bio\" cols=\"14\" rows=\"4\"&gt;&lt;/textarea&gt;\r\n &lt;br class=\"clear\" /&gt;\r\n &lt;/fieldset&gt;\r\n &lt;/form&gt;\r\n&lt;/body&gt;\r\n\r\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 1750099, "author": "AlfaTeK", "author_id": 43671, "author_profile": "https://Stackoverflow.com/users/43671", "pm_score": 0, "selected": false, "text": "<p>I don't think <a href=\"https://stackoverflow.com/questions/180647/how-to-line-up-html-input-elements#180656\">Ron's</a> idea works... </p>\n\n<p>test case:</p>\n\n<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n \"http://www.w3.org/TR/html4/loose.dtd\"&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;title&gt;&lt;/title&gt;\n &lt;link href=\"styles/reset.css\" rel=\"stylesheet\" type=\"text/css\"/&gt;\n\n &lt;style type=\"text/css\"&gt;\n input, select{\n width: 100%;\n }\n &lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n\n&lt;div style=\"width: 200px;\"&gt;\n &lt;input type=\"text\"&gt;\n &lt;select&gt;\n &lt;option&gt;asdasd&lt;/option&gt;\n &lt;option&gt;asdasd&lt;/option&gt;\n &lt;/select&gt;\n\n&lt;/div&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>This results in the input being some px wider than the select (this is probably OS-dependent). I'm not sure if this could be achieved, even with the +5px trick as the styling of the select seems to be OS (at least windows theme) dependent.</p>\n" }, { "answer_id": 7861529, "author": "Dalius", "author_id": 1008798, "author_profile": "https://Stackoverflow.com/users/1008798", "pm_score": 2, "selected": false, "text": "<p>I found that if you set <strong>select</strong> and <strong>input</strong> element border and padding to 0, they are same width. (Tested on Chrome 14, Firefox 7.0.1, Opera 11.51, IE 9)</p>\n\n<p>Putting 1px border/padding on select and input elements makes input element 2 pixels wider. For example:</p>\n\n<pre><code>&lt;form class=\"style\"&gt;\n &lt;input name=\"someInput\" /&gt;\n &lt;select name=\"options\"&gt;\n &lt;option value=\"1\"&gt;Value 1&lt;/option&gt;\n &lt;option value=\"2\"&gt;Value 2&lt;/option&gt;\n &lt;/select&gt;\n&lt;/form&gt;\n\n.style select {\n width: 100px;\n padding: 1px;\n border: 1px solid black;\n}\n.style input {\n width: 96px; /* -2 px for 1px padding(1px from each side) and -2px for border\n (select element seems to put border inside, not outside?) */\n padding: 1px;\n border: 1px solid black;\n}\n</code></pre>\n" }, { "answer_id": 9112877, "author": "Slawa", "author_id": 417153, "author_profile": "https://Stackoverflow.com/users/417153", "pm_score": 0, "selected": false, "text": "<p>If you desperately need { width: 100%; } and not specified with widths in pixels, then jQuery is your friend:</p>\n\n<pre><code>$(function () {\n var allSelects = $('input[type=\"text\"], textarea');\n allSelects.css('width', (allSelects.width()-6)+'px');\n}\n</code></pre>\n\n<p>-6 pixels works best for me (FF9), edit as you see fit.</p>\n" }, { "answer_id": 11011842, "author": "Jim", "author_id": 470206, "author_profile": "https://Stackoverflow.com/users/470206", "pm_score": 0, "selected": false, "text": "<p>This is because with an &lt;input&gt;, the border and padding is added on to the width (like with most other elements). With a &lt;select&gt;, the border and padding is included in the width, just like in the old IE quirks mode.</p>\n\n<p>You can get round this by increasing the width to take account of this:</p>\n\n<pre><code>input { width: 200px; padding: 10px; border-width:5px; }\nselect { width: 230px; padding: 10px; border-width:5px; }\n</code></pre>\n\n<p>Or (if you can rely on browser support) you can use the new CSS3 box-sizing property to make them behave consistently, and draw padding and border outside of the element width:</p>\n\n<pre><code>input, select {\n width: 200px;\n padding: 10px;\n border-width:5px;\n -webkit-box-sizing: content-box; /* Safari/Chrome, other WebKit */\n -moz-box-sizing: content-box; /* Firefox, other Gecko */\n box-sizing: content-box; /* Opera/IE 8+ */\n}\n</code></pre>\n\n<p>Alternatively, you can set box-sizing to border-box to make the inputs behave like the selects, with padding drawn inside the width of the box.</p>\n\n<p>Tested in Chrome, IE8, FF</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18926/" ]
I am hoping to find a resource for lining up input elements in a HTML page. I find it difficult to get a select element and a text box to be the same width even when using the width style attribute, and it is even more difficult across browsers. Finally, file inputs seem impossible to get to the same width cross browser. Are there any good guides or tips for accomplishing this? Perhaps there are some default CSS attributes I should be setting.
I tested this out in Internet Explorer 7, Firefox 3 and Safari/Google Chrome. I definitely see the problem with `<select>` and `<input type="file">`. My findings showed that if you styled all the inputs at the same width, the `<select>` would be about 5 pixels shorter in all browsers. Using the [Eric Meyer CSS reset script](http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/) does not help this issue, however if you simply make your `<select>` inputs 5 pixels wider you'll get very good (albeit not perfect) alignment in the major browsers. The only one that differs is Safari/Google Chrome, and it appears to be 1 or 2 pixels wider than all the other browsers. As far as the `<input type="file">` is concerned, you don't have much flexibility with styling there. If JavaScript is an option for you, you can implement the method [shown on quirksmode](http://www.quirksmode.org/dom/inputfile.html) to achieve greater control over the styling of the file upload control. See my full working example below in XHTML 1.0 Strict for a typical form with consistent input widths. Note that this does not use the 100% width trick pointed out by others here because it has the same problem with inconsistent widths. Additionally there are no tables used to render the form as tables should only be used for tabular data and not layout. ```html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Example Form</title> <style type="text/css"> label, input, select, textarea { display: block; width: 200px; float: left; margin-bottom: 1em; } select { width: 205px; } label { text-align: right; width: 100px; padding-right: 2em; } .clear { clear: both; } </style> </head> <body> <form action="#"> <fieldset> <legend>User Profile</legend> <label for="fname">First Name</label> <input id="fname" name="fname" type="text" /> <br class="clear" /> <label for="lname">Last Name</label> <input id="lname" name="lname" type="text" /> <br class="clear" /> <label for="fav_lang">Favorite Language</label> <select id="fav_lang" name="fav_lang"> <option value="c#">C#</option> <option value="java">Java</option> <option value="ruby">Ruby</option> <option value="python">Python</option> <option value="perl">Perl</option> </select> <br class="clear" /> <label for="bio">Biography</label> <textarea id="bio" name="bio" cols="14" rows="4"></textarea> <br class="clear" /> </fieldset> </form> </body> </html> ```
180,658
<p>When 'val' below is not a <code>bool</code> I get an exception, I believe I can use <code>TryParse</code> but I'm not sure how best to use it with my code below. Can anyone help?</p> <pre><code>checkBox.Checked = Convert.ToBoolean(val); </code></pre> <p>Thanks</p>
[ { "answer_id": 180663, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 4, "selected": false, "text": "<p>The code is as follows to determine whether the string <code>val</code> is a valid Boolean value and use it to set the <code>Checked</code> property if so. You need to decide what action you would take if it does not represent a valid value.</p>\n\n<pre><code>bool result;\nif (bool.TryParse(val, out result))\n{\n // val does represent a Boolean\n checkBox.Checked = result;\n}\nelse\n{\n // val does not represent a Boolean\n}\n</code></pre>\n" }, { "answer_id": 180665, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 3, "selected": false, "text": "<p>Assuming that if its not a valid boolean, you don't want it checked:</p>\n\n<pre><code>bool result = false;\nbool.TryParse(val, out result);\ncheckBox.Checked = result;\n</code></pre>\n" }, { "answer_id": 180666, "author": "Yes - that Jake.", "author_id": 5287, "author_profile": "https://Stackoverflow.com/users/5287", "pm_score": 1, "selected": false, "text": "<pre><code>bool z = false;\nif(Boolean.TryParse(val, out z))\n{\n checkBox.Checked = z;\n}\n</code></pre>\n\n<p>Just a note: Parse and convert are different operations and may lead to different results.</p>\n" }, { "answer_id": 180672, "author": "Mesh", "author_id": 15710, "author_profile": "https://Stackoverflow.com/users/15710", "pm_score": 0, "selected": false, "text": "<p>bool isBool = false;</p>\n\n<p>bool.TryParse( val, ref isBool );<br /></p>\n\n<pre><code>if( isBool ) \n{\n ///ok;\n\n}\nelse\n{\n // fail;\n}\n</code></pre>\n" }, { "answer_id": 180677, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 0, "selected": false, "text": "<p>Well it depends; if you want checkBox.Checked to be equal to true if val - if it is a string - parses to true then use the following:-</p>\n\n<pre><code>bool output;\ncheckBox.Checked = bool.TryParse(val, out output) &amp;&amp; output;\n</code></pre>\n\n<p>If bool is not a string then you need to decide how to deal with it depending on its type, e.g.:-</p>\n\n<pre><code>checkBox.Checked = val != 0; \n</code></pre>\n\n<p>etc.</p>\n" }, { "answer_id": 184276, "author": "pezi_pink_squirrel", "author_id": 24757, "author_profile": "https://Stackoverflow.com/users/24757", "pm_score": 0, "selected": false, "text": "<p>Good answers here already.</p>\n\n<p>I will however add, do be careful with TryParse, because contrary to what its name indicates, it can infact still throw an ArgumentException!</p>\n\n<p>That's one of my pet annoyances with .NET! :)</p>\n" }, { "answer_id": 4511177, "author": "mkamoski", "author_id": 348907, "author_profile": "https://Stackoverflow.com/users/348907", "pm_score": 0, "selected": false, "text": "<p>FWIW, the following may also come in handy in this (or similar) cases...</p>\n\n<pre><code>bool myBool = val ?? false;\n</code></pre>\n\n<p>...which is the good old \"null-coalescing operator\" and quite nice.</p>\n\n<p>Read more about it here if you are interested: <a href=\"http://msdn.microsoft.com/en-us/library/ms173224.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ms173224.aspx</a></p>\n" }, { "answer_id": 15793180, "author": "Mick Bruno", "author_id": 730366, "author_profile": "https://Stackoverflow.com/users/730366", "pm_score": -1, "selected": false, "text": "<p>Just posted this same snippet for another question, but here is the code I use across projects for doing a much better job of handling booleans in all their assorted versions:</p>\n\n<pre><code>bool shouldCheck;\nTryParseBool(val, out shouldCheck);\ncheckBox.Checked = shouldCheck;\n\n/// &lt;summary&gt;\n/// Legal values: Case insensitive strings TRUE/FALSE, T/F, YES/NO, Y/N, numbers (0 =&gt; false, non-zero =&gt; true)\n/// Similar to \"bool.TryParse(string text, out bool)\" except that it handles values other than 'true'/'false'\n/// &lt;/summary&gt;\npublic static bool TryParseBool(object inVal, out bool retVal)\n{\n // There are a couple of built-in ways to convert values to boolean, but unfortunately they skip things like YES/NO, 1/0, T/F\n //bool.TryParse(string, out bool retVal) (.NET 4.0 Only); Convert.ToBoolean(object) (requires try/catch)\n inVal = (inVal ?? \"\").ToString().Trim().ToUpper();\n switch ((string)inVal)\n {\n case \"TRUE\":\n case \"T\":\n case \"YES\":\n case \"Y\":\n retVal = true;\n return true;\n case \"FALSE\":\n case \"F\":\n case \"NO\":\n case \"N\":\n retVal = false;\n return true;\n default:\n // If value can be parsed as a number, 0==false, non-zero==true (old C/C++ usage)\n double number;\n if (double.TryParse((string)inVal, out number))\n {\n retVal = (number != 0);\n return true;\n }\n // If not a valid value for conversion, return false (not parsed)\n retVal = false;\n return false;\n }\n}\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When 'val' below is not a `bool` I get an exception, I believe I can use `TryParse` but I'm not sure how best to use it with my code below. Can anyone help? ``` checkBox.Checked = Convert.ToBoolean(val); ``` Thanks
The code is as follows to determine whether the string `val` is a valid Boolean value and use it to set the `Checked` property if so. You need to decide what action you would take if it does not represent a valid value. ``` bool result; if (bool.TryParse(val, out result)) { // val does represent a Boolean checkBox.Checked = result; } else { // val does not represent a Boolean } ```
180,741
<p>How do you iterate over each file in a directory with a .bat or .cmd file?</p> <p>For simplicity please provide an answer that just echoes the filename or file path.</p>
[ { "answer_id": 180749, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 10, "selected": true, "text": "<p>Command line usage:</p>\n\n<pre><code>for /f %f in ('dir /b c:\\') do echo %f\n</code></pre>\n\n<p>Batch file usage:</p>\n\n<pre><code>for /f %%f in ('dir /b c:\\') do echo %%f\n</code></pre>\n\n<p><strong>Update</strong>: if the directory contains files with space in the names, you need to change the delimiter the <code>for /f</code> command is using. for example, you can use the pipe char.</p>\n\n<pre><code>for /f \"delims=|\" %%f in ('dir /b c:\\') do echo %%f\n</code></pre>\n\n<p><strong>Update 2</strong>: (quick one year and a half after the original answer :-)) If the directory name itself has a space in the name, you can use the <code>usebackq</code> option on the <code>for</code>:</p>\n\n<pre><code>for /f \"usebackq delims=|\" %%f in (`dir /b \"c:\\program files\"`) do echo %%f\n</code></pre>\n\n<p>And if you need to use output redirection or command piping, use the escape char (<code>^</code>):</p>\n\n<pre><code>for /f \"usebackq delims=|\" %%f in (`dir /b \"c:\\program files\" ^| findstr /i microsoft`) do echo %%f\n</code></pre>\n" }, { "answer_id": 180758, "author": "mstrobl", "author_id": 25965, "author_profile": "https://Stackoverflow.com/users/25965", "pm_score": 5, "selected": false, "text": "<p>Use </p>\n\n<pre><code>for /r path %%var in (*.*) do some_command %%var\n</code></pre>\n\n<p>with:</p>\n\n<ul>\n<li>path being the starting path.</li>\n<li>%%var being some identifier.</li>\n<li>*.* being a filemask OR the contents of a variable.</li>\n<li>some_command being the command to execute with the path and var concatenated as parameters.</li>\n</ul>\n" }, { "answer_id": 12965217, "author": "Paul Houx", "author_id": 858219, "author_profile": "https://Stackoverflow.com/users/858219", "pm_score": 7, "selected": false, "text": "<p>Alternatively, use:</p>\n\n<pre><code>forfiles /s /m *.png /c \"cmd /c echo @path\"\n</code></pre>\n\n<p>The forfiles command is available in Windows Vista and up.</p>\n" }, { "answer_id": 16553191, "author": "Anon", "author_id": 2383535, "author_profile": "https://Stackoverflow.com/users/2383535", "pm_score": 0, "selected": false, "text": "<p>I had some malware that marked all files in a directory as hidden/system/readonly. If anyone else finds themselves in this situation, cd into the directory and run <code>for /f \"delims=|\" %f in ('forfiles') do attrib -s -h -r %f</code>.</p>\n" }, { "answer_id": 19849383, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 6, "selected": false, "text": "<p>Easiest method:</p>\n\n<p>From Command Line, use:</p>\n\n<pre><code>for %f in (*.*) do echo %f\n</code></pre>\n\n<p>From a Batch File (double up the % percent signs):</p>\n\n<pre><code>for %%f in (*.*) do echo %%f\n</code></pre>\n\n<p>From a Batch File with folder specified as 1st parameter:</p>\n\n<pre><code>for %%f in (%1\\*.*) do echo %%f\n</code></pre>\n" }, { "answer_id": 36683463, "author": "thistleknot", "author_id": 1731972, "author_profile": "https://Stackoverflow.com/users/1731972", "pm_score": 3, "selected": false, "text": "<p>Another way:</p>\n\n<pre><code>for %f in (*.mp4) do call ffmpeg -i \"%~f\" -vcodec copy -acodec copy \"%~nf.avi\"\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
How do you iterate over each file in a directory with a .bat or .cmd file? For simplicity please provide an answer that just echoes the filename or file path.
Command line usage: ``` for /f %f in ('dir /b c:\') do echo %f ``` Batch file usage: ``` for /f %%f in ('dir /b c:\') do echo %%f ``` **Update**: if the directory contains files with space in the names, you need to change the delimiter the `for /f` command is using. for example, you can use the pipe char. ``` for /f "delims=|" %%f in ('dir /b c:\') do echo %%f ``` **Update 2**: (quick one year and a half after the original answer :-)) If the directory name itself has a space in the name, you can use the `usebackq` option on the `for`: ``` for /f "usebackq delims=|" %%f in (`dir /b "c:\program files"`) do echo %%f ``` And if you need to use output redirection or command piping, use the escape char (`^`): ``` for /f "usebackq delims=|" %%f in (`dir /b "c:\program files" ^| findstr /i microsoft`) do echo %%f ```
180,750
<p>Is there a way to take substrings of a string with .bat/.cmd files?</p> <p>For example given the string "hello.txt" is there a way to strip the .txt?</p> <p>EDIT: Also is there a more general way to do this, not under the assumption that it is a file name or file path?</p>
[ { "answer_id": 180766, "author": "Andrew", "author_id": 15127, "author_profile": "https://Stackoverflow.com/users/15127", "pm_score": 4, "selected": true, "text": "<p>If this is a file passed as a parameter, you can use %~n1, like this:</p>\n\n<pre><code>test.bat\n----------\necho %~n1 %~n2\n\nc:\\&gt; test.bat myfile.txt my.long.file.bat\n myfile my.long.file\n</code></pre>\n\n<p>If you know the length of the string you can use the substring operator:</p>\n\n<pre><code>echo %variable:0,4% =&gt; \"test.txt\" =&gt; \"test\"\n</code></pre>\n\n<p>And to get everything EXCEPT the last 4 characters:</p>\n\n<pre><code>echo %variable:~0,-4% =&gt; \"file...name.txt\" =&gt; \"file...name\"\n</code></pre>\n\n<ul>\n<li><a href=\"http://www.batchfiles.co.nr/\" rel=\"nofollow noreferrer\">BatchFiles Website (kind advanced)</a></li>\n<li><a href=\"http://forums.afterdawn.com/thread_view.cfm/514228\" rel=\"nofollow noreferrer\">Decent forum post</a></li>\n<li><a href=\"http://groups.google.com/group/alt.msdos.batch.nt/msg/923423bf3143fcdd?pli=1\" rel=\"nofollow noreferrer\">Another Good Post</a></li>\n</ul>\n" }, { "answer_id": 180768, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 0, "selected": false, "text": "<p>For an arbitrary string, I don't think so.</p>\n\n<p>For this very example, <code>%~n1</code> will resolve to a name without extension.</p>\n" }, { "answer_id": 180786, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 2, "selected": false, "text": "<p>The general substring syntax in .cmd files (and .bat files post Win95) is:</p>\n\n<pre>\n%variable:~num_chars_to_skip,num_chars_to_keep%\n</pre>\n\n<p>This page provides more options: <a href=\"http://www.ss64.com/nt/syntax-substring.html\" rel=\"nofollow noreferrer\">VarSubstring</a></p>\n" }, { "answer_id": 180790, "author": "pmg", "author_id": 25324, "author_profile": "https://Stackoverflow.com/users/25324", "pm_score": 1, "selected": false, "text": "<p>Try <code>help set</code> for some string processing available for cmd.exe.\nThe help for set includes things you can do normally, outside the 'set' command</p>\n\n<p>You can do things like</p>\n\n<pre><code>set source=hello.txt\nREM print hello\necho %source:~0,-4%\nREM print o.t\necho %source:~4,3%\nREM print help.txt\necho %source:lo=p%\nREM etc\necho %source:llo=%\n</code></pre>\n\n<p>There may be somethings wrong in the 'code' above. I'm writing it from memory, without a cmd.exe available near me to test.</p>\n" }, { "answer_id": 181647, "author": "Denes Tarjan", "author_id": 17617, "author_profile": "https://Stackoverflow.com/users/17617", "pm_score": 2, "selected": false, "text": "<p>For substring and other interesting \"variable substitution\" methods you can get help with:</p>\n\n<blockquote>\n <p>set /?</p>\n</blockquote>\n\n<p>For string parsing (e.g. finding a '.' in a string) try</p>\n\n<blockquote>\n <p>for /?</p>\n</blockquote>\n" }, { "answer_id": 182621, "author": "Noam", "author_id": 20719, "author_profile": "https://Stackoverflow.com/users/20719", "pm_score": 1, "selected": false, "text": "<p>Best way is just to install python (or perl)\nBelieve me, I've tried almost everything, and it's just headache to do text manipulation in 'DOS' (or actually anything else).</p>\n" }, { "answer_id": 231542, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can also look at the documentation for call (call /?) for getting file and directory-based specific substring info as well.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
Is there a way to take substrings of a string with .bat/.cmd files? For example given the string "hello.txt" is there a way to strip the .txt? EDIT: Also is there a more general way to do this, not under the assumption that it is a file name or file path?
If this is a file passed as a parameter, you can use %~n1, like this: ``` test.bat ---------- echo %~n1 %~n2 c:\> test.bat myfile.txt my.long.file.bat myfile my.long.file ``` If you know the length of the string you can use the substring operator: ``` echo %variable:0,4% => "test.txt" => "test" ``` And to get everything EXCEPT the last 4 characters: ``` echo %variable:~0,-4% => "file...name.txt" => "file...name" ``` * [BatchFiles Website (kind advanced)](http://www.batchfiles.co.nr/) * [Decent forum post](http://forums.afterdawn.com/thread_view.cfm/514228) * [Another Good Post](http://groups.google.com/group/alt.msdos.batch.nt/msg/923423bf3143fcdd?pli=1)
180,760
<p>Can someone explain how to use if-then statements and for loops in Makefiles? I can't seem to find any good documentation with examples.</p>
[ { "answer_id": 180769, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<p>Have you tried the <a href=\"http://www.gnu.org/software/make/manual/make.html#Conditionals\" rel=\"noreferrer\">GNU make documentation</a>? It has a whole section about conditionals with examples.</p>\n" }, { "answer_id": 180775, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 4, "selected": false, "text": "<p>Here's an example if:</p>\n\n<pre><code>ifeq ($(strip $(OS)),Linux)\n PYTHON = /usr/bin/python\n FIND = /usr/bin/find\nendif\n</code></pre>\n\n<p>Note that this comes with a word of warning that different versions of Make have slightly different syntax, none of which seems to be documented very well.</p>\n" }, { "answer_id": 180818, "author": "John Mulder", "author_id": 2242, "author_profile": "https://Stackoverflow.com/users/2242", "pm_score": 7, "selected": true, "text": "<p><strong>Conditional Forms</strong> </p>\n\n<p>Simple </p>\n\n<pre><code>conditional-directive\ntext-if-true\nendif\n</code></pre>\n\n<p>Moderately Complex </p>\n\n<pre><code>conditional-directive\ntext-if-true\nelse\ntext-if-false\nendif\n</code></pre>\n\n<p>More Complex </p>\n\n<pre><code>conditional-directive\ntext-if-one-is-true\nelse\nconditional-directive\ntext-if-true\nelse\ntext-if-false\nendif\nendif\n</code></pre>\n\n<p><strong>Conditional Directives</strong> </p>\n\n<p>If Equal Syntax </p>\n\n<pre><code>ifeq (arg1, arg2)\nifeq 'arg1' 'arg2'\nifeq \"arg1\" \"arg2\"\nifeq \"arg1\" 'arg2'\nifeq 'arg1' \"arg2\"\n</code></pre>\n\n<p>If Not Equal Syntax </p>\n\n<pre><code>ifneq (arg1, arg2)\nifneq 'arg1' 'arg2'\nifneq \"arg1\" \"arg2\"\nifneq \"arg1\" 'arg2'\nifneq 'arg1' \"arg2\"\n</code></pre>\n\n<p>If Defined Syntax </p>\n\n<pre><code>ifdef variable-name\n</code></pre>\n\n<p>If Not Defined Syntax </p>\n\n<pre><code>ifndef variable-name \n</code></pre>\n\n<p><strong>foreach Function</strong> </p>\n\n<p>foreach Function Syntax </p>\n\n<pre><code>$(foreach var, list, text) \n</code></pre>\n\n<p>foreach Semantics<br>\nFor each whitespace separated word in \"list\", the variable named by \"var\" is set to that word and text is executed.</p>\n" }, { "answer_id": 5893113, "author": "Kramer", "author_id": 125368, "author_profile": "https://Stackoverflow.com/users/125368", "pm_score": 3, "selected": false, "text": "<p>You do see for loops alot of the time, but they are usually not needed. Here is an example of how one might perform a for loop without resorting to the shell</p>\n\n<pre><code>LIST_OF_THINGS_TO_DO = do_this do_that \n$(LIST_OF_THINGS_TO_DO): \n run $@ &gt; [email protected]\n\nSUBDIRS = snafu fubar\n$(SUBDIRS):\n cd $@ &amp;&amp; $(MAKE)\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2039/" ]
Can someone explain how to use if-then statements and for loops in Makefiles? I can't seem to find any good documentation with examples.
**Conditional Forms** Simple ``` conditional-directive text-if-true endif ``` Moderately Complex ``` conditional-directive text-if-true else text-if-false endif ``` More Complex ``` conditional-directive text-if-one-is-true else conditional-directive text-if-true else text-if-false endif endif ``` **Conditional Directives** If Equal Syntax ``` ifeq (arg1, arg2) ifeq 'arg1' 'arg2' ifeq "arg1" "arg2" ifeq "arg1" 'arg2' ifeq 'arg1' "arg2" ``` If Not Equal Syntax ``` ifneq (arg1, arg2) ifneq 'arg1' 'arg2' ifneq "arg1" "arg2" ifneq "arg1" 'arg2' ifneq 'arg1' "arg2" ``` If Defined Syntax ``` ifdef variable-name ``` If Not Defined Syntax ``` ifndef variable-name ``` **foreach Function** foreach Function Syntax ``` $(foreach var, list, text) ``` foreach Semantics For each whitespace separated word in "list", the variable named by "var" is set to that word and text is executed.
180,777
<p>I have a ListBox which displays items of variable height. I want to show as many items as will fit in the available space, without showing a vertical scrollbar. Other than surgery on the ListBox item template, is there a way to only show the number of items which will fit without scrolling?</p>
[ { "answer_id": 180824, "author": "Brian Leahy", "author_id": 580, "author_profile": "https://Stackoverflow.com/users/580", "pm_score": 5, "selected": true, "text": "<pre><code> &lt;ListBox ScrollViewer.VerticalScrollBarVisibility=\"Auto\" /&gt; \n</code></pre>\n\n<p>the default is visible </p>\n" }, { "answer_id": 789909, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I don't think the default is \"Visible\". I think it's \"Auto\". Jon wanted to set it to \"Hidden\".</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5/" ]
I have a ListBox which displays items of variable height. I want to show as many items as will fit in the available space, without showing a vertical scrollbar. Other than surgery on the ListBox item template, is there a way to only show the number of items which will fit without scrolling?
``` <ListBox ScrollViewer.VerticalScrollBarVisibility="Auto" /> ``` the default is visible
180,793
<p>I need to clip out all the occurances of the pattern '--' that are <em>inside</em> single quotes in long string (leaving intact the ones that are outside single quotes). </p> <p>Is there a RegEx way of doing this? (using it with an iterator from the language is OK).</p> <p>For example, starting with</p> <pre><code>"xxxx rt / $ 'dfdf--fggh-dfgdfg' ghgh- dddd -- 'dfdf' ghh-g '--ggh--' vcbcvb" </code></pre> <p>I should end up with:</p> <pre><code>"xxxx rt / $ 'dfdffggh-dfgdfg' ghgh- dddd -- 'dfdf' ghh-g 'ggh' vcbcvb" </code></pre> <p>So I am looking for a regex that could be run from the following languages as shown:</p> <pre><code> +-------------+------------------------------------------+ | Language | RegEx | +-------------+------------------------------------------+ | JavaScript | input.replace(/someregex/g, "") | | PHP | preg_replace('/someregex/', "", input) | | Python | re.sub(r'someregex', "", input) | | Ruby | input.gsub(/someregex/, "") | +-------------+------------------------------------------+ </code></pre>
[ { "answer_id": 180798, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 1, "selected": false, "text": "<p>This cannot be done with regular expressions, because you need to maintain state on whether you're inside single quotes or outside, and regex is inherently stateless. (Also, as far as I understand, single quotes can be escaped without terminating the \"inside\" region).</p>\n\n<p>Your best bet is to iterate through the string character by character, keeping a boolean flag on whether or not you're inside a quoted region - and remove the --'s that way.</p>\n" }, { "answer_id": 180837, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "<p>Hm. There <em>might</em> be a way in Python if there are no quoted apostrophes, given that there is the <code>(?(</code><em>id/name</em><code>)</code><em>yes-pattern</em><code>|</code><em>no-pattern</em><code>)</code> construct in regular expressions, but it goes way over my head currently.</p>\n\n<p>Does this help?</p>\n\n<pre><code>def remove_double_dashes_in_apostrophes(text):\n return \"'\".join(\n part.replace(\"--\", \"\") if (ix&amp;1) else part\n for ix, part in enumerate(text.split(\"'\")))\n</code></pre>\n\n<p>Seems to work for me. What it does, is split the input text to parts on apostrophes, and replace the \"--\" only when the part is odd-numbered (i.e. there has been an odd number of apostrophes before the part). Note about \"odd numbered\": part numbering starts from zero!</p>\n" }, { "answer_id": 180856, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 1, "selected": false, "text": "<p>If bending the rules a little is allowed, this could work:</p>\n\n<pre><code>import re\np = re.compile(r\"((?:^[^']*')?[^']*?(?:'[^']*'[^']*?)*?)(-{2,})\")\ntxt = \"xxxx rt / $ 'dfdf--fggh-dfgdfg' ghgh- dddd -- 'dfdf' ghh-g '--ggh--' vcbcvb\"\nprint re.sub(p, r'\\1-', txt)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>xxxx rt / $ 'dfdf-fggh-dfgdfg' ghgh- dddd -- 'dfdf' ghh-g '-ggh-' vcbcvb\n</code></pre>\n\n<p>The regex:</p>\n\n<pre><code>( # Group 1\n (?:^[^']*')? # Start of string, up till the first single quote\n [^']*? # Inside the single quotes, as few characters as possible\n (?:\n '[^']*' # No double dashes inside theses single quotes, jump to the next.\n [^']*?\n )*? # as few as possible\n)\n(-{2,}) # The dashes themselves (Group 2)\n</code></pre>\n\n<p>If there where different delimiters for start and end, you could use something like this:</p>\n\n<pre><code>-{2,}(?=[^'`]*`)\n</code></pre>\n\n<hr>\n\n<p><strong>Edit:</strong> I realized that if the string does not contain any quotes, it will match all double dashes in the string. One way of fixing it would be to change</p>\n\n<pre><code>(?:^[^']*')?\n</code></pre>\n\n<p>in the beginning to</p>\n\n<pre><code>(?:^[^']*'|(?!^))\n</code></pre>\n\n<p>Updated regex:</p>\n\n<pre><code>((?:^[^']*'|(?!^))[^']*?(?:'[^']*'[^']*?)*?)(-{2,})\n</code></pre>\n" }, { "answer_id": 180950, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 0, "selected": false, "text": "<p>You can use the following sed script, I believe:</p>\n\n<pre><code>:again\ns/'\\(.*\\)--\\(.*\\)'/'\\1\\2'/g\nt again\n</code></pre>\n\n<p>Store that in a file (rmdashdash.sed) and do whatever exec magic in your scripting language allows you to do the following shell equivalent:</p>\n\n<p>sed -f rmdotdot.sed &lt; <em>file containing your input data</em></p>\n\n<p>What the script does is:</p>\n\n<p><strong><code>:again</code></strong> &lt;-- just a label</p>\n\n<p><strong><code>s/'\\(.*\\)--\\(.*\\)'/'\\1\\2'/g</code></strong></p>\n\n<p>substitute, for the pattern ' followed by anything followed by -- followed by anything followed by ', just the two anythings within quotes.</p>\n\n<p><strong><code>t again</code></strong> &lt;-- feed the resulting string back into sed again.</p>\n\n<p>Note that this script will convert '----' into '', since it is a sequence of two --'s within quotes. However, '---' will be converted into '-'.</p>\n\n<p>Ain't no school like old school.</p>\n" }, { "answer_id": 181181, "author": "Mike Berrow", "author_id": 17251, "author_profile": "https://Stackoverflow.com/users/17251", "pm_score": 3, "selected": true, "text": "<p>I found another way to do this from an answer by <b>Greg Hewgill</b> at <a href=\"https://stackoverflow.com/questions/138552\">Qn138522</a><br>\nIt is based on using this regex (adapted to contain the pattern I was looking for):</p>\n\n<pre><code>--(?=[^\\']*'([^']|'[^']*')*$)\n</code></pre>\n\n<p>Greg explains:</p>\n\n<blockquote>\n <p>\"What this does is use the non-capturing match <code>(?=...)</code> to check that the character x is within a quoted string. It looks for some nonquote characters up to the next quote, then looks for a sequence of either single characters or quoted groups of characters, until the end of the string. This relies on your assumption that the quotes are always balanced. This is also not very efficient.\"</p>\n</blockquote>\n\n<p>The usage examples would be :</p>\n\n<ul>\n<li>JavaScript: <code>input.replace(/--(?=[^']*'([^']|'[^']*')*$)/g, \"\")</code></li>\n<li>PHP: <code>preg_replace('/--(?=[^\\']*'([^']|'[^']*')*$)/', \"\", input)</code></li>\n<li>Python: <code>re.sub(r'--(?=[^\\']*'([^']|'[^']*')*$)', \"\", input)</code></li>\n<li>Ruby: <code>input.gsub(/--(?=[^\\']*'([^']|'[^']*')*$)/, \"\")</code></li>\n</ul>\n\n<p>I have tested this for Ruby and it provides the desired result.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17251/" ]
I need to clip out all the occurances of the pattern '--' that are *inside* single quotes in long string (leaving intact the ones that are outside single quotes). Is there a RegEx way of doing this? (using it with an iterator from the language is OK). For example, starting with ``` "xxxx rt / $ 'dfdf--fggh-dfgdfg' ghgh- dddd -- 'dfdf' ghh-g '--ggh--' vcbcvb" ``` I should end up with: ``` "xxxx rt / $ 'dfdffggh-dfgdfg' ghgh- dddd -- 'dfdf' ghh-g 'ggh' vcbcvb" ``` So I am looking for a regex that could be run from the following languages as shown: ``` +-------------+------------------------------------------+ | Language | RegEx | +-------------+------------------------------------------+ | JavaScript | input.replace(/someregex/g, "") | | PHP | preg_replace('/someregex/', "", input) | | Python | re.sub(r'someregex', "", input) | | Ruby | input.gsub(/someregex/, "") | +-------------+------------------------------------------+ ```
I found another way to do this from an answer by **Greg Hewgill** at [Qn138522](https://stackoverflow.com/questions/138552) It is based on using this regex (adapted to contain the pattern I was looking for): ``` --(?=[^\']*'([^']|'[^']*')*$) ``` Greg explains: > > "What this does is use the non-capturing match `(?=...)` to check that the character x is within a quoted string. It looks for some nonquote characters up to the next quote, then looks for a sequence of either single characters or quoted groups of characters, until the end of the string. This relies on your assumption that the quotes are always balanced. This is also not very efficient." > > > The usage examples would be : * JavaScript: `input.replace(/--(?=[^']*'([^']|'[^']*')*$)/g, "")` * PHP: `preg_replace('/--(?=[^\']*'([^']|'[^']*')*$)/', "", input)` * Python: `re.sub(r'--(?=[^\']*'([^']|'[^']*')*$)', "", input)` * Ruby: `input.gsub(/--(?=[^\']*'([^']|'[^']*')*$)/, "")` I have tested this for Ruby and it provides the desired result.
180,796
<p>I have a servlet which is in the same web application as the JSF servlet. How do I replace (rather than redirect) the servlet response with the JSF response? </p>
[ { "answer_id": 180903, "author": "Martin", "author_id": 24364, "author_profile": "https://Stackoverflow.com/users/24364", "pm_score": 1, "selected": false, "text": "<p>Not sure I fully understand your question - but if you want to include the output from a JSF page in your servlet response, something like:</p>\n\n<pre><code>public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {\n // Do stuff\n req.getRequestDispatcher(\"/blah.jsf\").forward(req, res);\n // Do other stuff\n}\n</code></pre>\n\n<p>Should do the trick</p>\n" }, { "answer_id": 6114847, "author": "Ondřej Xicht Světlík", "author_id": 768106, "author_profile": "https://Stackoverflow.com/users/768106", "pm_score": 0, "selected": false, "text": "<p>I recommend using <a href=\"http://urlrewritefilter.googlecode.com/svn/trunk/src/doc/manual/3.2/index.html\" rel=\"nofollow\">urlrewritefilter</a>.</p>\n\n<p>Simple</p>\n\n<pre><code> &lt;rule&gt;\n &lt;from&gt;^/my/servlet/uri&lt;/from&gt;\n &lt;to&gt;/jsfpage.jsf&lt;/to&gt;\n &lt;/rule&gt;\n</code></pre>\n\n<p>should be enough.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a servlet which is in the same web application as the JSF servlet. How do I replace (rather than redirect) the servlet response with the JSF response?
Not sure I fully understand your question - but if you want to include the output from a JSF page in your servlet response, something like: ``` public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { // Do stuff req.getRequestDispatcher("/blah.jsf").forward(req, res); // Do other stuff } ``` Should do the trick
180,809
<p>Just wondering if there is an easy way to add the functionality to duplicate an existing listing in the admin interface?</p> <p>In data entry we have run into a situation where a lot of items share generic data with another item, and to save time it would be very nice to quickly duplicate an existing listing and only alter the changed data. Using a better model structure would be one way of reducing the duplication of the data, but there may be situation where the duplicated data needs to be changed on an individual basis in the future.</p>
[ { "answer_id": 180816, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 8, "selected": true, "text": "<p>You can <a href=\"http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_as\" rel=\"noreferrer\">save as</a> by just enabling adding this to your ModelAdmin:</p>\n\n<pre><code>save_as = True\n</code></pre>\n\n<p>This replaces the \"Save and add another\" button with a \"Save as\" button. \"Save as\" means the object will be saved as a new object (with a new ID), rather than the old object.</p>\n" }, { "answer_id": 49752122, "author": "kontextify", "author_id": 2231950, "author_profile": "https://Stackoverflow.com/users/2231950", "pm_score": 3, "selected": false, "text": "<p>There's a better (but not built-in) solution here:</p>\n\n<p><a href=\"https://github.com/RealGeeks/django-modelclone\" rel=\"noreferrer\">https://github.com/RealGeeks/django-modelclone</a></p>\n\n<p>From their README:</p>\n\n<blockquote>\n <p>Django Admin has a <code>save_as</code> feature that adds a new button to your\n Change page to save a new instance of that object.</p>\n \n <p>I don't like the way this feature works because you will save an\n identical copy of the original object (if you don't get validation\n errors) as soon as you click that link, and if you forget to make the\n small changes that you wanted in the new object you will end up with a\n duplicate of the existing object.</p>\n \n <p>On the other hand, django-modelclone offers an intermediate view, that\n basically pre-fills the form for you. So you can modify and then save\n a new instance. Or just go away without side effects.</p>\n</blockquote>\n" }, { "answer_id": 56566322, "author": "Abel", "author_id": 7995920, "author_profile": "https://Stackoverflow.com/users/7995920", "pm_score": 0, "selected": false, "text": "<p>You can also apply this method: <a href=\"https://stackoverflow.com/a/4054256/7995920\">https://stackoverflow.com/a/4054256/7995920</a></p>\n\n<p>In my case, with unique constraint in the 'name' field, this action works, and can be requested from any form:</p>\n\n<hr>\n\n<pre><code>def duplicate_jorn(modeladmin, request, queryset):\n post_url = request.META['HTTP_REFERER']\n\n for object in queryset:\n object.id = None\n object.name = object.name+'-b'\n object.save()\n\n return HttpResponseRedirect(post_url)\n</code></pre>\n\n<hr>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23366/" ]
Just wondering if there is an easy way to add the functionality to duplicate an existing listing in the admin interface? In data entry we have run into a situation where a lot of items share generic data with another item, and to save time it would be very nice to quickly duplicate an existing listing and only alter the changed data. Using a better model structure would be one way of reducing the duplication of the data, but there may be situation where the duplicated data needs to be changed on an individual basis in the future.
You can [save as](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_as) by just enabling adding this to your ModelAdmin: ``` save_as = True ``` This replaces the "Save and add another" button with a "Save as" button. "Save as" means the object will be saved as a new object (with a new ID), rather than the old object.
180,841
<p>Here are some gems:</p> <p>Literals:</p> <pre><code>var obj = {}; // Object literal, equivalent to var obj = new Object(); var arr = []; // Array literal, equivalent to var arr = new Array(); var regex = /something/; // Regular expression literal, equivalent to var regex = new RegExp('something'); </code></pre> <p>Defaults:</p> <pre><code>arg = arg || 'default'; // if arg evaluates to false, use 'default', which is the same as: arg = !!arg ? arg : 'default'; </code></pre> <p>Of course we know anonymous functions, but being able to treat them as literals and execute them on the spot (as a closure) is great:</p> <pre><code>(function() { ... })(); // Creates an anonymous function and executes it </code></pre> <p><strong>Question:</strong> What other great syntactic sugar is available in javascript?</p>
[ { "answer_id": 180854, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 5, "selected": false, "text": "<p>In Mozilla (and reportedly IE7) you can create an XML constant using:</p>\n\n<pre>\nvar xml = &lt;elem&gt;&lt;/elem&gt;;\n</pre>\n\n<p>You can substitute variables as well:</p>\n\n<pre>\nvar elem = \"html\";\nvar text = \"Some text\";\nvar xml = &lt;{elem}&gt;{text}&lt;/{elem}&gt;;\n</pre>\n" }, { "answer_id": 180866, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 4, "selected": false, "text": "<p>Use <code>===</code> to compare value <strong>and</strong> type:</p>\n\n<pre>\nvar i = 0;\nvar s = \"0\";\n\nif (i == s) // true\n\nif (i === s) // false\n</pre>\n" }, { "answer_id": 180867, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 3, "selected": false, "text": "<p>This isn't a javascript exclusive, but saves like three lines of code:</p>\n\n<pre><code>check ? value1 : value2\n</code></pre>\n" }, { "answer_id": 180907, "author": "VirtuosiMedia", "author_id": 13281, "author_profile": "https://Stackoverflow.com/users/13281", "pm_score": 2, "selected": false, "text": "<p>A little bit more on levik's example:</p>\n\n<pre><code>var foo = (condition) ? value1 : value2;\n</code></pre>\n" }, { "answer_id": 180916, "author": "steve_c", "author_id": 769, "author_profile": "https://Stackoverflow.com/users/769", "pm_score": 5, "selected": false, "text": "<p>Being able to extend native JavaScript types via prototypal inheritance.</p>\n\n<pre><code>String.prototype.isNullOrEmpty = function(input) {\n return input === null || input.length === 0;\n}\n</code></pre>\n" }, { "answer_id": 180920, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 4, "selected": false, "text": "<p>Multi-line strings:</p>\n\n<pre>\nvar str = \"This is \\\nall one \\\nstring.\";\n</pre>\n\n<p>Since you cannot indent the subsequent lines without also adding the whitespace into the string, people generally prefer to concatenate with the plus operator. But this does provide a nice <a href=\"http://en.wikipedia.org/wiki/Heredoc\" rel=\"noreferrer\">here document </a> capability.</p>\n" }, { "answer_id": 180933, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 5, "selected": false, "text": "<p>Using anonymous functions and a closure to create a private variable (information hiding) and the associated get/set methods:</p>\n\n<pre><code>var getter, setter;\n\n(function()\n{\n var _privateVar=123;\n getter = function() { return _privateVar; };\n setter = function(v) { _privateVar = v; };\n})()\n</code></pre>\n" }, { "answer_id": 181005, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 5, "selected": false, "text": "<p>Object membership test:</p>\n\n<pre>\nvar props = { a: 1, b: 2 };\n\n(\"a\" in props) // true\n(\"b\" in props) // true\n(\"c\" in props) // false\n</pre>\n" }, { "answer_id": 181186, "author": "dicroce", "author_id": 3886, "author_profile": "https://Stackoverflow.com/users/3886", "pm_score": 1, "selected": false, "text": "<p>I love being able to eval() a json string and get back a fully populated data structure.\nI Hate having to write everything at least twice (once for IE, again for Mozilla).</p>\n" }, { "answer_id": 181939, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://ejohn.org/blog/javascript-getters-and-setters/\" rel=\"noreferrer\">Getters and setters</a>:</p>\n\n<pre><code>function Foo(bar)\n{\n this._bar = bar;\n}\n\nFoo.prototype =\n{\n get bar()\n {\n return this._bar;\n },\n\n set bar(bar)\n {\n this._bar = bar.toUpperCase();\n }\n};\n</code></pre>\n\n<p>Gives us:</p>\n\n<pre><code>&gt;&gt;&gt; var myFoo = new Foo(\"bar\");\n&gt;&gt;&gt; myFoo.bar\n\"BAR\"\n&gt;&gt;&gt; myFoo.bar = \"Baz\";\n&gt;&gt;&gt; myFoo.bar\n\"BAZ\"\n</code></pre>\n" }, { "answer_id": 182231, "author": "Pablo Cabrera", "author_id": 12540, "author_profile": "https://Stackoverflow.com/users/12540", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:forEach\" rel=\"nofollow noreferrer\">Array#forEach</a> on Javascript 1.6</p>\n\n<pre><code>myArray.forEach(function(element) { alert(element); });\n</code></pre>\n" }, { "answer_id": 186150, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "<p>I forgot:</p>\n\n<pre><code>(function() { ... }).someMethod(); // Functions as objects\n</code></pre>\n" }, { "answer_id": 224114, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 7, "selected": true, "text": "<p>Getting the current datetime as milliseconds:</p>\n\n<pre><code>Date.now()\n</code></pre>\n\n<p>For example, to time the execution of a section of code:</p>\n\n<pre><code>var start = Date.now();\n// some code\nalert((Date.now() - start) + \" ms elapsed\");\n</code></pre>\n" }, { "answer_id": 308796, "author": "J c", "author_id": 25837, "author_profile": "https://Stackoverflow.com/users/25837", "pm_score": 4, "selected": false, "text": "<p>Repeating a string such as \"-\" a specific number of times by leveraging the join method on an empty array:</p>\n\n<pre><code>var s = new Array(repeat+1).join(\"-\");\n</code></pre>\n\n<p>Results in \"---\" when repeat == 3.</p>\n" }, { "answer_id": 700998, "author": "Serkan Yersen", "author_id": 85094, "author_profile": "https://Stackoverflow.com/users/85094", "pm_score": 4, "selected": false, "text": "<pre><code>var tags = {\n name: \"Jack\",\n location: \"USA\"\n};\n\n\"Name: {name}&lt;br&gt;From {location}\".replace(/\\{(.*?)\\}/gim, function(all, match){\n return tags[match];\n});\n</code></pre>\n\n<p>callback for string replace is just useful.</p>\n" }, { "answer_id": 701061, "author": "Martijn Laarman", "author_id": 47020, "author_profile": "https://Stackoverflow.com/users/47020", "pm_score": 0, "selected": false, "text": "<p>int to string cast</p>\n\n<pre><code>var i = 12;\nvar s = i+\"\";\n</code></pre>\n" }, { "answer_id": 1221345, "author": "vvo", "author_id": 147079, "author_profile": "https://Stackoverflow.com/users/147079", "pm_score": 2, "selected": false, "text": "<p>Following obj || {default:true} syntax :</p>\n\n<p>calling your function with this : hello(neededOne &amp;&amp; neededTwo &amp;&amp; needThree) if one parameter is undefined or false then it will call hello(false), <strong>sometimes</strong> usefull</p>\n" }, { "answer_id": 1221417, "author": "RameshVel", "author_id": 97572, "author_profile": "https://Stackoverflow.com/users/97572", "pm_score": 1, "selected": false, "text": "<p>Assigining the frequently used keywords (or any methods) to the simple variables like ths</p>\n\n<pre><code> var $$ = document.getElementById;\n\n $$('samText');\n</code></pre>\n" }, { "answer_id": 1345481, "author": "pramodc84", "author_id": 40614, "author_profile": "https://Stackoverflow.com/users/40614", "pm_score": 4, "selected": false, "text": "<p><strong>Resize the Length of an Array</strong></p>\n\n<p>length property is a <strong>not read only</strong>.\nYou can use it to increase or decrease the size of an array.</p>\n\n<pre><code>var myArray = [1,2,3];\nmyArray.length // 3 elements.\nmyArray.length = 2; //Deletes the last element.\nmyArray.length = 20 // Adds 18 elements to the array; the elements have the empty value. A sparse array.\n</code></pre>\n" }, { "answer_id": 1361134, "author": "pramodc84", "author_id": 40614, "author_profile": "https://Stackoverflow.com/users/40614", "pm_score": 0, "selected": false, "text": "<pre><code>element.innerHTML = \"\"; // Replaces body of HTML element with an empty string.\n</code></pre>\n\n<p>A shortcut to delete all child nodes of element.</p>\n" }, { "answer_id": 3525010, "author": "palswim", "author_id": 393280, "author_profile": "https://Stackoverflow.com/users/393280", "pm_score": 1, "selected": false, "text": "<p>JavaScript's Date class providing a semi-\"Fluent Interface\". This makes up for not being able to extract the date portion from a Date class directly:</p>\n\n<pre><code>var today = new Date((new Date()).setHours(0, 0, 0, 0));\n</code></pre>\n\n<p>It's not a fully Fluent Interface because the following will only give us a numerical value which is not actually a Date object:</p>\n\n<pre><code>var today = new Date().setHours(0, 0, 0, 0);\n</code></pre>\n" }, { "answer_id": 3526226, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 1, "selected": false, "text": "<p>Default fallback:</p>\n\n<pre><code>var foo = {}; // empty object literal\n\nalert(foo.bar) // will alert \"undefined\"\n\nalert(foo.bar || \"bar\"); // will alert the fallback (\"bar\")\n</code></pre>\n\n<p>A practical example:</p>\n\n<pre><code>// will result in a type error\nif (foo.bar.length === 0)\n\n// with a default fallback you are always sure that the length\n// property will be available.\nif ((foo.bar || \"\").length === 0) \n</code></pre>\n" }, { "answer_id": 3529178, "author": "Skilldrick", "author_id": 49376, "author_profile": "https://Stackoverflow.com/users/49376", "pm_score": 4, "selected": false, "text": "<p>Like the default operator, <code>||</code> is the guard operator, <code>&amp;&amp;</code>.</p>\n\n<pre><code>answer = obj &amp;&amp; obj.property\n</code></pre>\n\n<p>as opposed to</p>\n\n<pre><code>if (obj) {\n answer = obj.property;\n}\nelse {\n answer = null;\n}\n</code></pre>\n" }, { "answer_id": 3653054, "author": "mkoistinen", "author_id": 440805, "author_profile": "https://Stackoverflow.com/users/440805", "pm_score": 2, "selected": false, "text": "<p>Create an anonymous object literal with simply: ({})</p>\n\n<p>Example: need to know if objects have the valueOf method:</p>\n\n<p>var hasValueOf = !!({}).valueOf</p>\n\n<p>Bonus syntactic sugar: the double-not '!!' for converting pretty much anything into a Boolean very succinctly.</p>\n" }, { "answer_id": 3918632, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 2, "selected": false, "text": "<p>In parsing situations with a fixed set of component parts:</p>\n\n<pre><code>var str = \"John Doe\";\n</code></pre>\n\n<p>You can assign the results directly into variables, using the \"destructuring assignment\" synatx:</p>\n\n<pre><code>var [fname, lname] = str.split(\" \");\nalert(lname + \", \" + fname);\n</code></pre>\n\n<p>Which is a bit more readable than:</p>\n\n<pre><code>var a = str.split(\" \");\nalert(a[1] + \", \" + a[0]);\n</code></pre>\n\n<p>Alternately:</p>\n\n<pre><code>var [str, fname, lname] = str.match(/(.*) (.*)/);\n</code></pre>\n\n<p>Note that this is a <a href=\"http://en.wikipedia.org/wiki/JavaScript#Versions\" rel=\"nofollow\">Javascript 1.7</a> feature. So that's Mozilla 2.0+ and Chrome 6+ browsers, at this time.</p>\n" }, { "answer_id": 5257738, "author": "manixrock", "author_id": 93691, "author_profile": "https://Stackoverflow.com/users/93691", "pm_score": 1, "selected": false, "text": "<p>I love how simple it is to work with lists:</p>\n\n<pre><code>var numberName = [\"zero\", \"one\", \"two\", \"three\", \"four\"][number];\n</code></pre>\n\n<p>And hashes:</p>\n\n<pre><code>var numberValue = {\"zero\":0, \"one\":1, \"two\":2, \"three\":3, \"four\":4}[numberName];\n</code></pre>\n\n<p>In most other languages this would be quite heavy code. Value defaults are also lovely. For example error code reporting:</p>\n\n<pre><code>var errorDesc = {301: \"Moved Permanently\",\n 404: \"Resource not found\",\n 503: \"Server down\"\n }[errorNo] || \"An unknown error has occurred\";\n</code></pre>\n" }, { "answer_id": 5628693, "author": "ming_codes", "author_id": 387028, "author_profile": "https://Stackoverflow.com/users/387028", "pm_score": 1, "selected": false, "text": "<p>Here's one I just discovered: null check before calling function:</p>\n\n<pre><code>a = b &amp;&amp; b.length;\n</code></pre>\n\n<p>This is a shorter equivalent to: </p>\n\n<pre><code>a = b ? b.length : null;\n</code></pre>\n\n<p>The best part is that you can check a property chain:</p>\n\n<pre><code>a = b &amp;&amp; b.c &amp;&amp; b.c.length;\n</code></pre>\n" }, { "answer_id": 37650287, "author": "Gerard Simpson", "author_id": 4476186, "author_profile": "https://Stackoverflow.com/users/4476186", "pm_score": 2, "selected": false, "text": "<p>Immediately Invoked Arrow function:</p>\n\n<pre><code>var test = \"hello, world!\";\n(() =&gt; test)(); //returns \"hello, world!\";\n</code></pre>\n" }, { "answer_id": 44949871, "author": "Raimonds", "author_id": 2349048, "author_profile": "https://Stackoverflow.com/users/2349048", "pm_score": 0, "selected": false, "text": "<p>Convert string to integer defaulting to 0 if imposible,</p>\n\n<pre><code>0 | \"3\" //result = 3\n0 | \"some string\" -&gt; //result = 0\n0 | \"0\" -&gt; 0 //result = 0\n</code></pre>\n\n<p>Can be useful in some cases, mostly when 0 is considered as bad result</p>\n" }, { "answer_id": 46314286, "author": "Mohan Kumar", "author_id": 4919836, "author_profile": "https://Stackoverflow.com/users/4919836", "pm_score": 0, "selected": false, "text": "<p><strong><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"nofollow noreferrer\">Template literals</a></strong></p>\n\n<pre><code>var a = 10;\nvar b = 20;\nvar text = `${a} + ${b} = ${a+b}`;\n</code></pre>\n\n<p>then the <strong>text</strong> variable will be like below!</p>\n\n<blockquote>\n <p>10 + 20 = 30</p>\n</blockquote>\n" }, { "answer_id": 71998266, "author": "Amin Dannak", "author_id": 13049584, "author_profile": "https://Stackoverflow.com/users/13049584", "pm_score": 0, "selected": false, "text": "<p>optional chaining (<code>?.</code>) can be used so instead of:</p>\n<p><code>if(error &amp;&amp; error.response &amp;&amp; error.response.msg){ // do something}</code></p>\n<p>we can:</p>\n<p><code>if(error?.response?.msg){ // do something }</code></p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining\" rel=\"nofollow noreferrer\">more about optional chaining here</a></p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17964/" ]
Here are some gems: Literals: ``` var obj = {}; // Object literal, equivalent to var obj = new Object(); var arr = []; // Array literal, equivalent to var arr = new Array(); var regex = /something/; // Regular expression literal, equivalent to var regex = new RegExp('something'); ``` Defaults: ``` arg = arg || 'default'; // if arg evaluates to false, use 'default', which is the same as: arg = !!arg ? arg : 'default'; ``` Of course we know anonymous functions, but being able to treat them as literals and execute them on the spot (as a closure) is great: ``` (function() { ... })(); // Creates an anonymous function and executes it ``` **Question:** What other great syntactic sugar is available in javascript?
Getting the current datetime as milliseconds: ``` Date.now() ``` For example, to time the execution of a section of code: ``` var start = Date.now(); // some code alert((Date.now() - start) + " ms elapsed"); ```
180,844
<p>How would you reference the models (Accord, CRV, Prius, etc) in this structure? Is this a bad structure to be able to extract the makes...then use a make to get the models...then use the model to get the options?</p> <pre><code>var cars = [ { "makes" : "Honda", "models" : [ {'Accord' : ["2dr","4dr"]} , {'CRV' : ["2dr","Hatchback"]} , {'Pilot' : ["base","superDuper"] } ] }, { "makes" : "Toyota", "models" : [ {'Prius' : ["green","reallyGreen"]} , {'Camry' : ["sporty","square"]} , {'Corolla' : ["cheap","superFly"] } ] } ]; </code></pre> <p>Thanks</p>
[ { "answer_id": 180850, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 3, "selected": false, "text": "<p><strike> cars[0].models.Accord\n cars[0].models.CRV\n cars[0].models.Pilot</strike> (See <a href=\"https://stackoverflow.com/questions/180844/#180861\">olliej</a>'s answer)</p>\n\n<p>Though, it may be easier to use the following access concept:</p>\n\n<pre><code>cars.Honda.Accord\ncars.Toyota.Prius\n</code></pre>\n\n<p>...using...</p>\n\n<pre><code>var cars = {\n Honda : {\n Accord : [\"2dr\", \"4dr\"],\n CRV : [\"2dr\", \"Hatchback\"],\n Pilot : [\"base\", \"superDuper\"]\n },\n Toyota : {\n Prius : [\"green\", \"reallyGreen\"],\n Camry : [\"sporty\", \"square\"],\n Corolla : [\"cheap\", \"superFly\"]\n }\n};\n</code></pre>\n" }, { "answer_id": 180861, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 2, "selected": false, "text": "<p>Jonathan's is correct, but he missed the additional level of Array's at the model level, so it should be</p>\n\n<pre><code> cars[0].models[0].Accord\n cars[0].models[1].CRV\n</code></pre>\n\n<p>etc</p>\n\n<p>I suspect you would find it easier to use a structure along the lines of:</p>\n\n<pre><code>var cars = [\n{makes : \"Honda\",\n models : {\n Accord : [\"2dr\",\"4dr\"],\n CRV : [\"2dr\",\"Hatchback\"],\n Pilot: [\"base\",\"superDuper\"] \n }\n}, \n{makes :\"Toyota\",\n models : {\n Prius : [\"green\",\"reallyGreen\"],\n Camry : [\"sporty\",\"square\"],\n Corolla : [\"cheap\",\"superFly\"]\n }\n}];\n</code></pre>\n\n<p>In which the <code>models</code> array is replaced by an object (or associative array if you like)</p>\n\n<p>[edit (olliej): tidying up code in second example]</p>\n" }, { "answer_id": 180863, "author": "Daddy Warbox", "author_id": 19825, "author_profile": "https://Stackoverflow.com/users/19825", "pm_score": 0, "selected": false, "text": "<p>If I were you, I wouldn't lump all your data into one big multidimensional array/object literal mess like that. I'd encapsulate each object and use methods to access the data. It'll mess with your brain a lot less.</p>\n" }, { "answer_id": 180952, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 2, "selected": false, "text": "<p>You can traverse models with this code:</p>\n\n<pre>\nfor (var i = 0, carslen = cars.length; i &lt; carslen; i++) {\n for (var j = 0, modelslen = cars[i].models.length; j &lt; modelslen; j++) {\n // do something with cars[i].models[j]\n }\n}\n</pre>\n\n<p>but I agree with Olliej about changing the structure of your JSON to his format.</p>\n" }, { "answer_id": 180968, "author": "Marko Dumic", "author_id": 5817, "author_profile": "https://Stackoverflow.com/users/5817", "pm_score": 4, "selected": true, "text": "<p>The structure:</p>\n\n<pre><code>var cars = [\n { name: 'Honda', models: [\n { name: 'Accord', features: ['2dr', '4dr'] },\n { name: 'CRV', features: ['2dr', 'Hatchback'] },\n { name: 'Pilot', features: ['base', 'superDuper'] }\n ]},\n\n { name: 'Toyota', models: [\n { name: 'Prius', features: ['green', 'superGreen'] },\n { name: 'Camry', features: ['sporty', 'square'] },\n { name: 'Corolla', features: ['cheap', 'superFly'] }\n ]}\n];\n</code></pre>\n\n<p>I wrote about the traversal and everything else <a href=\"https://stackoverflow.com/questions/180451/using-javascript-and-jquery-to-populate-related-select-boxes-with-array-structu#180926\">here</a>.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
How would you reference the models (Accord, CRV, Prius, etc) in this structure? Is this a bad structure to be able to extract the makes...then use a make to get the models...then use the model to get the options? ``` var cars = [ { "makes" : "Honda", "models" : [ {'Accord' : ["2dr","4dr"]} , {'CRV' : ["2dr","Hatchback"]} , {'Pilot' : ["base","superDuper"] } ] }, { "makes" : "Toyota", "models" : [ {'Prius' : ["green","reallyGreen"]} , {'Camry' : ["sporty","square"]} , {'Corolla' : ["cheap","superFly"] } ] } ]; ``` Thanks
The structure: ``` var cars = [ { name: 'Honda', models: [ { name: 'Accord', features: ['2dr', '4dr'] }, { name: 'CRV', features: ['2dr', 'Hatchback'] }, { name: 'Pilot', features: ['base', 'superDuper'] } ]}, { name: 'Toyota', models: [ { name: 'Prius', features: ['green', 'superGreen'] }, { name: 'Camry', features: ['sporty', 'square'] }, { name: 'Corolla', features: ['cheap', 'superFly'] } ]} ]; ``` I wrote about the traversal and everything else [here](https://stackoverflow.com/questions/180451/using-javascript-and-jquery-to-populate-related-select-boxes-with-array-structu#180926).
180,853
<p>What is the maximum length for the text string contained in a CEdit control in MFC? I get a beep when trying to add a character after the character 30001 is this documented anywhere? Can I display longer texts in a CEdit? Should I use another control?</p> <p>As "Windows programmer" says down below, the text length limit is not the same when the user types as when we programatically set the text using SetWindowText. The limit for setting a text programatically is not mentioned anywhere. The default text lentgth limit for the user typing is wrong. (see my own post below). </p> <p>I'm guessing that after I call pEdit->SetLimitText(0) the limit for both programatically and user input text length is 7FFFFFFE bytes. Am I right?</p> <p>In vista, when pasting text longer than 40000 characters into a CEdit, it becomes unresponsive. It does not matter if I called SetLimitText(100000) previously.</p>
[ { "answer_id": 181345, "author": "ryan_s", "author_id": 13728, "author_profile": "https://Stackoverflow.com/users/13728", "pm_score": 3, "selected": false, "text": "<p>You can find out what the maximum is for your control by calling <a href=\"http://msdn.microsoft.com/en-us/library/xctw3bfb(VS.80).aspx\" rel=\"noreferrer\">CEdit::GetLimitText()</a> on your control. This returns the maximum size for character data in bytes. You can change the maximum size using the <a href=\"http://msdn.microsoft.com/en-us/library/c4db48kc(VS.80).aspx\" rel=\"noreferrer\">CEdit::SetLimitText()</a> function.</p>\n\n<p>The SetLimitText() function is equivalent to sending an <a href=\"http://msdn.microsoft.com/en-us/library/bb761647(VS.85).aspx\" rel=\"noreferrer\">EM_SETLIMITTEXT</a> message. The documentation for that message gives the maximum sizes that can be used, but since these are MSDN links that will probably be broken by tomorrow, I'll copy the relevant information :)</p>\n\n<p>The UINT parameter is interpreted as:</p>\n\n<blockquote>\n <p>The maximum number of TCHARs the user\n can enter. For ANSI text, this is the\n number of bytes; for Unicode text,\n this is the number of characters. This\n number does not include the\n terminating null character. Rich edit\n controls: If this parameter is zero,\n the text length is set to 64,000\n characters.</p>\n \n <p>Edit controls on Windows NT/2000/XP:\n If this parameter is zero, the text\n length is set to 0x7FFFFFFE characters\n for single-line edit controls or –1\n for multiline edit controls.</p>\n \n <p>Edit controls on Windows 95/98/Me: If\n this parameter is zero, the text\n length is set to 0x7FFE characters for\n single-line edit controls or 0xFFFF\n for multiline edit controls.</p>\n</blockquote>\n\n<p>Also, from the Remarks section:</p>\n\n<blockquote>\n <p>Before EM_SETLIMITTEXT is called, the\n default limit for the amount of text a\n user can enter in an edit control is\n 32,767 characters.</p>\n \n <p>Edit controls on Windows NT/2000/XP:\n For single-line edit controls, the\n text limit is either 0x7FFFFFFE bytes\n or the value of the wParam parameter,\n whichever is smaller. For multiline\n edit controls, this value is either –1\n bytes or the value of the wParam\n parameter, whichever is smaller.</p>\n \n <p>Edit controls on Windows 95/98/Me: For\n single-line edit controls, the text\n limit is either 0x7FFE bytes or the\n value of the wParam parameter,\n whichever is smaller. For multiline\n edit controls, this value is either\n 0xFFFF bytes or the value of the\n wParam parameter, whichever is\n smaller.</p>\n</blockquote>\n\n<p>I assume they meant 0xFFFFFFFF instead of -1 in the second paragraph there...</p>\n" }, { "answer_id": 181391, "author": "Windows programmer", "author_id": 23705, "author_profile": "https://Stackoverflow.com/users/23705", "pm_score": 2, "selected": false, "text": "<p>\"(in characters it can display)\" != \"when trying to add a character\".</p>\n\n<p>\"when trying to add a character\" == \"The maximum number of TCHARs the user can enter\"\nunless you mean programmatically trying to add a character.</p>\n\n<p>\"0x7FFFFFFE characters\" != \"0x7FFFFFFE bytes\"\nexcept sometimes, a fact which the quoted MSDN text understands sometimes.</p>\n\n<p>I'll bet no one knows the answer to the original question. But \"0x7FFFFFFE bytes\" is likely one of many limits.</p>\n" }, { "answer_id": 184484, "author": "rec", "author_id": 14022, "author_profile": "https://Stackoverflow.com/users/14022", "pm_score": 5, "selected": true, "text": "<p>I found the documentation is wrong when mentioning the default size for a single line CEdit control in vista.</p>\n\n<p>I ran this code:</p>\n\n<pre><code>CWnd* pWnd = dlg.GetDlgItem(nItemId);\nCEdit *edit = static_cast&lt;CEdit*&gt;(pWnd); //dynamic_cast does not work\nif(edit != 0)\n{\n UINT limit = edit-&gt;GetLimitText(); //The current text limit, in bytes, for this CEdit object.\n //value returned: 30000 (0x7530)\n edit-&gt;SetLimitText(0);\n limit = edit-&gt;GetLimitText();\n //value returned: 2147483646 (0x7FFFFFFE) \n}\n</code></pre>\n\n<p>the documentation states:</p>\n\n<blockquote>\n <p>Before EM_SETLIMITTEXT is called, the\n default limit for the amount of text a\n user can enter in an edit control is\n 32,767 characters.</p>\n</blockquote>\n\n<p>which is apparently wrong.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14022/" ]
What is the maximum length for the text string contained in a CEdit control in MFC? I get a beep when trying to add a character after the character 30001 is this documented anywhere? Can I display longer texts in a CEdit? Should I use another control? As "Windows programmer" says down below, the text length limit is not the same when the user types as when we programatically set the text using SetWindowText. The limit for setting a text programatically is not mentioned anywhere. The default text lentgth limit for the user typing is wrong. (see my own post below). I'm guessing that after I call pEdit->SetLimitText(0) the limit for both programatically and user input text length is 7FFFFFFE bytes. Am I right? In vista, when pasting text longer than 40000 characters into a CEdit, it becomes unresponsive. It does not matter if I called SetLimitText(100000) previously.
I found the documentation is wrong when mentioning the default size for a single line CEdit control in vista. I ran this code: ``` CWnd* pWnd = dlg.GetDlgItem(nItemId); CEdit *edit = static_cast<CEdit*>(pWnd); //dynamic_cast does not work if(edit != 0) { UINT limit = edit->GetLimitText(); //The current text limit, in bytes, for this CEdit object. //value returned: 30000 (0x7530) edit->SetLimitText(0); limit = edit->GetLimitText(); //value returned: 2147483646 (0x7FFFFFFE) } ``` the documentation states: > > Before EM\_SETLIMITTEXT is called, the > default limit for the amount of text a > user can enter in an edit control is > 32,767 characters. > > > which is apparently wrong.
180,884
<p>When using </p> <pre><code>$('.foo').click(function(){ alert("I haz class alertz!"); return false; }); </code></pre> <p>in application.js, and</p> <pre><code>&lt;a href = "" class = "foo" id = "foobar_1" &gt;Teh Foobar &lt;/a&gt; </code></pre> <p>in any div that initializes with the page, when clicking "Teh Foobar" it alerts and doesn't follow the link. However, when using the same code in application.js, and</p> <pre><code>&lt;a href = "" class = "foo" id = "foobar_1" &gt;Teh Foobar &lt;/a&gt; </code></pre> <p>is being returned into a div by a</p> <pre><code>form_remote_tag </code></pre> <p>when clicked, "Teh Foobar" fails to alert, and functions as a link.</p> <p>What is happening, and how do I get around it?</p>
[ { "answer_id": 180876, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 5, "selected": false, "text": "<p>We've used <a href=\"http://www.openssl.org/\" rel=\"noreferrer\">OpenSSL</a> with good success. Portable, standards compliant and easy to use.</p>\n" }, { "answer_id": 180881, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 4, "selected": false, "text": "<p>I'm gonna have to go with <a href=\"https://github.com/libtom/libtomcrypt\" rel=\"noreferrer\">LibTomCrypt</a>. It's often overlooked for OpenSSL, but TomCrypt is just so lightweight and simple. As for quality, TomCrypt is widely accepted as top-quality encryption. Also, it's license is public domain which avoids the attribution hassle for your documentation that BSD licenses give you when writing commercial software.</p>\n" }, { "answer_id": 180890, "author": "dicroce", "author_id": 3886, "author_profile": "https://Stackoverflow.com/users/3886", "pm_score": 3, "selected": false, "text": "<p>My favorite is GNU's library:</p>\n<p><a href=\"http://www.gnu.org/software/libgcrypt/\" rel=\"nofollow noreferrer\">libgcrypt</a></p>\n<p>Its performance is good, and it's used EVERYWHERE so it's very well tested.</p>\n" }, { "answer_id": 181047, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 2, "selected": false, "text": "<p>The C++ version isn't out yet but goolge KeyCzar <a href=\"http://code.google.com/p/keyczar/\" rel=\"nofollow noreferrer\">http://code.google.com/p/keyczar/</a> might be worth looking at. Whatever you feel about their business they do have a lot of smart programmers working for them.</p>\n" }, { "answer_id": 181185, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://cryptopp.com\" rel=\"nofollow noreferrer\">Crypto++</a> seems to have a very good reputation</p>\n\n<p>Wikipedia - <a href=\"https://en.wikipedia.org/wiki/Crypto%2B%2B\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Crypto%2B%2B</a></p>\n\n<p>GitHub - <a href=\"https://github.com/weidai11/cryptopp\" rel=\"nofollow noreferrer\">https://github.com/weidai11/cryptopp</a></p>\n" }, { "answer_id": 181841, "author": "Roel", "author_id": 11449, "author_profile": "https://Stackoverflow.com/users/11449", "pm_score": 4, "selected": false, "text": "<p>I've used CryptoPP in the past (<a href=\"http://www.cryptopp.com/\" rel=\"noreferrer\">http://www.cryptopp.com/</a>) and although its API style and programming paradigms take a little getting used to, I liked it in the end. It provides a wide range of symmetric and asymmetric algorithms with much flexibility. Documentation is so-so, the API docs are there but there's little 'high-level' overview and simple sample code. I ended up puzzling together pieces of code from around the net. It was easy to integrate into my project (linked statically). I'm using MSVC - 2003 when I started using it, now switched to 2008. It's portable across several platforms (check out the website). I've always used the default RNG, don't know which one that is.</p>\n" }, { "answer_id": 183332, "author": "bortzmeyer", "author_id": 15625, "author_profile": "https://Stackoverflow.com/users/15625", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.gnupg.org/related_software/gpgme/index.en.html\" rel=\"nofollow noreferrer\">GPGme</a>. Simple to use and compatible with the <a href=\"http://www.ietf.org/rfc/rfc4880.txt\" rel=\"nofollow noreferrer\">OpenPGP format</a></p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/180884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23885/" ]
When using ``` $('.foo').click(function(){ alert("I haz class alertz!"); return false; }); ``` in application.js, and ``` <a href = "" class = "foo" id = "foobar_1" >Teh Foobar </a> ``` in any div that initializes with the page, when clicking "Teh Foobar" it alerts and doesn't follow the link. However, when using the same code in application.js, and ``` <a href = "" class = "foo" id = "foobar_1" >Teh Foobar </a> ``` is being returned into a div by a ``` form_remote_tag ``` when clicked, "Teh Foobar" fails to alert, and functions as a link. What is happening, and how do I get around it?
We've used [OpenSSL](http://www.openssl.org/) with good success. Portable, standards compliant and easy to use.
180,924
<p>Working in Eclipse on a Dynamic Web Project (using Tomcat (v5.5) as the app server), is there some way I can configure things so Tomcat will start with security turned on (i.e. as if I ran catalina.sh start -security)?</p>
[ { "answer_id": 180964, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<p>I'm assuming that you're using Tomcat 5.5.x</p>\n\n<p>after looking at catalina.bat/catalina.sh, all the -security flag does is to set \n-Djava.security.policy==\"%CATALINA_BASE%\\conf\\catalina.policy\"</p>\n\n<p>Most people have CATALINA_BASE set to TOMCAT_HOME or CATALINA_HOME</p>\n\n<p>So, if you have installed tomcat in the directoryc:\\tomcat, then all you need to do is to set an option in the tomcat plugin to include the above policy.<br>\ni.e, add this to JAVA_OPTIONS : -Djava.security.policy==\"c:\\tomcat\\conf\\catalina.policy\".</p>\n\n<p>That's all and restart.</p>\n" }, { "answer_id": 181401, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": 4, "selected": true, "text": "<p>Go into 'Window' -> 'Preferences' then select 'Java' -> 'Installed JREs', clone the JRE used by Tomcat and add the following to the default VM Arguments</p>\n\n<pre><code>-Djava.security.manager -Djava.security.policy=\"XXXX\\conf\\catalina.policy\"\n</code></pre>\n\n<p>With XXXX replaced by the appropriate path - Mine was <code>C:\\Program Files\\Apache Software Foundation\\Tomcat 5.5</code>). Then change the JRE name (I added \"security enabled\" to the end) and click 'Finish'.</p>\n\n<p>After that, open 'Server' -> 'Runtime Environments' in the preferences, and select your Apache Tomcat environment, then click the 'Edit...' button. In the resulting window, select the new security enabled JRE, then click 'Finish' and restart Tomcat.</p>\n" }, { "answer_id": 15018320, "author": "hotohoto", "author_id": 1874690, "author_profile": "https://Stackoverflow.com/users/1874690", "pm_score": 2, "selected": false, "text": "<p>Or you can just check \"Enable Security\" in Server Overview page.</p>\n\n<p>(Server -> your server setting -> Overview )</p>\n\n<p>then eclipse will add parameters below</p>\n\n<blockquote>\n <p>-Djava.security.manager -Djava.security.policy=X:XXX\\XXX.metadata.plugins\\org.eclipse.wst.server.core\\tmp0\\conf\\catalina.policy\n -Dwtp.configured.security=true</p>\n</blockquote>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/180924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
Working in Eclipse on a Dynamic Web Project (using Tomcat (v5.5) as the app server), is there some way I can configure things so Tomcat will start with security turned on (i.e. as if I ran catalina.sh start -security)?
Go into 'Window' -> 'Preferences' then select 'Java' -> 'Installed JREs', clone the JRE used by Tomcat and add the following to the default VM Arguments ``` -Djava.security.manager -Djava.security.policy="XXXX\conf\catalina.policy" ``` With XXXX replaced by the appropriate path - Mine was `C:\Program Files\Apache Software Foundation\Tomcat 5.5`). Then change the JRE name (I added "security enabled" to the end) and click 'Finish'. After that, open 'Server' -> 'Runtime Environments' in the preferences, and select your Apache Tomcat environment, then click the 'Edit...' button. In the resulting window, select the new security enabled JRE, then click 'Finish' and restart Tomcat.
180,929
<p>I want to programmatically create a new column in an MS Access table. I've tried many permutations of <code>ALTER TABLE MyTable Add MyField DECIMAL (9,4) NULL;</code> and got: </p> <blockquote> <p>Syntax Error in Field Definition</p> </blockquote> <p>I can easily create a number field that goes to a <code>Double</code> type, but I want <code>decimal</code>. I would very strongly prefer to do this in a single <code>ALTER TABLE</code> statement and not have to create a field and then alter it. </p> <p>I am using Access 2003.</p>
[ { "answer_id": 180980, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 2, "selected": false, "text": "<p>The ALTER TABLE syntax is only supported in Jet 4.0/ACE while in\nANSI-92 Query Mode. Try an ADO connection e.g.</p>\n\n<p>CurrentProject.Connection.Execute \"ALTER TABLE myTbl ADD COLUMN myColumn DECIMAL(9,4)\"</p>\n" }, { "answer_id": 181169, "author": "Chris OC", "author_id": 11041, "author_profile": "https://Stackoverflow.com/users/11041", "pm_score": 3, "selected": false, "text": "<p>The decimal data type isn't supported in the default Jet 4.0 mdb file. You have to use the SQL Server compatibility syntax (ANSI 92) setting to use the decimal data type in the SQL Window.</p>\n\n<p>Click on the menu, Tools > Options. Click on the Tables/Query tab. Mark the check box for \"This database\" in the SQL Server compatibility syntax (ANSI 92) section. This mode will affect the entire db, including queries with wildcards, so you may want to try this on a copy of your db.</p>\n\n<p>Paste this into the SQL window:</p>\n\n<pre><code>ALTER TABLE MyTable\n Add COLUMN MyField DECIMAL (9,4) NULL;\n</code></pre>\n\n<p>If you don't want to alter the mode of your database, you must use vba code with the adodb library:</p>\n\n<pre><code>Dim conn As ADODB.Connection\n\nSet conn = CurrentProject.Connection\nconn.Execute \"ALTER TABLE MyTable \" _\n &amp; \"ADD COLUMN MyField DECIMAL (9,4) NULL;\"\nconn.Close\n</code></pre>\n" }, { "answer_id": 181763, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 3, "selected": true, "text": "<p>If you want to create a new column in an acces table, it is easy to use the DAO.tableDef object:</p>\n\n<pre><code>Dim my_tableDef As DAO.TableDef\nDim my_field As DAO.Field\n\nSet my_tableDef = currentDb.TableDefs(my_table)\nSet my_Field = my_tableDef.CreateField(my_fieldName, dbDecimal, myFieldSize)\nmy_Field.decimalPlaces = myDecimalPlaces\nmy_Field.defaultValue = myDefaultValue\n\nmy_tableDef.Fields.Append my_Field\n\nset my_Field = nothing\nset my_tableDef = nothing\n</code></pre>\n\n<p>Of course you can further delete it.</p>\n\n<p>You might have the posibility to do so with ADODB (or ADOX?) object, but as long as you are working on an mdb file, DAO is straight and efficient.</p>\n\n<p>PS: after checking on some forums, it seems there is a bug with decimal fields and DAO. <a href=\"http://allenbrowne.com/bug-08.html\" rel=\"nofollow noreferrer\">http://allenbrowne.com/bug-08.html</a>. Advices are \"go for double\"(which is what I do usually to avoid any loosy issues related to decimal rounding) or use \"implicite\" ADO to modify your database</p>\n\n<pre><code>strSql = \"ALTER TABLE MyTable ADD COLUMN MyField DECIMAL (28,3);\"\nCurrentProject.Connection.Execute strSql\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/180929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12897/" ]
I want to programmatically create a new column in an MS Access table. I've tried many permutations of `ALTER TABLE MyTable Add MyField DECIMAL (9,4) NULL;` and got: > > Syntax Error in Field Definition > > > I can easily create a number field that goes to a `Double` type, but I want `decimal`. I would very strongly prefer to do this in a single `ALTER TABLE` statement and not have to create a field and then alter it. I am using Access 2003.
If you want to create a new column in an acces table, it is easy to use the DAO.tableDef object: ``` Dim my_tableDef As DAO.TableDef Dim my_field As DAO.Field Set my_tableDef = currentDb.TableDefs(my_table) Set my_Field = my_tableDef.CreateField(my_fieldName, dbDecimal, myFieldSize) my_Field.decimalPlaces = myDecimalPlaces my_Field.defaultValue = myDefaultValue my_tableDef.Fields.Append my_Field set my_Field = nothing set my_tableDef = nothing ``` Of course you can further delete it. You might have the posibility to do so with ADODB (or ADOX?) object, but as long as you are working on an mdb file, DAO is straight and efficient. PS: after checking on some forums, it seems there is a bug with decimal fields and DAO. <http://allenbrowne.com/bug-08.html>. Advices are "go for double"(which is what I do usually to avoid any loosy issues related to decimal rounding) or use "implicite" ADO to modify your database ``` strSql = "ALTER TABLE MyTable ADD COLUMN MyField DECIMAL (28,3);" CurrentProject.Connection.Execute strSql ```
180,930
<p>I am attempting to use linq to shape list of data into a particular shape to be returned as Json from an ajax call.</p> <p>Given this data:</p> <pre><code>var data = new List&lt;string&gt;(); data.Add("One"); data.Add("Two"); data.Add("Three"); </code></pre> <p>And this code: ** Which is not correct and is what needs to be fixed!! **</p> <pre><code>var shaped = data.Select(c =&gt; new { c = c } ).ToList(); serializer.Serialize(shaped,sb); string desiredResult = sb.ToString(); </code></pre> <p>I would like <code>desiredResult</code> to be:</p> <pre><code>{ "One": "One", "Two": "Two", "Three": "Three" } </code></pre> <p>but it is currently:</p> <p><code>{ "c" : "One" },{ "c" : "Two" }</code>, etc. </p> <p>One problem is that on the left side of the object initializer I want the value of <code>c</code>, not <code>c</code> itself...</p>
[ { "answer_id": 180980, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 2, "selected": false, "text": "<p>The ALTER TABLE syntax is only supported in Jet 4.0/ACE while in\nANSI-92 Query Mode. Try an ADO connection e.g.</p>\n\n<p>CurrentProject.Connection.Execute \"ALTER TABLE myTbl ADD COLUMN myColumn DECIMAL(9,4)\"</p>\n" }, { "answer_id": 181169, "author": "Chris OC", "author_id": 11041, "author_profile": "https://Stackoverflow.com/users/11041", "pm_score": 3, "selected": false, "text": "<p>The decimal data type isn't supported in the default Jet 4.0 mdb file. You have to use the SQL Server compatibility syntax (ANSI 92) setting to use the decimal data type in the SQL Window.</p>\n\n<p>Click on the menu, Tools > Options. Click on the Tables/Query tab. Mark the check box for \"This database\" in the SQL Server compatibility syntax (ANSI 92) section. This mode will affect the entire db, including queries with wildcards, so you may want to try this on a copy of your db.</p>\n\n<p>Paste this into the SQL window:</p>\n\n<pre><code>ALTER TABLE MyTable\n Add COLUMN MyField DECIMAL (9,4) NULL;\n</code></pre>\n\n<p>If you don't want to alter the mode of your database, you must use vba code with the adodb library:</p>\n\n<pre><code>Dim conn As ADODB.Connection\n\nSet conn = CurrentProject.Connection\nconn.Execute \"ALTER TABLE MyTable \" _\n &amp; \"ADD COLUMN MyField DECIMAL (9,4) NULL;\"\nconn.Close\n</code></pre>\n" }, { "answer_id": 181763, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 3, "selected": true, "text": "<p>If you want to create a new column in an acces table, it is easy to use the DAO.tableDef object:</p>\n\n<pre><code>Dim my_tableDef As DAO.TableDef\nDim my_field As DAO.Field\n\nSet my_tableDef = currentDb.TableDefs(my_table)\nSet my_Field = my_tableDef.CreateField(my_fieldName, dbDecimal, myFieldSize)\nmy_Field.decimalPlaces = myDecimalPlaces\nmy_Field.defaultValue = myDefaultValue\n\nmy_tableDef.Fields.Append my_Field\n\nset my_Field = nothing\nset my_tableDef = nothing\n</code></pre>\n\n<p>Of course you can further delete it.</p>\n\n<p>You might have the posibility to do so with ADODB (or ADOX?) object, but as long as you are working on an mdb file, DAO is straight and efficient.</p>\n\n<p>PS: after checking on some forums, it seems there is a bug with decimal fields and DAO. <a href=\"http://allenbrowne.com/bug-08.html\" rel=\"nofollow noreferrer\">http://allenbrowne.com/bug-08.html</a>. Advices are \"go for double\"(which is what I do usually to avoid any loosy issues related to decimal rounding) or use \"implicite\" ADO to modify your database</p>\n\n<pre><code>strSql = \"ALTER TABLE MyTable ADD COLUMN MyField DECIMAL (28,3);\"\nCurrentProject.Connection.Execute strSql\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/180930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/410357/" ]
I am attempting to use linq to shape list of data into a particular shape to be returned as Json from an ajax call. Given this data: ``` var data = new List<string>(); data.Add("One"); data.Add("Two"); data.Add("Three"); ``` And this code: \*\* Which is not correct and is what needs to be fixed!! \*\* ``` var shaped = data.Select(c => new { c = c } ).ToList(); serializer.Serialize(shaped,sb); string desiredResult = sb.ToString(); ``` I would like `desiredResult` to be: ``` { "One": "One", "Two": "Two", "Three": "Three" } ``` but it is currently: `{ "c" : "One" },{ "c" : "Two" }`, etc. One problem is that on the left side of the object initializer I want the value of `c`, not `c` itself...
If you want to create a new column in an acces table, it is easy to use the DAO.tableDef object: ``` Dim my_tableDef As DAO.TableDef Dim my_field As DAO.Field Set my_tableDef = currentDb.TableDefs(my_table) Set my_Field = my_tableDef.CreateField(my_fieldName, dbDecimal, myFieldSize) my_Field.decimalPlaces = myDecimalPlaces my_Field.defaultValue = myDefaultValue my_tableDef.Fields.Append my_Field set my_Field = nothing set my_tableDef = nothing ``` Of course you can further delete it. You might have the posibility to do so with ADODB (or ADOX?) object, but as long as you are working on an mdb file, DAO is straight and efficient. PS: after checking on some forums, it seems there is a bug with decimal fields and DAO. <http://allenbrowne.com/bug-08.html>. Advices are "go for double"(which is what I do usually to avoid any loosy issues related to decimal rounding) or use "implicite" ADO to modify your database ``` strSql = "ALTER TABLE MyTable ADD COLUMN MyField DECIMAL (28,3);" CurrentProject.Connection.Execute strSql ```
180,935
<p>I've got a LOT of tests written for a piece of software (which is a GREAT thing) but it was built essentially as a standalone test in C#. While this works well enough, it suffers from a few shortcomings, not the least of which is that it isn't using a standard testing framework and ends up requiring the person running the test to comment out calls to tests that shouldn't be run (when it isn't desired to run the entire test 'suite'). I'd like to incorporate it into my automated testing process.</p> <p>I saw that the Test Edition of VS 2008 has the notion of a 'Generic Test' that might do what I want, but we're not in a position to spend the money on that version currently. I recently started using the VS 2008 Pro version.</p> <p>These test methods follow a familiar pattern:</p> <ul> <li>Do some setup for the test. </li> <li>Execute the test.</li> <li>Reset for the next test.</li> </ul> <p>Each of them returns a bool (pass/fail) and a string ref to a fail reason, filled in if it fails.</p> <p>On the bright side, at least the test methods are consistent. </p> <p>I am sitting here tonight contemplating the approach I might take tomorrow morning to migrate all this test code to a testing framework and, frankly, I'm not all that excited about the idea of poring over 8-9K lines of test code by hand to do the conversion. </p> <p>Have you had any experience undertaking such a conversion? Do you have any tips? I think I might be stuck slogging through it all doing global search/replaces and hand-changing the tests.</p> <p>Any thoughts?</p>
[ { "answer_id": 180966, "author": "Jonathan Beerhalter", "author_id": 18927, "author_profile": "https://Stackoverflow.com/users/18927", "pm_score": 1, "selected": false, "text": "<p>You're about to live through the idiom of \"An Ounce of Prevention is worth a pound of cure\". Its especially true in programming. </p>\n\n<p>You make no mention of NUnit(which I think was bought by Microsoft for 2008, but don't hold me to that). Is there a paticular reason you didn't just use NUnit in the first place?</p>\n" }, { "answer_id": 180977, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 3, "selected": true, "text": "<p>If you use NUnit (which you should), you'll need to create a new test method for each of your current test methods. NUnit uses reflection to query the test class for methods marked with the <code>[Test]</code> attribute, which is how it builds its list of the tests that show up in the UI, and the test classes use the NUnit <code>Assert</code> method to indicate whether they've passed or failed.</p>\n\n<p>It seems to me that if your test methods are as consistent as you say, all of those NUnit methods would look something like this:</p>\n\n<pre><code>[Test]\npublic void MyTest()\n{\n string msg;\n bool result = OldTestClass.MyTest(out msg);\n if (!result)\n {\n Console.WriteLine(msg);\n }\n Assert.AreEqual(result, true);\n</code></pre>\n\n<p>}</p>\n\n<p>Once you get that to work, your next step is to write a program that uses reflection to get all of the test method names on your old test class and produces a .cs file that has an NUnit method for each of your original test methods.</p>\n\n<p>Annoying, maybe, but not extremely painful. And you'll only need to do it once.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/180935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7862/" ]
I've got a LOT of tests written for a piece of software (which is a GREAT thing) but it was built essentially as a standalone test in C#. While this works well enough, it suffers from a few shortcomings, not the least of which is that it isn't using a standard testing framework and ends up requiring the person running the test to comment out calls to tests that shouldn't be run (when it isn't desired to run the entire test 'suite'). I'd like to incorporate it into my automated testing process. I saw that the Test Edition of VS 2008 has the notion of a 'Generic Test' that might do what I want, but we're not in a position to spend the money on that version currently. I recently started using the VS 2008 Pro version. These test methods follow a familiar pattern: * Do some setup for the test. * Execute the test. * Reset for the next test. Each of them returns a bool (pass/fail) and a string ref to a fail reason, filled in if it fails. On the bright side, at least the test methods are consistent. I am sitting here tonight contemplating the approach I might take tomorrow morning to migrate all this test code to a testing framework and, frankly, I'm not all that excited about the idea of poring over 8-9K lines of test code by hand to do the conversion. Have you had any experience undertaking such a conversion? Do you have any tips? I think I might be stuck slogging through it all doing global search/replaces and hand-changing the tests. Any thoughts?
If you use NUnit (which you should), you'll need to create a new test method for each of your current test methods. NUnit uses reflection to query the test class for methods marked with the `[Test]` attribute, which is how it builds its list of the tests that show up in the UI, and the test classes use the NUnit `Assert` method to indicate whether they've passed or failed. It seems to me that if your test methods are as consistent as you say, all of those NUnit methods would look something like this: ``` [Test] public void MyTest() { string msg; bool result = OldTestClass.MyTest(out msg); if (!result) { Console.WriteLine(msg); } Assert.AreEqual(result, true); ``` } Once you get that to work, your next step is to write a program that uses reflection to get all of the test method names on your old test class and produces a .cs file that has an NUnit method for each of your original test methods. Annoying, maybe, but not extremely painful. And you'll only need to do it once.
180,947
<p>Is there a freely available Base64 decoding code snippet in C++?</p>
[ { "answer_id": 180949, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 8, "selected": true, "text": "<p>See <em><a href=\"http://www.adp-gmbh.ch/cpp/common/base64.html\" rel=\"noreferrer\">Encoding and decoding base 64 with C++</a></em>.</p>\n<p>Here is the implementation from that page:</p>\n<pre><code>/*\n base64.cpp and base64.h\n\n Copyright (C) 2004-2008 René Nyffenegger\n\n This source code is provided 'as-is', without any express or implied\n warranty. In no event will the author be held liable for any damages\n arising from the use of this software.\n\n Permission is granted to anyone to use this software for any purpose,\n including commercial applications, and to alter it and redistribute it\n freely, subject to the following restrictions:\n\n 1. The origin of this source code must not be misrepresented; you must not\n claim that you wrote the original source code. If you use this source code\n in a product, an acknowledgment in the product documentation would be\n appreciated but is not required.\n\n 2. Altered source versions must be plainly marked as such, and must not be\n misrepresented as being the original source code.\n\n 3. This notice may not be removed or altered from any source distribution.\n\n René Nyffenegger [email protected]\n\n*/\n\nstatic const std::string base64_chars =\n &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;\n &quot;abcdefghijklmnopqrstuvwxyz&quot;\n &quot;0123456789+/&quot;;\n\n\nstatic inline bool is_base64(unsigned char c) {\n return (isalnum(c) || (c == '+') || (c == '/'));\n}\n\nstd::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {\n std::string ret;\n int i = 0;\n int j = 0;\n unsigned char char_array_3[3];\n unsigned char char_array_4[4];\n\n while (in_len--) {\n char_array_3[i++] = *(bytes_to_encode++);\n if (i == 3) {\n char_array_4[0] = (char_array_3[0] &amp; 0xfc) &gt;&gt; 2;\n char_array_4[1] = ((char_array_3[0] &amp; 0x03) &lt;&lt; 4) + ((char_array_3[1] &amp; 0xf0) &gt;&gt; 4);\n char_array_4[2] = ((char_array_3[1] &amp; 0x0f) &lt;&lt; 2) + ((char_array_3[2] &amp; 0xc0) &gt;&gt; 6);\n char_array_4[3] = char_array_3[2] &amp; 0x3f;\n\n for(i = 0; (i &lt;4) ; i++)\n ret += base64_chars[char_array_4[i]];\n i = 0;\n }\n }\n\n if (i)\n {\n for(j = i; j &lt; 3; j++)\n char_array_3[j] = '\\0';\n\n char_array_4[0] = (char_array_3[0] &amp; 0xfc) &gt;&gt; 2;\n char_array_4[1] = ((char_array_3[0] &amp; 0x03) &lt;&lt; 4) + ((char_array_3[1] &amp; 0xf0) &gt;&gt; 4);\n char_array_4[2] = ((char_array_3[1] &amp; 0x0f) &lt;&lt; 2) + ((char_array_3[2] &amp; 0xc0) &gt;&gt; 6);\n char_array_4[3] = char_array_3[2] &amp; 0x3f;\n\n for (j = 0; (j &lt; i + 1); j++)\n ret += base64_chars[char_array_4[j]];\n\n while((i++ &lt; 3))\n ret += '=';\n\n }\n\n return ret;\n\n}\nstd::string base64_decode(std::string const&amp; encoded_string) {\n int in_len = encoded_string.size();\n int i = 0;\n int j = 0;\n int in_ = 0;\n unsigned char char_array_4[4], char_array_3[3];\n std::string ret;\n\n while (in_len-- &amp;&amp; ( encoded_string[in_] != '=') &amp;&amp; is_base64(encoded_string[in_])) {\n char_array_4[i++] = encoded_string[in_]; in_++;\n if (i ==4) {\n for (i = 0; i &lt;4; i++)\n char_array_4[i] = base64_chars.find(char_array_4[i]);\n\n char_array_3[0] = (char_array_4[0] &lt;&lt; 2) + ((char_array_4[1] &amp; 0x30) &gt;&gt; 4);\n char_array_3[1] = ((char_array_4[1] &amp; 0xf) &lt;&lt; 4) + ((char_array_4[2] &amp; 0x3c) &gt;&gt; 2);\n char_array_3[2] = ((char_array_4[2] &amp; 0x3) &lt;&lt; 6) + char_array_4[3];\n\n for (i = 0; (i &lt; 3); i++)\n ret += char_array_3[i];\n i = 0;\n }\n }\n\n if (i) {\n for (j = i; j &lt;4; j++)\n char_array_4[j] = 0;\n\n for (j = 0; j &lt;4; j++)\n char_array_4[j] = base64_chars.find(char_array_4[j]);\n\n char_array_3[0] = (char_array_4[0] &lt;&lt; 2) + ((char_array_4[1] &amp; 0x30) &gt;&gt; 4);\n char_array_3[1] = ((char_array_4[1] &amp; 0xf) &lt;&lt; 4) + ((char_array_4[2] &amp; 0x3c) &gt;&gt; 2);\n char_array_3[2] = ((char_array_4[2] &amp; 0x3) &lt;&lt; 6) + char_array_4[3];\n\n for (j = 0; (j &lt; i - 1); j++) ret += char_array_3[j];\n }\n\n return ret;\n}\n</code></pre>\n" }, { "answer_id": 13935718, "author": "LihO", "author_id": 1168156, "author_profile": "https://Stackoverflow.com/users/1168156", "pm_score": 7, "selected": false, "text": "<p>Here's my modification of <a href=\"http://www.adp-gmbh.ch/cpp/common/base64.html\" rel=\"noreferrer\">the implementation that was originally written by <em>René Nyffenegger</em></a>. And why have I modified it? Well, because it didn't seem appropriate to me that I should work with binary data stored within <code>std::string</code> object ;)</p>\n<p><strong>base64.h</strong>:</p>\n<pre><code>#ifndef _BASE64_H_\n#define _BASE64_H_\n\n#include &lt;vector&gt;\n#include &lt;string&gt;\ntypedef unsigned char BYTE;\n\nstd::string base64_encode(BYTE const* buf, unsigned int bufLen);\nstd::vector&lt;BYTE&gt; base64_decode(std::string const&amp;);\n\n#endif\n</code></pre>\n<p><strong>base64.cpp</strong>:</p>\n<pre><code>#include &quot;base64.h&quot;\n#include &lt;iostream&gt;\n\nstatic const std::string base64_chars =\n &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;\n &quot;abcdefghijklmnopqrstuvwxyz&quot;\n &quot;0123456789+/&quot;;\n\n\nstatic inline bool is_base64(BYTE c) {\n return (isalnum(c) || (c == '+') || (c == '/'));\n}\n\nstd::string base64_encode(BYTE const* buf, unsigned int bufLen) {\n std::string ret;\n int i = 0;\n int j = 0;\n BYTE char_array_3[3];\n BYTE char_array_4[4];\n\n while (bufLen--) {\n char_array_3[i++] = *(buf++);\n if (i == 3) {\n char_array_4[0] = (char_array_3[0] &amp; 0xfc) &gt;&gt; 2;\n char_array_4[1] = ((char_array_3[0] &amp; 0x03) &lt;&lt; 4) + ((char_array_3[1] &amp; 0xf0) &gt;&gt; 4);\n char_array_4[2] = ((char_array_3[1] &amp; 0x0f) &lt;&lt; 2) + ((char_array_3[2] &amp; 0xc0) &gt;&gt; 6);\n char_array_4[3] = char_array_3[2] &amp; 0x3f;\n\n for(i = 0; (i &lt;4) ; i++)\n ret += base64_chars[char_array_4[i]];\n i = 0;\n }\n }\n\n if (i)\n {\n for(j = i; j &lt; 3; j++)\n char_array_3[j] = '\\0';\n\n char_array_4[0] = (char_array_3[0] &amp; 0xfc) &gt;&gt; 2;\n char_array_4[1] = ((char_array_3[0] &amp; 0x03) &lt;&lt; 4) + ((char_array_3[1] &amp; 0xf0) &gt;&gt; 4);\n char_array_4[2] = ((char_array_3[1] &amp; 0x0f) &lt;&lt; 2) + ((char_array_3[2] &amp; 0xc0) &gt;&gt; 6);\n char_array_4[3] = char_array_3[2] &amp; 0x3f;\n\n for (j = 0; (j &lt; i + 1); j++)\n ret += base64_chars[char_array_4[j]];\n\n while((i++ &lt; 3))\n ret += '=';\n }\n\n return ret;\n}\n\nstd::vector&lt;BYTE&gt; base64_decode(std::string const&amp; encoded_string) {\n int in_len = encoded_string.size();\n int i = 0;\n int j = 0;\n int in_ = 0;\n BYTE char_array_4[4], char_array_3[3];\n std::vector&lt;BYTE&gt; ret;\n\n while (in_len-- &amp;&amp; ( encoded_string[in_] != '=') &amp;&amp; is_base64(encoded_string[in_])) {\n char_array_4[i++] = encoded_string[in_]; in_++;\n if (i ==4) {\n for (i = 0; i &lt;4; i++)\n char_array_4[i] = base64_chars.find(char_array_4[i]);\n\n char_array_3[0] = (char_array_4[0] &lt;&lt; 2) + ((char_array_4[1] &amp; 0x30) &gt;&gt; 4);\n char_array_3[1] = ((char_array_4[1] &amp; 0xf) &lt;&lt; 4) + ((char_array_4[2] &amp; 0x3c) &gt;&gt; 2);\n char_array_3[2] = ((char_array_4[2] &amp; 0x3) &lt;&lt; 6) + char_array_4[3];\n\n for (i = 0; (i &lt; 3); i++)\n ret.push_back(char_array_3[i]);\n i = 0;\n }\n }\n\n if (i) {\n for (j = i; j &lt;4; j++)\n char_array_4[j] = 0;\n\n for (j = 0; j &lt;4; j++)\n char_array_4[j] = base64_chars.find(char_array_4[j]);\n\n char_array_3[0] = (char_array_4[0] &lt;&lt; 2) + ((char_array_4[1] &amp; 0x30) &gt;&gt; 4);\n char_array_3[1] = ((char_array_4[1] &amp; 0xf) &lt;&lt; 4) + ((char_array_4[2] &amp; 0x3c) &gt;&gt; 2);\n char_array_3[2] = ((char_array_4[2] &amp; 0x3) &lt;&lt; 6) + char_array_4[3];\n\n for (j = 0; (j &lt; i - 1); j++) ret.push_back(char_array_3[j]);\n }\n\n return ret;\n}\n</code></pre>\n<p>Here's the usage:</p>\n<pre><code>std::vector&lt;BYTE&gt; myData;\n...\nstd::string encodedData = base64_encode(&amp;myData[0], myData.size());\nstd::vector&lt;BYTE&gt; decodedData = base64_decode(encodedData);\n</code></pre>\n" }, { "answer_id": 25123052, "author": "azawadzki", "author_id": 3905597, "author_profile": "https://Stackoverflow.com/users/3905597", "pm_score": 4, "selected": false, "text": "<p>Using <a href=\"https://code.google.com/p/base-n/\" rel=\"noreferrer\">base-n</a> mini lib, you can do the following:</p>\n<pre><code>some_data_t in[] { ... };\nconstexpr int len = sizeof(in)/sizeof(in[0]);\n\nstd::string encoded;\nbn::encode_b64(in, in + len, std::back_inserter(encoded));\n\nsome_data_t out[len];\nbn::decode_b64(encoded.begin(), encoded.end(), out);\n</code></pre>\n<p>The API is generic, iterator-based.</p>\n<p>Disclosure: I'm the author.</p>\n" }, { "answer_id": 31322410, "author": "DaedalusAlpha", "author_id": 498519, "author_profile": "https://Stackoverflow.com/users/498519", "pm_score": 4, "selected": false, "text": "<p><em>According to <a href=\"https://stackoverflow.com/questions/342409/how-do-i-base64-encode-decode-in-c/41094722#41094722\">this excellent comparison</a> made by GaspardP I would not choose this solution. It's not the worst, but it's not the best either. The only thing it got going for it is that it's possibly easier to understand.</em></p>\n<p>I found the other two answers to be pretty hard to understand. They also produce some warnings in my compiler and the use of a find function in the decode part should result in a pretty bad efficiency. So I decided to roll my own.</p>\n<p>Header:</p>\n<pre><code>#ifndef _BASE64_H_\n#define _BASE64_H_\n\n#include &lt;vector&gt;\n#include &lt;string&gt;\ntypedef unsigned char BYTE;\n\nclass Base64\n{\npublic:\n static std::string encode(const std::vector&lt;BYTE&gt;&amp; buf);\n static std::string encode(const BYTE* buf, unsigned int bufLen);\n static std::vector&lt;BYTE&gt; decode(std::string encoded_string);\n};\n\n#endif\n</code></pre>\n<p>Body:</p>\n<pre><code>static const BYTE from_base64[] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 62, 255, 63,\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 255, 255, 255,\n 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 63,\n 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255};\n\nstatic const char to_base64[] =\n &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;\n &quot;abcdefghijklmnopqrstuvwxyz&quot;\n &quot;0123456789+/&quot;;\n\n\nstd::string Base64::encode(const std::vector&lt;BYTE&gt;&amp; buf)\n{\n if (buf.empty())\n return &quot;&quot;; // Avoid dereferencing buf if it's empty\n return encode(&amp;buf[0], (unsigned int)buf.size());\n}\n\nstd::string Base64::encode(const BYTE* buf, unsigned int bufLen)\n{\n // Calculate how many bytes that needs to be added to get a multiple of 3\n size_t missing = 0;\n size_t ret_size = bufLen;\n while ((ret_size % 3) != 0)\n {\n ++ret_size;\n ++missing;\n }\n\n // Expand the return string size to a multiple of 4\n ret_size = 4*ret_size/3;\n\n std::string ret;\n ret.reserve(ret_size);\n\n for (unsigned int i=0; i&lt;ret_size/4; ++i)\n {\n // Read a group of three bytes (avoid buffer overrun by replacing with 0)\n size_t index = i*3;\n BYTE b3[3];\n b3[0] = (index+0 &lt; bufLen) ? buf[index+0] : 0;\n b3[1] = (index+1 &lt; bufLen) ? buf[index+1] : 0;\n b3[2] = (index+2 &lt; bufLen) ? buf[index+2] : 0;\n\n // Transform into four base 64 characters\n BYTE b4[4];\n b4[0] = ((b3[0] &amp; 0xfc) &gt;&gt; 2);\n b4[1] = ((b3[0] &amp; 0x03) &lt;&lt; 4) + ((b3[1] &amp; 0xf0) &gt;&gt; 4);\n b4[2] = ((b3[1] &amp; 0x0f) &lt;&lt; 2) + ((b3[2] &amp; 0xc0) &gt;&gt; 6);\n b4[3] = ((b3[2] &amp; 0x3f) &lt;&lt; 0);\n\n // Add the base 64 characters to the return value\n ret.push_back(to_base64[b4[0]]);\n ret.push_back(to_base64[b4[1]]);\n ret.push_back(to_base64[b4[2]]);\n ret.push_back(to_base64[b4[3]]);\n }\n\n // Replace data that is invalid (always as many as there are missing bytes)\n for (size_t i=0; i&lt;missing; ++i)\n ret[ret_size - i - 1] = '=';\n\n return ret;\n}\n\nstd::vector&lt;BYTE&gt; Base64::decode(std::string encoded_string)\n{\n // Make sure string length is a multiple of 4\n while ((encoded_string.size() % 4) != 0)\n encoded_string.push_back('=');\n\n size_t encoded_size = encoded_string.size();\n std::vector&lt;BYTE&gt; ret;\n ret.reserve(3*encoded_size/4);\n\n for (size_t i=0; i&lt;encoded_size; i += 4)\n {\n // Get values for each group of four base 64 characters\n BYTE b4[4];\n b4[0] = (encoded_string[i+0] &lt;= 'z') ? from_base64[encoded_string[i+0]] : 0xff;\n b4[1] = (encoded_string[i+1] &lt;= 'z') ? from_base64[encoded_string[i+1]] : 0xff;\n b4[2] = (encoded_string[i+2] &lt;= 'z') ? from_base64[encoded_string[i+2]] : 0xff;\n b4[3] = (encoded_string[i+3] &lt;= 'z') ? from_base64[encoded_string[i+3]] : 0xff;\n\n // Transform into a group of three bytes\n BYTE b3[3];\n b3[0] = ((b4[0] &amp; 0x3f) &lt;&lt; 2) + ((b4[1] &amp; 0x30) &gt;&gt; 4);\n b3[1] = ((b4[1] &amp; 0x0f) &lt;&lt; 4) + ((b4[2] &amp; 0x3c) &gt;&gt; 2);\n b3[2] = ((b4[2] &amp; 0x03) &lt;&lt; 6) + ((b4[3] &amp; 0x3f) &gt;&gt; 0);\n\n // Add the byte to the return value if it isn't part of an '=' character (indicated by 0xff)\n if (b4[1] != 0xff) ret.push_back(b3[0]);\n if (b4[2] != 0xff) ret.push_back(b3[1]);\n if (b4[3] != 0xff) ret.push_back(b3[2]);\n }\n\n return ret;\n}\n</code></pre>\n<p>Usage:</p>\n<pre><code>BYTE buf[] = &quot;ABCD&quot;;\nstd::string encoded = Base64::encode(buf, 4);\n// encoded = &quot;QUJDRA==&quot;\nstd::vector&lt;BYTE&gt; decoded = Base64::decode(encoded);\n</code></pre>\n<p>A bonus here is that the decode function can also decode the URL variant of Base64 encoding.</p>\n" }, { "answer_id": 34571089, "author": "Manuel Martinez", "author_id": 5739045, "author_profile": "https://Stackoverflow.com/users/5739045", "pm_score": 6, "selected": false, "text": "<p>There are several snippets here. However, this one is compact, efficient, and C++11 friendly:</p>\n<pre><code>static std::string base64_encode(const std::string &amp;in) {\n\n std::string out;\n\n int val = 0, valb = -6;\n for (uchar c : in) {\n val = (val &lt;&lt; 8) + c;\n valb += 8;\n while (valb &gt;= 0) {\n out.push_back(&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/&quot;[(val&gt;&gt;valb)&amp;0x3F]);\n valb -= 6;\n }\n }\n if (valb&gt;-6) out.push_back(&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/&quot;[((val&lt;&lt;8)&gt;&gt;(valb+8))&amp;0x3F]);\n while (out.size()%4) out.push_back('=');\n return out;\n}\n\nstatic std::string base64_decode(const std::string &amp;in) {\n\n std::string out;\n\n std::vector&lt;int&gt; T(256,-1);\n for (int i=0; i&lt;64; i++) T[&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/&quot;[i]] = i;\n\n int val=0, valb=-8;\n for (uchar c : in) {\n if (T[c] == -1) break;\n val = (val &lt;&lt; 6) + T[c];\n valb += 6;\n if (valb &gt;= 0) {\n out.push_back(char((val&gt;&gt;valb)&amp;0xFF));\n valb -= 8;\n }\n }\n return out;\n}\n</code></pre>\n" }, { "answer_id": 35328409, "author": "elegant dice", "author_id": 924505, "author_profile": "https://Stackoverflow.com/users/924505", "pm_score": 3, "selected": false, "text": "<p>My variation on <a href=\"https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c/31322410#31322410\">DaedalusAlpha's answer</a>:</p>\n<p>It avoids copying the parameters at the expense of a couple of tests.</p>\n<p>Uses uint8_t instead of BYTE.</p>\n<p>Adds some handy functions for dealing with strings, although usually the input data is binary and may have zero bytes inside, so typically should not be manipulated as a string (which often implies null-terminated data).</p>\n<p>Also adds some casts to fix compiler warnings (at least on GCC, I haven't run it through MSVC yet).</p>\n<p>Part of file <em>base64.hpp</em>:</p>\n<pre><code>void base64_encode(string &amp; out, const vector&lt;uint8_t&gt;&amp; buf);\nvoid base64_encode(string &amp; out, const uint8_t* buf, size_t bufLen);\nvoid base64_encode(string &amp; out, string const&amp; buf);\n\nvoid base64_decode(vector&lt;uint8_t&gt; &amp; out, string const&amp; encoded_string);\n\n// Use this if you know the output should be a valid string\nvoid base64_decode(string &amp; out, string const&amp; encoded_string);\n</code></pre>\n<h3>File <em>base64.cpp</em>:</h3>\n<pre><code>static const uint8_t from_base64[128] = {\n // 8 rows of 16 = 128\n // Note: only requires 123 entries, as we only lookup for &lt;= z , which z=122\n\n 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 62, 255, 63,\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 0, 255, 255, 255,\n 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 63,\n 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255\n};\n\nstatic const char to_base64[65] =\n &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;\n &quot;abcdefghijklmnopqrstuvwxyz&quot;\n &quot;0123456789+/&quot;;\n\n\nvoid base64_encode(string &amp; out, string const&amp; buf)\n{\n if (buf.empty())\n base64_encode(out, NULL, 0);\n else\n base64_encode(out, reinterpret_cast&lt;uint8_t const*&gt;(&amp;buf[0]), buf.size());\n}\n\n\nvoid base64_encode(string &amp; out, std::vector&lt;uint8_t&gt; const&amp; buf)\n{\n if (buf.empty())\n base64_encode(out, NULL, 0);\n else\n base64_encode(out, &amp;buf[0], buf.size());\n}\n\nvoid base64_encode(string &amp; ret, uint8_t const* buf, size_t bufLen)\n{\n // Calculate how many bytes that needs to be added to get a multiple of 3\n size_t missing = 0;\n size_t ret_size = bufLen;\n while ((ret_size % 3) != 0)\n {\n ++ret_size;\n ++missing;\n }\n\n // Expand the return string size to a multiple of 4\n ret_size = 4*ret_size/3;\n\n ret.clear();\n ret.reserve(ret_size);\n\n for (size_t i = 0; i &lt; ret_size/4; ++i)\n {\n // Read a group of three bytes (avoid buffer overrun by replacing with 0)\n const size_t index = i*3;\n const uint8_t b3_0 = (index+0 &lt; bufLen) ? buf[index+0] : 0;\n const uint8_t b3_1 = (index+1 &lt; bufLen) ? buf[index+1] : 0;\n const uint8_t b3_2 = (index+2 &lt; bufLen) ? buf[index+2] : 0;\n\n // Transform into four base 64 characters\n const uint8_t b4_0 = ((b3_0 &amp; 0xfc) &gt;&gt; 2);\n const uint8_t b4_1 = ((b3_0 &amp; 0x03) &lt;&lt; 4) + ((b3_1 &amp; 0xf0) &gt;&gt; 4);\n const uint8_t b4_2 = ((b3_1 &amp; 0x0f) &lt;&lt; 2) + ((b3_2 &amp; 0xc0) &gt;&gt; 6);\n const uint8_t b4_3 = ((b3_2 &amp; 0x3f) &lt;&lt; 0);\n\n // Add the base 64 characters to the return value\n ret.push_back(to_base64[b4_0]);\n ret.push_back(to_base64[b4_1]);\n ret.push_back(to_base64[b4_2]);\n ret.push_back(to_base64[b4_3]);\n }\n\n // Replace data that is invalid (always as many as there are missing bytes)\n for (size_t i = 0; i != missing; ++i)\n ret[ret_size - i - 1] = '=';\n}\n\n\ntemplate &lt;class Out&gt;\nvoid base64_decode_any( Out &amp; ret, std::string const&amp; in)\n{\n typedef typename Out::value_type T;\n\n // Make sure the *intended* string length is a multiple of 4\n size_t encoded_size = in.size();\n\n while ((encoded_size % 4) != 0)\n ++encoded_size;\n\n const size_t N = in.size();\n ret.clear();\n ret.reserve(3*encoded_size/4);\n\n for (size_t i = 0; i &lt; encoded_size; i += 4)\n {\n // Note: 'z' == 122\n\n // Get values for each group of four base 64 characters\n const uint8_t b4_0 = ( in[i+0] &lt;= 'z') ? from_base64[static_cast&lt;uint8_t&gt;(in[i+0])] : 0xff;\n const uint8_t b4_1 = (i+1 &lt; N and in[i+1] &lt;= 'z') ? from_base64[static_cast&lt;uint8_t&gt;(in[i+1])] : 0xff;\n const uint8_t b4_2 = (i+2 &lt; N and in[i+2] &lt;= 'z') ? from_base64[static_cast&lt;uint8_t&gt;(in[i+2])] : 0xff;\n const uint8_t b4_3 = (i+3 &lt; N and in[i+3] &lt;= 'z') ? from_base64[static_cast&lt;uint8_t&gt;(in[i+3])] : 0xff;\n\n // Transform into a group of three bytes\n const uint8_t b3_0 = ((b4_0 &amp; 0x3f) &lt;&lt; 2) + ((b4_1 &amp; 0x30) &gt;&gt; 4);\n const uint8_t b3_1 = ((b4_1 &amp; 0x0f) &lt;&lt; 4) + ((b4_2 &amp; 0x3c) &gt;&gt; 2);\n const uint8_t b3_2 = ((b4_2 &amp; 0x03) &lt;&lt; 6) + ((b4_3 &amp; 0x3f) &gt;&gt; 0);\n\n // Add the byte to the return value if it isn't part of an '=' character (indicated by 0xff)\n if (b4_1 != 0xff) ret.push_back( static_cast&lt;T&gt;(b3_0) );\n if (b4_2 != 0xff) ret.push_back( static_cast&lt;T&gt;(b3_1) );\n if (b4_3 != 0xff) ret.push_back( static_cast&lt;T&gt;(b3_2) );\n }\n}\n\nvoid base64_decode(vector&lt;uint8_t&gt; &amp; out, string const&amp; encoded_string)\n{\n base64_decode_any(out, encoded_string);\n}\n\nvoid base64_decode(string &amp; out, string const&amp; encoded_string)\n{\n base64_decode_any(out, encoded_string);\n}\n</code></pre>\n" }, { "answer_id": 37109258, "author": "polfosol ఠ_ఠ", "author_id": 5358284, "author_profile": "https://Stackoverflow.com/users/5358284", "pm_score": 5, "selected": false, "text": "<p>I think this one works better:</p>\n<pre><code>#include &lt;string&gt;\n\nstatic const char* B64chars = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/&quot;;\n\nstatic const int B64index[256] =\n{\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 63, 62, 62, 63,\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0,\n 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 63,\n 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51\n};\n\nconst std::string b64encode(const void* data, const size_t &amp;len)\n{\n std::string result((len + 2) / 3 * 4, '=');\n unsigned char *p = (unsigned char*) data;\n char *str = &amp;result[0];\n size_t j = 0, pad = len % 3;\n const size_t last = len - pad;\n\n for (size_t i = 0; i &lt; last; i += 3)\n {\n int n = int(p[i]) &lt;&lt; 16 | int(p[i + 1]) &lt;&lt; 8 | p[i + 2];\n str[j++] = B64chars[n &gt;&gt; 18];\n str[j++] = B64chars[n &gt;&gt; 12 &amp; 0x3F];\n str[j++] = B64chars[n &gt;&gt; 6 &amp; 0x3F];\n str[j++] = B64chars[n &amp; 0x3F];\n }\n if (pad) /// Set padding\n {\n int n = --pad ? int(p[last]) &lt;&lt; 8 | p[last + 1] : p[last];\n str[j++] = B64chars[pad ? n &gt;&gt; 10 &amp; 0x3F : n &gt;&gt; 2];\n str[j++] = B64chars[pad ? n &gt;&gt; 4 &amp; 0x03F : n &lt;&lt; 4 &amp; 0x3F];\n str[j++] = pad ? B64chars[n &lt;&lt; 2 &amp; 0x3F] : '=';\n }\n return result;\n}\n\nconst std::string b64decode(const void* data, const size_t &amp;len)\n{\n if (len == 0) return &quot;&quot;;\n\n unsigned char *p = (unsigned char*) data;\n size_t j = 0,\n pad1 = len % 4 || p[len - 1] == '=',\n pad2 = pad1 &amp;&amp; (len % 4 &gt; 2 || p[len - 2] != '=');\n const size_t last = (len - pad1) / 4 &lt;&lt; 2;\n std::string result(last / 4 * 3 + pad1 + pad2, '\\0');\n unsigned char *str = (unsigned char*) &amp;result[0];\n\n for (size_t i = 0; i &lt; last; i += 4)\n {\n int n = B64index[p[i]] &lt;&lt; 18 | B64index[p[i + 1]] &lt;&lt; 12 | B64index[p[i + 2]] &lt;&lt; 6 | B64index[p[i + 3]];\n str[j++] = n &gt;&gt; 16;\n str[j++] = n &gt;&gt; 8 &amp; 0xFF;\n str[j++] = n &amp; 0xFF;\n }\n if (pad1)\n {\n int n = B64index[p[last]] &lt;&lt; 18 | B64index[p[last + 1]] &lt;&lt; 12;\n str[j++] = n &gt;&gt; 16;\n if (pad2)\n {\n n |= B64index[p[last + 2]] &lt;&lt; 6;\n str[j++] = n &gt;&gt; 8 &amp; 0xFF;\n }\n }\n return result;\n}\n\nstd::string b64encode(const std::string&amp; str)\n{\n return b64encode(str.c_str(), str.size());\n}\n\nstd::string b64decode(const std::string&amp; str64)\n{\n return b64decode(str64.c_str(), str64.size());\n}\n</code></pre>\n<p>Thanks to <a href=\"https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c/37109258#comment65046388_37109258\">Jens Alfke for pointing out a performance issue</a>, I have made some modifications to this <em>old</em> post. This one works way faster than before. Its other advantage is smooth handling of corrupt data as well.</p>\n<p><em>Last edition</em>: Although in these kinds of problems, it seems that speed is an overkill, but just for the fun of it I have made some other modifications to make this one the fastest algorithm out there AFAIK. Special thanks goes to <a href=\"https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c/37109258#comment69418312_37109258\">GaspardP for his valuable suggestions</a> and nice benchmark.</p>\n" }, { "answer_id": 44562527, "author": "nunojpg", "author_id": 1590596, "author_profile": "https://Stackoverflow.com/users/1590596", "pm_score": 3, "selected": false, "text": "<p>A little variation with a more compact lookup table and using C++17 features:</p>\n<pre><code>std::string base64_decode(const std::string_view in) {\n // table from '+' to 'z'\n const uint8_t lookup[] = {\n 62, 255, 62, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255,\n 255, 0, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,\n 255, 255, 255, 255, 63, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,\n 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51};\n static_assert(sizeof(lookup) == 'z' - '+' + 1);\n\n std::string out;\n int val = 0, valb = -8;\n for (uint8_t c : in) {\n if (c &lt; '+' || c &gt; 'z')\n break;\n c -= '+';\n if (lookup[c] &gt;= 64)\n break;\n val = (val &lt;&lt; 6) + lookup[c];\n valb += 6;\n if (valb &gt;= 0) {\n out.push_back(char((val &gt;&gt; valb) &amp; 0xFF));\n valb -= 8;\n }\n }\n return out;\n}\n</code></pre>\n<p>If you don't have std::string_view, try instead std::experimental::string_view.</p>\n" }, { "answer_id": 59227838, "author": "Macelaru Tiberiu", "author_id": 8647757, "author_profile": "https://Stackoverflow.com/users/8647757", "pm_score": 2, "selected": false, "text": "<p>I use this:</p>\n<pre><code>class BinaryVector {\npublic:\n std::vector&lt;char&gt; bytes;\n\n uint64_t bit_count = 0;\n\npublic:\n /* Add a bit to the end */\n void push_back(bool bit);\n\n /* Return false if character is unrecognized */\n bool pushBase64Char(char b64_c);\n};\n\nvoid BinaryVector::push_back(bool bit)\n{\n if (!bit_count || bit_count % 8 == 0) {\n bytes.push_back(bit &lt;&lt; 7);\n }\n else {\n uint8_t next_bit = 8 - (bit_count % 8) - 1;\n bytes[bit_count / 8] |= bit &lt;&lt; next_bit;\n }\n bit_count++;\n}\n\n/* Converts one Base64 character to 6 bits */\nbool BinaryVector::pushBase64Char(char c)\n{\n uint8_t d;\n\n // A to Z\n if (c &gt; 0x40 &amp;&amp; c &lt; 0x5b) {\n d = c - 65; // Base64 A is 0\n }\n // a to z\n else if (c &gt; 0x60 &amp;&amp; c &lt; 0x7b) {\n d = c - 97 + 26; // Base64 a is 26\n }\n // 0 to 9\n else if (c &gt; 0x2F &amp;&amp; c &lt; 0x3a) {\n d = c - 48 + 52; // Base64 0 is 52\n }\n else if (c == '+') {\n d = 0b111110;\n }\n else if (c == '/') {\n d = 0b111111;\n }\n else if (c == '=') {\n d = 0;\n }\n else {\n return false;\n }\n\n push_back(d &amp; 0b100000);\n push_back(d &amp; 0b010000);\n push_back(d &amp; 0b001000);\n push_back(d &amp; 0b000100);\n push_back(d &amp; 0b000010);\n push_back(d &amp; 0b000001);\n\n return true;\n}\n\nbool loadBase64(std::vector&lt;char&gt;&amp; b64_bin, BinaryVector&amp; vec)\n{\n for (char&amp; c : b64_bin) {\n if (!vec.pushBase64Char(c)) {\n return false;\n }\n }\n return true;\n}\n\n</code></pre>\n<p>Use <code>vec.bytes</code> to access converted data.</p>\n" }, { "answer_id": 59464829, "author": "tutralex", "author_id": 12589146, "author_profile": "https://Stackoverflow.com/users/12589146", "pm_score": 2, "selected": false, "text": "<p>My version is a simple fast encoder (decoder) of Base64 for C++Builder.</p>\n<pre><code>// ---------------------------------------------------------------------------\nUnicodeString __fastcall TExample::Base64Encode(void *data, int length)\n{\n if (length &lt;= 0)\n return L&quot;&quot;;\n static const char set[] = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/&quot;;\n unsigned char *in = (unsigned char*)data;\n char *pos, *out = pos = new char[((length - 1) / 3 + 1) &lt;&lt; 2];\n while ((length -= 3) &gt;= 0)\n {\n pos[0] = set[in[0] &gt;&gt; 2];\n pos[1] = set[((in[0] &amp; 0x03) &lt;&lt; 4) | (in[1] &gt;&gt; 4)];\n pos[2] = set[((in[1] &amp; 0x0F) &lt;&lt; 2) | (in[2] &gt;&gt; 6)];\n pos[3] = set[in[2] &amp; 0x3F];\n pos += 4;\n in += 3;\n };\n if ((length &amp; 2) != 0)\n {\n pos[0] = set[in[0] &gt;&gt; 2];\n if ((length &amp; 1) != 0)\n {\n pos[1] = set[((in[0] &amp; 0x03) &lt;&lt; 4) | (in[1] &gt;&gt; 4)];\n pos[2] = set[(in[1] &amp; 0x0F) &lt;&lt; 2];\n }\n else\n {\n pos[1] = set[(in[0] &amp; 0x03) &lt;&lt; 4];\n pos[2] = '=';\n };\n pos[3] = '=';\n pos += 4;\n };\n UnicodeString code = UnicodeString(out, pos - out);\n delete[] out;\n return code;\n};\n\n// ---------------------------------------------------------------------------\nint __fastcall TExample::Base64Decode(const UnicodeString &amp;code, unsigned char **data)\n{\n int length;\n if (((length = code.Length()) == 0) || ((length &amp; 3) != 0))\n return 0;\n wchar_t *str = code.c_str();\n unsigned char *pos, *out = pos = new unsigned char[(length &gt;&gt; 2) * 3];\n while (*str != 0)\n {\n length = -1;\n int shift = 18, bits = 0;\n do\n {\n wchar_t s = str[++length];\n if ((s &gt;= L'A') &amp;&amp; (s &lt;= L'Z'))\n bits |= (s - L'A') &lt;&lt; shift;\n else if ((s &gt;= L'a') &amp;&amp; (s &lt;= L'z'))\n bits |= (s - (L'a' - 26)) &lt;&lt; shift;\n else if (((s &gt;= L'0') &amp;&amp; (s &lt;= L'9')))\n bits |= (s - (L'0' - 52)) &lt;&lt; shift;\n else if (s == L'+')\n bits |= 62 &lt;&lt; shift;\n else if (s == L'/')\n bits |= 63 &lt;&lt; shift;\n else if (s == L'=')\n {\n length--;\n break;\n }\n else\n {\n delete[] out;\n return 0;\n };\n }\n while ((shift -= 6) &gt;= 0);\n pos[0] = bits &gt;&gt; 16;\n pos[1] = bits &gt;&gt; 8;\n pos[2] = bits;\n pos += length;\n str += 4;\n };\n *data = out;\n return pos - out;\n};\n//---------------------------------------------------------------------------\n</code></pre>\n" }, { "answer_id": 60573554, "author": "rokstar", "author_id": 2150412, "author_profile": "https://Stackoverflow.com/users/2150412", "pm_score": 1, "selected": false, "text": "<p>I firstly made my own version and then found this topic.</p>\n<p>Why does my version look simpler than others presented here? Am I doing something wrong? I didn't test it for speed.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>inline char const* b64units = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/&quot;;\n\ninline char* b64encode(void const* a, int64_t b) {\n ASSERT(a != nullptr);\n if (b &gt; 0) {\n uint8_t const* aa = static_cast&lt;uint8_t const*&gt;(a);\n uint8_t v = 0;\n int64_t bp = 0;\n int64_t sb = 0;\n int8_t off = 0;\n int64_t nt = ((b + 2) / 3) * 4;\n int64_t nd = (b * 8) / 6;\n int64_t tl = ((b * 8) % 6) ? 1 : 0;\n int64_t nf = nt - nd - tl;\n int64_t ri = 0;\n char* r = new char[nt + 1]();\n for (int64_t i = 0; i &lt; nd; i++) {\n v = (aa[sb] &lt;&lt; off) | (aa[sb + 1] &gt;&gt; (8 - off));\n v &gt;&gt;= 2;\n r[ri] = b64units[v];\n ri += 1;\n bp += 6;\n sb = (bp / 8);\n off = (bp % 8);\n }\n if (tl &gt; 0) {\n v = (aa[sb] &lt;&lt; off);\n v &gt;&gt;= 2;\n r[ri] = b64units[v];\n ri += 1;\n }\n for (int64_t i = 0; i &lt; nf; i++) {\n r[ri] = '=';\n ri += 1;\n }\n return r;\n } else return nullptr;\n}\n</code></pre>\n<p>P.S.: My method works well. I tested it with <a href=\"https://en.wikipedia.org/wiki/Node.js\" rel=\"nofollow noreferrer\">Node.js</a>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>let data = 'stackabuse.com';\nlet buff = new Buffer(data);\nlet base64data = buff.toString('base64');\n</code></pre>\n" }, { "answer_id": 65612289, "author": "t.m.", "author_id": 6686454, "author_profile": "https://Stackoverflow.com/users/6686454", "pm_score": 0, "selected": false, "text": "<p>I liked <a href=\"https://github.com/mvorbrodt/blog/blob/master/src/base64.hpp\" rel=\"nofollow noreferrer\">this solution on GitHub</a>.</p>\n<p>It is a single hpp file and it uses the vector&lt;byte&gt; type for raw data unlike the accepted answer.</p>\n<pre><code>#pragma once\n\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;stdexcept&gt;\n#include &lt;cstdint&gt;\n\nnamespace base64\n{\n inline static const char kEncodeLookup[] = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/&quot;;\n inline static const char kPadCharacter = '=';\n\n using byte = std::uint8_t;\n\n inline std::string encode(const std::vector&lt;byte&gt;&amp; input)\n {\n std::string encoded;\n encoded.reserve(((input.size() / 3) + (input.size() % 3 &gt; 0)) * 4);\n\n std::uint32_t temp{};\n auto it = input.begin();\n\n for(std::size_t i = 0; i &lt; input.size() / 3; ++i)\n {\n temp = (*it++) &lt;&lt; 16;\n temp += (*it++) &lt;&lt; 8;\n temp += (*it++);\n encoded.append(1, kEncodeLookup[(temp &amp; 0x00FC0000) &gt;&gt; 18]);\n encoded.append(1, kEncodeLookup[(temp &amp; 0x0003F000) &gt;&gt; 12]);\n encoded.append(1, kEncodeLookup[(temp &amp; 0x00000FC0) &gt;&gt; 6 ]);\n encoded.append(1, kEncodeLookup[(temp &amp; 0x0000003F) ]);\n }\n\n switch(input.size() % 3)\n {\n case 1:\n temp = (*it++) &lt;&lt; 16;\n encoded.append(1, kEncodeLookup[(temp &amp; 0x00FC0000) &gt;&gt; 18]);\n encoded.append(1, kEncodeLookup[(temp &amp; 0x0003F000) &gt;&gt; 12]);\n encoded.append(2, kPadCharacter);\n break;\n case 2:\n temp = (*it++) &lt;&lt; 16;\n temp += (*it++) &lt;&lt; 8;\n encoded.append(1, kEncodeLookup[(temp &amp; 0x00FC0000) &gt;&gt; 18]);\n encoded.append(1, kEncodeLookup[(temp &amp; 0x0003F000) &gt;&gt; 12]);\n encoded.append(1, kEncodeLookup[(temp &amp; 0x00000FC0) &gt;&gt; 6 ]);\n encoded.append(1, kPadCharacter);\n break;\n }\n\n return encoded;\n }\n\n std::vector&lt;byte&gt; decode(const std::string&amp; input)\n {\n if(input.length() % 4)\n throw std::runtime_error(&quot;Invalid base64 length!&quot;);\n\n std::size_t padding{};\n\n if(input.length())\n {\n if(input[input.length() - 1] == kPadCharacter) padding++;\n if(input[input.length() - 2] == kPadCharacter) padding++;\n }\n\n std::vector&lt;byte&gt; decoded;\n decoded.reserve(((input.length() / 4) * 3) - padding);\n\n std::uint32_t temp{};\n auto it = input.begin();\n\n while(it &lt; input.end())\n {\n for(std::size_t i = 0; i &lt; 4; ++i)\n {\n temp &lt;&lt;= 6;\n if (*it &gt;= 0x41 &amp;&amp; *it &lt;= 0x5A) temp |= *it - 0x41;\n else if(*it &gt;= 0x61 &amp;&amp; *it &lt;= 0x7A) temp |= *it - 0x47;\n else if(*it &gt;= 0x30 &amp;&amp; *it &lt;= 0x39) temp |= *it + 0x04;\n else if(*it == 0x2B) temp |= 0x3E;\n else if(*it == 0x2F) temp |= 0x3F;\n else if(*it == kPadCharacter)\n {\n switch(input.end() - it)\n {\n case 1:\n decoded.push_back((temp &gt;&gt; 16) &amp; 0x000000FF);\n decoded.push_back((temp &gt;&gt; 8 ) &amp; 0x000000FF);\n return decoded;\n case 2:\n decoded.push_back((temp &gt;&gt; 10) &amp; 0x000000FF);\n return decoded;\n default:\n throw std::runtime_error(&quot;Invalid padding in base64!&quot;);\n }\n }\n else throw std::runtime_error(&quot;Invalid character in base64!&quot;);\n\n ++it;\n }\n\n decoded.push_back((temp &gt;&gt; 16) &amp; 0x000000FF);\n decoded.push_back((temp &gt;&gt; 8 ) &amp; 0x000000FF);\n decoded.push_back((temp ) &amp; 0x000000FF);\n }\n\n return decoded;\n }\n}\n</code></pre>\n" }, { "answer_id": 66353595, "author": "A.Hristov", "author_id": 12315365, "author_profile": "https://Stackoverflow.com/users/12315365", "pm_score": 0, "selected": false, "text": "<p>Here is one written by me which uses unions and bit fields for maximum efficiency and readibility.</p>\n<pre><code>const char PADDING_CHAR = '=';\nconst char* ALPHABET = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/&quot;;\nconst uint8_t DECODED_ALPHBET[128]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,62,0,0,0,63,52,53,54,55,56,57,58,59,60,61,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,0,0,0,0,0,0,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,0,0,0,0,0};\n\n/**\n * Given a string, this function will encode it in 64b (with padding)\n */\nstd::string encodeBase64(const std::string&amp; binaryText)\n{\n std::string encoded((binaryText.size()/3 + (binaryText.size()%3 &gt; 0)) &lt;&lt; 2, PADDING_CHAR);\n\n const char* bytes = binaryText.data();\n union\n {\n uint32_t temp = 0;\n struct\n {\n uint32_t first : 6, second : 6, third : 6, fourth : 6;\n } tempBytes;\n };\n std::string::iterator currEncoding = encoded.begin();\n\n for(uint32_t i = 0, lim = binaryText.size() / 3; i &lt; lim; ++i, bytes+=3)\n {\n temp = bytes[0] &lt;&lt; 16 | bytes[1] &lt;&lt; 8 | bytes[2];\n (*currEncoding++) = ALPHABET[tempBytes.fourth];\n (*currEncoding++) = ALPHABET[tempBytes.third];\n (*currEncoding++) = ALPHABET[tempBytes.second];\n (*currEncoding++) = ALPHABET[tempBytes.first];\n }\n\n switch(binaryText.size() % 3)\n {\n case 1:\n temp = bytes[0] &lt;&lt; 16;\n (*currEncoding++) = ALPHABET[tempBytes.fourth];\n (*currEncoding++) = ALPHABET[tempBytes.third];\n break;\n case 2:\n temp = bytes[0] &lt;&lt; 16 | bytes[1] &lt;&lt; 8;\n (*currEncoding++) = ALPHABET[tempBytes.fourth];\n (*currEncoding++) = ALPHABET[tempBytes.third];\n (*currEncoding++) = ALPHABET[tempBytes.second];\n break;\n }\n\n return encoded;\n}\n\n/**\n * Given a 64b padding-encoded string, this function will decode it.\n */\nstd::string decodeBase64(const std::string&amp; base64Text)\n{\n if( base64Text.empty() )\n return &quot;&quot;;\n\n assert((base64Text.size()&amp;3) == 0 &amp;&amp; &quot;The base64 text to be decoded must have a length devisible by 4!&quot;);\n\n uint32_t numPadding = (*std::prev(base64Text.end(),1) == PADDING_CHAR) + (*std::prev(base64Text.end(),2) == PADDING_CHAR);\n\n std::string decoded((base64Text.size()*3&gt;&gt;2) - numPadding, '.');\n\n union\n {\n uint32_t temp;\n char tempBytes[4];\n };\n const uint8_t* bytes = reinterpret_cast&lt;const uint8_t*&gt;(base64Text.data());\n\n std::string::iterator currDecoding = decoded.begin();\n\n for(uint32_t i = 0, lim = (base64Text.size() &gt;&gt; 2) - (numPadding!=0); i &lt; lim; ++i, bytes+=4)\n {\n temp = DECODED_ALPHBET[bytes[0]] &lt;&lt; 18 | DECODED_ALPHBET[bytes[1]] &lt;&lt; 12 | DECODED_ALPHBET[bytes[2]] &lt;&lt; 6 | DECODED_ALPHBET[bytes[3]];\n (*currDecoding++) = tempBytes[2];\n (*currDecoding++) = tempBytes[1];\n (*currDecoding++) = tempBytes[0];\n }\n\n switch (numPadding)\n {\n case 2:\n temp = DECODED_ALPHBET[bytes[0]] &lt;&lt; 18 | DECODED_ALPHBET[bytes[1]] &lt;&lt; 12;\n (*currDecoding++) = tempBytes[2];\n break;\n \n case 1:\n temp = DECODED_ALPHBET[bytes[0]] &lt;&lt; 18 | DECODED_ALPHBET[bytes[1]] &lt;&lt; 12 | DECODED_ALPHBET[bytes[2]] &lt;&lt; 6;\n (*currDecoding++) = tempBytes[2];\n (*currDecoding++) = tempBytes[1];\n break;\n }\n\n return decoded;\n}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/180947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19104/" ]
Is there a freely available Base64 decoding code snippet in C++?
See *[Encoding and decoding base 64 with C++](http://www.adp-gmbh.ch/cpp/common/base64.html)*. Here is the implementation from that page: ``` /* base64.cpp and base64.h Copyright (C) 2004-2008 René Nyffenegger This source code is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. René Nyffenegger [email protected] */ static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) { std::string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i <4) ; i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for(j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while((i++ < 3)) ret += '='; } return ret; } std::string base64_decode(std::string const& encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i <4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret += char_array_3[i]; i = 0; } } if (i) { for (j = i; j <4; j++) char_array_4[j] = 0; for (j = 0; j <4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; } return ret; } ```
180,979
<p>I am getting very frustrated because I cannot seem to figure out why Collections shuffling is not working properly.</p> <p>Lets say that I am trying to shuffle the <code>randomizer</code> array. </p> <pre><code>int[] randomizer = new int[] {200,300,212,111,6,2332}; Collections.shuffle(Arrays.asList(randomizer)); </code></pre> <p>For some reason the elements stay sorted exactly the same whether or not I call the shuffle method. Any ideas? </p>
[ { "answer_id": 180990, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "<p><code>Arrays.asList</code> cannot be used with arrays of primitives. Use this instead:</p>\n\n<pre><code>Integer[] randomizer = new Integer[] {200,300,212,111,6,2332}; \nCollections.shuffle(Arrays.asList(randomizer));\n</code></pre>\n\n<p>The same rule applies to most classes in the collections framework, in that you can't use primitive types.</p>\n\n<p>The original code (with <code>int[]</code>) compiled fine, but did not work as intended, because of the behaviour of the variadic method <code>asList</code>: it just makes a one-element list, with the <code>int</code> array as its only member.</p>\n" }, { "answer_id": 181013, "author": "John Gardner", "author_id": 13687, "author_profile": "https://Stackoverflow.com/users/13687", "pm_score": 0, "selected": false, "text": "<p>Chris' answer is correct.</p>\n\n<p>As i said in a comment on Chris' answer, your underlying array will change appropriately unless the arraylist needs to grow, and the list creates a new one and copies items into it.</p>\n\n<p>You may want to keep a reference to the list and iterate over that after the Arrays.asList call, and not iterate over the array after that, iterate over the List instead.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/180979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14013/" ]
I am getting very frustrated because I cannot seem to figure out why Collections shuffling is not working properly. Lets say that I am trying to shuffle the `randomizer` array. ``` int[] randomizer = new int[] {200,300,212,111,6,2332}; Collections.shuffle(Arrays.asList(randomizer)); ``` For some reason the elements stay sorted exactly the same whether or not I call the shuffle method. Any ideas?
`Arrays.asList` cannot be used with arrays of primitives. Use this instead: ``` Integer[] randomizer = new Integer[] {200,300,212,111,6,2332}; Collections.shuffle(Arrays.asList(randomizer)); ``` The same rule applies to most classes in the collections framework, in that you can't use primitive types. The original code (with `int[]`) compiled fine, but did not work as intended, because of the behaviour of the variadic method `asList`: it just makes a one-element list, with the `int` array as its only member.
180,986
<p>What is the difference between the <code>search()</code> and <code>match()</code> functions in the Python <code>re</code> module?</p> <p>I've read the <a href="https://docs.python.org/2/library/re.html?highlight=matching%20searching#search-vs-match" rel="nofollow noreferrer">Python 2 documentation</a> (<a href="https://docs.python.org/3/library/re.html#search-vs-match" rel="nofollow noreferrer">Python 3 documentation</a>), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head. Or at least I'll have a better place to return with my question and it will take less time to re-learn it.</p>
[ { "answer_id": 180993, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 10, "selected": true, "text": "<p><code>re.match</code> is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using <code>^</code> in the pattern.</p>\n\n<p>As the <a href=\"http://docs.python.org/2/library/re.html#re.match\" rel=\"noreferrer\">re.match documentation</a> says:</p>\n\n<blockquote>\n <p>If zero or more characters at the\n <strong>beginning of string</strong> match the regular expression pattern, return a\n corresponding <code>MatchObject</code> instance.\n Return <code>None</code> if the string does not\n match the pattern; note that this is\n different from a zero-length match.</p>\n \n <p>Note: If you want to locate a match\n anywhere in string, use <code>search()</code>\n instead.</p>\n</blockquote>\n\n<p><code>re.search</code> searches the entire string, as <a href=\"http://docs.python.org/2/library/re.html#re.search\" rel=\"noreferrer\">the documentation says</a>:</p>\n\n<blockquote>\n <p><strong>Scan through string</strong> looking for a\n location where the regular expression\n pattern produces a match, and return a\n corresponding <code>MatchObject</code> instance.\n Return <code>None</code> if no position in the\n string matches the pattern; note that\n this is different from finding a\n zero-length match at some point in the\n string.</p>\n</blockquote>\n\n<p>So if you need to match at the beginning of the string, or to match the entire string use <code>match</code>. It is faster. Otherwise use <code>search</code>.</p>\n\n<p>The documentation has a <a href=\"http://docs.python.org/2/library/re.html#search-vs-match\" rel=\"noreferrer\">specific section for <code>match</code> vs. <code>search</code></a> that also covers multiline strings:</p>\n\n<blockquote>\n <p>Python offers two different primitive\n operations based on regular\n expressions: <code>match</code> checks for a match\n <strong>only at the beginning</strong> of the string,\n while <code>search</code> checks for a match\n <strong>anywhere</strong> in the string (this is what\n Perl does by default).</p>\n \n <p>Note that <code>match</code> may differ from <code>search</code>\n even when using a regular expression\n beginning with <code>'^'</code>: <code>'^'</code> matches only\n at the start of the string, or in\n <code>MULTILINE</code> mode also immediately\n following a newline. The “<code>match</code>”\n operation succeeds <em>only if the pattern\n matches at the <strong>start</strong> of the string</em>\n regardless of mode, or at the starting\n position given by the optional <code>pos</code>\n argument regardless of whether a\n newline precedes it.</p>\n</blockquote>\n\n<p>Now, enough talk. Time to see some example code:</p>\n\n<pre><code># example code:\nstring_with_newlines = \"\"\"something\nsomeotherthing\"\"\"\n\nimport re\n\nprint re.match('some', string_with_newlines) # matches\nprint re.match('someother', \n string_with_newlines) # won't match\nprint re.match('^someother', string_with_newlines, \n re.MULTILINE) # also won't match\nprint re.search('someother', \n string_with_newlines) # finds something\nprint re.search('^someother', string_with_newlines, \n re.MULTILINE) # also finds something\n\nm = re.compile('thing$', re.MULTILINE)\n\nprint m.match(string_with_newlines) # no match\nprint m.match(string_with_newlines, pos=4) # matches\nprint m.search(string_with_newlines, \n re.MULTILINE) # also matches\n</code></pre>\n" }, { "answer_id": 181000, "author": "cschol", "author_id": 2386, "author_profile": "https://Stackoverflow.com/users/2386", "pm_score": 4, "selected": false, "text": "<p>re.match attempts to match a pattern <strong>at the beginning of the string</strong>. re.search attempts to match the pattern <strong>throughout the string</strong> until it finds a match.</p>\n" }, { "answer_id": 181028, "author": "xilun", "author_id": 17064, "author_profile": "https://Stackoverflow.com/users/17064", "pm_score": 6, "selected": false, "text": "<p><code>re.search</code> <strong>search</strong>es for the pattern <strong>throughout the string</strong>, whereas <code>re.match</code> does <em>not search</em> the pattern; if it does not, it has no other choice than to <strong>match</strong> it at start of the string.</p>\n" }, { "answer_id": 8687988, "author": "Dhanasekaran Anbalagan", "author_id": 795595, "author_profile": "https://Stackoverflow.com/users/795595", "pm_score": 7, "selected": false, "text": "<p><code>search</code> &rArr; find something anywhere in the string and return a match object.</p>\n\n<p><code>match</code> &rArr; find something at the <em>beginning</em> of the string and return a match object.</p>\n" }, { "answer_id": 31715754, "author": "ldR", "author_id": 5172000, "author_profile": "https://Stackoverflow.com/users/5172000", "pm_score": 5, "selected": false, "text": "<p>You can refer the below example to understand the working of <code>re.match</code> and re.search</p>\n\n<pre><code>a = \"123abc\"\nt = re.match(\"[a-z]+\",a)\nt = re.search(\"[a-z]+\",a)\n</code></pre>\n\n<p><code>re.match</code> will return <code>none</code>, but <code>re.search</code> will return <code>abc</code>.</p>\n" }, { "answer_id": 37363575, "author": "CODE-REaD", "author_id": 5025060, "author_profile": "https://Stackoverflow.com/users/5025060", "pm_score": 5, "selected": false, "text": "<p>The difference is, <strong><code>re.match()</code> misleads anyone accustomed to <em>Perl</em>, <em>grep</em>, or <em>sed</em> regular expression matching, and <code>re.search()</code> does not.</strong> :-)</p>\n\n<p>More soberly, <a href=\"http://www.johndcook.com/blog/python_regex/\" rel=\"noreferrer\">As John D. Cook remarks</a>, <code>re.match()</code> \"behaves as if every pattern has ^ prepended.\" In other words, <code>re.match('pattern')</code> equals <code>re.search('^pattern')</code>. So it anchors a pattern's left side. But it also <em>doesn't anchor a pattern's right side:</em> that still requires a terminating <code>$</code>.</p>\n\n<p>Frankly given the above, I think <code>re.match()</code> should be deprecated. I would be interested to know reasons it should be retained.</p>\n" }, { "answer_id": 49710946, "author": "Jeyekomon", "author_id": 1232660, "author_profile": "https://Stackoverflow.com/users/1232660", "pm_score": 6, "selected": false, "text": "<blockquote>\n<p>match is much faster than search, so instead of doing regex.search(&quot;word&quot;) you can do regex.match((.*?)word(.*?)) and gain tons of performance if you are working with millions of samples.</p>\n</blockquote>\n<p><a href=\"https://stackoverflow.com/questions/180986/what-is-the-difference-between-re-search-and-re-match#comment62326091_180993\">This comment from @ivan_bilan under the accepted answer above</a> got me thinking if such <em>hack</em> is actually speeding anything up, so let's find out how many tons of performance you will really gain.</p>\n<p>I prepared the following test suite:</p>\n<pre><code>import random\nimport re\nimport string\nimport time\n\nLENGTH = 10\nLIST_SIZE = 1000000\n\ndef generate_word():\n word = [random.choice(string.ascii_lowercase) for _ in range(LENGTH)]\n word = ''.join(word)\n return word\n\nwordlist = [generate_word() for _ in range(LIST_SIZE)]\n\nstart = time.time()\n[re.search('python', word) for word in wordlist]\nprint('search:', time.time() - start)\n\nstart = time.time()\n[re.match('(.*?)python(.*?)', word) for word in wordlist]\nprint('match:', time.time() - start)\n</code></pre>\n<p>I made 10 measurements (1M, 2M, ..., 10M words) which gave me the following plot:</p>\n<p><a href=\"https://i.stack.imgur.com/g55A6.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/g55A6.png\" alt=\"match vs. search regex speedtest line plot\" /></a></p>\n<p>As you can see, <strong>searching for the pattern <code>'python'</code> is faster</strong> than matching the pattern <code>'(.*?)python(.*?)'</code>.</p>\n<p><em>Python is smart. Avoid trying to be smarter.</em></p>\n" }, { "answer_id": 53074635, "author": "U12-Forward", "author_id": 8708364, "author_profile": "https://Stackoverflow.com/users/8708364", "pm_score": 5, "selected": false, "text": "<p>Much shorter:</p>\n\n<ul>\n<li><p><code>search</code> scans through the whole string.</p></li>\n<li><p><code>match</code> scans only the beginning of the string.</p></li>\n</ul>\n\n<p>Following Ex says it:</p>\n\n<pre><code>&gt;&gt;&gt; a = \"123abc\"\n&gt;&gt;&gt; re.match(\"[a-z]+\",a)\nNone\n&gt;&gt;&gt; re.search(\"[a-z]+\",a)\nabc\n</code></pre>\n" }, { "answer_id": 72683643, "author": "Pall Arpad", "author_id": 7381099, "author_profile": "https://Stackoverflow.com/users/7381099", "pm_score": 0, "selected": false, "text": "<p><strong>Quick answer</strong></p>\n<pre><code>re.search('test', ' test') # returns a Truthy match object (because the search starts from any index) \n\nre.match('test', ' test') # returns None (because the search start from 0 index)\nre.match('test', 'test') # returns a Truthy match object (match at 0 index)\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/180986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
What is the difference between the `search()` and `match()` functions in the Python `re` module? I've read the [Python 2 documentation](https://docs.python.org/2/library/re.html?highlight=matching%20searching#search-vs-match) ([Python 3 documentation](https://docs.python.org/3/library/re.html#search-vs-match)), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head. Or at least I'll have a better place to return with my question and it will take less time to re-learn it.
`re.match` is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using `^` in the pattern. As the [re.match documentation](http://docs.python.org/2/library/re.html#re.match) says: > > If zero or more characters at the > **beginning of string** match the regular expression pattern, return a > corresponding `MatchObject` instance. > Return `None` if the string does not > match the pattern; note that this is > different from a zero-length match. > > > Note: If you want to locate a match > anywhere in string, use `search()` > instead. > > > `re.search` searches the entire string, as [the documentation says](http://docs.python.org/2/library/re.html#re.search): > > **Scan through string** looking for a > location where the regular expression > pattern produces a match, and return a > corresponding `MatchObject` instance. > Return `None` if no position in the > string matches the pattern; note that > this is different from finding a > zero-length match at some point in the > string. > > > So if you need to match at the beginning of the string, or to match the entire string use `match`. It is faster. Otherwise use `search`. The documentation has a [specific section for `match` vs. `search`](http://docs.python.org/2/library/re.html#search-vs-match) that also covers multiline strings: > > Python offers two different primitive > operations based on regular > expressions: `match` checks for a match > **only at the beginning** of the string, > while `search` checks for a match > **anywhere** in the string (this is what > Perl does by default). > > > Note that `match` may differ from `search` > even when using a regular expression > beginning with `'^'`: `'^'` matches only > at the start of the string, or in > `MULTILINE` mode also immediately > following a newline. The “`match`” > operation succeeds *only if the pattern > matches at the **start** of the string* > regardless of mode, or at the starting > position given by the optional `pos` > argument regardless of whether a > newline precedes it. > > > Now, enough talk. Time to see some example code: ``` # example code: string_with_newlines = """something someotherthing""" import re print re.match('some', string_with_newlines) # matches print re.match('someother', string_with_newlines) # won't match print re.match('^someother', string_with_newlines, re.MULTILINE) # also won't match print re.search('someother', string_with_newlines) # finds something print re.search('^someother', string_with_newlines, re.MULTILINE) # also finds something m = re.compile('thing$', re.MULTILINE) print m.match(string_with_newlines) # no match print m.match(string_with_newlines, pos=4) # matches print m.search(string_with_newlines, re.MULTILINE) # also matches ```
181,018
<p>My application has no forms. It runs by calling Application.Run();</p>
[ { "answer_id": 181020, "author": "Haim Bender", "author_id": 44972, "author_profile": "https://Stackoverflow.com/users/44972", "pm_score": 3, "selected": true, "text": "<p>Call </p>\n\n<pre><code>System.Windows.Forms.Application.Exit();\n</code></pre>\n" }, { "answer_id": 181098, "author": "Ryan Taylor", "author_id": 6231, "author_profile": "https://Stackoverflow.com/users/6231", "pm_score": 1, "selected": false, "text": "<p>The other option is <code>Environment.Exit()</code>, however if your application does rely on the Application classes, <code>System.Windows.Forms.Application.Exit()</code> is the more \"proper\" way of handling it.</p>\n" }, { "answer_id": 181370, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 0, "selected": false, "text": "<p>Just like the MSDN documentation for the <a href=\"http://msdn.microsoft.com/en-us/library/ms157900.aspx\" rel=\"nofollow noreferrer\">Application.Run()</a> suggests:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.application.exit.aspx\" rel=\"nofollow noreferrer\">Application.Exit()</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.application.exitthread.aspx\" rel=\"nofollow noreferrer\">Application.ExitThread()</a></li>\n</ul>\n\n<p><em>Note, that most Windows Forms developers will not need to use Application.Run(). Are you sure you need message pumping in your app?</em></p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44972/" ]
My application has no forms. It runs by calling Application.Run();
Call ``` System.Windows.Forms.Application.Exit(); ```
181,029
<p>Has anyone been able to implement the JQuery grid plugin, jqGrid? I'm trying to implement the JSON paging, and I feel like I'm getting close, but that I am also being swamped by inconsequential details. If anyone could post some sample code, I would greatly appreciate it.</p>
[ { "answer_id": 181072, "author": "tsimon", "author_id": 1685, "author_profile": "https://Stackoverflow.com/users/1685", "pm_score": 0, "selected": false, "text": "<p>I'm just floundering trying to pull everything together. My first concern is simply generating a correct JSON response. My returned class appears to be serialised as a property named 'd' - is this a JQuery thing, or ASP.Net web method convention? I'm afraid that jqGrid will be looking for the data to be top-level, whereas asp.net will put it in a property called 'd':</p>\n\n<pre><code> [WebMethod]\n [ScriptMethod(ResponseFormat = ResponseFormat.Json)]\n public static object GetData() {\n TestClass tc = new TestClass() { One = \"Hello\", Two = \"World\" };\n return tc;\n }\n\n\n $(\"#divResults\").click(function() {\n $.ajax({\n type: \"POST\",\n url: \"GridData_bak.aspx/GetData\",\n data: \"{}\",\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n success: function(test) {\n // Replace the div's content with the page method's return.\n $(\"#divResults\").text(test.d.One);\n },\n error: function(msg) {\n $(\"#divResults\").text(msg);\n }\n });\n });\n</code></pre>\n" }, { "answer_id": 308688, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The flexgrid plugin is quite sparse on doumentation however in a small section on the demo page there is a tut on creating a json serialized object, this is a bit misleading because the grid requires a specific format, I have ported the php code for xml option with a little monkey grease you can do the same for the json formatting</p>\n\n<p>heres my xml port</p>\n\n<pre><code>the setup for the grid\n $(\"#tableToFlex\").flexigrid({\n url: 'WebService.asmx/getData'}\n ... *other configs* ...);\n</code></pre>\n\n<p>please consider the following code in the webservice.asmx class</p>\n\n<pre><code>&lt;WebMethod()&gt; _\n&lt;ScriptMethod(ResponseFormat:=ResponseFormat.Xml)&gt; _\nPublic Function getData(ByVal page As Integer, _\n ByVal qtype As String, _\n ByVal Query As String, _\n ByVal rp As Integer, _\n ByVal sortname As String, _\n ByVal sortorder As String) As System.Xml.XmlDocument\n 'note these parameters are inputted to determine paging and constrains for the resultant rows\n\n 'Sample list to send to the grid\n Dim list = New List(Of ApplicationStateInformation)\n 'Sample row object that holds name , surname , address, idnumber ...\n list.Add(New RowObjects( \"test1\", \"test1\", \"test1\", \"12345\"))\n list.Add(New RowObjects( \"test2\", \"test2\", \"test2\", \"12345\"))\n list.Add(New RowObjects( \"test3\", \"test3\", \"test3\", \"12345\"))\n list.Add(New RowObjects( \"test4\", \"test4\", \"test4\", \"12345\"))\n 'retun a xml doc, as we are using the xml format on the flexgrid\n\n Dim returnDoc = New System.Xml.XmlDocument()\n returnDoc.Load(New IO.StringReader(ToXmlResult(list)))\n Return returnDoc\nEnd Function\n\nPrivate Function ToXmlResult(ByVal list As List(Of RowObjects)) As String\n 'this is the xml document format the grid understands\n Dim result As String = \"&lt;?xml version=\"\"1.0\"\" encoding=\"\"utf-8\"\"?&gt;\" &amp; vbCrLf\n result += \"&lt;rows&gt;\" &amp; vbCrLf\n result += String.Format(\"&lt;page&gt;{0}&lt;/page&gt;\" &amp; vbCrLf, \"1\")\n result += String.Format(\"&lt;total&gt;{0}&lt;/total&gt;\" &amp; vbCrLf, \"10\")\n For Each item In list\n result += ConvertRowData(item)\n Next\n result += \"&lt;/rows&gt;\" &amp; vbCrLf\n Return result\nEnd Function\n\nPrivate Function ConvertRowData(ByVal row As RowObjects) As String\n\n Dim result As String = String.Format(\"&lt;row id='{0}'&gt;\" &amp; vbCrLf, row.IdNumber.ToString)\n 'THESE SHOULD BE HTML ENCODED (the format arg) but I left it out\n result += String.Format(\"&lt;cell&gt;&lt;![CDATA[{0}]]&gt;&lt;/cell&gt;\" &amp; vbCrLf, row.Name)\n result += String.Format(\"&lt;cell&gt;&lt;![CDATA[{0}]]&gt;&lt;/cell&gt;\" &amp; vbCrLf, row.Surname)\n result += String.Format(\"&lt;cell&gt;&lt;![CDATA[{0}]]&gt;&lt;/cell&gt;\" &amp; vbCrLf, row.IdNumber)\n\n result += \"&lt;/row&gt;\" &amp; vbCrLf\n Return result\nEnd Function\n</code></pre>\n" }, { "answer_id": 308949, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 0, "selected": false, "text": "<p>the d in the json is an inbuilt defense against a potential exploit</p>\n\n<p><a href=\"http://bartreyserhove.blogspot.com/2008/08/aspnet-mvc-and-jqgrid.html\" rel=\"nofollow noreferrer\">example</a> I found that uses mvc</p>\n\n<p>Full info <a href=\"http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx\" rel=\"nofollow noreferrer\">here</a> </p>\n" }, { "answer_id": 432734, "author": "nshaw", "author_id": 29426, "author_profile": "https://Stackoverflow.com/users/29426", "pm_score": 4, "selected": true, "text": "<p>Found your post while I was trying to do this for my project. I got it working. For anyone who needs it in the future, jqGrid won't work out of the box with JSON and ASP.NET. You need to make a couple of small modifications to grid.base.js. Around line 829, replace the json case section with the following:</p>\n\n<pre><code>case \"json\":\n gdata = JSON.stringify(gdata); //ASP.NET expects JSON as a string\n $.ajax({ url: ts.p.url, \n type: ts.p.mtype, \n dataType: \"json\", \n contentType: \"application/json; charset=utf-8\", //required by ASP.NET\n data: gdata, \n complete: function(JSON, st) { if (st == \"success\") { addJSONData(cleanUp(JSON.responseText), ts.grid.bDiv); if (loadComplete) { loadComplete(); } } }, \n error: function(xhr, st, err) { if (loadError) { loadError(xhr, st, err); } endReq(); }, \n beforeSend: function(xhr) { if (loadBeforeSend) { loadBeforeSend(xhr); } } });\n if (ts.p.loadonce || ts.p.treeGrid) { ts.p.datatype = \"local\"; }\n break;\n</code></pre>\n\n<p>Then add the following function:</p>\n\n<pre><code>function cleanUp(responseText) {\n var myObject = JSON.parse(responseText); //more secure than eval\n return myObject.d; //ASP.NET special\n}\n</code></pre>\n\n<p>You will also need to include the <a href=\"https://github.com/douglascrockford/JSON-js/blob/master/json2.js\" rel=\"nofollow noreferrer\">JSON parser and stringifier</a>. Along with working with ASP.NET, this revised code is also <a href=\"http://www.json.org/js.html\" rel=\"nofollow noreferrer\">more secure</a> because the eval statement is gone.</p>\n\n<p><strong>EDIT:</strong> I should have also noted that you might have to make similar edits to grid.celledit.js, grid.formedit.js, grid.inlinedit.js, and grid.subgrid.js.</p>\n" }, { "answer_id": 432783, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 2, "selected": false, "text": "<p>I've just jTemplates for doing client-side paging with jQuery and ASP.NET. I did a blog post on it which you can find here: <a href=\"http://www.aaron-powell.com/blog.aspx?id=1209\" rel=\"nofollow noreferrer\">http://www.aaron-powell.com/blog.aspx?id=1209</a></p>\n\n<p>It looks at how to create a templated data location, return the data from ASP.NET and then implement a paging solution.</p>\n" }, { "answer_id": 433477, "author": "Element", "author_id": 50970, "author_profile": "https://Stackoverflow.com/users/50970", "pm_score": 0, "selected": false, "text": "<p>I think you can make jqgrid work with json &amp; asp.net without modifying grid.base.js and other jqgrid files, you have to use the datatype property to define your own custom ajax call and define a json reader, jqgrid will then use your custom ajax call and reader every time the grid reloads.</p>\n\n<p>The process is similar for xml you just define an xmlreader instead of a jsonreader.</p>\n\n<p>All the properties of the jsonreader are defined in the <a href=\"http://www.secondpersonplural.ca/jqgriddocs/index.htm\" rel=\"nofollow noreferrer\">online documentation</a> </p>\n\n<p>For examples of custom datatype see \"Function as datatype\" in the <a href=\"http://trirand.com/jqgrid/jqgrid.html\" rel=\"nofollow noreferrer\">live demo page</a> under \"New in 3.3\"</p>\n" }, { "answer_id": 486768, "author": "ari", "author_id": 54801, "author_profile": "https://Stackoverflow.com/users/54801", "pm_score": 0, "selected": false, "text": "<p>My Implement:</p>\n\n<p>data: \"{'page':'\" + gdata.page + \"','rows':'\" + gdata.rows + \"','sidx':'\" + gdata.sidx + \"','sord':'\" + gdata.sord + \"','nd':'\" + gdata.nd + \"','_search':'\" + gdata._search + \"','searchField':'\" + ts.p.searchdata.searchField + \"','searchString':'\" + ts.p.searchdata.searchString + \"','searchOper':'\" + ts.p.searchdata.searchOper + \"'}\",</p>\n\n<p>success: function(JSON, st) {\nif (st == \"success\") { addJSONData(JSON.d, ts.grid.bDiv); if (loadComplete) { loadComplete(); } }</p>\n\n<p>Insted using complete ajax event use success event. this way is prevent the double json seralize.</p>\n\n<p>Just one thing that i didnt realize with cell editing:\nAssume that I want edit multiple cells with same data type (int).\nI have only one web method! and I cant oveload with a same data type with diffrent name!\nIs anyone solve this kind of probleme?</p>\n" }, { "answer_id": 711631, "author": "darren", "author_id": 51688, "author_profile": "https://Stackoverflow.com/users/51688", "pm_score": 1, "selected": false, "text": "<p>You can use the ASP.Net MVC JsonResult to populate the grid.</p>\n\n<p>Person Class</p>\n\n<pre><code>public class Person\n{\n public int ID { get; set; }\n public string Name { get; set; }\n public DateTime Birthday { get; set; }\n\n public static IEnumerable&lt;Person&gt; GetABunchOfPeople()\n {\n // Get a bunch of People.\n }\n}\n</code></pre>\n\n<p>In your controller you would have:</p>\n\n<pre><code>public JsonResult GetABunchOfPeopleAsJson()\n{\n var rows = (Person.GetABunchOfPeople()\n .Select(c =&gt; new\n {\n id = c.ID,\n cell = new[]\n {\n c.ID.ToString(),\n c.Name,\n c.Birthday.ToShortDateString()\n }\n })).ToArray();\n\n return new JsonResult\n {\n Data = new\n {\n page = 1,\n records = rows.Length,\n rows,\n total = 1\n }\n };\n}\n</code></pre>\n\n<p>And the jqGrid configuration for the url would be:</p>\n\n<pre><code>url: '&lt;%= ResolveUrl(\"~/Person/GetAllPeople\") %&gt;',\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1685/" ]
Has anyone been able to implement the JQuery grid plugin, jqGrid? I'm trying to implement the JSON paging, and I feel like I'm getting close, but that I am also being swamped by inconsequential details. If anyone could post some sample code, I would greatly appreciate it.
Found your post while I was trying to do this for my project. I got it working. For anyone who needs it in the future, jqGrid won't work out of the box with JSON and ASP.NET. You need to make a couple of small modifications to grid.base.js. Around line 829, replace the json case section with the following: ``` case "json": gdata = JSON.stringify(gdata); //ASP.NET expects JSON as a string $.ajax({ url: ts.p.url, type: ts.p.mtype, dataType: "json", contentType: "application/json; charset=utf-8", //required by ASP.NET data: gdata, complete: function(JSON, st) { if (st == "success") { addJSONData(cleanUp(JSON.responseText), ts.grid.bDiv); if (loadComplete) { loadComplete(); } } }, error: function(xhr, st, err) { if (loadError) { loadError(xhr, st, err); } endReq(); }, beforeSend: function(xhr) { if (loadBeforeSend) { loadBeforeSend(xhr); } } }); if (ts.p.loadonce || ts.p.treeGrid) { ts.p.datatype = "local"; } break; ``` Then add the following function: ``` function cleanUp(responseText) { var myObject = JSON.parse(responseText); //more secure than eval return myObject.d; //ASP.NET special } ``` You will also need to include the [JSON parser and stringifier](https://github.com/douglascrockford/JSON-js/blob/master/json2.js). Along with working with ASP.NET, this revised code is also [more secure](http://www.json.org/js.html) because the eval statement is gone. **EDIT:** I should have also noted that you might have to make similar edits to grid.celledit.js, grid.formedit.js, grid.inlinedit.js, and grid.subgrid.js.
181,036
<p>I'm trying to get this simple PowerShell script working, but I think something is fundamentally wrong. ;-)</p> <pre><code>ls | ForEach { &quot;C:\Working\tools\custom-tool.exe&quot; $_ } </code></pre> <p>I basically want to get files in a directory, and pass them one by one as arguments to the custom tool.</p>
[ { "answer_id": 181065, "author": "slipsec", "author_id": 1635, "author_profile": "https://Stackoverflow.com/users/1635", "pm_score": 6, "selected": true, "text": "<pre><code>ls | %{C:\\Working\\tools\\custom-tool.exe $_}\n</code></pre>\n\n<p>As each object comes down the pipeline the tool will be run against it. Putting quotes around the command string causes it to be... a string! The local variable \"$_\" it then likely doesn't know what to do with so pukes with an error.</p>\n" }, { "answer_id": 182154, "author": "Jeffery Hicks", "author_id": 25508, "author_profile": "https://Stackoverflow.com/users/25508", "pm_score": 3, "selected": false, "text": "<p>I'm betting your tool needs the full path. The $_ is each file object that comes through the pipeline. You likely need to use an expression like this:</p>\n\n<pre><code>ls | %{C:\\Working\\tools\\custom-tool.exe $_.fullname}\n</code></pre>\n" }, { "answer_id": 182535, "author": "tomasr", "author_id": 10292, "author_profile": "https://Stackoverflow.com/users/10292", "pm_score": 6, "selected": false, "text": "<p>If you still need quotes around the command path (say, if you've got spaces), just do it like this:</p>\n\n<pre><code>ls | % { &amp;\"C:\\Working\\tools\\custom-tool.exe\" $_.FullName }\n</code></pre>\n\n<p>Notice the use of &amp; before the string to force PowerShell to interpret it as a command and not a string.</p>\n" }, { "answer_id": 188255, "author": "EdgeVB", "author_id": 24863, "author_profile": "https://Stackoverflow.com/users/24863", "pm_score": 2, "selected": false, "text": "<p>Both Jeffrery Hicks and slipsec are correct. Yank the double quotes off.</p>\n\n<p>$_ or $_.fullname worked in my test script (below). YMMV with your custom-tool.</p>\n\n<pre><code>gci | % { c:\\windows\\notepad.exe $_.fullname }\n</code></pre>\n\n<p>or</p>\n\n<pre><code>gci | % { c:\\windows\\notepad.exe $_ }\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18437/" ]
I'm trying to get this simple PowerShell script working, but I think something is fundamentally wrong. ;-) ``` ls | ForEach { "C:\Working\tools\custom-tool.exe" $_ } ``` I basically want to get files in a directory, and pass them one by one as arguments to the custom tool.
``` ls | %{C:\Working\tools\custom-tool.exe $_} ``` As each object comes down the pipeline the tool will be run against it. Putting quotes around the command string causes it to be... a string! The local variable "$\_" it then likely doesn't know what to do with so pukes with an error.
181,037
<p>I am looking for a method to compare and sort UTF-8 strings in C++ in a case-insensitive manner to use it in a <a href="http://www.sqlite.org/c3ref/create_collation.html" rel="noreferrer">custom collation function in SQLite</a>.</p> <ol> <li>The method should <em>ideally</em> be locale-independent. However I won't be holding my breath, as far as I know, collation is very language-dependent, so anything that works on languages other than English will do, even if it means switching locales.</li> <li>Options include using standard C or C++ library or a <em>small</em> (suitable for embedded system) and <em>non-GPL</em> (suitable for a proprietary system) third-party library.</li> </ol> <p>What I have so far:</p> <ol> <li><code>strcoll</code> with C locales and <code>std::collate</code>/<code>std::collate_byname</code> are case-sensitive. (Are there case-insensitive versions of these?)</li> <li><p>I tried to use a POSIX strcasecmp, but it seems to be <a href="http://www.opengroup.org/onlinepubs/007908775/xsh/strcasecmp.html" rel="noreferrer">not defined</a> for locales other than <code>"POSIX"</code></p> <blockquote> <p><em>In the POSIX locale, strcasecmp() and strncasecmp() do upper to lower conversions, then a byte comparison. The results are unspecified in other locales.</em></p> </blockquote> <p>And, indeed, the result of <code>strcasecmp</code> does not change between locales on Linux with GLIBC.</p> <pre><code>#include &lt;clocale&gt; #include &lt;cstdio&gt; #include &lt;cassert&gt; #include &lt;cstring&gt; const static char *s1 = "Äaa"; const static char *s2 = "äaa"; int main() { printf("strcasecmp('%s', '%s') == %d\n", s1, s2, strcasecmp(s1, s2)); printf("strcoll('%s', '%s') == %d\n", s1, s2, strcoll(s1, s2)); assert(setlocale(LC_ALL, "en_AU.UTF-8")); printf("strcasecmp('%s', '%s') == %d\n", s1, s2, strcasecmp(s1, s2)); printf("strcoll('%s', '%s') == %d\n", s1, s2, strcoll(s1, s2)); assert(setlocale(LC_ALL, "fi_FI.UTF-8")); printf("strcasecmp('%s', '%s') == %d\n", s1, s2, strcasecmp(s1, s2)); printf("strcoll('%s', '%s') == %d\n", s1, s2, strcoll(s1, s2)); } </code></pre> <p>This is printed:</p> <pre><code>strcasecmp('Äaa', 'äaa') == -32 strcoll('Äaa', 'äaa') == -32 strcasecmp('Äaa', 'äaa') == -32 strcoll('Äaa', 'äaa') == 7 strcasecmp('Äaa', 'äaa') == -32 strcoll('Äaa', 'äaa') == 7 </code></pre></li> </ol> <p>P. S.</p> <p>And yes, I am aware about <a href="http://icu-project.org/" rel="noreferrer">ICU</a>, but we can't use it on the embedded platform due to its <a href="http://www.icu-project.org/charts/icu4c_footprint.html" rel="noreferrer">enormous size</a>.</p>
[ { "answer_id": 181129, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "<p>I don't think there's a standard C/C++ library function you can use. You'll have to roll your own or use a 3rd-party library. The full Unicode specification for locale-specific collation can be found here: <a href=\"http://www.unicode.org/reports/tr10/\" rel=\"nofollow noreferrer\"><a href=\"http://www.unicode.org/reports/tr10/\" rel=\"nofollow noreferrer\">http://www.unicode.org/reports/tr10/</a></a> (<strong>warning</strong>: this is a <em>long</em> document).</p>\n" }, { "answer_id": 186948, "author": "Harold Ekstrom", "author_id": 8429, "author_profile": "https://Stackoverflow.com/users/8429", "pm_score": 0, "selected": false, "text": "<p>On Windows you can call fall back on the OS function CompareStringW and use the NORM_IGNORECASE flag. You'll have to convert your UTF-8 strings to UTF-16 first. Otherwise, take a look at IBM's <a href=\"http://www-01.ibm.com/software/globalization/icu/index.jsp\" rel=\"nofollow noreferrer\">International Components for Unicode</a>.</p>\n" }, { "answer_id": 187144, "author": "Ray", "author_id": 13327, "author_profile": "https://Stackoverflow.com/users/13327", "pm_score": 0, "selected": false, "text": "<p>I believe you will need to roll your own or use an third party library. I recommend a third party library because there are a lot of rules that need to be followed to get true international support - best to let someone who is an expert deal with them.</p>\n" }, { "answer_id": 190950, "author": "Dave Van den Eynde", "author_id": 455874, "author_profile": "https://Stackoverflow.com/users/455874", "pm_score": 0, "selected": false, "text": "<p>I have no definitive answer in the form of example code, but I should point out that an UTF-8 bytestream contains, in fact, Unicode characters and you have to use the wchar_t versions of the C/C++ runtime library. </p>\n\n<p>You have to convert those UTF-8 bytes into wchar_t strings first, though. This is not very hard, as the UTF-8 encoding standard is <a href=\"http://en.wikipedia.org/wiki/UTF-8\" rel=\"nofollow noreferrer\">very well documented</a>. I know this, because I've done it, but I can't share that code with you. </p>\n" }, { "answer_id": 191269, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 4, "selected": true, "text": "<p>What you really want is logically impossible. There is no locale-independent, case-insensitive way of sorting strings. The simple counter-example is \"i\" &lt;> \"I\" ? The naive answer is no, but in Turkish these strings are unequal. \"i\" is uppercased to \"İ\" (U+130 Latin Capital I with dot above)</p>\n\n<p>UTF-8 strings add extra complexity to the question. They're perfectly valid multi-byte char* strings, if you have an appropriate locale. But neither the C nor the C++ standard defines such a locale; check with your vendor (too many embedded vendors, sorry, no genearl answer here). So you HAVE to pick a locale whose multi-byte encoding is UTF-8, for the mbscmp function to work. This of course influences the sort order, which is locale dependent. And if you have NO locale in which const char* is UTF-8, you can't use this trick at all. (As I understand it, Microsoft's CRT suffers from this. Their multi-byte code only handles characters up to 2 bytes; UTF-8 needs 3)</p>\n\n<p>wchar_t is not the standard solution either. It supposedly is so wide that you don't have to deal with multi-byte encodings, but your collation will still depend on locale (LC_COLLATE) . However, using wchar_t means you now choose locales that do not use UTF-8 for const char*.</p>\n\n<p>With this done, you can basically write your own ordering by converting strings to lowercase and comparing them. It's not perfect. Do you expect L\"ß\" == L\"ss\" ? They're not even the same length. Yet, for a German you have to consider them equal. Can you live with that?</p>\n" }, { "answer_id": 552755, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you are using it to do searching and sorting for your locale only, I suggest your function to call a simple replace function that convert both multi-byte strings into one byte per char ones using a table like:<br />\n<br />\nA -> a<br />\nà -> a<br />\ná -> a<br />\nß -> ss<br />\nÇ -> c<br>\nand so on</p>\n\n<p>Then simply call strcmp and return the results.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23643/" ]
I am looking for a method to compare and sort UTF-8 strings in C++ in a case-insensitive manner to use it in a [custom collation function in SQLite](http://www.sqlite.org/c3ref/create_collation.html). 1. The method should *ideally* be locale-independent. However I won't be holding my breath, as far as I know, collation is very language-dependent, so anything that works on languages other than English will do, even if it means switching locales. 2. Options include using standard C or C++ library or a *small* (suitable for embedded system) and *non-GPL* (suitable for a proprietary system) third-party library. What I have so far: 1. `strcoll` with C locales and `std::collate`/`std::collate_byname` are case-sensitive. (Are there case-insensitive versions of these?) 2. I tried to use a POSIX strcasecmp, but it seems to be [not defined](http://www.opengroup.org/onlinepubs/007908775/xsh/strcasecmp.html) for locales other than `"POSIX"` > > *In the POSIX locale, strcasecmp() and strncasecmp() do upper to lower conversions, then a byte comparison. The results are unspecified in other locales.* > > > And, indeed, the result of `strcasecmp` does not change between locales on Linux with GLIBC. ``` #include <clocale> #include <cstdio> #include <cassert> #include <cstring> const static char *s1 = "Äaa"; const static char *s2 = "äaa"; int main() { printf("strcasecmp('%s', '%s') == %d\n", s1, s2, strcasecmp(s1, s2)); printf("strcoll('%s', '%s') == %d\n", s1, s2, strcoll(s1, s2)); assert(setlocale(LC_ALL, "en_AU.UTF-8")); printf("strcasecmp('%s', '%s') == %d\n", s1, s2, strcasecmp(s1, s2)); printf("strcoll('%s', '%s') == %d\n", s1, s2, strcoll(s1, s2)); assert(setlocale(LC_ALL, "fi_FI.UTF-8")); printf("strcasecmp('%s', '%s') == %d\n", s1, s2, strcasecmp(s1, s2)); printf("strcoll('%s', '%s') == %d\n", s1, s2, strcoll(s1, s2)); } ``` This is printed: ``` strcasecmp('Äaa', 'äaa') == -32 strcoll('Äaa', 'äaa') == -32 strcasecmp('Äaa', 'äaa') == -32 strcoll('Äaa', 'äaa') == 7 strcasecmp('Äaa', 'äaa') == -32 strcoll('Äaa', 'äaa') == 7 ``` P. S. And yes, I am aware about [ICU](http://icu-project.org/), but we can't use it on the embedded platform due to its [enormous size](http://www.icu-project.org/charts/icu4c_footprint.html).
What you really want is logically impossible. There is no locale-independent, case-insensitive way of sorting strings. The simple counter-example is "i" <> "I" ? The naive answer is no, but in Turkish these strings are unequal. "i" is uppercased to "İ" (U+130 Latin Capital I with dot above) UTF-8 strings add extra complexity to the question. They're perfectly valid multi-byte char\* strings, if you have an appropriate locale. But neither the C nor the C++ standard defines such a locale; check with your vendor (too many embedded vendors, sorry, no genearl answer here). So you HAVE to pick a locale whose multi-byte encoding is UTF-8, for the mbscmp function to work. This of course influences the sort order, which is locale dependent. And if you have NO locale in which const char\* is UTF-8, you can't use this trick at all. (As I understand it, Microsoft's CRT suffers from this. Their multi-byte code only handles characters up to 2 bytes; UTF-8 needs 3) wchar\_t is not the standard solution either. It supposedly is so wide that you don't have to deal with multi-byte encodings, but your collation will still depend on locale (LC\_COLLATE) . However, using wchar\_t means you now choose locales that do not use UTF-8 for const char\*. With this done, you can basically write your own ordering by converting strings to lowercase and comparing them. It's not perfect. Do you expect L"ß" == L"ss" ? They're not even the same length. Yet, for a German you have to consider them equal. Can you live with that?
181,064
<p>For my current C++ project I need to detect a unique string for every monitor that is connected and active on a large number of computers. </p> <p>Research has pointed to 2 options</p> <ol> <li><p>Use WMI and query the Win32_DesktopMonitor for all active monitors. Use the PNPDeviceID for unique identification of monitors.</p></li> <li><p>Use the EnumDisplayDevices API, and dig down to get the device ID.</p></li> </ol> <p>I'm interested in using the device id for unique model identification because monitors using the default plug and play driver will report a generic string as the monitor name "default plug and play monitor" </p> <p>I have been experiencing issues with the WMI method, it seems to be only returning 1 monitor on my Vista machine, looking at the doco it turns out it does not work as expected on non WDDM devices. </p> <p>The EnumDisplayDevices seems to be a little problematic to get going when it runs from a background service (especially on Vista), If it's in session 0 it will return no info. </p> <ul> <li><p>Has anyone else had to do something similar (find unique model string for all connected active monitors?) </p></li> <li><p>What approach worked best?</p></li> </ul>
[ { "answer_id": 183284, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 0, "selected": false, "text": "<p>I've never tried doing it from a service, but <code>EnumDisplayDevices</code> generally works well when run as a user. I believe that services run in a separate (and headless) session, which could explain the problem you're seeing there.</p>\n\n<p>Could you run a helper program from your service, impersonating a user account that has access to the displays?</p>\n" }, { "answer_id": 183620, "author": "akalenuk", "author_id": 25459, "author_profile": "https://Stackoverflow.com/users/25459", "pm_score": 1, "selected": false, "text": "<p>We've been toying with EnumDisplayDevices in order to detect if the current video card manufacturer is NVIDIA. It's not the same, but maybe it would help. Our piece looked like this:</p>\n\n<pre><code>int disp_num = 0;\n BOOL res = TRUE;\n do {\n DISPLAY_DEVICE disp_dev_info; \n ZeroMemory( &amp;disp_dev_info, sizeof(DISPLAY_DEVICE) );\n disp_dev_info.cb = sizeof(DISPLAY_DEVICE);\n res = EnumDisplayDevices( 0, disp_num++, &amp;disp_dev_info, 0x00000001 );\n if(res &amp;&amp;\n disp_dev_info.DeviceString[0]!=0 &amp;&amp; disp_dev_info.DeviceString[0]=='N' &amp;&amp;\n disp_dev_info.DeviceString[1]!=0 &amp;&amp; disp_dev_info.DeviceString[1]=='V' &amp;&amp; \n disp_dev_info.DeviceString[2]!=0 &amp;&amp; disp_dev_info.DeviceString[2]=='I' &amp;&amp; \n disp_dev_info.DeviceString[3]!=0 &amp;&amp; disp_dev_info.DeviceString[3]=='D' &amp;&amp; \n disp_dev_info.DeviceString[4]!=0 &amp;&amp; disp_dev_info.DeviceString[4]=='I' &amp;&amp; \n disp_dev_info.DeviceString[5]!=0 &amp;&amp; disp_dev_info.DeviceString[5]=='A'){\n isNVidia = true;\n }\n int x = 0;\n }while( res != FALSE );\n</code></pre>\n\n<p>Pretty dumb, but working.</p>\n" }, { "answer_id": 201709, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 1, "selected": false, "text": "<p>The Win32_DesktopMonitor method only returns 1 monitor on my Vista machine as well. The PnP ID seems to be set correctly, though.</p>\n\n<p>I've had a quick play with the EnumDisplayDevices API, and while it seems to discover the adapter details reliably (presumably because most people won't leave it as \"Standard VGA\" for long), it only returns \"Plug and Play Monitor\" for the connected monitors.</p>\n\n<p>This echoes research that I did into this several years ago (had to put some code together to aid in dusting those memories off).</p>\n\n<p>This is from a normal user account. If you've got a reliable way to get EnumDisplayDevices to return the PnP ID, even in normal user sessions, I'd be interested -- we're currently investigating if any of this information is available to a device driver.</p>\n\n<p>One thing you could do, if running the code from session #0 isn't reliable enough, is to see if you can spawn a helper process (either using CreateProcessAsUser or using COM with activation monikers) that'll run in the user's context.</p>\n" }, { "answer_id": 202877, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 4, "selected": true, "text": "<p>This is my current work-in-progress code for detecting the monitor device id, reliably. </p>\n\n<pre><code>CString DeviceID;\nDISPLAY_DEVICE dd; \ndd.cb = sizeof(dd); \nDWORD dev = 0; \n// device index \nint id = 1; \n// monitor number, as used by Display Properties &gt; Settings\n\nwhile (EnumDisplayDevices(0, dev, &amp;dd, 0))\n{\n DISPLAY_DEVICE ddMon;\n ZeroMemory(&amp;ddMon, sizeof(ddMon));\n ddMon.cb = sizeof(ddMon);\n DWORD devMon = 0;\n\n while (EnumDisplayDevices(dd.DeviceName, devMon, &amp;ddMon, 0))\n {\n if (ddMon.StateFlags &amp; DISPLAY_DEVICE_ACTIVE &amp;&amp; \n !(ddMon.StateFlags &amp; DISPLAY_DEVICE_MIRRORING_DRIVER))\n {\n DeviceID.Format (L\"%s\", ddMon.DeviceID);\n DeviceID = DeviceID.Mid (8, DeviceID.Find (L\"\\\\\", 9) - 8);\n }\n devMon++;\n\n ZeroMemory(&amp;ddMon, sizeof(ddMon));\n ddMon.cb = sizeof(ddMon);\n }\n\n ZeroMemory(&amp;dd, sizeof(dd));\n dd.cb = sizeof(dd);\n dev++; \n}\n</code></pre>\n" }, { "answer_id": 7468393, "author": "rix0rrr", "author_id": 2474, "author_profile": "https://Stackoverflow.com/users/2474", "pm_score": 2, "selected": false, "text": "<p>I've just discovered you can query Win32_PnPEntity for service=\"monitor\", and it will return all monitors.</p>\n\n<p>Results on my machine:</p>\n\n<pre><code>select * from Win32_PnPEntity where service=\"monitor\"\n\nAvailability | Caption | ClassGuid | CompatibleID | ConfigManagerErrorCode | ConfigManagerUserConfig | CreationClassName | Description | DeviceID | ErrorCleared | ErrorDescription | HardwareID | InstallDate | LastErrorCode | Manufacturer | Name | PNPDeviceID | PowerManagementCapabilities | PowerManagementSupported | Service | Status | StatusInfo | SystemCreationClassName | SystemName\n | Dell 2007FP (Digital) | {4d36e96e-e325-11ce-bfc1-08002be10318} | array[0..0] | 0 | False | Win32_PnPEntity | Dell 2007FP (Digital) | DISPLAY\\DELA021\\5&amp;4F61016&amp;0&amp;UID257 | | | array[0..0] | | | Dell Inc. | Dell 2007FP (Digital) | DISPLAY\\DELA021\\5&amp;4F61016&amp;0&amp;UID257 | | | monitor | OK | | Win32_ComputerSystem | 8HVS05J\n | Dell ST2320L_Digital | {4d36e96e-e325-11ce-bfc1-08002be10318} | array[0..0] | 0 | False | Win32_PnPEntity | Dell ST2320L_Digital | DISPLAY\\DELF023\\5&amp;4F61016&amp;0&amp;UID256 | | | array[0..0] | | | Dell Inc. | Dell ST2320L_Digital | DISPLAY\\DELF023\\5&amp;4F61016&amp;0&amp;UID256 | | | monitor | OK | | Win32_ComputerSystem | 8HVS05J\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17174/" ]
For my current C++ project I need to detect a unique string for every monitor that is connected and active on a large number of computers. Research has pointed to 2 options 1. Use WMI and query the Win32\_DesktopMonitor for all active monitors. Use the PNPDeviceID for unique identification of monitors. 2. Use the EnumDisplayDevices API, and dig down to get the device ID. I'm interested in using the device id for unique model identification because monitors using the default plug and play driver will report a generic string as the monitor name "default plug and play monitor" I have been experiencing issues with the WMI method, it seems to be only returning 1 monitor on my Vista machine, looking at the doco it turns out it does not work as expected on non WDDM devices. The EnumDisplayDevices seems to be a little problematic to get going when it runs from a background service (especially on Vista), If it's in session 0 it will return no info. * Has anyone else had to do something similar (find unique model string for all connected active monitors?) * What approach worked best?
This is my current work-in-progress code for detecting the monitor device id, reliably. ``` CString DeviceID; DISPLAY_DEVICE dd; dd.cb = sizeof(dd); DWORD dev = 0; // device index int id = 1; // monitor number, as used by Display Properties > Settings while (EnumDisplayDevices(0, dev, &dd, 0)) { DISPLAY_DEVICE ddMon; ZeroMemory(&ddMon, sizeof(ddMon)); ddMon.cb = sizeof(ddMon); DWORD devMon = 0; while (EnumDisplayDevices(dd.DeviceName, devMon, &ddMon, 0)) { if (ddMon.StateFlags & DISPLAY_DEVICE_ACTIVE && !(ddMon.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER)) { DeviceID.Format (L"%s", ddMon.DeviceID); DeviceID = DeviceID.Mid (8, DeviceID.Find (L"\\", 9) - 8); } devMon++; ZeroMemory(&ddMon, sizeof(ddMon)); ddMon.cb = sizeof(ddMon); } ZeroMemory(&dd, sizeof(dd)); dd.cb = sizeof(dd); dev++; } ```
181,082
<p>I have followed all the instructions here: <a href="http://www.tonyspencer.com/2003/10/22/curl-with-php-and-apache-on-windows/" rel="noreferrer">http://www.tonyspencer.com/2003/10/22/curl-with-php-and-apache-on-windows/</a></p> <p>to install &amp; config apache get the PHP5 packages and get the CURL packages.</p> <p>I run the apache and run a PHP script. no problem. but when I run the php script with curl, it fails. </p> <p>It returns: <code>**Call to undefined function curl_version() in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\testing.php on line 5**</code></p> <p>In which line 5 is a called to <code>curl_init()</code></p> <p>I output the php -i to see whether the right path to extension is called. It is correctly set:</p> <pre><code>extension_dir =&gt; C:\PHP\ext =&gt; C:\PHP\ext cURL support =&gt; enabled cURL Information =&gt; libcurl/7.16.0 OpenSSL/0.9.8g zlib/1.2.3 </code></pre> <p>I even tried to run <code>curl_version()</code> but still, same kind of error comes up.<br> It looks like the PHP can't find the CURL extension, but the <code>php.ini</code> (and also php -i) shows that it is set.</p> <p>any idea? :)</p> <pre><code>P.S&gt; System I m running on: Windows XP Apache 2.2 PHP 5.2.6 CURL Win32 Generic Binaries: Win32 2000/XP metalink 7.19.0 binary SSL enabled Daniel Stenberg 249 KB </code></pre> <p>I didn't get this: </p> <pre><code>Win32 2000/XP 7.19.0 libcurl SSL enabled Günter Knauf 1.55 MB Should I get this one instead? </code></pre> <hr> <p>The reason I need to use CURL is that it is the requirement from my project. So, I can only stick with that. XAMPP... how does it work in Windows? Is there any site that you can recommend? Thanks.</p> <p>I have tried a lot of things on installing cURL and check everything, but still, I'm stilling circling around the problem and have no idea what's going on. </p> <p>The Apache server uses the right PHP.ini. and the PHP.ini has the correct extension_dir and extension=php_curl.dll I have no idea why it doesn't work. even I follow every step for setting it up. :(</p>
[ { "answer_id": 181220, "author": "boxoft", "author_id": 23773, "author_profile": "https://Stackoverflow.com/users/23773", "pm_score": 4, "selected": false, "text": "<p>I'm using XAMPP, in which there are several php.ini files.</p>\n\n<p>You can find the line in the php.ini files:\n<code>;extension=php_curl.dll</code></p>\n\n<p>Please remove <code>;</code> at the beginning of this line. And you may need to restart apache server.</p>\n" }, { "answer_id": 181555, "author": "SchizoDuckie", "author_id": 18077, "author_profile": "https://Stackoverflow.com/users/18077", "pm_score": 6, "selected": true, "text": "<p>You're probably mistaking what PHP.ini you need to edit. first, add a PHPinfo(); to a info.php, and run it from your browser.</p>\n\n<p>Write down the PHP ini directory path you see in the variables list now!\nYou will probably notice that it's different from your PHP-CLI ini file.</p>\n\n<p>Enable the extension</p>\n\n<p>You're done :-)</p>\n" }, { "answer_id": 182450, "author": "boxoft", "author_id": 23773, "author_profile": "https://Stackoverflow.com/users/23773", "pm_score": 1, "selected": false, "text": "<p>You may find XAMPP at <a href=\"http://www.apachefriends.org/en/xampp.html\" rel=\"nofollow noreferrer\">http://www.apachefriends.org/en/xampp.html</a></p>\n\n<p><a href=\"http://www.apachefriends.org/en/xampp-windows.html\" rel=\"nofollow noreferrer\">http://www.apachefriends.org/en/xampp-windows.html</a> explains XMAPP for Windows.</p>\n\n<p>Yes, there are 3 php.ini files after installation, one is for php4, one is for php5, and one is for apache. Please modify them accordingly.</p>\n" }, { "answer_id": 185266, "author": "murvinlai", "author_id": 196874, "author_profile": "https://Stackoverflow.com/users/196874", "pm_score": 1, "selected": false, "text": "<p>I solved the problem.</p>\n\n<p>In my apache, I have to specify: </p>\n\n<p>PHPIniDir \"C://php\"\nAddType application/x-httpd-php .php</p>\n\n<p>and for php.ini, instead of using the php.ini_recommend, use php.ini_dist to configure my php.ini.</p>\n\n<p>then make sure the php engine has turned on.\nthen it works now. Thanks all.</p>\n" }, { "answer_id": 526025, "author": "TrentCoder", "author_id": 63908, "author_profile": "https://Stackoverflow.com/users/63908", "pm_score": 2, "selected": false, "text": "<p>I recently installed Curl on PHP5 for Windows Vista. I did <em>not</em> enable the CURL library when I initially installed PHP5, so nothing about Curl was showing up in phpinfo() or php.ini. </p>\n\n<p>I installed CURL by re-running the PHP5 installer (php-5.2.8-win32-installer.msi for me) and choosing \"Change\". Then, I added the CURL component. Restart Apache, and CURL should work. CURL will show up in phpinfo(). Also, here is a sample script you can run to verify it works. It displays an RSS feed from Google:</p>\n\n<pre><code> &lt;?php\n error_reporting(E_ALL);\n ini_set('display_errors', '1');\n $ch = curl_init();\n curl_setopt($ch, CURLOPT_URL,\n 'http://news.google.com/news?hl=en&amp;topic=t&amp;output=rss');\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\n $contents = curl_exec ($ch);\n echo $contents;\n curl_close ($ch);\n ?&gt;\n</code></pre>\n" }, { "answer_id": 8241228, "author": "Neelesh", "author_id": 537695, "author_profile": "https://Stackoverflow.com/users/537695", "pm_score": 0, "selected": false, "text": "<p>You can use binary file of curl .download file from here :\n <a href=\"http://www.paehl.com/open_source/?CURL_7.22.0\" rel=\"nofollow\">http://www.paehl.com/open_source/?CURL_7.22.0</a>\nDownload the file and after extract put in to any drive and set the absolute path into environment now you can also use curl as a command in windows. like \nc:\\curl -u [email protected]:password <a href=\"http://localhost:3000/user/sign_in\" rel=\"nofollow\">http://localhost:3000/user/sign_in</a></p>\n" }, { "answer_id": 10400414, "author": "Marcin Majchrzak", "author_id": 546081, "author_profile": "https://Stackoverflow.com/users/546081", "pm_score": 3, "selected": false, "text": "<p>I had also problems with this. After all these steps made correctly and some fixed misunderstandings (there is no extensions_dir but extension_dir, and there is no sessions.save_path but session.save_path) nothing works.</p>\n\n<p>Finally I found this note at php.net:</p>\n\n<p><strong>Note: Note to Win32 Users:\nIn order to enable this module on a Windows environment, libeay32.dll and ssleay32.dll must be present in your PATH. You don't need libcurl.dll from the cURL site.</strong></p>\n\n<p>So I copied ssleay32.dll, libeay32.dll &amp; php_curl.dll From /PHP to Windows/system32 and replaced already existing files (I noticed there were older versions of ssleay32.dll and libeay32.dll). After that I found CURL section in php_info(); and finally everything works.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 13953839, "author": "Rakesh", "author_id": 1915996, "author_profile": "https://Stackoverflow.com/users/1915996", "pm_score": 2, "selected": false, "text": "<p>Note: Note to Win32 Users\nIn order to enable this module (cURL) on a Windows environment, libeay32.dll and ssleay32.dll must be present in your PATH. You don't need libcurl.dll from the cURL site. </p>\n\n<p>This note solved my problem. Thought of sharing. libeay32.dll &amp; ssleay.dll you will find in your php installation folder.</p>\n" }, { "answer_id": 17074237, "author": "curiousBoy", "author_id": 2166856, "author_profile": "https://Stackoverflow.com/users/2166856", "pm_score": 6, "selected": false, "text": "<p><strong>Use the following steps to install curl:</strong></p>\n\n<ol>\n<li><p>Open <a href=\"https://curl.haxx.se/dlwiz?type=bin\" rel=\"noreferrer\">https://curl.haxx.se/dlwiz?type=bin</a> in a browser.</p></li>\n<li><p>Select your operating system in the dropdown box: either Windows /Win32 or Win 64. Click Select!</p></li>\n<li><p>For Win 32, choose whether you will use curl in a Windows Command Prompt (Generic) or in a Cygwin terminal (cygwin). For Win 64, choose whether you will use curl in a Windows Command Prompt (Generic) or MinGW (MinGW64). Click Select!</p></li>\n<li><p>If required, choose your Windows operating system. Finish.</p></li>\n<li><p>Click Download for the version which has SSL enabled or disabled</p></li>\n<li><p>Open the downloaded zip file. Extract the files to an easy-to-find place, such as C:\\Program Files.</p></li>\n</ol>\n\n<p><strong>Testing curl</strong></p>\n\n<ol>\n<li><p>Open up the Windows Command Prompt terminal. (From the Start menu, click Run, then type cmd.)</p></li>\n<li><p>Set the path to include the directory where you put curl.exe. For example, if you put it in C:\\Program Files\\curl, then you would type the following command:\nset path=%path%;\"c:\\Program Files\\curl\"</p></li>\n</ol>\n\n<p>NOTE: You can also directly copy the curl.exe file any existing path in your path</p>\n\n<ol start=\"3\">\n<li>Type curl. \nYou should see the following message:\ncurl: try 'curl –help' or 'curl –message' for more information\nThis means that curl is installed and the path is correct.</li>\n</ol>\n" }, { "answer_id": 28184708, "author": "RizonBarns", "author_id": 2302672, "author_profile": "https://Stackoverflow.com/users/2302672", "pm_score": 2, "selected": false, "text": "<p>I agree with Erroid, you must add PHP directory into PATH environment.</p>\n\n<pre><code>PATH=%PATH%;&lt;Your_PHP_Path&gt;\n</code></pre>\n\n<p>Example</p>\n\n<pre><code>PATH=%PATH%;C:\\php\n</code></pre>\n\n<p>It worked for me. Thank you.</p>\n" }, { "answer_id": 30073534, "author": "Nuadu", "author_id": 4693736, "author_profile": "https://Stackoverflow.com/users/4693736", "pm_score": 3, "selected": false, "text": "<p>Another answer for other people who have had this problem</p>\n\n<p>when you un comment the extension line, change it to:</p>\n\n<pre><code>extension=C:/php/ext/php_curl.dll\n</code></pre>\n\n<p>or the location of the extension folder, for me it did not work until i did this</p>\n" }, { "answer_id": 44271774, "author": "Manny Irizarry", "author_id": 8008729, "author_profile": "https://Stackoverflow.com/users/8008729", "pm_score": 0, "selected": false, "text": "<p>You can also use <a href=\"https://www.cygwin.com/\" rel=\"nofollow noreferrer\">CygWin</a> and install the cURL package. It works very well and flawlessly!!</p>\n" }, { "answer_id": 53508130, "author": "ESP32", "author_id": 3177115, "author_profile": "https://Stackoverflow.com/users/3177115", "pm_score": 0, "selected": false, "text": "<p>I have tried everything - but nothing helped. After searching for several hours I found this information:</p>\n\n<blockquote>\n <p>Apache 2.4.18 for some reason does not load php 7.2 curl. I updated my\n Apache to 2.4.29 and curl loaded instantly</p>\n</blockquote>\n\n<p><a href=\"http://forum.wampserver.com/read.php?2,149346,149348\" rel=\"nofollow noreferrer\">http://forum.wampserver.com/read.php?2,149346,149348</a></p>\n\n<p>What should I say: I updated Apache and curl was running like charm</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196874/" ]
I have followed all the instructions here: <http://www.tonyspencer.com/2003/10/22/curl-with-php-and-apache-on-windows/> to install & config apache get the PHP5 packages and get the CURL packages. I run the apache and run a PHP script. no problem. but when I run the php script with curl, it fails. It returns: `**Call to undefined function curl_version() in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\testing.php on line 5**` In which line 5 is a called to `curl_init()` I output the php -i to see whether the right path to extension is called. It is correctly set: ``` extension_dir => C:\PHP\ext => C:\PHP\ext cURL support => enabled cURL Information => libcurl/7.16.0 OpenSSL/0.9.8g zlib/1.2.3 ``` I even tried to run `curl_version()` but still, same kind of error comes up. It looks like the PHP can't find the CURL extension, but the `php.ini` (and also php -i) shows that it is set. any idea? :) ``` P.S> System I m running on: Windows XP Apache 2.2 PHP 5.2.6 CURL Win32 Generic Binaries: Win32 2000/XP metalink 7.19.0 binary SSL enabled Daniel Stenberg 249 KB ``` I didn't get this: ``` Win32 2000/XP 7.19.0 libcurl SSL enabled Günter Knauf 1.55 MB Should I get this one instead? ``` --- The reason I need to use CURL is that it is the requirement from my project. So, I can only stick with that. XAMPP... how does it work in Windows? Is there any site that you can recommend? Thanks. I have tried a lot of things on installing cURL and check everything, but still, I'm stilling circling around the problem and have no idea what's going on. The Apache server uses the right PHP.ini. and the PHP.ini has the correct extension\_dir and extension=php\_curl.dll I have no idea why it doesn't work. even I follow every step for setting it up. :(
You're probably mistaking what PHP.ini you need to edit. first, add a PHPinfo(); to a info.php, and run it from your browser. Write down the PHP ini directory path you see in the variables list now! You will probably notice that it's different from your PHP-CLI ini file. Enable the extension You're done :-)
181,090
<p>I have a tree of active record objects, something like:</p> <pre><code>class Part &lt; ActiveRecord::Base has_many :sub_parts, :class_name =&gt; "Part" def complicated_calculation if sub_parts.size &gt; 0 return self.sub_parts.inject(0){ |sum, current| sum + current.complicated_calculation } else sleep(1) return rand(10000) end end end </code></pre> <p>It is too costly to recalculate the complicated_calculation each time. So, I need a way to cache the value. However, if any part is changed, it needs to invalidate its cache and the cache of its parent, and grandparent, etc.</p> <p>As a rough draft, I created a column to hold the cached calculation in the "parts" table, but this smells a little rotten. It seems like there should be a cleaner way to cache the calculated values without stuffing them along side the "real" columns.</p>
[ { "answer_id": 181093, "author": "epochwolf", "author_id": 16204, "author_profile": "https://Stackoverflow.com/users/16204", "pm_score": 2, "selected": false, "text": "<p>Have a field similar to a counter cache. For example: order_items_amount and have that be a cached calculated field. </p>\n\n<p>Use a after_save filter to recalculate the field on anything that can modify that value. (Including the record itself)</p>\n\n<p>Edit: This is basically what you have now. I don't know of any cleaner solution unless you wanted to store cached calculated fields in another table.</p>\n" }, { "answer_id": 181211, "author": "scottd", "author_id": 5935, "author_profile": "https://Stackoverflow.com/users/5935", "pm_score": 2, "selected": false, "text": "<p>Either using a before_save or an ActiveRecord Observer is the way to go to make sure the cached value is up-to-date. I would use a before_save and then check to see if the value you use in the calculation actually changed. That way you don't have to update the cache if you don't need to.<br>\nStoring the value in the db will allow you to cache the calculations over multiple requests. Another option for this is to store the value in memcache. You can make a special accessor and setter for that value that can check the memcache and update it if needed.<br>\nAnother thought: Will there be cases where you will change a value in one of the models and need the calculation to be updated before you do the save? In that case you will need to dirty the cache value whenever you update any of the calculation values in the model, not with a before_save.</p>\n" }, { "answer_id": 181502, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 4, "selected": true, "text": "<ol>\n<li><p>You can stuff the actually cached values in the Rails cache (use memcached if you require that it be distributed).</p></li>\n<li><p>The tough bit is cache expiry, but cache expiry is uncommon, right? In that case, we can just loop over each of the parent objects in turn and zap its cache, too. I added some ActiveRecord magic to your class to make getting the parent objects simplicity itself -- and you don't even need to touch your database. Remember to call <code>Part.sweep_complicated_cache(some_part)</code> as appropriate in your code -- you can put this in callbacks, etc, but I can't add it for you because I don't understand when <code>complicated_calculation</code> is changing.</p>\n\n<pre><code>class Part &lt; ActiveRecord::Base\n has_many :sub_parts, :class_name =&gt; \"Part\"\n belongs_to :parent_part, :class_name =&gt; \"Part\", :foreign_key =&gt; :part_id\n\n @@MAX_PART_NESTING = 25 #pick any sanity-saving value\n\n def complicated_calculation (...)\n if cache.contains? [id, :complicated_calculation]\n cache[ [id, :complicated_calculation] ]\n else\n cache[ [id, :complicated_calculation] ] = complicated_calculation_helper (...)\n end\n end\n\n def complicated_calculation_helper\n #your implementation goes here\n end\n\n def Part.sweep_complicated_cache(start_part)\n level = 1 # keep track to prevent infinite loop in event there is a cycle in parts\n current_part = self\n\n cache[ [current_part.id, :complicated_calculation] ].delete\n while ( (level &lt;= 1 &lt; @@MAX_PART_NESTING) &amp;&amp; (current_part.parent_part)) {\n current_part = current_part.parent_part)\n cache[ [current_part.id, :complicated_calculation] ].delete\n end\n end\nend\n</code></pre></li>\n</ol>\n" }, { "answer_id": 181675, "author": "August Lilleaas", "author_id": 26051, "author_profile": "https://Stackoverflow.com/users/26051", "pm_score": 5, "selected": false, "text": "<p>I suggest using association callbacks.</p>\n\n<pre><code>class Part &lt; ActiveRecord::Base\n has_many :sub_parts,\n :class_name =&gt; \"Part\",\n :after_add =&gt; :count_sub_parts,\n :after_remove =&gt; :count_sub_parts\n\n private\n\n def count_sub_parts\n update_attribute(:sub_part_count, calculate_sub_part_count)\n end\n\n def calculate_sub_part_count\n # perform the actual calculation here\n end\nend\n</code></pre>\n\n<p>Nice and easy =)</p>\n" }, { "answer_id": 198260, "author": "hernan43", "author_id": 27521, "author_profile": "https://Stackoverflow.com/users/27521", "pm_score": 1, "selected": false, "text": "<p>I've found that sometimes there is good reason to de-normalize information in your database. I have something similar in an app that I am working on and I just re-calculate that field anytime the collection changes. </p>\n\n<p>It doesn't use a cache and it stores the most up to date figure in the database. </p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23899/" ]
I have a tree of active record objects, something like: ``` class Part < ActiveRecord::Base has_many :sub_parts, :class_name => "Part" def complicated_calculation if sub_parts.size > 0 return self.sub_parts.inject(0){ |sum, current| sum + current.complicated_calculation } else sleep(1) return rand(10000) end end end ``` It is too costly to recalculate the complicated\_calculation each time. So, I need a way to cache the value. However, if any part is changed, it needs to invalidate its cache and the cache of its parent, and grandparent, etc. As a rough draft, I created a column to hold the cached calculation in the "parts" table, but this smells a little rotten. It seems like there should be a cleaner way to cache the calculated values without stuffing them along side the "real" columns.
1. You can stuff the actually cached values in the Rails cache (use memcached if you require that it be distributed). 2. The tough bit is cache expiry, but cache expiry is uncommon, right? In that case, we can just loop over each of the parent objects in turn and zap its cache, too. I added some ActiveRecord magic to your class to make getting the parent objects simplicity itself -- and you don't even need to touch your database. Remember to call `Part.sweep_complicated_cache(some_part)` as appropriate in your code -- you can put this in callbacks, etc, but I can't add it for you because I don't understand when `complicated_calculation` is changing. ``` class Part < ActiveRecord::Base has_many :sub_parts, :class_name => "Part" belongs_to :parent_part, :class_name => "Part", :foreign_key => :part_id @@MAX_PART_NESTING = 25 #pick any sanity-saving value def complicated_calculation (...) if cache.contains? [id, :complicated_calculation] cache[ [id, :complicated_calculation] ] else cache[ [id, :complicated_calculation] ] = complicated_calculation_helper (...) end end def complicated_calculation_helper #your implementation goes here end def Part.sweep_complicated_cache(start_part) level = 1 # keep track to prevent infinite loop in event there is a cycle in parts current_part = self cache[ [current_part.id, :complicated_calculation] ].delete while ( (level <= 1 < @@MAX_PART_NESTING) && (current_part.parent_part)) { current_part = current_part.parent_part) cache[ [current_part.id, :complicated_calculation] ].delete end end end ```
181,091
<p>I have an array of hashes, and I want the unique values out of it. Calling <code>Array.uniq</code> doesn't give me what I expect.</p> <pre><code>a = [{:a =&gt; 1},{:a =&gt; 2}, {:a =&gt; 1}] a.uniq # =&gt; [{:a =&gt; 1}, {:a =&gt; 2}, {:a =&gt; 1}] </code></pre> <p>Where I expected:</p> <pre><code>[{:a =&gt; 1}, {:a =&gt; 2}] </code></pre> <p>In searching around on the net, I didn't come up with a solution that I was happy with. Folks recommended redefining <code>Hash.eql?</code> and <code>Hash.hash</code>, since that is what <code>Array.uniq</code> is querying.</p> <p>Edit: Where I ran into this in the real world, the hashes were slightly more complex. They were the result of parsed JSON that had multiple fields, some of which the values were hashes as well. I had an array of those results that I wanted to filter out the unique values.</p> <p>I don't like the redefine <code>Hash.eql?</code> and <code>Hash.hash</code> solution, because I would either have to redefine <code>Hash</code> globally, or redefine it for each entry in my array. Changing the definition of <code>Hash</code> for each entry would be cumbersome, especially since there may be nested hashes inside of each entry.</p> <p>Changing <code>Hash</code> globally has some potential, especially if it were done temporarily. I'd want to build another class or helper function that wrapped saving off the old definitions, and restoring them, but I think this adds more complexity than is really needed.</p> <p>Using <code>inject</code> seems like a good alternative to redefining <code>Hash</code>.</p>
[ { "answer_id": 181096, "author": "Aaron Hinni", "author_id": 12086, "author_profile": "https://Stackoverflow.com/users/12086", "pm_score": 6, "selected": true, "text": "<p>I can get what I want by calling <code>inject</code></p>\n\n<pre><code>a = [{:a =&gt; 1},{:a =&gt; 2}, {:a =&gt; 1}]\na.inject([]) { |result,h| result &lt;&lt; h unless result.include?(h); result }\n</code></pre>\n\n<p>This will return:</p>\n\n<pre><code>[{:a=&gt;1}, {:a=&gt;2}]\n</code></pre>\n" }, { "answer_id": 181396, "author": "Mark Reid", "author_id": 24057, "author_profile": "https://Stackoverflow.com/users/24057", "pm_score": 0, "selected": false, "text": "<p>The answer you give is similar to the one discussed <a href=\"http://mikeburnscoder.wordpress.com/2008/01/18/uniquify-an-array-of-hashes-in-ruby/\" rel=\"nofollow noreferrer\">here</a>. It overrides the <code>hash</code> and <code>eql?</code> methods on the hashes that are to appear in the array which then makes <code>uniq</code> behave correctly.</p>\n" }, { "answer_id": 183692, "author": "glenn mcdonald", "author_id": 7919, "author_profile": "https://Stackoverflow.com/users/7919", "pm_score": 2, "selected": false, "text": "<p>Assuming your hashes are always single key-value pairs, this will work:</p>\n\n<pre><code>a.map {|h| h.to_a[0]}.uniq.map {|k,v| {k =&gt; v}}\n</code></pre>\n\n<p>Hash.to_a creates an array of key-value arrays, so the first map gets you:</p>\n\n<pre><code>[[:a, 1], [:a, 2], [:a, 1]]\n</code></pre>\n\n<p>uniq on Arrays does what you want, giving you:</p>\n\n<pre><code>[[:a, 1], [:a, 2]]\n</code></pre>\n\n<p>and then the second map puts them back together as hashes again.</p>\n" }, { "answer_id": 618369, "author": "edthix", "author_id": 33552, "author_profile": "https://Stackoverflow.com/users/33552", "pm_score": 0, "selected": false, "text": "<p>found on google \n<a href=\"http://mikeburnscoder.wordpress.com/2008/01/18/uniquify-an-array-of-hashes-in-ruby/\" rel=\"nofollow noreferrer\">http://mikeburnscoder.wordpress.com/2008/01/18/uniquify-an-array-of-hashes-in-ruby/</a></p>\n" }, { "answer_id": 834604, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I've had a similar situation, but hashes had keys. I used sorting method.</p>\n\n<p>What I mean:</p>\n\n<p>you have an array:</p>\n\n<pre><code>[{:x=&gt;1},{:x=&gt;2},{:x=&gt;3},{:x=&gt;2},{:x=&gt;1}]\n</code></pre>\n\n<p>you sort it (<code>#sort_by {|t| t[:x]}</code>) and get this:</p>\n\n<pre><code>[{:x=&gt;1}, {:x=&gt;1}, {:x=&gt;2}, {:x=&gt;2}, {:x=&gt;3}]\n</code></pre>\n\n<p>now a bit modified version of answer by Aaaron Hinni:</p>\n\n<pre><code>your_array.inject([]) do |result,item| \n result &lt;&lt; item if !result.last||result.last[:x]!=item[:x]\n result\nend\n</code></pre>\n\n<p>I've also tried:</p>\n\n<pre><code>test.inject([]) {|r,h| r&lt;&lt;h unless r.find {|t| t[:x]==h[:x]}; r}.sort_by {|t| t[:x]}\n</code></pre>\n\n<p>but it's very slow. here is my benchmark:</p>\n\n<pre><code>test=[]\n1000.times {test&lt;&lt;{:x=&gt;rand}}\n\nBenchmark.bmbm do |bm|\n bm.report(\"sorting: \") do\n test.sort_by {|t| t[:x]}.inject([]) {|r,h| r&lt;&lt;h if !r.last||r.last[:x]!=h[:x]; r}\n end\n bm.report(\"inject: \") {test.inject([]) {|r,h| r&lt;&lt;h unless r.find {|t| t[:x]==h[:x]}; r}.sort_by {|t| t[:x]} }\nend\n</code></pre>\n\n<p>results:</p>\n\n<pre><code>Rehearsal ---------------------------------------------\nsorting: 0.010000 0.000000 0.010000 ( 0.005633)\ninject: 0.470000 0.140000 0.610000 ( 0.621973)\n------------------------------------ total: 0.620000sec\n\n user system total real\nsorting: 0.010000 0.000000 0.010000 ( 0.003839)\ninject: 0.480000 0.130000 0.610000 ( 0.612438)\n</code></pre>\n" }, { "answer_id": 5626441, "author": "fl00r", "author_id": 298624, "author_profile": "https://Stackoverflow.com/users/298624", "pm_score": 4, "selected": false, "text": "<p>Ruby 1.8.7+ will return just what you have expected:</p>\n\n<pre><code>[{:a=&gt;1}, {:a=&gt;2}, {:a=&gt;1}].uniq\n#=&gt; [{:a=&gt;1}, {:a=&gt;2}] \n</code></pre>\n" }, { "answer_id": 13274328, "author": "yoniLavi", "author_id": 493553, "author_profile": "https://Stackoverflow.com/users/493553", "pm_score": 0, "selected": false, "text": "<p>The pipe method on arrays (available since 1.8.6) performs set union (returning an array), so the following is another possible way to get unique elements of any array <code>a</code>:</p>\n\n<p><code>[] | a</code></p>\n" }, { "answer_id": 27776023, "author": "shajin", "author_id": 519680, "author_profile": "https://Stackoverflow.com/users/519680", "pm_score": 2, "selected": false, "text": "<p>You can use (tested in ruby 1.9.3),</p>\n\n<pre><code>[{a: 1},{a: 2},{a:1}].uniq =&gt; [{a:1},{a: 2}]\n[{a: 1,b: 2},{a: 2, b: 2},{a: 1, b: 3}].uniq_by {|v| v[:a]} =&gt; [{a: 1,b: 2},{a: 2, b: 2}]\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12086/" ]
I have an array of hashes, and I want the unique values out of it. Calling `Array.uniq` doesn't give me what I expect. ``` a = [{:a => 1},{:a => 2}, {:a => 1}] a.uniq # => [{:a => 1}, {:a => 2}, {:a => 1}] ``` Where I expected: ``` [{:a => 1}, {:a => 2}] ``` In searching around on the net, I didn't come up with a solution that I was happy with. Folks recommended redefining `Hash.eql?` and `Hash.hash`, since that is what `Array.uniq` is querying. Edit: Where I ran into this in the real world, the hashes were slightly more complex. They were the result of parsed JSON that had multiple fields, some of which the values were hashes as well. I had an array of those results that I wanted to filter out the unique values. I don't like the redefine `Hash.eql?` and `Hash.hash` solution, because I would either have to redefine `Hash` globally, or redefine it for each entry in my array. Changing the definition of `Hash` for each entry would be cumbersome, especially since there may be nested hashes inside of each entry. Changing `Hash` globally has some potential, especially if it were done temporarily. I'd want to build another class or helper function that wrapped saving off the old definitions, and restoring them, but I think this adds more complexity than is really needed. Using `inject` seems like a good alternative to redefining `Hash`.
I can get what I want by calling `inject` ``` a = [{:a => 1},{:a => 2}, {:a => 1}] a.inject([]) { |result,h| result << h unless result.include?(h); result } ``` This will return: ``` [{:a=>1}, {:a=>2}] ```
181,097
<p>I wanted to do something like this:</p> <pre><code>&lt;asp:Label ID="lblMyLabel" onclick="lblMyLabel_Click" runat="server"&gt;My Label&lt;/asp:Label&gt; </code></pre> <p>I know that in Javascript I can do:</p> <pre><code>&lt;span onclick="foo();"&gt;My Label&lt;/span&gt; </code></pre> <p>So I'm wondering why I can't do that with a Label object.</p>
[ { "answer_id": 181103, "author": "Brian Kim", "author_id": 5704, "author_profile": "https://Stackoverflow.com/users/5704", "pm_score": 7, "selected": true, "text": "<p>You can use Attributes to add onclick client side callback.</p>\n\n<p>I didn't know you can do this on span tags, but if it works you can add 'onclick' by <code>lblMyLabel.Attributes.Add(\"onclick\", \"foo();\");</code> </p>\n\n<p>But <code>foo();</code> would need to be a client side javascript function.</p>\n\n<p><code>System.Web.UI.WebControls.Label</code> does NOT have OnClick server event. You could look into using AJAX if you want server callback with example above.</p>\n\n<p>You could also use <code>LinkButton</code> like other say. You can make it not look like a link by using CSS, if it is just that underline you are concerned about. </p>\n\n<p>ASPX:</p>\n\n<pre><code>&lt;asp:LinkButton ID=\"LinkButton1\" runat=\"server\" \n CssClass=\"imjusttext\" OnClick=\"LinkButton1_Click\"&gt;\nLinkButton\n&lt;/asp:LinkButton&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>a.imjusttext{ color: #000000; text-decoration: none; }\na.imjusttext:hover { text-decoration: none; }\n</code></pre>\n" }, { "answer_id": 181108, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 3, "selected": false, "text": "<p>You can do it in code in the page_load eg:</p>\n\n<pre><code>void Page_Load(object sender, EventArgs e) \n{\n lblMyLabel.Attributes.Add(\"onclick\",\n \"javascript:alert('ALERT ALERT!!!')\");\n}\n</code></pre>\n" }, { "answer_id": 181109, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>I think you can, but it's a client-side onclick handler, not server side. It will complain about the attribute not being supported (or some such) but I think it renders correctly. If you want to to a server-side handler, I think you'll need to do a LinkButton.</p>\n" }, { "answer_id": 181110, "author": "Pavel Chuchuva", "author_id": 14131, "author_profile": "https://Stackoverflow.com/users/14131", "pm_score": 1, "selected": false, "text": "<p>As far as I know that's impossible. Label control emits <code>&lt;span</code>> element which is “unclickable” on the server side. You would need to replace your Label control with a LinkButton.</p>\n" }, { "answer_id": 181113, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 2, "selected": false, "text": "<p>If you want an onclick event, why don't you use a linkbutton, which has the <code>onclientclick</code> event:</p>\n\n<pre><code>&lt;asp:linkbutton id=\"lblMyLink\" onclientclick=\"lblMyLink_Click\" runat=\"server\"&gt;My Label&lt;/asp:linkbutton&gt;\n</code></pre>\n\n<p>You can use CSS to make the link look like whatever you want</p>\n" }, { "answer_id": 181118, "author": "CodeChef", "author_id": 21786, "author_profile": "https://Stackoverflow.com/users/21786", "pm_score": 4, "selected": false, "text": "<p>Your question doesn't specify if you mean to raise the click event on the server (VB or c#) or the client (javascript.) If you're looking for a server-side event you should use a link button with css that makes the link appear as a label. You can then use the link button's server-side click event. If you're looking for a client-side click event - just type it into your server control markup <br/> <code>asp:label id=\"MyLabel\" runat=\"server\" onclick=\"javascript:alert('hello');\" Text=\"Click Me\";</code> <br/>ASP.NET will emit additional attributes in the html markup that generates.</p>\n" }, { "answer_id": 181124, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 1, "selected": false, "text": "<p>Another hack would be to use a hidden link or button with style=\"display:none;\" and trigger the click on the server control from a javascript function in the span.</p>\n\n<p>Something like this:</p>\n\n<pre><code>&lt;asp:linkbutton id=\"lblMyLink\" onClick=\"lblMyLink_Click\" runat=\"server\" style=\"display:none;\"&gt;My Link&lt;/asp:linkbutton&gt;\n&lt;span onclick=\"document.getElementById('lblMyLink').click();\"&gt;My Label&lt;/span&gt;\n</code></pre>\n" }, { "answer_id": 181128, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "<p>you could always roll out your own control which produces a span, with the .net's standard postback javascript, but as stated earlier using a linklabel with a CSS class would be easier</p>\n" }, { "answer_id": 714981, "author": "Doug", "author_id": 82266, "author_profile": "https://Stackoverflow.com/users/82266", "pm_score": 0, "selected": false, "text": "<p>Just to chime in on this issue,\nI used a label in my .aspx page that was only to be visible in my DataList Item template if there were child records in the dataset.</p>\n\n<p>I added a onclick function to the label:</p>\n\n<p>moreOptionsLabel.Attributes.Add(\"onclick\", string.Format(\"toggle_visibility('{0}')\", div.ClientID)); </p>\n\n<p>in my .cs file. It will now control a div tag in the .aspx page to show or hide the records - because the onclick points to a client side javascript function. Notice the div.ClientID, that makes this workable in a datalist.</p>\n\n<p>As noted above - the span tag does indeed become functional with \"onclick\". And since the label control is rendered as a span after the page request, using the Addtribute.Add(\"onclick\".... does work.</p>\n\n<p>The result is show/hide functionality of data with out doing a postback. If you use the LinkButton, or simlar controls - the postback and page reload is unavoidable - unless you want to get into some Ajax stuff.</p>\n\n<p>NOTE: the span tag won't look clickable unless you style it with an underline and hand cursor.</p>\n\n<p>Credit to this idea comes from Will Asrari over at <a href=\"http://www.willasrari.com/blog/display-nested-repeaters-and-gridviews-asynchronously/000292.aspx\" rel=\"nofollow noreferrer\">http://www.willasrari.com/blog/display-nested-repeaters-and-gridviews-asynchronously/000292.aspx</a> </p>\n" }, { "answer_id": 1397852, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You need to create a class object that inherits from the label and onclick event handler which will be a method by yourslef and use your object as a custom label.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
I wanted to do something like this: ``` <asp:Label ID="lblMyLabel" onclick="lblMyLabel_Click" runat="server">My Label</asp:Label> ``` I know that in Javascript I can do: ``` <span onclick="foo();">My Label</span> ``` So I'm wondering why I can't do that with a Label object.
You can use Attributes to add onclick client side callback. I didn't know you can do this on span tags, but if it works you can add 'onclick' by `lblMyLabel.Attributes.Add("onclick", "foo();");` But `foo();` would need to be a client side javascript function. `System.Web.UI.WebControls.Label` does NOT have OnClick server event. You could look into using AJAX if you want server callback with example above. You could also use `LinkButton` like other say. You can make it not look like a link by using CSS, if it is just that underline you are concerned about. ASPX: ``` <asp:LinkButton ID="LinkButton1" runat="server" CssClass="imjusttext" OnClick="LinkButton1_Click"> LinkButton </asp:LinkButton> ``` CSS: ``` a.imjusttext{ color: #000000; text-decoration: none; } a.imjusttext:hover { text-decoration: none; } ```
181,106
<p>Is a new (or different) instance of <code>TestCase</code> object is used to run each test method in a JUnit test case? Or one instance is reused for all the tests?</p> <pre><code>public class MyTest extends TestCase { public void testSomething() { ... } public void testSomethingElse() { ... } } </code></pre> <p>While running this test, how many instances of <code>MyTest</code> class is created?</p> <p>If possible, provide a link to a document or source code where I can verify the behaviour.</p>
[ { "answer_id": 181111, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 3, "selected": false, "text": "<p>Yes, a separate instance is created.</p>\n\n<p>While running that test, 2 instances of MyTest gets created.</p>\n\n<p>If you want a different behavior, one option is to use a similar tool called TestNG(<a href=\"http://testng.org/doc/\" rel=\"noreferrer\">http://testng.org/doc/</a>).</p>\n" }, { "answer_id": 181114, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 2, "selected": false, "text": "<p>If you are asking this because you are concerned about data being initialized and re-initialized in your constructor, be aware that the prescribed way to initialize your test cases data is via setUp() and tearDown() exclusively.</p>\n" }, { "answer_id": 181178, "author": "Dov Wasserman", "author_id": 26010, "author_profile": "https://Stackoverflow.com/users/26010", "pm_score": 3, "selected": true, "text": "<p>I couldn't find a clear answer in the JUnit docs about your question, but the intent, as anjanb wrote, is that each test is independent of the others, so a new TestCase instance could be created for each test to be run.</p>\n\n<p>If you have expensive test setup (\"<em>fixtures</em>\") that you want to be shared across all test cases in a test class, you can use the <strong>@BeforeClass</strong> annotation on a static method to achieve this result: <a href=\"http://junit.sourceforge.net/javadoc_40/org/junit/BeforeClass.html\" rel=\"nofollow noreferrer\">http://junit.sourceforge.net/javadoc_40/org/junit/BeforeClass.html</a>. Note however, that a new instance may still be created for each test, but that won't affect the static data your @BeforeTest method has initialized.</p>\n" }, { "answer_id": 181311, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 2, "selected": false, "text": "<p>There's one instance for each test run. Try</p>\n\n<pre><code>public class MyTest extends TestCase {\n public MyTest() { System.out.println(\"MyTest Constructor\");\n public void setUp() { System.out.println(\"MyTest setUp\");\n public void tearDown() { System.out.println(\"MyTest tearDown\");\n public void testSomething() { System.out.println(\"MyTest testSomething\");\n public void testSomethingElse() { System.out.println(\"MyTest testSomethingElse\");\n}\n</code></pre>\n\n<p>The Sourcecode (including that to newer versions - your and my example is Junit 3) is on <a href=\"http://www.junit.org\" rel=\"nofollow noreferrer\">http://www.junit.org</a></p>\n" }, { "answer_id": 3204729, "author": "orbfish", "author_id": 407502, "author_profile": "https://Stackoverflow.com/users/407502", "pm_score": 0, "selected": false, "text": "<p>Yes, definitely. I found that data I stored in instance variables could not be accessed between tests due to this design.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13326/" ]
Is a new (or different) instance of `TestCase` object is used to run each test method in a JUnit test case? Or one instance is reused for all the tests? ``` public class MyTest extends TestCase { public void testSomething() { ... } public void testSomethingElse() { ... } } ``` While running this test, how many instances of `MyTest` class is created? If possible, provide a link to a document or source code where I can verify the behaviour.
I couldn't find a clear answer in the JUnit docs about your question, but the intent, as anjanb wrote, is that each test is independent of the others, so a new TestCase instance could be created for each test to be run. If you have expensive test setup ("*fixtures*") that you want to be shared across all test cases in a test class, you can use the **@BeforeClass** annotation on a static method to achieve this result: <http://junit.sourceforge.net/javadoc_40/org/junit/BeforeClass.html>. Note however, that a new instance may still be created for each test, but that won't affect the static data your @BeforeTest method has initialized.
181,132
<p>On my homepage I got:</p> <pre><code>&lt;ul id="login"&gt; &lt;li&gt; &lt;a id="loginswitch" href="./login-page"&gt;log-in&lt;/a&gt; | &lt;/li&gt; &lt;li&gt; &lt;a id="signupswitch" href="./signup-page"&gt;sign-up&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Via MooTools, I get these anchor elements by id so that once they're clicked, a flashy div will popup below them that contains the login or signup form (with methods to stop the propagation of events of course) and upon filling-up the fields the AJAX call kicks in - that's supposed to create a session and reload the page so that the user would have a visual that he is now logged in and user-level-controls appears etc..</p> <p>The ajax call is initiated by the MooTools AJAX class and <code>evalScripts</code> option is set to true. The AJAX page returns the script code:</p> <pre><code>&lt;script type="text/javascript"&gt;window.location = self.location;&lt;/script&gt; </code></pre> <p>This system works perfectly - now I'm wondering why if I change the anchors' <code>href</code> values to <code>href="#"</code> my scripts won't work anymore?</p> <p>Does it have anything to do with the window?</p> <p>Did it change its property when I clicked a link or so even when the event's propagation was stopped??</p>
[ { "answer_id": 181137, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 1, "selected": false, "text": "<p>Going to an anchor on a page -- which is what <code>#</code> signifies -- does not require a reload.</p>\n" }, { "answer_id": 196643, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 5, "selected": true, "text": "<pre><code>window.location = self.location;\n</code></pre>\n<p><strong>This JavaScript is executing</strong>.</p>\n<p>When it executes, the browser is being told to replace the value of <code>window.location</code> with a new value. <strong>Not all browsers</strong> will react the same way here. Some will probably work as you expect, but others will get smart about it and compare the two values. <strong>The browser knows</strong> what page it's on, and it knows that you're just asking for it to go to the same page.</p>\n<p><strong>Browser Cache</strong></p>\n<p>The browser even has a copy of your current page in <strong>cache</strong>. It can talk to the server and ask whether the page it has in cache is still valid. If the cache is valid, it may decide not to force a reload of the page. Behind the scenes, this happens with HTTP headers. Browsers and servers can communicate over HTTP in many ways. In this case, your browser sends a quick request to the server saying something like this:</p>\n<pre><code>GET /stackoverflow.com/posts/196643/index.html\nHTTP/1.1\nHost: www.stackoverflow.com\nUser-Agent: Mozilla/5.0\nIf-Modified-Since: Sun, 12 Oct 2008 20:41:31 GMT\n</code></pre>\n<p>This is called a <strong>conditional GET request</strong>. By saying <em>If-Modified-Since</em>, your browser is saying, &quot;Give me that file, but only if it has been modified since the last time I saw it.&quot;</p>\n<p>Long story short, you haven't explicitly told the browser to reload the page.</p>\n<p><strong>Here's how you can:</strong></p>\n<pre><code>location.reload( true );\n</code></pre>\n<p>The &quot;true&quot; is an <strong>optional parameter</strong>, for <strong>forcing a reload</strong>. The browser won't even look at the cache. It will just do as you say.</p>\n" }, { "answer_id": 217097, "author": "Kent Brewster", "author_id": 1151280, "author_profile": "https://Stackoverflow.com/users/1151280", "pm_score": 0, "selected": false, "text": "<p>If they handed me this particular task at work I'd kick it back to design. Unless we're talking about a secure page, or an OpenID login, you should not pop up a log-in or sign-in form. Users need to learn to look for that https: at the top of their page, and never sign in if they don't see it.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24744/" ]
On my homepage I got: ``` <ul id="login"> <li> <a id="loginswitch" href="./login-page">log-in</a> | </li> <li> <a id="signupswitch" href="./signup-page">sign-up</a> </li> </ul> ``` Via MooTools, I get these anchor elements by id so that once they're clicked, a flashy div will popup below them that contains the login or signup form (with methods to stop the propagation of events of course) and upon filling-up the fields the AJAX call kicks in - that's supposed to create a session and reload the page so that the user would have a visual that he is now logged in and user-level-controls appears etc.. The ajax call is initiated by the MooTools AJAX class and `evalScripts` option is set to true. The AJAX page returns the script code: ``` <script type="text/javascript">window.location = self.location;</script> ``` This system works perfectly - now I'm wondering why if I change the anchors' `href` values to `href="#"` my scripts won't work anymore? Does it have anything to do with the window? Did it change its property when I clicked a link or so even when the event's propagation was stopped??
``` window.location = self.location; ``` **This JavaScript is executing**. When it executes, the browser is being told to replace the value of `window.location` with a new value. **Not all browsers** will react the same way here. Some will probably work as you expect, but others will get smart about it and compare the two values. **The browser knows** what page it's on, and it knows that you're just asking for it to go to the same page. **Browser Cache** The browser even has a copy of your current page in **cache**. It can talk to the server and ask whether the page it has in cache is still valid. If the cache is valid, it may decide not to force a reload of the page. Behind the scenes, this happens with HTTP headers. Browsers and servers can communicate over HTTP in many ways. In this case, your browser sends a quick request to the server saying something like this: ``` GET /stackoverflow.com/posts/196643/index.html HTTP/1.1 Host: www.stackoverflow.com User-Agent: Mozilla/5.0 If-Modified-Since: Sun, 12 Oct 2008 20:41:31 GMT ``` This is called a **conditional GET request**. By saying *If-Modified-Since*, your browser is saying, "Give me that file, but only if it has been modified since the last time I saw it." Long story short, you haven't explicitly told the browser to reload the page. **Here's how you can:** ``` location.reload( true ); ``` The "true" is an **optional parameter**, for **forcing a reload**. The browser won't even look at the cache. It will just do as you say.
181,136
<p>I have a text file with multiple records. I want to search a name and date, for example if I typed <code>JULIUS CESAR</code> as name then the whole data about <code>JULIUS</code> will be extracted. What if I want only to extract information?</p> <pre><code>Record number: 1 Date: 08-Oct-08 Time: 23:45:01 Name: JULIUS CESAR Address: BAGUIO CITY, Philippines Information: I lived in Peza Loakan, Bagiou City A Computer Engineering student An OJT at TIPI. 23 years old. Record number: 2 Date: 09-Oct-08 Time: 23:45:01 Name: JOHN Castro Address: BAGUIO CITY, Philippines Information: I lived in Peza Loakan, Bagiou City A Electronics Comm. Engineering Student at SLU. An OJT at TIPI. My Hobby is Programming. Record number: 3 Date: 08-Oct-08 Time: 23:45:01 Name: CESAR JOSE Address: BAGUIO CITY, Philippines Information: Hi,, I lived Manila City A Computer Engineering student Working at TIPI. </code></pre>
[ { "answer_id": 181156, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>If it is one line per entry, you could use a regular expression such as:</p>\n\n<pre><code>$name = \"JULIUS CESAR\";\n</code></pre>\n\n<p>Then use: </p>\n\n<pre><code>/$name/i \n</code></pre>\n\n<p>to test if each line is about \"JULIUS CESAR.\" Then you simply have to use the following regex to extract the information (once you find the line):</p>\n\n<pre><code>/Record number: (\\d+) Date: (\\d+)-(\\w+)-(\\d+) Time: (\\d+):(\\d+):(\\d+) Name: $name Address: ([\\w\\s]+), ([\\w\\s]+?) Information: (.+?)$/i\n</code></pre>\n\n<p>$1 = record number</p>\n\n<p>$2-$4 = date</p>\n\n<p>$5-$7 = time</p>\n\n<p>$6 = address</p>\n\n<p>$7 = comments</p>\n\n<p>I would write a code example, but my perl is rusty. I hope this helps :)</p>\n" }, { "answer_id": 181167, "author": "Robert Elwell", "author_id": 23102, "author_profile": "https://Stackoverflow.com/users/23102", "pm_score": -1, "selected": false, "text": "<p>In PHP, you can run a SQL select statement like:</p>\n\n<p>\"SELECT * WHERE <code>name</code> LIKE 'JULIUS%';\"</p>\n\n<p>There are native aspects of PHP where you can get all of your results in an associative array. I'm pretty sure it's ordered by row order. Then you can just do something like this:</p>\n\n<p>echo implode(\" \", $whole_row);</p>\n\n<p>Hope this is what you're looking for!</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a text file with multiple records. I want to search a name and date, for example if I typed `JULIUS CESAR` as name then the whole data about `JULIUS` will be extracted. What if I want only to extract information? ``` Record number: 1 Date: 08-Oct-08 Time: 23:45:01 Name: JULIUS CESAR Address: BAGUIO CITY, Philippines Information: I lived in Peza Loakan, Bagiou City A Computer Engineering student An OJT at TIPI. 23 years old. Record number: 2 Date: 09-Oct-08 Time: 23:45:01 Name: JOHN Castro Address: BAGUIO CITY, Philippines Information: I lived in Peza Loakan, Bagiou City A Electronics Comm. Engineering Student at SLU. An OJT at TIPI. My Hobby is Programming. Record number: 3 Date: 08-Oct-08 Time: 23:45:01 Name: CESAR JOSE Address: BAGUIO CITY, Philippines Information: Hi,, I lived Manila City A Computer Engineering student Working at TIPI. ```
If it is one line per entry, you could use a regular expression such as: ``` $name = "JULIUS CESAR"; ``` Then use: ``` /$name/i ``` to test if each line is about "JULIUS CESAR." Then you simply have to use the following regex to extract the information (once you find the line): ``` /Record number: (\d+) Date: (\d+)-(\w+)-(\d+) Time: (\d+):(\d+):(\d+) Name: $name Address: ([\w\s]+), ([\w\s]+?) Information: (.+?)$/i ``` $1 = record number $2-$4 = date $5-$7 = time $6 = address $7 = comments I would write a code example, but my perl is rusty. I hope this helps :)
181,158
<p>i have a databound GridView in asp.net 2.0 with a row-selection link. When a row is selected, I want to programmatically add a table row below the selected row, in order to nest another grid et al.</p> <p>I am researching this for a client and for an article, and i think my google-fu is not strong tonight. Any suggestions?</p> <p>EDIT: I actually had a working solution but Visual Studio was nutted up somehow; closing and re-opening VS and rebuilding everything fixed the problem ;-)</p> <p>My solution is posted below, please tell me how to make it better if possible. Thanks!</p>
[ { "answer_id": 181168, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 4, "selected": true, "text": "<p>I think I figured it out. Here is a solution that seems to work. It could be improved using user controls but this is the gist of it:</p>\n\n<pre><code>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n if (e.Row.RowType == DataControlRowType.DataRow &amp;&amp; \n (e.Row.RowState &amp; DataControlRowState.Selected) &gt; 0)\n {\n Table tbl = (Table)e.Row.Parent;\n GridViewRow tr = new GridViewRow(e.Row.RowIndex + 1, -1,\n DataControlRowType.EmptyDataRow, DataControlRowState.Normal);\n TableCell tc = new TableCell();\n tc.ColumnSpan = GridView1.Columns.Count;\n tc.Controls.Add(\n makeChildGrid(Convert.ToInt32(\n ((DataRowView)e.Row.DataItem)[\"ROW_ID_FIELD\"])));\n tr.Cells.Add(tc);\n tbl.Rows.Add(tr);\n }\n}\n\nprotected GridView makeChildGrid(int id)\n{\n GridView gv = new GridView();\n SqlDataSource sqlds = new SqlDataSource();\n sqlds.DataSourceMode = SqlDataSourceMode.DataSet;\n sqlds.ConnectionString = SqlDataSource1.ConnectionString;\n sqlds.SelectCommand = \"SELECT * from MY_TABLE_NAME \" +\n \"WHERE KEY_FIELD = \" + id.ToString();\n DataView dv = (DataView)sqlds.Select(DataSourceSelectArguments.Empty);\n gv.DataSource = dv;\n gv.DataBind(); //not sure this is necessary...?\n return gv;\n}\n</code></pre>\n" }, { "answer_id": 1036522, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Thank you for sharing this code.</p>\n\n<p>I am trying to do the same thing (creating nested gridview), but actually, you don't have to create the gridview yourself. Instead, you just can wrap the control within tags.\nI have seen an example here <a href=\"http://www.codeproject.com/KB/aspnet/EditNestedGridView.aspx?msg=3089755#xx3089755xx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/aspnet/EditNestedGridView.aspx?msg=3089755#xx3089755xx</a></p>\n\n<p>You would see that the developer has nested gv control just by wraping the second gridview control within tags.</p>\n\n<p>If you CAN do what he is doing by code, it would be more effecient. You wouldn't need to display all selected fields!! In addition, you would visually be able to have some controls added to your child gridview.</p>\n\n<p>I have converted your code to vb and working perfectly.</p>\n\n<p>Thanks</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9345/" ]
i have a databound GridView in asp.net 2.0 with a row-selection link. When a row is selected, I want to programmatically add a table row below the selected row, in order to nest another grid et al. I am researching this for a client and for an article, and i think my google-fu is not strong tonight. Any suggestions? EDIT: I actually had a working solution but Visual Studio was nutted up somehow; closing and re-opening VS and rebuilding everything fixed the problem ;-) My solution is posted below, please tell me how to make it better if possible. Thanks!
I think I figured it out. Here is a solution that seems to work. It could be improved using user controls but this is the gist of it: ``` protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Selected) > 0) { Table tbl = (Table)e.Row.Parent; GridViewRow tr = new GridViewRow(e.Row.RowIndex + 1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal); TableCell tc = new TableCell(); tc.ColumnSpan = GridView1.Columns.Count; tc.Controls.Add( makeChildGrid(Convert.ToInt32( ((DataRowView)e.Row.DataItem)["ROW_ID_FIELD"]))); tr.Cells.Add(tc); tbl.Rows.Add(tr); } } protected GridView makeChildGrid(int id) { GridView gv = new GridView(); SqlDataSource sqlds = new SqlDataSource(); sqlds.DataSourceMode = SqlDataSourceMode.DataSet; sqlds.ConnectionString = SqlDataSource1.ConnectionString; sqlds.SelectCommand = "SELECT * from MY_TABLE_NAME " + "WHERE KEY_FIELD = " + id.ToString(); DataView dv = (DataView)sqlds.Select(DataSourceSelectArguments.Empty); gv.DataSource = dv; gv.DataBind(); //not sure this is necessary...? return gv; } ```
181,159
<p>I'm trying to generate a unique ID in php in order to store user-uploaded content on a FS without conflicts. I'm using php, and at the moment this little snippet is responsible for generating the UID:</p> <pre><code>$id = tempnam (".", ""); unlink($id); $id = substr($id, 2); </code></pre> <p>This code is hideous: it creates a temporary file on the FS and deletes it, retaining only the relevant unique part of the generated string.</p> <p>Is there any better way to do this, most preferably without any external dependencies?</p> <p>Thanks much!</p>
[ { "answer_id": 181162, "author": "Robert Elwell", "author_id": 23102, "author_profile": "https://Stackoverflow.com/users/23102", "pm_score": 3, "selected": false, "text": "<p>uniqid() is what you're looking for in most practical situations.</p>\n\n<p>You can make it even more \"uniq\" by adding a large random number after it.</p>\n" }, { "answer_id": 181163, "author": "Xenph Yan", "author_id": 264, "author_profile": "https://Stackoverflow.com/users/264", "pm_score": 5, "selected": true, "text": "<pre><code>string uniqid ([ string $prefix [, bool $more_entropy ]] )\n</code></pre>\n\n<p>Gets a prefixed unique identifier based on the current time in microseconds.</p>\n\n<pre><code>USAGE: $id = uniqid(rand(), true);\n</code></pre>\n" }, { "answer_id": 9010772, "author": "Will Rhodes", "author_id": 992429, "author_profile": "https://Stackoverflow.com/users/992429", "pm_score": 3, "selected": false, "text": "<p>Since both uniqid() and rand() are functions based on the current time, rand() adds almost no entropy, since the time will change only a tiny amount between the respective calls. </p>\n\n<p>As long as you use the <code>more_entropy</code> option, you should never have a collision within a single server. If you use clustering, be sure to include a prefix that differs between servers.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1266/" ]
I'm trying to generate a unique ID in php in order to store user-uploaded content on a FS without conflicts. I'm using php, and at the moment this little snippet is responsible for generating the UID: ``` $id = tempnam (".", ""); unlink($id); $id = substr($id, 2); ``` This code is hideous: it creates a temporary file on the FS and deletes it, retaining only the relevant unique part of the generated string. Is there any better way to do this, most preferably without any external dependencies? Thanks much!
``` string uniqid ([ string $prefix [, bool $more_entropy ]] ) ``` Gets a prefixed unique identifier based on the current time in microseconds. ``` USAGE: $id = uniqid(rand(), true); ```
181,188
<p>In VB.NET I often <code>Catch…When</code>:</p> <pre><code>Try … Catch e As ArgumentNullException When e.ParamName.ToUpper() = "SAMPLES" … End Try </code></pre> <p>Is there a C# equivalent to <code>Catch…When</code>?</p> <p>I don't want to resort to using an <code>if</code> statement inside a <code>catch</code> if possible.</p>
[ { "answer_id": 181190, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 4, "selected": false, "text": "<p>There's no equivalent to <code>Catch…When</code> in C#. You will really have to resort to an <code>if</code> statement inside your <code>catch</code>, then rethrow if your condition isn't fulfilled:</p>\n\n<pre><code>try\n{\n …\n}\ncatch (ArgumentNullException e)\n{\n if (\"SAMPLES\" == e.ParamName.ToUpper())\n {\n … // handle exception\n }\n else\n {\n throw; // condition not fulfilled, let someone else handle the exception\n } \n}\n</code></pre>\n" }, { "answer_id": 181270, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 4, "selected": false, "text": "<p>That won't recreate the same semantics as the VB Catch When expression. There is one key difference. The VB When expression is executed before the stack unwind occurs. If you were to examine the stack at the point of a when Filter, you would actually see the frame where the exception was thrown. </p>\n\n<p>Having an if in the catch block is different because the catch block executes after the stack is unwound. This is especially important when it comes to error reporting. In the VB scenario you have the capability of crashing with a stack trace including the failure. It's not possible to get that behavior in C#. </p>\n\n<p>EDIT:</p>\n\n<p>Wrote a <a href=\"https://learn.microsoft.com/en-gb/archive/blogs/jaredpar/vb-catch-when-why-so-special\" rel=\"nofollow noreferrer\">detailed blog post</a> on the subject.</p>\n" }, { "answer_id": 22959433, "author": "Joe", "author_id": 1324810, "author_profile": "https://Stackoverflow.com/users/1324810", "pm_score": 5, "selected": true, "text": "<p>This functionality was announced for C# 6. It is now possible to write</p>\n\n<pre><code>try { … }\ncatch (MyException e) when (myfilter(e))\n{\n …\n}\n</code></pre>\n\n<p>You can download the preview of <a href=\"http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs.aspx\" rel=\"noreferrer\">Visual Studio 2015</a> now to check this out, or wait for the official release.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8280/" ]
In VB.NET I often `Catch…When`: ``` Try … Catch e As ArgumentNullException When e.ParamName.ToUpper() = "SAMPLES" … End Try ``` Is there a C# equivalent to `Catch…When`? I don't want to resort to using an `if` statement inside a `catch` if possible.
This functionality was announced for C# 6. It is now possible to write ``` try { … } catch (MyException e) when (myfilter(e)) { … } ``` You can download the preview of [Visual Studio 2015](http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs.aspx) now to check this out, or wait for the official release.
181,189
<p>After being through numerous forums available on the net for last 5 days, I am still not able to completely track down the browser close event. My requirement is to generate a popup message, when user tries to close the browser.</p> <p>I have called my javascript function on body 'onbeforeunload' event. And I have hardcoded the conditions to check the mouse-coordinates for the red 'X' buton of browser, refresh, File-close or <kbd>Alt</kbd>-<kbd>F4</kbd>.</p> <p>My code works fine when browser window is Maximized, but fails if we shrink it after a limit. Please help me, if some body has already found the solution to a similar problem.</p> <p>Thank you.</p> <h3>Aggregated Responses of OP</h3> ------ <p>Ok, just tell me if it is possible to detect if a user has clicked on the Refresh button of the browser. Also, Refresh can be triggered by Right-click - Refresh or <kbd>Ctrl</kbd>-<kbd>R</kbd>. My requirement is to make a variable false on Refresh. I am just able to do it on <kbd>F5</kbd>, but all other ways are still out of my reach. The same would be applied to Back button.</p> <hr /> <p>Hi ppl, Thanks for all who replied at least. I have talked to my seniors regarding this and they have now understood and have compromised with the browser menu buttons. So now my task has become easy. Now, I am using a variable and making it true by default. As, I mentioned earlier I just have to catch the onbeforeunload and popup a message when user tries to leave. The message will not popup when user is navigating to other pages, as I have made the variable as false on all the links of my page using following piece of code:</p> <pre><code>document.onclick = function() { //To check if user is navigating from the page by clicking on a hyperlink. if (event.srcElement.tagName == 'A') blnShowMsg = false; //To not popup the warning message else blnShowMsg = true; //To popup the warning message } </code></pre> <p>In my case still the message is shown when user does Refresh, back or goes to any link in Favorites, etc.</p> <hr /> <p>Thanks buddy, but I have already gone through that and didn't find much help there too. My seniors are not happy with that solution as putting a flag on every link of my application is a complicated job and they fear of breaking the application. Any other suggestions would be appreciated. Thanks once again.</p> <hr /> <p>Is there no one who can think of a solution here!!! where are all the experts???</p>
[ { "answer_id": 181944, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 4, "selected": false, "text": "<p>The question isn't an unusual one. Yet after 5 days searching the internet you still haven't found a satisfactory answer. That in itself should be a fairly plain indicator.</p>\n\n<p>What I've found on the web is there is a serious aversion to the 'no can do' answer. When something can't be done the normal response is to make no response.</p>\n\n<p>Bottom line is not only can what you are trying do not be done it should not be done.</p>\n\n<p>I think you need to go back to your seniors and explain to them that a Web UI is a <strong>guest</strong> hosted by a browser on a client machine. This <em>guest</em> status is an important one.</p>\n\n<p>Would you want a guest in your home to have the power to enforce you to alert them when you want to go to the toilet? No?</p>\n\n<p>Similarly the browser limits what info the guest UI is allowed to access. Even if you found a workaround for the fact that browsers aren't giving up this info voluntarily, such clever hacks are fragile and likely to be constant source of bugs.</p>\n\n<p>Since its likely that the application was originally intended to be delivered via the browser before any code was cut, the fault lies with including the requirement in the first place.</p>\n\n<p>All we can do sympathise with you in being asked to perform an near impossible and certainly not sensible requirement.</p>\n" }, { "answer_id": 182347, "author": "Stein G. Strindhaug", "author_id": 26115, "author_profile": "https://Stackoverflow.com/users/26115", "pm_score": 1, "selected": false, "text": "<p>I believe there was some ways to do this in <em>some</em> browsers (and probably not very reliably) some years ago. Because I remember those awful massive spam-popups that spawned more popups as you closed one. But that's why it's not a good idea to allow scripts to detect this, and why browsers should prevent it and most modern browsers probably does.</p>\n\n<p>I was asked to do something similar for a survey invitation script; they wanted to ask the visitor if they would like to answer a survey about their website, and then the survey should pop up when they leave the site. The solution I found was to (repeatedly) explain the management that this was probably impossible, or at best <em>very</em> unreliable; and instead the survey should popup immediately (if the visitor agreed to take the survey) and the intro page should tell the visitor to leave this window open and go back to it after reviewing the page. </p>\n" }, { "answer_id": 190449, "author": "Stein G. Strindhaug", "author_id": 26115, "author_profile": "https://Stackoverflow.com/users/26115", "pm_score": 1, "selected": false, "text": "<p>In your function:</p>\n\n<pre><code>document.onclick = function()\n {\n //To check if user is navigating from the page by clicking on a hyperlink.\n if (event.srcElement.tagName == 'A')\n blnShowMsg = false; //To not popup the warning message\n else\n blnShowMsg = true; //To popup the warning message\n }\n</code></pre>\n\n<p>blnShowMsg will be true for <em>any</em> click on your page except <em>sometimes</em> when the user click a link. I say sometimes because if event.srcElement.tagName doesn't work in some browser it will allways be true. And you have to add <em>lots</em> of cases to to allow using form controls etc... Some browsers can even automatically reload a page, and I'm not sure if onload events will run then or not.</p>\n\n<p>But popping a warning about leaving the page (or similar) all the time is sure to annoy a lot of people, and they'll probably leave permanently... </p>\n\n<p>If you're making for instance a online program where it's critical that something is saved before leaving, I'll say that catching the before unload event is a little too late, better to make some kind of autosave (see Gmail) and/or some kind of non-obtrusive warning when the user mouseover the navigation menues without saving.</p>\n\n<p>But you can't force stupid users not to do anything stupid, on a web interface this is even more true because you have less controll: if the user <em>want</em> to terminate the program before saving they <em>will</em> find a way to do so, and they <em>will</em> call you and complain when the unsaved data dissapears ;P</p>\n" }, { "answer_id": 221414, "author": "Kevin Dark", "author_id": 26151, "author_profile": "https://Stackoverflow.com/users/26151", "pm_score": 1, "selected": false, "text": "<p>I have a method that is a bit clunky but it will work in most instances.</p>\n\n<p>Create a \"Holding\" popup page containing a FRAMESET with one, 100% single FRAME and place the normal onUnload and onbeforeUnload event handlers in the HEAD.</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;script language=\"Javascript\" type=\"text/javascript\"&gt;\n window.onbeforeunload = exitCheck;\n window.onunload = onCloseDoSomething;\n\n function onCloseDoSomething()\n {\n alert(\"This is executed at unload\");\n }\n\n function exitCheck(evt)\n {\n return \"Any string here.\"}\n &lt;/script&gt;\n &lt;/head&gt;\n\n &lt;frameset rows=\"100%\"&gt;\n &lt;FRAME name=\"main\" src=\"http://www.yourDomain.com/yourActualPage.aspx\"&gt;\n &lt;/frameset&gt;\n&lt;body&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Using this method you are free to use the actual page you want to see, post back and click hyperlinks without the outer frame onUnload or onbeforeUnload event being fired.</p>\n\n<p>If the outer frame is refreshed or actually closed the events will fire.</p>\n\n<p>Like i said, not full-proof but will get round the firing of the event on every postback.</p>\n" }, { "answer_id": 261523, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "<blockquote>\n <blockquote>\n <p>\"Thanks buddy, but I have already gone through that and didn't find much help there\n too. My seniors are not happy with that solution as putting a flag on evry link of my \n application is a complicated job and they fear of breaking the application. Any other \n suggestions would be appreciated. Thanks once again.\"</p>\n </blockquote>\n</blockquote>\n\n<p>If you use jQuery, you can add link flags automatically. The way I would handle your problem is when the user performs the \"dangerous\" actions, iterate all the page links that are \"dangerous\" and then bind events to them. </p>\n\n<pre><code>$(\"#dangerbutton\").click(function(){ \n $(\"a\").not( safeList ).click(function()\n {\n var dest = $(this).attr('href');\n someWarningFunction(function(){ \n /* Stay where we are because user opted to stay */\n },function(){ \n /* Continue Following Link because user didn't mind */\n window.location= dest; \n });\n return false;\n });\n});\n</code></pre>\n\n<p>This way will <strong>only</strong> fire on link clicks <strong>on</strong> your page. Users have to get used to the fact that \"close window == cancel everything\" logic, because many use and trust that facility. </p>\n" }, { "answer_id": 2721657, "author": "eliza sahoo", "author_id": 326901, "author_profile": "https://Stackoverflow.com/users/326901", "pm_score": 0, "selected": false, "text": "<p>You <a href=\"http://www.mindfiresolutions.com/Warning-the-user-before-leaving-the-page-792.php\" rel=\"nofollow noreferrer\">might</a> have seen in many of the web form pages to warn the user before closing the page.When somebody refreshes the page, then there is a chance for loosing all filled data. In that case it is very helpful.</p>\n\n<p>Page life cycle includes two events like onunload and onbeforeunload. For this case you need to bind the script function in window. Onbeforeunload so that it will be called when page is unloading.</p>\n\n<p>Again this warning should not be fired when you are actually submitting the page. For that set a boolean value (e.g. shouldsubmit) to submit the page.</p>\n" }, { "answer_id": 5740376, "author": "Kasipan K", "author_id": 718397, "author_profile": "https://Stackoverflow.com/users/718397", "pm_score": 2, "selected": false, "text": "<p>Add this script to your HTML: </p>\n\n<pre><code> window.onbeforeunload = function (e)\n {\n\n e = e || window.event;\n var y = e.pageY || e.clientY;\n if (y &lt; 0){\n return \"Do You really Want to Close the window ?\"\n }\n else {\n return \"Refreshing this page can result in data loss.\"; \n }\n\n }\n</code></pre>\n" }, { "answer_id": 34320767, "author": "Michael Cole", "author_id": 1483977, "author_profile": "https://Stackoverflow.com/users/1483977", "pm_score": 1, "selected": false, "text": "<p><code>onunload</code> and <code>onbeforeunload</code> are not meant for this, so will naturally be unreliable.</p>\n\n<p>A better solution is to change the problem. Have the client send a heartbeat, periodically telling the server the page is still active. When the hearbeat stops, you know you can clean up the server.</p>\n\n<p>You might find this interesting: <a href=\"https://stackoverflow.com/a/3586772/1483977\">https://stackoverflow.com/a/3586772/1483977</a></p>\n\n<p>Or this: <a href=\"https://stackoverflow.com/questions/568977/identifying-between-refresh-and-close-browser-actions/13916847#13916847\">Identifying Between Refresh And Close Browser Actions</a></p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
After being through numerous forums available on the net for last 5 days, I am still not able to completely track down the browser close event. My requirement is to generate a popup message, when user tries to close the browser. I have called my javascript function on body 'onbeforeunload' event. And I have hardcoded the conditions to check the mouse-coordinates for the red 'X' buton of browser, refresh, File-close or `Alt`-`F4`. My code works fine when browser window is Maximized, but fails if we shrink it after a limit. Please help me, if some body has already found the solution to a similar problem. Thank you. ### Aggregated Responses of OP ------ Ok, just tell me if it is possible to detect if a user has clicked on the Refresh button of the browser. Also, Refresh can be triggered by Right-click - Refresh or `Ctrl`-`R`. My requirement is to make a variable false on Refresh. I am just able to do it on `F5`, but all other ways are still out of my reach. The same would be applied to Back button. --- Hi ppl, Thanks for all who replied at least. I have talked to my seniors regarding this and they have now understood and have compromised with the browser menu buttons. So now my task has become easy. Now, I am using a variable and making it true by default. As, I mentioned earlier I just have to catch the onbeforeunload and popup a message when user tries to leave. The message will not popup when user is navigating to other pages, as I have made the variable as false on all the links of my page using following piece of code: ``` document.onclick = function() { //To check if user is navigating from the page by clicking on a hyperlink. if (event.srcElement.tagName == 'A') blnShowMsg = false; //To not popup the warning message else blnShowMsg = true; //To popup the warning message } ``` In my case still the message is shown when user does Refresh, back or goes to any link in Favorites, etc. --- Thanks buddy, but I have already gone through that and didn't find much help there too. My seniors are not happy with that solution as putting a flag on every link of my application is a complicated job and they fear of breaking the application. Any other suggestions would be appreciated. Thanks once again. --- Is there no one who can think of a solution here!!! where are all the experts???
The question isn't an unusual one. Yet after 5 days searching the internet you still haven't found a satisfactory answer. That in itself should be a fairly plain indicator. What I've found on the web is there is a serious aversion to the 'no can do' answer. When something can't be done the normal response is to make no response. Bottom line is not only can what you are trying do not be done it should not be done. I think you need to go back to your seniors and explain to them that a Web UI is a **guest** hosted by a browser on a client machine. This *guest* status is an important one. Would you want a guest in your home to have the power to enforce you to alert them when you want to go to the toilet? No? Similarly the browser limits what info the guest UI is allowed to access. Even if you found a workaround for the fact that browsers aren't giving up this info voluntarily, such clever hacks are fragile and likely to be constant source of bugs. Since its likely that the application was originally intended to be delivered via the browser before any code was cut, the fault lies with including the requirement in the first place. All we can do sympathise with you in being asked to perform an near impossible and certainly not sensible requirement.
181,191
<p>Let me preface this by saying I'm a complete amateur when it comes to RegEx and only started a few days ago. I'm trying to solve a problem formatting a file and have hit a hitch with a particular type of data. The input file is structured like this:</p> <pre> Two words,Word,Word,Word,"Number, number" </pre> <p>What I need to do is format it like this...</p> <pre> "Two words","Word",Word","Word","Number, number" </pre> <p>I have had a RegEx pattern of </p> <pre>s/,/","/g</pre> <p>working, except it also replaces the comma in the already quoted Number, number section, which causes the field to separate and breaks the file. Essentially, I need to modify my pattern to replace a comma with "," [quote comma quote], but only when that comma isn't followed by a space. Note that the other fields will never have a space following the comma, only the delimited number list.</p> <p>I managed to write up</p> <pre>s/,[A-Za-z0-9]/","/g</pre> <p>which, while matching the appropriate strings, would replace the comma AND the following letter. I have heard of backreferences and think that might be what I need to use? My understanding was that</p> <pre>s/(,)[A-Za-z0-9]\b</pre> <p>should work, but it doesn't.</p> <p>Anyone have an idea?</p>
[ { "answer_id": 181208, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": true, "text": "<p><code>s/,([^ ])/\",\"$1/</code> will match a \"<code>,</code>\" followed by a \"not-a-space\", capturing the not-a-space, then replacing the whole thing with the captured part.</p>\n\n<p>Depending on which regex engine you're using, you might be writing <code>\\1</code> or other things instead of <code>$1</code>.</p>\n\n<p>If you're using Perl or otherwise have access to a regex engine with negative lookahead, <code>s/,(?! )/\",\"/</code> (a \"<code>,</code>\" not followed by a space) works.</p>\n\n<p>Your input looks like CSV, though, and if it actually is, you'd be better off parsing it with a real CSV parser rather than with regexes. There's lot of other odd corner cases to worry about.</p>\n" }, { "answer_id": 181219, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 2, "selected": false, "text": "<p>My experience has been that this is not a great use of regexes. As already said, CSV files are better handled by real CSV parsers. You didn't tag a language, so it's hard to tell, but in perl, I use Text::CSV_XS or DBD::CSV (allowing me SQL to access a CSV file as if it were a table, which, of course, uses Text::CSV_XS under the covers). Far simpler than rolling my own, and far more robust than using regexes.</p>\n" }, { "answer_id": 181255, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 0, "selected": false, "text": "<p>This question is similar to: <a href=\"https://stackoverflow.com/questions/180793/replace-patterns-that-are-inside-delimiters-using-a-regular-expression-call\" title=\"Replace patterns that are inside delimiters using a regular expression call\">Replace patterns that are inside delimiters using a regular expression call</a>.</p>\n\n<p>This could work:</p>\n\n<pre><code>s/\"([^\"]*)\"|([^\",]+)/\"$1$2\"/g\n</code></pre>\n" }, { "answer_id": 181264, "author": "Robert Elwell", "author_id": 23102, "author_profile": "https://Stackoverflow.com/users/23102", "pm_score": 0, "selected": false, "text": "<p>Looks like you're using Sed.</p>\n\n<p>While your pattern seems to be a little inconsistent, I'm assuming you'd like every item separated by commas to have quotations around it. Otherwise, you're looking at areas of computational complexity regular expressions are not meant to handle.</p>\n\n<p>Through sed, your command would be:</p>\n\n<pre><code> sed 's/[ \\\"]*,[ \\\"]*/\\\", \\\"/g'\n</code></pre>\n\n<p>Note that you'll still have to put doublequotes at the beginning and end of the string.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25045/" ]
Let me preface this by saying I'm a complete amateur when it comes to RegEx and only started a few days ago. I'm trying to solve a problem formatting a file and have hit a hitch with a particular type of data. The input file is structured like this: ``` Two words,Word,Word,Word,"Number, number" ``` What I need to do is format it like this... ``` "Two words","Word",Word","Word","Number, number" ``` I have had a RegEx pattern of ``` s/,/","/g ``` working, except it also replaces the comma in the already quoted Number, number section, which causes the field to separate and breaks the file. Essentially, I need to modify my pattern to replace a comma with "," [quote comma quote], but only when that comma isn't followed by a space. Note that the other fields will never have a space following the comma, only the delimited number list. I managed to write up ``` s/,[A-Za-z0-9]/","/g ``` which, while matching the appropriate strings, would replace the comma AND the following letter. I have heard of backreferences and think that might be what I need to use? My understanding was that ``` s/(,)[A-Za-z0-9]\b ``` should work, but it doesn't. Anyone have an idea?
`s/,([^ ])/","$1/` will match a "`,`" followed by a "not-a-space", capturing the not-a-space, then replacing the whole thing with the captured part. Depending on which regex engine you're using, you might be writing `\1` or other things instead of `$1`. If you're using Perl or otherwise have access to a regex engine with negative lookahead, `s/,(?! )/","/` (a "`,`" not followed by a space) works. Your input looks like CSV, though, and if it actually is, you'd be better off parsing it with a real CSV parser rather than with regexes. There's lot of other odd corner cases to worry about.
181,209
<p>I have a function that looks like this</p> <pre><code>class NSNode { function insertAfter(NSNode $node) { ... } } </code></pre> <p>I'd like to be able to use that function to indicate that the node is being inserted at the start, therefore it is after <em>nothing</em>. The way I think about that is that <code>null</code> means "nothing", so I'd write my function call like this:</p> <pre><code>$myNode-&gt;insertAfter(null); </code></pre> <p>Except PHP throws an error saying that it was expecting an <code>NSNode</code> object. I'd like to stick to using the strict data typing in my function, but would like to be able to specify a null-esque value.</p> <p>So, short of changing it to <code>function insertAfter($node) { }</code>, is there a way I can pass something else to that function?</p> <hr> <p>Update: I've accepted Owen's answer because it answered the question itself. Everyone else's suggestions were really good and I'll actually be implementing them in this project, thanks!</p>
[ { "answer_id": 181218, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 1, "selected": false, "text": "<p>No, you can't pass something else to the function as that defeats the purpose of the static typing. In this situation, something like C# nullable would be nice i.e. NSNode?</p>\n\n<p>I'd suggest creating NSNode::insertFirst() although I think that you have it the wrong way round, why is a node inserting itself, shouldn't the collection be inserting and taking the node as a parameter? </p>\n" }, { "answer_id": 181223, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": true, "text": "<p>sure, just set a default \"null\"</p>\n\n<pre><code>function(NSNode $node = null) {\n// stuff....\n}\n</code></pre>\n\n<p>result being:</p>\n\n<pre><code>$obj-&gt;insertAfter(); // no error\n$obj-&gt;insertAfter(new NSNode); // no error\n$obj-&gt;insertAfter($somevar); // error expected NSNode\n</code></pre>\n" }, { "answer_id": 181232, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 1, "selected": false, "text": "<p>Better to have a function insertAtBeginning() or insertFirst() for legibility anyway. </p>\n\n<p>\"The way you think of it\" may not be the way the next guy thinks of it.</p>\n\n<p>insertAfter(null) might mean many things.</p>\n\n<p>Maybe null is a valid value and insertAfter means place it after the index that contains the value null.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
I have a function that looks like this ``` class NSNode { function insertAfter(NSNode $node) { ... } } ``` I'd like to be able to use that function to indicate that the node is being inserted at the start, therefore it is after *nothing*. The way I think about that is that `null` means "nothing", so I'd write my function call like this: ``` $myNode->insertAfter(null); ``` Except PHP throws an error saying that it was expecting an `NSNode` object. I'd like to stick to using the strict data typing in my function, but would like to be able to specify a null-esque value. So, short of changing it to `function insertAfter($node) { }`, is there a way I can pass something else to that function? --- Update: I've accepted Owen's answer because it answered the question itself. Everyone else's suggestions were really good and I'll actually be implementing them in this project, thanks!
sure, just set a default "null" ``` function(NSNode $node = null) { // stuff.... } ``` result being: ``` $obj->insertAfter(); // no error $obj->insertAfter(new NSNode); // no error $obj->insertAfter($somevar); // error expected NSNode ```
181,210
<p>I have an asp.net text form that contains numerous decimal fields that are optional. I want to selectively update the database but not inserting a "0" for fields that do not have data (maintaining the null status). </p> <p>Typically, I would create multiple functions, each with a different signature to handle this. However, I am inserting the data through a webservice which does not allow a function with the same name to have multiple signatures. I can think of a couple ways to work around this, but none "pragmatically".</p>
[ { "answer_id": 181229, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "<p>You could use the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.dbnull\" rel=\"nofollow noreferrer\">DBNull class</a> to represent a null value on your web service code. </p>\n\n<p>While you would still have to use a surrogate value (e.g., 0 or -1), and then just evaluate that value to convert it into the <code>DBNull</code> object.</p>\n" }, { "answer_id": 181310, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/b3h38hb0(VS.80).aspx\" rel=\"nofollow noreferrer\">Nullable Types</a> are meant for the same purpose. They represent value types with the possibility of having no data in them. Presence of value can be checked using HasValue property of these types.</p>\n\n<p>Pseudo code to read the fields:</p>\n\n<pre><code>decimal? dValue; // default value is null\n if(decimalValueExists)\n{\n dValue = &lt;value read from text file&gt;\n} \n</code></pre>\n\n<p>When you say multiple methods - I assume these are overloaded methods to be able to add optional fields (so n optional fields means n more methods)</p>\n\n<p>You can avoid writing those methods by writing single method. Suppose you have one required field and one optional field:</p>\n\n<pre><code>public class MyFields\n{\n decimal req1;\n decimal? opt1; // optional field 1 \n}\n</code></pre>\n\n<p>Then define the web service method to use it:</p>\n\n<pre><code>[WebMethod]\nvoid MyWSMethod(MyFields myFields)\n{/* code here will ultimately call InsertMyFields */}\n\nvoid InsertMyFields(MyFields myFields)\n{\n using (SqlConnection connection = new SqlConnection(connectionString))\n {\n // Create the command and set its properties.\n SqlCommand command = new SqlCommand();\n command.Connection = connection;\n command.CommandText = \"AddMyFields\";\n command.CommandType = CommandType.StoredProcedure;\n\n // Add the required input parameter\n SqlParameter parameter1 = new SqlParameter();\n parameter1.ParameterName = \"@ReqField1\";\n parameter1.SqlDbType = SqlDbType.NVarChar;\n parameter1.Direction = ParameterDirection.Input;\n parameter1.Value = myFields.req1;\n\n // Add the parameter to the Parameters collection. \n command.Parameters.Add(parameter1);\n\n // Add the optional parameter and set its properties.\n SqlParameter parameter2 = new SqlParameter();\n parameter2.ParameterName = \"@OptField1\";\n parameter2.SqlDbType = SqlDbType.NVarChar;\n parameter2.Direction = ParameterDirection.Input;\n parameter2.Value = myFields.opt1 ?? DBNull.Value; //null coalescing operator\n\n // Add the parameter to the Parameters collection. \n command.Parameters.Add(parameter2);\n\n //.. rest of the code\n }\n\n} \n</code></pre>\n\n<p>If the nullable type has a value, <a href=\"http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx\" rel=\"nofollow noreferrer\">Null Coalescing Operator</a> will set the value or else it will set the other value that you specify (DBNull.Value in our case).</p>\n" }, { "answer_id": 181333, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 2, "selected": false, "text": "<p>You may be able to define your parameters as nullable decimals. The C# syntax for a nullable value type like this:</p>\n\n<pre><code>decimal? rebateAmountOrWhatever;\n</code></pre>\n\n<p>You can then store nulls in the variable and compare the variable to null.</p>\n\n<pre><code>new SqlParameter(\"@RebateAmount\", \n rebateAmountOrWhatever == null ? (object)DBNull.Value : (object)rebateAmountOrWhatever)\n</code></pre>\n\n<p>There is also great fun to be had using the ?? operator like this:</p>\n\n<pre><code>new SqlParameter(\"@RebateAmount\", \n (object)rebateAmountOrWhatever ?? (object)DBNull.Value)\n</code></pre>\n\n<p>An equivalent way to declare the variable is with the Nullable&lt;> generic type like this:</p>\n\n<pre><code>Nullable&lt;decimal&gt; currentIraBalance = null;\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3149/" ]
I have an asp.net text form that contains numerous decimal fields that are optional. I want to selectively update the database but not inserting a "0" for fields that do not have data (maintaining the null status). Typically, I would create multiple functions, each with a different signature to handle this. However, I am inserting the data through a webservice which does not allow a function with the same name to have multiple signatures. I can think of a couple ways to work around this, but none "pragmatically".
[Nullable Types](http://msdn.microsoft.com/en-us/library/b3h38hb0(VS.80).aspx) are meant for the same purpose. They represent value types with the possibility of having no data in them. Presence of value can be checked using HasValue property of these types. Pseudo code to read the fields: ``` decimal? dValue; // default value is null if(decimalValueExists) { dValue = <value read from text file> } ``` When you say multiple methods - I assume these are overloaded methods to be able to add optional fields (so n optional fields means n more methods) You can avoid writing those methods by writing single method. Suppose you have one required field and one optional field: ``` public class MyFields { decimal req1; decimal? opt1; // optional field 1 } ``` Then define the web service method to use it: ``` [WebMethod] void MyWSMethod(MyFields myFields) {/* code here will ultimately call InsertMyFields */} void InsertMyFields(MyFields myFields) { using (SqlConnection connection = new SqlConnection(connectionString)) { // Create the command and set its properties. SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "AddMyFields"; command.CommandType = CommandType.StoredProcedure; // Add the required input parameter SqlParameter parameter1 = new SqlParameter(); parameter1.ParameterName = "@ReqField1"; parameter1.SqlDbType = SqlDbType.NVarChar; parameter1.Direction = ParameterDirection.Input; parameter1.Value = myFields.req1; // Add the parameter to the Parameters collection. command.Parameters.Add(parameter1); // Add the optional parameter and set its properties. SqlParameter parameter2 = new SqlParameter(); parameter2.ParameterName = "@OptField1"; parameter2.SqlDbType = SqlDbType.NVarChar; parameter2.Direction = ParameterDirection.Input; parameter2.Value = myFields.opt1 ?? DBNull.Value; //null coalescing operator // Add the parameter to the Parameters collection. command.Parameters.Add(parameter2); //.. rest of the code } } ``` If the nullable type has a value, [Null Coalescing Operator](http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx) will set the value or else it will set the other value that you specify (DBNull.Value in our case).
181,212
<p>Ok, this is a weird one. The junk data isn't random either, it appears to be substrings of the executable itself.</p> <pre><code>private void Form1_Load(object sender, EventArgs e) { string s = GetValue(); // at this point, s == "400". Why isn't really relevant (dumbed down a test) if (s != "18446744073709551615") throw new Exception(); // When the exception is thrown though, the string is set to random // data from inside the executable. } </code></pre> <p>This seems dependant on certain seemingly insignificant implementation details in GetValue() such as calls to string.Format() being in different places.</p> <p>Has anyone ever run into something similar or have any ideas what might cause this?</p>
[ { "answer_id": 181244, "author": "Ryan Taylor", "author_id": 6231, "author_profile": "https://Stackoverflow.com/users/6231", "pm_score": 0, "selected": false, "text": "<p>If you're checking the variable after the exception has been thrown and is now out of scope, then it should be pointing to nothing more than garbage sitting in memory. Have you tried checking the value of this variable both before and after the exception has been thrown?</p>\n" }, { "answer_id": 181250, "author": "Windows programmer", "author_id": 23705, "author_profile": "https://Stackoverflow.com/users/23705", "pm_score": 3, "selected": true, "text": "<p>\"And I'm checking it in the \"Locals\" window in VS\"</p>\n\n<p>That explains it. Contrary to popular belief, C# is allowed to do some amount of optimization. If you don't add a \"KeepAlive\" at the end of your function, the value doesn't really have to be stored.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
Ok, this is a weird one. The junk data isn't random either, it appears to be substrings of the executable itself. ``` private void Form1_Load(object sender, EventArgs e) { string s = GetValue(); // at this point, s == "400". Why isn't really relevant (dumbed down a test) if (s != "18446744073709551615") throw new Exception(); // When the exception is thrown though, the string is set to random // data from inside the executable. } ``` This seems dependant on certain seemingly insignificant implementation details in GetValue() such as calls to string.Format() being in different places. Has anyone ever run into something similar or have any ideas what might cause this?
"And I'm checking it in the "Locals" window in VS" That explains it. Contrary to popular belief, C# is allowed to do some amount of optimization. If you don't add a "KeepAlive" at the end of your function, the value doesn't really have to be stored.
181,214
<p>Implementing a file upload under html is fairly simple, but I just noticed that there is an 'accept' attribute that can be added to the <code>&lt;input type="file" ...&gt;</code> tag.</p> <p>Is this attribute useful as a way of limiting file uploads to images, etc? What is the best way to use it?</p> <p>Alternatively, is there a way to limit file types, preferably in the file dialog, for an html file input tag?</p>
[ { "answer_id": 181291, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 5, "selected": false, "text": "<p>Accept attribute was introduced in the <a href=\"https://www.rfc-editor.org/rfc/rfc1867\" rel=\"nofollow noreferrer\">RFC 1867</a>, intending to enable file-type filtering based on MIME type for the file-select control. But as of 2008, most, if not all, browsers make no use of this attribute. Using client-side scripting, you can make a sort of extension based validation, for submit data of correct type (extension).</p>\n<p>Other solutions for advanced file uploading require Flash movies like <a href=\"http://swfupload.org/\" rel=\"nofollow noreferrer\">SWFUpload</a> or Java Applets like <a href=\"http://sourceforge.net/projects/jupload/\" rel=\"nofollow noreferrer\">JUpload</a>.</p>\n" }, { "answer_id": 181507, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 3, "selected": false, "text": "<p>If the browser uses this attribute, it is only as an help for the user, so he won't upload a multi-megabyte file just to see it rejected by the server...<br>\nSame for the <code>&lt;input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"100000\"&gt;</code> tag: if the browser uses it, it won't send the file but an error resulting in <code>UPLOAD_ERR_FORM_SIZE</code> (2) error in PHP (not sure how it is handled in other languages).<br>\nNote these are helps for the <em>user</em>. Of course, the server must always check the type and size of the file on its end: it is easy to tamper with these values on the client side.</p>\n" }, { "answer_id": 4197455, "author": "magikMaker", "author_id": 509879, "author_profile": "https://Stackoverflow.com/users/509879", "pm_score": 5, "selected": false, "text": "<p>It is supported by Chrome. It's not supposed to be used for validation, but for type hinting the OS. If you have an <code>accept=\"image/jpeg\"</code> attribute in a file upload the OS can only show files of the suggested type.</p>\n" }, { "answer_id": 8074187, "author": "Kevin Fee", "author_id": 949214, "author_profile": "https://Stackoverflow.com/users/949214", "pm_score": 4, "selected": false, "text": "<p>It's been a few years, and Chrome at least makes use of this attribute. This attribute is very useful from a usability standpoint as it will filter out the unnecessary files for the user, making their experience smoother. However, the user can still select \"all files\" from the type (or otherwise bypass the filter), thus you should always validate the file where it is actually used; If you're using it on the server, validate it there before using it. The user can always bypass any client-side scripting.</p>\n" }, { "answer_id": 10503561, "author": "0b10011", "author_id": 526741, "author_profile": "https://Stackoverflow.com/users/526741", "pm_score": 10, "selected": true, "text": "<p>The <code>accept</code> attribute is incredibly useful. It is a hint to browsers to only show files that are allowed for the current <code>input</code>. While it can typically be overridden by users, it helps narrow down the results for users by default, so they can get exactly what they're looking for without having to sift through a hundred different file types.</p>\n\n<h1>Usage</h1>\n\n<p><strong><em>Note:</strong> These examples were written based on the current specification and may not actually work in all (or any) browsers. The specification may also change in the future, which could break these examples.</em></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>h1 { font-size: 1em; margin:1em 0; }\r\nh1 ~ h1 { border-top: 1px solid #ccc; padding-top: 1em; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;h1&gt;Match all image files (image/*)&lt;/h1&gt;\r\n&lt;p&gt;&lt;label&gt;image/* &lt;input type=\"file\" accept=\"image/*\"&gt;&lt;/label&gt;&lt;/p&gt;\r\n\r\n&lt;h1&gt;Match all video files (video/*)&lt;/h1&gt;\r\n&lt;p&gt;&lt;label&gt;video/* &lt;input type=\"file\" accept=\"video/*\"&gt;&lt;/label&gt;&lt;/p&gt;\r\n\r\n&lt;h1&gt;Match all audio files (audio/*)&lt;/h1&gt;\r\n&lt;p&gt;&lt;label&gt;audio/* &lt;input type=\"file\" accept=\"audio/*\"&gt;&lt;/label&gt;&lt;/p&gt;\r\n\r\n&lt;h1&gt;Match all image files (image/*) and files with the extension \".someext\"&lt;/h1&gt;\r\n&lt;p&gt;&lt;label&gt;.someext,image/* &lt;input type=\"file\" accept=\".someext,image/*\"&gt;&lt;/label&gt;&lt;/p&gt;\r\n\r\n&lt;h1&gt;Match all image files (image/*) and video files (video/*)&lt;/h1&gt;\r\n&lt;p&gt;&lt;label&gt;image/*,video/* &lt;input type=\"file\" accept=\"image/*,video/*\"&gt;&lt;/label&gt;&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h1>From the HTML Specification (<a href=\"https://html.spec.whatwg.org/multipage/forms.html#attr-input-accept\" rel=\"noreferrer\">source</a>)</h1>\n\n<blockquote>\n <p>The <code>accept</code> attribute may be specified to provide user agents with a\n hint of what file types will be accepted.</p>\n \n <p>If specified, the attribute must consist of a\n <a href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/common-microsyntaxes.html#set-of-comma-separated-tokens\" rel=\"noreferrer\">set of comma-separated tokens</a>,\n each of which must be an\n <a href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/infrastructure.html#ascii-case-insensitive\" rel=\"noreferrer\">ASCII case-insensitive</a>\n match for one of the following:</p>\n \n <h3>The string <code>audio/*</code></h3>\n \n <ul>\n <li>Indicates that sound files are accepted.</li>\n </ul>\n \n <h3>The string <code>video/*</code></h3>\n \n <ul>\n <li>Indicates that video files are accepted.</li>\n </ul>\n \n <h3>The string <code>image/*</code></h3>\n \n <ul>\n <li>Indicates that image files are accepted.</li>\n </ul>\n \n <h3>A <a href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/infrastructure.html#valid-mime-type-with-no-parameters\" rel=\"noreferrer\">valid MIME type with no parameters</a></h3>\n \n <ul>\n <li>Indicates that files of the specified type are accepted.</li>\n </ul>\n \n <h3>A string whose first character is a U+002E FULL STOP character (.)</h3>\n \n <ul>\n <li>Indicates that files with the specified file extension are accepted.</li>\n </ul>\n</blockquote>\n" }, { "answer_id": 14839673, "author": "iconoclast", "author_id": 241142, "author_profile": "https://Stackoverflow.com/users/241142", "pm_score": 7, "selected": false, "text": "<p>Yes, it is extremely useful in browsers that support it, but the \"limiting\" is as a convenience to users (so they are not overwhelmed with irrelevant files) rather than as a way to prevent them from uploading things you don't want them uploading.</p>\n\n<p>It is supported in </p>\n\n<ul>\n<li>Chrome 16 +</li>\n<li>Safari 6 +</li>\n<li>Firefox 9 +</li>\n<li>IE 10 +</li>\n<li>Opera 11 + </li>\n</ul>\n\n<p>Here is <a href=\"http://webdesign.about.com/od/multimedia/a/mime-types-by-content-type.htm\">a list of content types</a> you can use with it, followed by the corresponding file extensions (though of course you can use any file extension):</p>\n\n<pre><code>application/envoy evy\napplication/fractals fif\napplication/futuresplash spl\napplication/hta hta\napplication/internet-property-stream acx\napplication/mac-binhex40 hqx\napplication/msword doc\napplication/msword dot\napplication/octet-stream *\napplication/octet-stream bin\napplication/octet-stream class\napplication/octet-stream dms\napplication/octet-stream exe\napplication/octet-stream lha\napplication/octet-stream lzh\napplication/oda oda\napplication/olescript axs\napplication/pdf pdf\napplication/pics-rules prf\napplication/pkcs10 p10\napplication/pkix-crl crl\napplication/postscript ai\napplication/postscript eps\napplication/postscript ps\napplication/rtf rtf\napplication/set-payment-initiation setpay\napplication/set-registration-initiation setreg\napplication/vnd.ms-excel xla\napplication/vnd.ms-excel xlc\napplication/vnd.ms-excel xlm\napplication/vnd.ms-excel xls\napplication/vnd.ms-excel xlt\napplication/vnd.ms-excel xlw\napplication/vnd.ms-outlook msg\napplication/vnd.ms-pkicertstore sst\napplication/vnd.ms-pkiseccat cat\napplication/vnd.ms-pkistl stl\napplication/vnd.ms-powerpoint pot\napplication/vnd.ms-powerpoint pps\napplication/vnd.ms-powerpoint ppt\napplication/vnd.ms-project mpp\napplication/vnd.ms-works wcm\napplication/vnd.ms-works wdb\napplication/vnd.ms-works wks\napplication/vnd.ms-works wps\napplication/winhlp hlp\napplication/x-bcpio bcpio\napplication/x-cdf cdf\napplication/x-compress z\napplication/x-compressed tgz\napplication/x-cpio cpio\napplication/x-csh csh\napplication/x-director dcr\napplication/x-director dir\napplication/x-director dxr\napplication/x-dvi dvi\napplication/x-gtar gtar\napplication/x-gzip gz\napplication/x-hdf hdf\napplication/x-internet-signup ins\napplication/x-internet-signup isp\napplication/x-iphone iii\napplication/x-javascript js\napplication/x-latex latex\napplication/x-msaccess mdb\napplication/x-mscardfile crd\napplication/x-msclip clp\napplication/x-msdownload dll\napplication/x-msmediaview m13\napplication/x-msmediaview m14\napplication/x-msmediaview mvb\napplication/x-msmetafile wmf\napplication/x-msmoney mny\napplication/x-mspublisher pub\napplication/x-msschedule scd\napplication/x-msterminal trm\napplication/x-mswrite wri\napplication/x-netcdf cdf\napplication/x-netcdf nc\napplication/x-perfmon pma\napplication/x-perfmon pmc\napplication/x-perfmon pml\napplication/x-perfmon pmr\napplication/x-perfmon pmw\napplication/x-pkcs12 p12\napplication/x-pkcs12 pfx\napplication/x-pkcs7-certificates p7b\napplication/x-pkcs7-certificates spc\napplication/x-pkcs7-certreqresp p7r\napplication/x-pkcs7-mime p7c\napplication/x-pkcs7-mime p7m\napplication/x-pkcs7-signature p7s\napplication/x-sh sh\napplication/x-shar shar\napplication/x-shockwave-flash swf\napplication/x-stuffit sit\napplication/x-sv4cpio sv4cpio\napplication/x-sv4crc sv4crc\napplication/x-tar tar\napplication/x-tcl tcl\napplication/x-tex tex\napplication/x-texinfo texi\napplication/x-texinfo texinfo\napplication/x-troff roff\napplication/x-troff t\napplication/x-troff tr\napplication/x-troff-man man\napplication/x-troff-me me\napplication/x-troff-ms ms\napplication/x-ustar ustar\napplication/x-wais-source src\napplication/x-x509-ca-cert cer\napplication/x-x509-ca-cert crt\napplication/x-x509-ca-cert der\napplication/ynd.ms-pkipko pko\napplication/zip zip\naudio/basic au\naudio/basic snd\naudio/mid mid\naudio/mid rmi\naudio/mpeg mp3\naudio/x-aiff aif\naudio/x-aiff aifc\naudio/x-aiff aiff\naudio/x-mpegurl m3u\naudio/x-pn-realaudio ra\naudio/x-pn-realaudio ram\naudio/x-wav wav\nimage/bmp bmp\nimage/cis-cod cod\nimage/gif gif\nimage/ief ief\nimage/jpeg jpe\nimage/jpeg jpeg\nimage/jpeg jpg\nimage/pipeg jfif\nimage/svg+xml svg\nimage/tiff tif\nimage/tiff tiff\nimage/x-cmu-raster ras\nimage/x-cmx cmx\nimage/x-icon ico\nimage/x-portable-anymap pnm\nimage/x-portable-bitmap pbm\nimage/x-portable-graymap pgm\nimage/x-portable-pixmap ppm\nimage/x-rgb rgb\nimage/x-xbitmap xbm\nimage/x-xpixmap xpm\nimage/x-xwindowdump xwd\nmessage/rfc822 mht\nmessage/rfc822 mhtml\nmessage/rfc822 nws\ntext/css css\ntext/h323 323\ntext/html htm\ntext/html html\ntext/html stm\ntext/iuls uls\ntext/plain bas\ntext/plain c\ntext/plain h\ntext/plain txt\ntext/richtext rtx\ntext/scriptlet sct\ntext/tab-separated-values tsv\ntext/webviewhtml htt\ntext/x-component htc\ntext/x-setext etx\ntext/x-vcard vcf\nvideo/mpeg mp2\nvideo/mpeg mpa\nvideo/mpeg mpe\nvideo/mpeg mpeg\nvideo/mpeg mpg\nvideo/mpeg mpv2\nvideo/quicktime mov\nvideo/quicktime qt\nvideo/x-la-asf lsf\nvideo/x-la-asf lsx\nvideo/x-ms-asf asf\nvideo/x-ms-asf asr\nvideo/x-ms-asf asx\nvideo/x-msvideo avi\nvideo/x-sgi-movie movie\nx-world/x-vrml flr\nx-world/x-vrml vrml\nx-world/x-vrml wrl\nx-world/x-vrml wrz\nx-world/x-vrml xaf\nx-world/x-vrml xof\n</code></pre>\n" }, { "answer_id": 25291778, "author": "Jakub Mendyk", "author_id": 2471388, "author_profile": "https://Stackoverflow.com/users/2471388", "pm_score": 0, "selected": false, "text": "<p>Back in 2008 this wasn't important because of the lack of mobile OS'es but now quite important thing. </p>\n\n<p>When you set accepted mime types, then in for example Android user is given system dialog with apps which can provide him the content of mime which file input accepts, what is great because navigating through files in file explorer on mobile devices is slow and often stressful.</p>\n\n<p>One important thing is that some mobile browsers (based on Android version of Chrome 36 and Chrome Beta 37) does not support app filtering over extension(s) and multiple mime types.</p>\n" }, { "answer_id": 32005632, "author": "Christophe Roussy", "author_id": 657427, "author_profile": "https://Stackoverflow.com/users/657427", "pm_score": 6, "selected": false, "text": "<p>In 2015 <strong>the only way</strong> I found to make it work for both <strong>Chrome</strong> and <strong>Firefox</strong> is to put all possible extensions you want to support, including variants (including the dot in front !):</p>\n<pre><code>accept=&quot;.jpeg, .jpg, .jpe, .jfif, .jif&quot;\n</code></pre>\n<p><strong>Problem with Firefox</strong>: Using the <code>image/jpeg</code> mime type Firefox will only show <code>.jpg</code> files, very strange as if the common <code>.jpeg</code> was not ok...</p>\n<p>Whatever you do, be sure to try with files having many different extensions.\nMaybe it even depends on the OS ... I suppose <code>accept</code> is case insensitive, but maybe not in every browser.</p>\n<p>Here is the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#accept\" rel=\"noreferrer\">MDN docs about accept</a>:</p>\n<blockquote>\n<p>accept\nIf the value of the type attribute is file, then this attribute will indicate the types of files that the server accepts, otherwise it\nwill be ignored. The value must be a comma-separated list of unique\ncontent type specifiers:</p>\n<pre><code> A file extension starting with the STOP character (U+002E). (e.g. .jpg, .png, .doc).\n A valid MIME type with no extensions.\n audio/* representing sound files. HTML5\n video/* representing video files. HTML5\n image/* representing image files. HTML5\n</code></pre>\n</blockquote>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/691/" ]
Implementing a file upload under html is fairly simple, but I just noticed that there is an 'accept' attribute that can be added to the `<input type="file" ...>` tag. Is this attribute useful as a way of limiting file uploads to images, etc? What is the best way to use it? Alternatively, is there a way to limit file types, preferably in the file dialog, for an html file input tag?
The `accept` attribute is incredibly useful. It is a hint to browsers to only show files that are allowed for the current `input`. While it can typically be overridden by users, it helps narrow down the results for users by default, so they can get exactly what they're looking for without having to sift through a hundred different file types. Usage ===== ***Note:*** These examples were written based on the current specification and may not actually work in all (or any) browsers. The specification may also change in the future, which could break these examples. ```css h1 { font-size: 1em; margin:1em 0; } h1 ~ h1 { border-top: 1px solid #ccc; padding-top: 1em; } ``` ```html <h1>Match all image files (image/*)</h1> <p><label>image/* <input type="file" accept="image/*"></label></p> <h1>Match all video files (video/*)</h1> <p><label>video/* <input type="file" accept="video/*"></label></p> <h1>Match all audio files (audio/*)</h1> <p><label>audio/* <input type="file" accept="audio/*"></label></p> <h1>Match all image files (image/*) and files with the extension ".someext"</h1> <p><label>.someext,image/* <input type="file" accept=".someext,image/*"></label></p> <h1>Match all image files (image/*) and video files (video/*)</h1> <p><label>image/*,video/* <input type="file" accept="image/*,video/*"></label></p> ``` From the HTML Specification ([source](https://html.spec.whatwg.org/multipage/forms.html#attr-input-accept)) =========================================================================================================== > > The `accept` attribute may be specified to provide user agents with a > hint of what file types will be accepted. > > > If specified, the attribute must consist of a > [set of comma-separated tokens](http://www.whatwg.org/specs/web-apps/current-work/multipage/common-microsyntaxes.html#set-of-comma-separated-tokens), > each of which must be an > [ASCII case-insensitive](http://www.whatwg.org/specs/web-apps/current-work/multipage/infrastructure.html#ascii-case-insensitive) > match for one of the following: > > > ### The string `audio/*` > > > * Indicates that sound files are accepted. > > > ### The string `video/*` > > > * Indicates that video files are accepted. > > > ### The string `image/*` > > > * Indicates that image files are accepted. > > > ### A [valid MIME type with no parameters](http://www.whatwg.org/specs/web-apps/current-work/multipage/infrastructure.html#valid-mime-type-with-no-parameters) > > > * Indicates that files of the specified type are accepted. > > > ### A string whose first character is a U+002E FULL STOP character (.) > > > * Indicates that files with the specified file extension are accepted. > > >
181,222
<p>I have a script which calls <code>mysql_connect()</code> to connect to a MySQL DB. When I run the script in a browser, it works. However, when I run it from a command line I receive the following error:</p> <pre><code>Call to undefined function mysql_connect() </code></pre> <p>This seems completely paradoxical. Anyone have any ideas as how I can run it from the command line. Btw, I run it from a bash shell like so:</p> <pre><code>php /path/to/script.php </code></pre>
[ { "answer_id": 181233, "author": "Robert Elwell", "author_id": 23102, "author_profile": "https://Stackoverflow.com/users/23102", "pm_score": 2, "selected": false, "text": "<p>While it may be a rudimentary answer, make sure you have the most up to date PHP client, and make sure that it's looking at the same PHP folder that you're working out of through Apache.</p>\n\n<p>If that doesn't work, try playing with mysqli and see if it's globally for the entire MySQL portion of PHP. If mysqli works and mysql_connect() doesn't, well, then, that's as good a time as any to swtich over to the OO side :-)</p>\n" }, { "answer_id": 181236, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 4, "selected": false, "text": "<p>It maybe using a default PHP configuration. I have found before that it doesn't use the same php.ini or doesn't use one at all. Therefore some of the extensions won't be enabled.</p>\n\n<p>Do this instead:</p>\n\n<pre><code>php -c /etc/php.ini /path/to/script.php\n</code></pre>\n\n<p>Where <code>/etc/php.ini</code> is the path to your ini file. You can find this by doing a <code>phpinfo();</code></p>\n" }, { "answer_id": 181240, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 1, "selected": false, "text": "<p>php-cli.ini might be the file your command line php interpreter is using.</p>\n" }, { "answer_id": 181865, "author": "boxoft", "author_id": 23773, "author_profile": "https://Stackoverflow.com/users/23773", "pm_score": 1, "selected": false, "text": "<p>Please make sure this line appears in php.ini</p>\n\n<p>extension=php_mysql.dll</p>\n\n<p>Please note that the php.ini used in command line may be different from the php.ini used by apache.</p>\n" }, { "answer_id": 182536, "author": "Gravstar", "author_id": 17381, "author_profile": "https://Stackoverflow.com/users/17381", "pm_score": 2, "selected": false, "text": "<p>Check if you php cmd version actually has mysql support:</p>\n\n<pre>\n &lt;? php\n echo php_info()\n ?&gt;\n</pre>\n\n<p>If not, then probably it's because it is a different version than the one used by your web server.</p>\n\n<p>Run php using the \"-m\" parameter in order to list all the compiled modules:</p>\n\n<pre>\n $ php -m\n</pre>\n\n<p>You should see the \"mysql\" module. If not, then i guess the php cmd version has not been compiled using the --with-mysql or the \"configure\" script could not included it due some reason.</p>\n" }, { "answer_id": 23510870, "author": "Herr", "author_id": 288774, "author_profile": "https://Stackoverflow.com/users/288774", "pm_score": 1, "selected": false, "text": "<p>This problem can arise when you are running Mac OS X and MAMP. The command line version tries to use the MAC OS X version, which happens to load no php.ini by default.</p>\n\n<p>You can check that with the command:</p>\n\n<pre><code>php --ini\n</code></pre>\n\n<p>See the missing config file?</p>\n\n<pre><code>Configuration File (php.ini) Path: /etc\nLoaded Configuration File: !!! THE CONFIG FILE IS MISSING HERE !!!\nScan for additional .ini files in: /Library/Server/Web/Config/php\nAdditional .ini files parsed: (none)\n</code></pre>\n\n<p>What you have to do is, load up the php.ini of your choice and copy it to the default location of your command line interpreter which is /etc and then run the above command again, you should see that the php.ini file is loaded which should look like:</p>\n\n<pre><code>Configuration File (php.ini) Path: /etc\nLoaded Configuration File: /etc/php.ini\nScan for additional .ini files in: /Library/Server/Web/Config/php\nAdditional .ini files parsed: (none)\n</code></pre>\n\n<p>You should also add this to the PHP.ini file in /etc</p>\n\n<pre><code>mysql.default_socket = /Applications/MAMP/tmp/mysql/mysql.sock\n</code></pre>\n\n<p>This should fix every problem.</p>\n\n<p>phew..</p>\n" }, { "answer_id": 43798698, "author": "Dubbo", "author_id": 879944, "author_profile": "https://Stackoverflow.com/users/879944", "pm_score": 0, "selected": false, "text": "<p>My system is CentOS.\nIn my case, the the path to mysql.so is incorrect.</p>\n\n<p>When I type </p>\n\n<pre><code>php -m\n</code></pre>\n\n<p>There is no mysql.</p>\n\n<p>In my original /etc/php.d/mysql.ini\nthere is only one line:</p>\n\n<pre><code>extension=mysql.so\n</code></pre>\n\n<p>So I use command: </p>\n\n<pre><code>rpm -ql php-mysql | grep mysql.so\n</code></pre>\n\n<p>to find out the correct path, which is </p>\n\n<pre><code>/usr/lib64/php/modules/mysql.so\n</code></pre>\n\n<p>then I replaced the line to :</p>\n\n<pre><code>extension=/usr/lib64/php/modules/mysql.so\n</code></pre>\n\n<p>then </p>\n\n<pre><code>service httpd restart \n</code></pre>\n\n<p>and </p>\n\n<pre><code>php -m\n</code></pre>\n\n<p>mysql is now loaded.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24059/" ]
I have a script which calls `mysql_connect()` to connect to a MySQL DB. When I run the script in a browser, it works. However, when I run it from a command line I receive the following error: ``` Call to undefined function mysql_connect() ``` This seems completely paradoxical. Anyone have any ideas as how I can run it from the command line. Btw, I run it from a bash shell like so: ``` php /path/to/script.php ```
It maybe using a default PHP configuration. I have found before that it doesn't use the same php.ini or doesn't use one at all. Therefore some of the extensions won't be enabled. Do this instead: ``` php -c /etc/php.ini /path/to/script.php ``` Where `/etc/php.ini` is the path to your ini file. You can find this by doing a `phpinfo();`
181,225
<p>I'm looking for a reasonably fast event handling mechanism in Java to generate and handle events across different JVMs running on different hosts.</p> <p>For event handling across multiple threads in a single JVM, I found some good candidates like Jetlang. But in my search for a distributed equivalent , I couldn't find anything that was lightweight enough to offer good performance.</p> <p>Does anyone know of any implementations that fit the bill?</p> <p><strong>Edit:</strong> Putting numbers to indicate performance is a bit difficult. But for example, if you implement a heartbeating mechanism using events and the heartbeat interval is 5 seconds, the heartbeat receiver should receive a sent heartbeat within say a second or two.</p> <p>Generally, a lightweight implementation gives good performance. A event handling mechanism involving a web server or any kind of centralized hub requiring powerful hardware (definitely not lightweight) to give good performance is not what I'm looking for. </p>
[ { "answer_id": 181331, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 2, "selected": false, "text": "<p>AMQP(Advanced Message Queuing Protocol ) -- more details :\n<a href=\"http://en.wikipedia.org/wiki/Advanced_Message_Queuing_Protocol\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Advanced_Message_Queuing_Protocol</a> is probably what you're looking for. </p>\n\n<p>It is used by financial service companies for their high performance requirements -- apache has an implementation going -- <a href=\"http://cwiki.apache.org/qpid/\" rel=\"nofollow noreferrer\">http://cwiki.apache.org/qpid/</a></p>\n\n<p>OpenAMQ - <a href=\"http://www.openamq.org/\" rel=\"nofollow noreferrer\">http://www.openamq.org/</a> is an older REFERENCE IMPLEMENTATION .</p>\n" }, { "answer_id": 181334, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 2, "selected": false, "text": "<p>Depending on your use case, <a href=\"http://terracotta.org\" rel=\"nofollow noreferrer\">Terracotta</a> may be an excellent choice.</p>\n" }, { "answer_id": 181932, "author": "James Strachan", "author_id": 2068211, "author_profile": "https://Stackoverflow.com/users/2068211", "pm_score": 1, "selected": false, "text": "<p>Whichever tool you use I'd recommend hiding the middleware APIs from your application logic. For example if you used the <a href=\"http://activemq.apache.org/camel/hiding-middleware.html\" rel=\"nofollow noreferrer\">Apache Camel approach to hiding middleware</a> you could then easily switch from AMQP to SEDA to JMS to ActiveMQ to JavaSpaces to your own custom MINA transport based on your exact requirements.</p>\n\n<p>If you want to use a message broker I'd recommend using <a href=\"http://activemq.apache.org/\" rel=\"nofollow noreferrer\">Apache ActiveMQ</a> which is the most popular and powerful open source message broker with the <a href=\"http://www.nabble.com/Apache-f90.html\" rel=\"nofollow noreferrer\">largest most active community behind it</a> both inside Apache and <a href=\"http://www.nabble.com/Java-Software-f787.html\" rel=\"nofollow noreferrer\">outside it</a>.</p>\n" }, { "answer_id": 198255, "author": "jamesh", "author_id": 4737, "author_profile": "https://Stackoverflow.com/users/4737", "pm_score": 0, "selected": false, "text": "<p>If a <a href=\"http://activemq.apache.org/\" rel=\"nofollow noreferrer\">JMS implementation</a> isn't for you, then you may be interested in an <a href=\"http://xmpp.org/about/\" rel=\"nofollow noreferrer\">XMPP</a> approach. There are multiple implementations, and also have a <a href=\"http://en.wikipedia.org/wiki/Publish/subscribe\" rel=\"nofollow noreferrer\">Publish-Subscribe</a> <a href=\"http://xmpp.org/tech/pubsub.shtml\" rel=\"nofollow noreferrer\">extension</a>. </p>\n" }, { "answer_id": 247657, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.hazelcast.com\" rel=\"noreferrer\">Hazelcast</a> Topic is a distributed pub-sub messaging solution.</p>\n<pre><code>public class Sample implements MessageListener {\n\n public static void main(String[] args) { \n Sample sample = new Sample();\n Topic topic = Hazelcast.getTopic (&quot;default&quot;); \n topic.addMessageListener(sample); \n topic.publish (&quot;my-message-object&quot;);\n } \n \n public void onMessage(Object msg) {\n System.out.println(&quot;Message received = &quot; + msg);\n } \n}\n</code></pre>\n<p>Hazelcast also supports events on distributed queue, map, set, list. All events are ordered too.</p>\n<p>Regards,</p>\n<p>-talip</p>\n<p><a href=\"http://www.hazelcast.com\" rel=\"noreferrer\">http://www.hazelcast.com</a></p>\n" }, { "answer_id": 247693, "author": "Pavel Rodionov", "author_id": 29487, "author_profile": "https://Stackoverflow.com/users/29487", "pm_score": 2, "selected": false, "text": "<p>For distributed Event processing you could use <a href=\"http://esper.codehaus.org/\" rel=\"nofollow noreferrer\">Esper</a>.It could process up to 500 000 event/s on a dual CPU 2GHz Intel based hardware.It's very stable because many banks use this solution. It supports JMS input and output adapter based on Spring JMS templates. So you could use any JMS implementation for event processing, i.e. <a href=\"http://activemq.apache.org\" rel=\"nofollow noreferrer\">ActiveMQ</a>.</p>\n" }, { "answer_id": 1129563, "author": "Matthew Phillips", "author_id": 138468, "author_profile": "https://Stackoverflow.com/users/138468", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"http://avis.sf.net/\" rel=\"nofollow noreferrer\">Avis event router</a> might be suitable for your needs. It's fast enough for near-real-time event delivery, such as sending mouse events for remote mouse control (an application we use it for daily).</p>\n\n<p>Avis is also being used for chat, virtual presence, and smart room automation where typically 10-20 computers are communicating over an Avis-based messaging bus. Its commercial cousin (Mantara Elvin) is used for high-volume commercial trade event processing.</p>\n" }, { "answer_id": 8662680, "author": "Synthesis", "author_id": 247948, "author_profile": "https://Stackoverflow.com/users/247948", "pm_score": 2, "selected": false, "text": "<p>ZeroMQ - <a href=\"http://www.zeromq.org/\" rel=\"nofollow\">http://www.zeromq.org/</a></p>\n\n<p>Although this is a transport layer, it can be tailored for event handling.</p>\n" }, { "answer_id": 8819943, "author": "Tom", "author_id": 394278, "author_profile": "https://Stackoverflow.com/users/394278", "pm_score": 1, "selected": false, "text": "<p>Take a look at akka (http://akka.io/). It offers a distributed actor model in the same vein as erlang for the JVM with both java and scala APIs. </p>\n" }, { "answer_id": 39725761, "author": "Tushar", "author_id": 3702618, "author_profile": "https://Stackoverflow.com/users/3702618", "pm_score": 1, "selected": false, "text": "<p>You need to implement <a href=\"https://sourcemaking.com/design_patterns/observer\" rel=\"nofollow\">Observer Design pattern</a> for distributed event handling in java. I am using event Streaming using MongoDB capped collection and Observers to achieve this.</p>\n\n<p>You can make an architecture in which your triggers a publish a document in capped collection and your observer thread waits for it using a tailable cursor. \nIf you did not understand what I have said above you need to brush up your <a href=\"https://university.mongodb.com/\" rel=\"nofollow\">MongoDB</a> and <a href=\"https://www.youtube.com/playlist?list=PLE7E8B7F4856C9B19\" rel=\"nofollow\">java skills</a></p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21647/" ]
I'm looking for a reasonably fast event handling mechanism in Java to generate and handle events across different JVMs running on different hosts. For event handling across multiple threads in a single JVM, I found some good candidates like Jetlang. But in my search for a distributed equivalent , I couldn't find anything that was lightweight enough to offer good performance. Does anyone know of any implementations that fit the bill? **Edit:** Putting numbers to indicate performance is a bit difficult. But for example, if you implement a heartbeating mechanism using events and the heartbeat interval is 5 seconds, the heartbeat receiver should receive a sent heartbeat within say a second or two. Generally, a lightweight implementation gives good performance. A event handling mechanism involving a web server or any kind of centralized hub requiring powerful hardware (definitely not lightweight) to give good performance is not what I'm looking for.
[Hazelcast](http://www.hazelcast.com) Topic is a distributed pub-sub messaging solution. ``` public class Sample implements MessageListener { public static void main(String[] args) { Sample sample = new Sample(); Topic topic = Hazelcast.getTopic ("default"); topic.addMessageListener(sample); topic.publish ("my-message-object"); } public void onMessage(Object msg) { System.out.println("Message received = " + msg); } } ``` Hazelcast also supports events on distributed queue, map, set, list. All events are ordered too. Regards, -talip <http://www.hazelcast.com>
181,226
<p>I am using an authentication attribute on some of my actions in an asp.net mvc page to refer people to a login screen if they have not authenticated. My problem is returning them to the referring page after they have logged in. I was just keeping track of the referring action and referring controller but that becomes problematic when I also need to keep track of some parameters. Is there some nifty built in trick about which I don't know?</p>
[ { "answer_id": 181774, "author": "Casper", "author_id": 18729, "author_profile": "https://Stackoverflow.com/users/18729", "pm_score": 2, "selected": false, "text": "<p>What I did to achieve that result might be overdoing it, and I'd like to see some other methods as well. However, here's my code. </p>\n\n<p>Please note it's using Moq to mock a context... And, I haven't done anything with the querystring yet (my routes don't contain any querystrings).</p>\n\n<pre><code>var urlReferrer = Request.UrlReferrer;\nif (urlReferrer != null)\n{\n var url = \"~\" + Server.UrlDecode(urlReferrer.PathAndQuery);\n\n // get routecollection\n var routeCollection = new RouteCollection();\n GlobalApplication.RegisterRoutes(routeCollection);\n\n // mcok context\n var context = new Mock&lt;HttpContextBase&gt;();\n var request = new Mock&lt;HttpRequestBase&gt;();\n context.Expect(ctx =&gt; ctx.Request).Returns(request.Object);\n\n // mock request\n // TODO: convert querystring to namevaluecollection\n // now it's just stripped\n if (url.IndexOf('?') &gt; 0)\n {\n url = url.Substring(0, url.IndexOf('?'));\n }\n\n var mock = Mock.Get(context.Object.Request);\n\n // TODO: insert namevaluecollection of querystring\n mock.Expect(req =&gt; req.QueryString).Returns(new NameValueCollection());\n mock.Expect(req =&gt; req.AppRelativeCurrentExecutionFilePath).Returns(url);\n mock.Expect(req =&gt; req.PathInfo).Returns(string.Empty); \n\n // get routedata with mocked context\n var routeData = routeCollection.GetRouteData(context.Object);\n var values = routeData.Values;\n\n return RedirectToAction(routeData.Values[\"action\"].ToString(), values);\n}\n</code></pre>\n\n<p>As I said, it's maybe a bit overcomplicated :)</p>\n" }, { "answer_id": 181796, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 3, "selected": true, "text": "<p>In case you're using FormsAuthentication, when ASP.NET redirects a user to the login page, the URL looks something like this:</p>\n\n<pre><code>http://www.mysite.com/Login?ReturnUrl=/Something\n</code></pre>\n\n<p>The login form's action attribute should have the same ReturnUrl parameter (either as hidden input or as part of Url) so that FormsAuthentication can pick it up and redirect, e.g. </p>\n\n<pre><code>&lt;form action=\"Login?ReturnUrl=&lt;%=Html.AttributeEncode(Request.QueryString[\"ReturnUrl\"]) %&gt;\"&gt;&lt;/form&gt;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>&lt;form&gt;&lt;input type=\"hidden\" name=\"ReturnUrl\" id=\"ReturnUrl\" value=\"&lt;%=Html.AttributeEncode(Request.QueryString[\"ReturnUrl\"])\"%&gt; /&gt;&lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 183981, "author": "Daniel Papasian", "author_id": 7548, "author_profile": "https://Stackoverflow.com/users/7548", "pm_score": 0, "selected": false, "text": "<p>You should always ensure that the referring URL is within your domain and a plausible string that they could be coming from. Otherwise this has the potential of being used with flash or other client side technologies to do things like response splitting or other attacks, known and unknown.</p>\n\n<p>The HTTP referer is user input, and it should be validated like any other. </p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361/" ]
I am using an authentication attribute on some of my actions in an asp.net mvc page to refer people to a login screen if they have not authenticated. My problem is returning them to the referring page after they have logged in. I was just keeping track of the referring action and referring controller but that becomes problematic when I also need to keep track of some parameters. Is there some nifty built in trick about which I don't know?
In case you're using FormsAuthentication, when ASP.NET redirects a user to the login page, the URL looks something like this: ``` http://www.mysite.com/Login?ReturnUrl=/Something ``` The login form's action attribute should have the same ReturnUrl parameter (either as hidden input or as part of Url) so that FormsAuthentication can pick it up and redirect, e.g. ``` <form action="Login?ReturnUrl=<%=Html.AttributeEncode(Request.QueryString["ReturnUrl"]) %>"></form> ``` or ``` <form><input type="hidden" name="ReturnUrl" id="ReturnUrl" value="<%=Html.AttributeEncode(Request.QueryString["ReturnUrl"])"%> /></form> ```
181,241
<p>Every time I use the "at" command, I get this message:</p> <pre><code>warning: commands will be executed using /bin/sh </code></pre> <p>What is it trying to warn me about? More importantly, how do I turn the warning off?</p>
[ { "answer_id": 181245, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 4, "selected": false, "text": "<p>It serves as a good warning to those of us that don't use bash as our shell, because we we'll forget that a feature that's in our day-to-day shell isn't going to be available when this code is run at the appointed time.</p>\n\n<p>i.e. </p>\n\n<pre><code>username@hostname$ at 23:00 \nwarning: commands will be executed using /bin/sh\nat&gt; rm **/*.pyc\nat&gt; &lt;EOT&gt;\njob 1 at 2008-10-08 23:00\n</code></pre>\n\n<p>The use of '**' there is perfectly valid zsh, but not /sbin/sh! It's easy to make these mistakes if you're used to using a different shell, and it's your responsibility to remember to do the right thing.</p>\n" }, { "answer_id": 181252, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 2, "selected": false, "text": "<p>If you wish to get around that message, have 'at' run a script that calls a specified environment, be it ksh, bash, csh, zsh, perl, etc.</p>\n\n<p><strong>addition</strong> - see the 'at' man page <a href=\"http://www.rt.com/man/at.1.html\" rel=\"nofollow noreferrer\">http://www.rt.com/man/at.1.html</a> for more information. </p>\n\n<pre><code>at and batch read commands from standard input or a specified file which are to be executed at a later time, using /bin/sh.\n</code></pre>\n" }, { "answer_id": 182525, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 3, "selected": false, "text": "<p>Does the warning have any harmful effect aside from being annoying? The man page doesn't mention any way of turning it off, so I don't think you can stop it from being emitted without rebuilding your <strong>at</strong> from source.</p>\n\n<p>Now, if you want to just not see it, you can use <code>at [time] 2&gt;/dev/null</code> to send it off to oblivion, but, unfortunately, the <code>at&gt;</code> prompts are printed to STDERR for some reason (a bug, IMO - they really should go to STDOUT), so they're also hidden by this.</p>\n\n<p>It may be possible to work up some shell plumbing which will eliminate the warning without also eating the prompts, but</p>\n\n<ol>\n<li>my attempt at this (<code>at [time] 2&gt;&amp;1 | grep -v warning</code>) doesn't work and</li>\n<li>even if you can find a combination that works, it won't be suitable for aliasing (since the time goes in the middle rather than at the end), so you'll need to either type it in full each time you use it or else write a wrapper script around <code>at</code> to handle it.</li>\n</ol>\n\n<p>So, unless it causes actual problems, I'd say you're probably best off just ignoring the warning like the rest of us.</p>\n" }, { "answer_id": 55071622, "author": "Matija Nalis", "author_id": 2600099, "author_profile": "https://Stackoverflow.com/users/2600099", "pm_score": 2, "selected": false, "text": "<p>The source code for <code>at.c</code> (from Debian at 3.1.20-3 version) contains an answer:</p>\n\n<blockquote>\n <p>/* POSIX.2 allows the shell specified by the user's SHELL environment \n variable, the login shell from the user's password database entry,<br>\n or /bin/sh to be the command interpreter that processes the at-job.<br>\n It also alows a warning diagnostic to be printed. Because of the<br>\n possible variance, we always output the diagnostic. */</p>\n \n <p>fprintf(stderr, \"warning: commands will be executed using /bin/sh\\n\");</p>\n</blockquote>\n\n<p>You can work around it with shell redirection:</p>\n\n<pre><code>% echo \"echo blah\" | at now+30min 2&gt;&amp;1 | fgrep -v 'warning: commands will be executed using /bin/sh'\njob 628 at Fri Mar 8 23:25:00 2019\n</code></pre>\n\n<p>Or you even create an function for your leisure use (for example for interactive shell in <code>~/.zshrc</code> or <code>~/.profile</code>):</p>\n\n<pre><code>at() {\n /usr/bin/at \"$@\" 2&gt;&amp;1 | fgrep -v 'warning: commands will be executed using /bin/sh'\n}\n</code></pre>\n\n<p>After that, it will not warn your about with that specific warning (while other warning/errors messages will still reach you)</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
Every time I use the "at" command, I get this message: ``` warning: commands will be executed using /bin/sh ``` What is it trying to warn me about? More importantly, how do I turn the warning off?
It serves as a good warning to those of us that don't use bash as our shell, because we we'll forget that a feature that's in our day-to-day shell isn't going to be available when this code is run at the appointed time. i.e. ``` username@hostname$ at 23:00 warning: commands will be executed using /bin/sh at> rm **/*.pyc at> <EOT> job 1 at 2008-10-08 23:00 ``` The use of '\*\*' there is perfectly valid zsh, but not /sbin/sh! It's easy to make these mistakes if you're used to using a different shell, and it's your responsibility to remember to do the right thing.