input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: How to update each dependency in package.json to the latest version?
<p>I copied <code>package.json</code> from another project and now want to bump all of the dependencies to their latest versions since this is a fresh project and I don't mind fixing something if it breaks.</p>
<p>What's the easiest way to do this?</p>
<p>The best way I know is to run <code>npm info express version</code> then update each dependency in <code>package.json</code> manually. There must be a better way.</p>
<pre><code>{
"name": "myproject",
"description": "my node project",
"version": "1.0.0",
"engines": {
"node": "0.8.4",
"npm": "1.1.65"
},
"private": true,
"dependencies": {
"express": "~3.0.3", // how do I get these bumped to latest?
"mongodb": "~1.2.5",
"underscore": "~1.4.2",
"rjs": "~2.9.0",
"jade": "~0.27.2",
"async": "~0.1.22"
}
}
</code></pre>
<hr />
<p>For <strong>Yarn</strong> specific solutions refer to <a href="https://stackoverflow.com/questions/62650640/how-do-i-update-each-dependency-in-package-json-to-the-latest-version-using-yarn">this Stack Overflow</a> thread.</p> | <p>Looks like <a href="https://www.npmjs.org/package/npm-check-updates" rel="noreferrer">npm-check-updates</a> is the only way to make this happen now.</p>
<pre><code>npm i -g npm-check-updates
ncu -u
npm install
</code></pre>
<hr />
<p>On npm <3.11:</p>
<p>Simply change every dependency's version to <code>*</code>, then run <code>npm update --save</code>. (<strong>Note:</strong> <a href="https://github.com/npm/npm/issues/13555" rel="noreferrer">broken in recent (3.11) versions of npm</a>).</p>
<p>Before:</p>
<pre><code> "dependencies": {
"express": "*",
"mongodb": "*",
"underscore": "*",
"rjs": "*",
"jade": "*",
"async": "*"
}
</code></pre>
<p>After:</p>
<pre><code> "dependencies": {
"express": "~3.2.0",
"mongodb": "~1.2.14",
"underscore": "~1.4.4",
"rjs": "~2.10.0",
"jade": "~0.29.0",
"async": "~0.2.7"
}
</code></pre>
<hr />
<p>Of course, this is the blunt hammer of updating dependencies. It's fine if—as you said—the project is empty and nothing can break.</p>
<p>On the other hand, if you're working in a more mature project, you probably want to verify that there are no breaking changes in your dependencies before upgrading.</p>
<p>To see which modules are outdated, just run <a href="https://docs.npmjs.com/cli/outdated" rel="noreferrer"><code>npm outdated</code></a>. It will list any installed dependencies that have newer versions available.</p>
<p>For <strong>Yarn</strong> specific solution, refer to <a href="https://stackoverflow.com/a/62650754/7344164">this StackOverflow answer</a>.</p> | {
"question_id": 16073603,
"question_date": "2013-04-18T02:39:04.573Z",
"question_score": 2461,
"tags": "node.js|npm",
"answer_id": 16074029,
"answer_date": "2013-04-18T03:35:05.653Z",
"answer_score": 2932
} |
Please answer the following Stack Overflow question:
Title: What is reflection and why is it useful?
<p>What is reflection, and why is it useful?</p>
<p>I'm particularly interested in <code>Java</code>, but I assume the principles are the same in any language.</p> | <p>The name reflection is used to describe code which is able to inspect other code in the same system (or itself).</p>
<p>For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to.</p>
<p>So, to give you a code example of this in Java (imagine the object in question is foo) :</p>
<pre><code>Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);
</code></pre>
<p>One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test.</p>
<p>There are some good reflection examples to get you started at <a href="http://docs.oracle.com/javase/tutorial/reflect/index.html" rel="noreferrer">http://docs.oracle.com/javase/tutorial/reflect/index.html</a></p>
<p>And finally, yes, the concepts are pretty much similar in other statically typed languages which support reflection (like C#). In dynamically typed languages, the use case described above is less necessary (since the compiler will allow any method to be called on any object, failing at runtime if it does not exist), but the second case of looking for methods which are marked or work in a certain way is still common.</p>
<p><strong>Update from a comment:</strong></p>
<blockquote>
<p>The ability to inspect the code in the system and see object types is
not reflection, but rather Type Introspection. Reflection is then the
ability to make modifications at runtime by making use of
introspection. The distinction is necessary here as some languages
support introspection, but do not support reflection. One such example
is C++</p>
</blockquote> | {
"question_id": 37628,
"question_date": "2008-09-01T08:39:21.633Z",
"question_score": 2459,
"tags": "java|reflection|terminology",
"answer_id": 37632,
"answer_date": "2008-09-01T08:44:58.657Z",
"answer_score": 1962
} |
Please answer the following Stack Overflow question:
Title: What are the differences between .gitignore and .gitkeep?
<p>What are the differences between <code>.gitignore</code> and <code>.gitkeep</code>? Are they the same thing with a different name, or do they both serve a different function?</p>
<p>I don't seem to be able to find much documentation on <code>.gitkeep</code>.</p> | <p><code>.gitkeep</code> isn’t documented, because it’s not a feature of Git.</p>
<p>Git <a href="https://git.wiki.kernel.org/index.php/Git_FAQ#Can_I_add_empty_directories.3F" rel="noreferrer">cannot add a completely empty directory</a>. People who want to track empty directories in Git have created the convention of putting files called <code>.gitkeep</code> in these directories. The file could be called anything; Git assigns no special significance to this name.</p>
<p>There is a competing convention of adding a <code>.gitignore</code> file to the empty directories to get them tracked, but some people see this as confusing since the goal is to keep the empty directories, not ignore them; <code>.gitignore</code> is also used to list files that should be ignored by Git when looking for untracked files.</p> | {
"question_id": 7229885,
"question_date": "2011-08-29T12:11:05.037Z",
"question_score": 2458,
"tags": "git|gitignore",
"answer_id": 7229996,
"answer_date": "2011-08-29T12:20:54.923Z",
"answer_score": 4307
} |
Please answer the following Stack Overflow question:
Title: How to print a number with commas as thousands separators in JavaScript
<p>I am trying to print an integer in <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> with commas as thousands separators. For example, I want to show the number 1234567 as "1,234,567". How would I go about doing this? </p>
<p>Here is how I am doing it:</p>
<pre><code>function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
}
</code></pre>
<p>Is there a simpler or more elegant way to do it? It would be nice if it works with floats also, but that is not necessary. It does not need to be locale-specific to decide between periods and commas. </p> | <p>I used the idea from Kerry's answer, but simplified it since I was just looking for something simple for my specific purpose. Here is what I have:</p>
<pre><code>function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}
function test(x, expect) {
const result = numberWithCommas(x);
const pass = result === expect;
console.log(`${pass ? "✓" : "ERROR ====>"} ${x} => ${result}`);
return pass;
}
let failures = 0;
failures += !test(0, "0");
failures += !test(100, "100");
failures += !test(1000, "1,000");
failures += !test(10000, "10,000");
failures += !test(100000, "100,000");
failures += !test(1000000, "1,000,000");
failures += !test(10000000, "10,000,000");
if (failures) {
console.log(`${failures} test(s) failed`);
} else {
console.log("All tests passed");
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
max-height: 100% !important;
}</code></pre>
</div>
</div>
</p>
<hr />
<p>The regex uses 2 lookahead assertions:</p>
<ul>
<li>a positive one to look for any point in the string that has a multiple of 3 digits in a row after it,</li>
<li>a negative assertion to make sure that point only has exactly a multiple of 3 digits. The replacement expression puts a comma there.</li>
</ul>
<p>For example, if you pass it <code>123456789.01</code>, the positive assertion will match every spot to the left of the 7 (since <code>789</code> is a multiple of 3 digits, <code>678</code> is a multiple of 3 digits, <code>567</code>, etc.). The negative assertion checks that the multiple of 3 digits does not have any digits after it. <code>789</code> has a period after it so it is exactly a multiple of 3 digits, so a comma goes there. <code>678</code> is a multiple of 3 digits but it has a <code>9</code> after it, so those 3 digits are part of a group of 4, and a comma does not go there. Similarly for <code>567</code>. <code>456789</code> is 6 digits, which is a multiple of 3, so a comma goes before that. <code>345678</code> is a multiple of 3, but it has a <code>9</code> after it, so no comma goes there. And so on. The <code>\B</code> keeps the regex from putting a comma at the beginning of the string.</p>
<p>@<a href="https://stackoverflow.com/users/1329075/neu-rah">neu-rah</a> mentioned that this function adds commas in undesirable places if there are more than 3 digits after the decimal point. If this is a problem, you can use this function:</p>
<pre><code>function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
function test(x, expect) {
const result = numberWithCommas(x);
const pass = result === expect;
console.log(`${pass ? "✓" : "ERROR ====>"} ${x} => ${result}`);
return pass;
}
let failures = 0;
failures += !test(0 , "0");
failures += !test(0.123456 , "0.123456");
failures += !test(100 , "100");
failures += !test(100.123456 , "100.123456");
failures += !test(1000 , "1,000");
failures += !test(1000.123456 , "1,000.123456");
failures += !test(10000 , "10,000");
failures += !test(10000.123456 , "10,000.123456");
failures += !test(100000 , "100,000");
failures += !test(100000.123456 , "100,000.123456");
failures += !test(1000000 , "1,000,000");
failures += !test(1000000.123456 , "1,000,000.123456");
failures += !test(10000000 , "10,000,000");
failures += !test(10000000.123456, "10,000,000.123456");
if (failures) {
console.log(`${failures} test(s) failed`);
} else {
console.log("All tests passed");
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
max-height: 100% !important;
}</code></pre>
</div>
</div>
</p>
<p>@<a href="https://stackoverflow.com/users/157247/t-j-crowder">t.j.crowder</a> pointed out that now that JavaScript has lookbehind (<a href="https://caniuse.com/#feat=js-regexp-lookbehind" rel="noreferrer">support info</a>), it can be solved in the regular expression itself:</p>
<pre><code>function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}
function test(x, expect) {
const result = numberWithCommas(x);
const pass = result === expect;
console.log(`${pass ? "✓" : "ERROR ====>"} ${x} => ${result}`);
return pass;
}
let failures = 0;
failures += !test(0, "0");
failures += !test(0.123456, "0.123456");
failures += !test(100, "100");
failures += !test(100.123456, "100.123456");
failures += !test(1000, "1,000");
failures += !test(1000.123456, "1,000.123456");
failures += !test(10000, "10,000");
failures += !test(10000.123456, "10,000.123456");
failures += !test(100000, "100,000");
failures += !test(100000.123456, "100,000.123456");
failures += !test(1000000, "1,000,000");
failures += !test(1000000.123456, "1,000,000.123456");
failures += !test(10000000, "10,000,000");
failures += !test(10000000.123456, "10,000,000.123456");
if (failures) {
console.log(`${failures} test(s) failed`);
} else {
console.log("All tests passed");
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
max-height: 100% !important;
}</code></pre>
</div>
</div>
</p>
<p><code>(?<!\.\d*)</code> is a negative lookbehind that says the match can't be preceded by a <code>.</code> followed by zero or more digits. The negative lookbehind is faster than the <code>split</code> and <code>join</code> solution (<a href="http://jsben.ch/umq99" rel="noreferrer">comparison</a>), at least in V8.</p> | {
"question_id": 2901102,
"question_date": "2010-05-24T23:42:31.087Z",
"question_score": 2454,
"tags": "javascript|formatting|numbers|integer",
"answer_id": 2901298,
"answer_date": "2010-05-25T00:40:59.833Z",
"answer_score": 3682
} |
Please answer the following Stack Overflow question:
Title: .prop() vs .attr()
<p>So <a href="http://api.jquery.com/category/version/1.6/" rel="noreferrer">jQuery 1.6</a> has the new function <a href="http://api.jquery.com/prop/" rel="noreferrer"><code>prop()</code></a>.</p>
<pre><code>$(selector).click(function(){
//instead of:
this.getAttribute('style');
//do i use:
$(this).prop('style');
//or:
$(this).attr('style');
})
</code></pre>
<p>or in this case do they do the same thing?</p>
<p>And if I <em>do</em> have to switch to using <code>prop()</code>, all the old <code>attr()</code> calls will break if i switch to 1.6?</p>
<p><strong>UPDATE</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>selector = '#id'
$(selector).click(function() {
//instead of:
var getAtt = this.getAttribute('style');
//do i use:
var thisProp = $(this).prop('style');
//or:
var thisAttr = $(this).attr('style');
console.log(getAtt, thisProp, thisAttr);
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<div id='id' style="color: red;background: orange;">test</div></code></pre>
</div>
</div>
</p>
<p>(see also this fiddle: <a href="http://jsfiddle.net/maniator/JpUF2/" rel="noreferrer">http://jsfiddle.net/maniator/JpUF2/</a>)</p>
<p>The console logs the <code>getAttribute</code> as a string, and the <code>attr</code> as a string, but the <code>prop</code> as a <code>CSSStyleDeclaration</code>, Why? And how does that affect my coding in the future?</p> | <p><strong>Update 1 November 2012</strong></p>
<p>My original answer applies specifically to jQuery 1.6. My advice remains the same but jQuery 1.6.1 changed things slightly: in the face of the predicted pile of broken websites, the jQuery team <a href="http://blog.jquery.com/2011/05/12/jquery-1-6-1-released/" rel="noreferrer">reverted <code>attr()</code> to something close to (but not exactly the same as) its old behaviour for Boolean attributes</a>. John Resig also <a href="http://ejohn.org/blog/jquery-16-and-attr/" rel="noreferrer">blogged about it</a>. I can see the difficulty they were in but still disagree with his recommendation to prefer <code>attr()</code>.</p>
<p><strong>Original answer</strong></p>
<p>If you've only ever used jQuery and not the DOM directly, this could be a confusing change, although it is definitely an improvement conceptually. Not so good for the bazillions of sites using jQuery that will break as a result of this change though.</p>
<p>I'll summarize the main issues:</p>
<ul>
<li>You usually want <code>prop()</code> rather than <code>attr()</code>.</li>
<li>In the majority of cases, <code>prop()</code> does what <code>attr()</code> used to do. Replacing calls to <code>attr()</code> with <code>prop()</code> in your code will generally work.</li>
<li>Properties are generally simpler to deal with than attributes. An attribute value may only be a string whereas a property can be of any type. For example, the <code>checked</code> property is a Boolean, the <code>style</code> property is an object with individual properties for each style, the <code>size</code> property is a number.</li>
<li>Where both a property and an attribute with the same name exists, usually updating one will update the other, but this is not the case for certain attributes of inputs, such as <code>value</code> and <code>checked</code>: for these attributes, the property always represents the current state while the attribute (except in old versions of IE) corresponds to the default value/checkedness of the input (reflected in the <code>defaultValue</code> / <code>defaultChecked</code> property).</li>
<li>This change removes some of the layer of magic jQuery stuck in front of attributes and properties, meaning jQuery developers will have to learn a bit about the difference between properties and attributes. This is a good thing.</li>
</ul>
<p>If you're a jQuery developer and are confused by this whole business about properties and attributes, you need to take a step back and learn a little about it, since jQuery is no longer trying so hard to shield you from this stuff. For the authoritative but somewhat dry word on the subject, there's the specs: <a href="http://www.w3.org/TR/dom/" rel="noreferrer">DOM4</a>, <a href="http://www.w3.org/TR/DOM-Level-2-HTML/" rel="noreferrer">HTML DOM</a>, <a href="http://www.w3.org/TR/DOM-Level-2-Core" rel="noreferrer">DOM Level 2</a>, <a href="http://www.w3.org/TR/DOM-Level-3-Core/" rel="noreferrer">DOM Level 3</a>. Mozilla's DOM documentation is valid for most modern browsers and is easier to read than the specs, so you may find their <a href="https://developer.mozilla.org/en/gecko_dom_reference" rel="noreferrer">DOM reference</a> helpful. There's a <a href="https://developer.mozilla.org/en/DOM/element#Properties" rel="noreferrer">section on element properties</a>.</p>
<p>As an example of how properties are simpler to deal with than attributes, consider a checkbox that is initially checked. Here are two possible pieces of valid HTML to do this:</p>
<pre><code><input id="cb" type="checkbox" checked>
<input id="cb" type="checkbox" checked="checked">
</code></pre>
<p>So, how do you find out if the checkbox is checked with jQuery? Look on Stack Overflow and you'll commonly find the following suggestions:</p>
<ul>
<li><code>if ( $("#cb").attr("checked") === true ) {...}</code></li>
<li><code>if ( $("#cb").attr("checked") == "checked" ) {...}</code></li>
<li><code>if ( $("#cb").is(":checked") ) {...}</code></li>
</ul>
<p>This is actually the simplest thing in the world to do with the <code>checked</code> Boolean property, which has existed and worked flawlessly in every major scriptable browser since 1995:</p>
<p><code>if (document.getElementById("cb").checked) {...}</code></p>
<p>The property also makes checking or unchecking the checkbox trivial:</p>
<p><code>document.getElementById("cb").checked = false</code></p>
<p>In jQuery 1.6, this unambiguously becomes</p>
<p><code>$("#cb").prop("checked", false)</code></p>
<p>The idea of using the <code>checked</code> attribute for scripting a checkbox is unhelpful and unnecessary. The property is what you need.</p>
<ul>
<li>It's not obvious what the correct way to check or uncheck the checkbox is using the <code>checked</code> attribute</li>
<li>The attribute value reflects the default rather than the current visible state (except in some older versions of IE, thus making things still harder). The attribute tells you nothing about the whether the checkbox on the page is checked. See <a href="http://jsfiddle.net/VktA6/49/" rel="noreferrer">http://jsfiddle.net/VktA6/49/</a>.</li>
</ul> | {
"question_id": 5874652,
"question_date": "2011-05-03T19:33:28.120Z",
"question_score": 2451,
"tags": "javascript|jquery|dom|attr|prop",
"answer_id": 5876747,
"answer_date": "2011-05-03T23:06:19.183Z",
"answer_score": 1946
} |
Please answer the following Stack Overflow question:
Title: How do I lowercase a string in Python?
<p>Is there a way to convert a string to lowercase?</p>
<pre><code>"Kilometers" → "kilometers"
</code></pre> | <p>Use <a href="https://docs.python.org/library/stdtypes.html#str.lower" rel="noreferrer"><code>str.lower()</code></a>:</p>
<pre><code>"Kilometer".lower()
</code></pre> | {
"question_id": 6797984,
"question_date": "2011-07-23T03:08:53.153Z",
"question_score": 2450,
"tags": "python|string|uppercase|lowercase",
"answer_id": 6797990,
"answer_date": "2011-07-23T03:09:58.443Z",
"answer_score": 3525
} |
Please answer the following Stack Overflow question:
Title: What is the difference between CMD and ENTRYPOINT in a Dockerfile?
<p>In Dockerfiles there are two commands that look similar to me: <code>CMD</code> and <code>ENTRYPOINT</code>. But I guess that there is a (subtle?) difference between them - otherwise it would not make any sense to have two commands for the very same thing.</p>
<p>The documentation states for <code>CMD</code>-</p>
<blockquote>
<p>The main purpose of a CMD is to provide defaults for an executing container.</p>
</blockquote>
<p>and for <code>ENTRYPOINT</code>:</p>
<blockquote>
<p>An ENTRYPOINT helps you to configure a container that you can run as an executable.</p>
</blockquote>
<p>So, what's the difference between those two commands?</p> | <p>Docker has a default entrypoint which is <code>/bin/sh -c</code> but does not have a default command.</p>
<p>When you run docker like this:
<code>docker run -i -t ubuntu bash</code>
the entrypoint is the default <code>/bin/sh -c</code>, the image is <code>ubuntu</code> and the command is <code>bash</code>.</p>
<p>The command is run via the entrypoint. i.e., the actual thing that gets executed is <code>/bin/sh -c bash</code>. This allowed Docker to implement <code>RUN</code> quickly by relying on the shell's parser.</p>
<p>Later on, people asked to be able to customize this, so <code>ENTRYPOINT</code> and <code>--entrypoint</code> were introduced.</p>
<p>Everything after the image name, <code>ubuntu</code> in the example above, is the command and is passed to the entrypoint. When using the <code>CMD</code> instruction, it is exactly as if you were executing<br />
<code>docker run -i -t ubuntu <cmd></code><br />
The parameter of the entrypoint is <code><cmd></code>.</p>
<p>You will also get the same result if you instead type this command <code>docker run -i -t ubuntu</code>: a bash shell will start in the container because in the <a href="https://github.com/dockerfile/ubuntu/blob/master/Dockerfile" rel="noreferrer">ubuntu Dockerfile</a> a default <code>CMD</code> is specified:<br />
<code>CMD ["bash"]</code>.</p>
<p>As everything is passed to the entrypoint, you can have a very nice behavior from your images. @Jiri example is good, it shows how to use an image as a "binary". When using <code>["/bin/cat"]</code> as entrypoint and then doing <code>docker run img /etc/passwd</code>, you get it, <code>/etc/passwd</code> is the command and is passed to the entrypoint so the end result execution is simply <code>/bin/cat /etc/passwd</code>.</p>
<p>Another example would be to have any cli as entrypoint. For instance, if you have a redis image, instead of running <code>docker run redisimg redis -H something -u toto get key</code>, you can simply have <code>ENTRYPOINT ["redis", "-H", "something", "-u", "toto"]</code> and then run like this for the same result: <code>docker run redisimg get key</code>.</p> | {
"question_id": 21553353,
"question_date": "2014-02-04T13:04:23.590Z",
"question_score": 2449,
"tags": "docker",
"answer_id": 21564990,
"answer_date": "2014-02-04T22:34:33.640Z",
"answer_score": 2352
} |
Please answer the following Stack Overflow question:
Title: How do I get the hash for the current commit in Git?
<p>How do I get the hash of the current commit in Git?</p> | <p>To turn any extended object reference into a hash, use <strong><a href="http://git-scm.com/docs/git-rev-parse" rel="noreferrer" title="git-rev-parse - Pick out and massage parameters"><code>git-rev-parse</code></a></strong>:</p>
<pre><code>git rev-parse HEAD
</code></pre>
<p>or</p>
<pre><code>git rev-parse --verify HEAD
</code></pre>
<p>To retrieve the short hash:</p>
<pre><code>git rev-parse --short HEAD
</code></pre>
<p>To turn <em>references</em> (e.g. <em>branches and tags</em>) into hashes, use <code>git show-ref</code> and <code>git for-each-ref</code>.</p> | {
"question_id": 949314,
"question_date": "2009-06-04T08:42:51.073Z",
"question_score": 2439,
"tags": "git|git-hash",
"answer_id": 949391,
"answer_date": "2009-06-04T09:05:57.627Z",
"answer_score": 3568
} |
Please answer the following Stack Overflow question:
Title: What is The Rule of Three?
<ul>
<li>What does <em>copying an object</em> mean?</li>
<li>What are the <em>copy constructor</em> and the <em>copy assignment operator</em>?</li>
<li>When do I need to declare them myself?</li>
<li>How can I prevent my objects from being copied?</li>
</ul> | <h1>Introduction</h1>
<p>C++ treats variables of user-defined types with <em>value semantics</em>.
This means that objects are implicitly copied in various contexts,
and we should understand what "copying an object" actually means.</p>
<p>Let us consider a simple example:</p>
<pre><code>class person
{
std::string name;
int age;
public:
person(const std::string& name, int age) : name(name), age(age)
{
}
};
int main()
{
person a("Bjarne Stroustrup", 60);
person b(a); // What happens here?
b = a; // And here?
}
</code></pre>
<p>(If you are puzzled by the <code>name(name), age(age)</code> part,
this is called a <a href="https://stackoverflow.com/questions/1272680/">member initializer list</a>.)</p>
<h1>Special member functions</h1>
<p>What does it mean to copy a <code>person</code> object?
The <code>main</code> function shows two distinct copying scenarios.
The initialization <code>person b(a);</code> is performed by the <em>copy constructor</em>.
Its job is to construct a fresh object based on the state of an existing object.
The assignment <code>b = a</code> is performed by the <em>copy assignment operator</em>.
Its job is generally a little more complicated,
because the target object is already in some valid state that needs to be dealt with.</p>
<p>Since we declared neither the copy constructor nor the assignment operator (nor the destructor) ourselves,
these are implicitly defined for us. Quote from the standard:</p>
<blockquote>
<p>The [...] copy constructor and copy assignment operator, [...] and destructor are special member functions.
[ <em>Note</em>: <strong>The implementation will implicitly declare these member functions
for some class types when the program does not explicitly declare them.</strong>
The implementation will implicitly define them if they are used. [...] <em>end note</em> ]
[n3126.pdf section 12 §1]</p>
</blockquote>
<p>By default, copying an object means copying its members:</p>
<blockquote>
<p>The implicitly-defined copy constructor for a non-union class X performs a memberwise copy of its subobjects.
[n3126.pdf section 12.8 §16]</p>
</blockquote>
<blockquote>
<p>The implicitly-defined copy assignment operator for a non-union class X performs memberwise copy assignment
of its subobjects.
[n3126.pdf section 12.8 §30]</p>
</blockquote>
<h2>Implicit definitions</h2>
<p>The implicitly-defined special member functions for <code>person</code> look like this:</p>
<pre><code>// 1. copy constructor
person(const person& that) : name(that.name), age(that.age)
{
}
// 2. copy assignment operator
person& operator=(const person& that)
{
name = that.name;
age = that.age;
return *this;
}
// 3. destructor
~person()
{
}
</code></pre>
<p>Memberwise copying is exactly what we want in this case:
<code>name</code> and <code>age</code> are copied, so we get a self-contained, independent <code>person</code> object.
The implicitly-defined destructor is always empty.
This is also fine in this case since we did not acquire any resources in the constructor.
The members' destructors are implicitly called after the <code>person</code> destructor is finished:</p>
<blockquote>
<p>After executing the body of the destructor and destroying any automatic objects allocated within the body,
a destructor for class X calls the destructors for X's direct [...] members
[n3126.pdf 12.4 §6]</p>
</blockquote>
<h1>Managing resources</h1>
<p>So when should we declare those special member functions explicitly?
When our class <em>manages a resource</em>, that is,
when an object of the class is <em>responsible</em> for that resource.
That usually means the resource is <em>acquired</em> in the constructor
(or passed into the constructor) and <em>released</em> in the destructor.</p>
<p>Let us go back in time to pre-standard C++.
There was no such thing as <code>std::string</code>, and programmers were in love with pointers.
The <code>person</code> class might have looked like this:</p>
<pre><code>class person
{
char* name;
int age;
public:
// the constructor acquires a resource:
// in this case, dynamic memory obtained via new[]
person(const char* the_name, int the_age)
{
name = new char[strlen(the_name) + 1];
strcpy(name, the_name);
age = the_age;
}
// the destructor must release this resource via delete[]
~person()
{
delete[] name;
}
};
</code></pre>
<p>Even today, people still write classes in this style and get into trouble:
"<em>I pushed a person into a vector and now I get crazy memory errors!</em>"
Remember that by default, copying an object means copying its members,
but copying the <code>name</code> member merely copies a pointer, <em>not</em> the character array it points to!
This has several unpleasant effects:</p>
<ol>
<li>Changes via <code>a</code> can be observed via <code>b</code>.</li>
<li>Once <code>b</code> is destroyed, <code>a.name</code> is a dangling pointer.</li>
<li>If <code>a</code> is destroyed, deleting the dangling pointer yields <a href="https://stackoverflow.com/questions/2397984/">undefined behavior</a>.</li>
<li>Since the assignment does not take into account what <code>name</code> pointed to before the assignment,
sooner or later you will get memory leaks all over the place.</li>
</ol>
<h2>Explicit definitions</h2>
<p>Since memberwise copying does not have the desired effect, we must define the copy constructor and the copy assignment operator explicitly to make deep copies of the character array:</p>
<pre><code>// 1. copy constructor
person(const person& that)
{
name = new char[strlen(that.name) + 1];
strcpy(name, that.name);
age = that.age;
}
// 2. copy assignment operator
person& operator=(const person& that)
{
if (this != &that)
{
delete[] name;
// This is a dangerous point in the flow of execution!
// We have temporarily invalidated the class invariants,
// and the next statement might throw an exception,
// leaving the object in an invalid state :(
name = new char[strlen(that.name) + 1];
strcpy(name, that.name);
age = that.age;
}
return *this;
}
</code></pre>
<p>Note the difference between initialization and assignment:
we must tear down the old state before assigning to <code>name</code> to prevent memory leaks.
Also, we have to protect against self-assignment of the form <code>x = x</code>.
Without that check, <code>delete[] name</code> would delete the array containing the <em>source</em> string,
because when you write <code>x = x</code>, both <code>this->name</code> and <code>that.name</code> contain the same pointer.</p>
<h2>Exception safety</h2>
<p>Unfortunately, this solution will fail if <code>new char[...]</code> throws an exception due to memory exhaustion.
One possible solution is to introduce a local variable and reorder the statements:</p>
<pre><code>// 2. copy assignment operator
person& operator=(const person& that)
{
char* local_name = new char[strlen(that.name) + 1];
// If the above statement throws,
// the object is still in the same state as before.
// None of the following statements will throw an exception :)
strcpy(local_name, that.name);
delete[] name;
name = local_name;
age = that.age;
return *this;
}
</code></pre>
<p>This also takes care of self-assignment without an explicit check.
An even more robust solution to this problem is the <a href="https://stackoverflow.com/questions/3279543/">copy-and-swap idiom</a>,
but I will not go into the details of exception safety here.
I only mentioned exceptions to make the following point: <strong>Writing classes that manage resources is hard.</strong></p>
<h2>Noncopyable resources</h2>
<p>Some resources cannot or should not be copied, such as file handles or mutexes.
In that case, simply declare the copy constructor and copy assignment operator as <code>private</code> without giving a definition:</p>
<pre><code>private:
person(const person& that);
person& operator=(const person& that);
</code></pre>
<p>Alternatively, you can inherit from <code>boost::noncopyable</code> or declare them as deleted (in C++11 and above):</p>
<pre><code>person(const person& that) = delete;
person& operator=(const person& that) = delete;
</code></pre>
<h2>The rule of three</h2>
<p>Sometimes you need to implement a class that manages a resource.
(Never manage multiple resources in a single class,
this will only lead to pain.)
In that case, remember the <strong>rule of three</strong>:</p>
<blockquote>
<p>If you need to explicitly declare either the destructor,
copy constructor or copy assignment operator yourself,
you probably need to explicitly declare all three of them.</p>
</blockquote>
<p>(Unfortunately, this "rule" is not enforced by the C++ standard or any compiler I am aware of.)</p>
<h2>The rule of five</h2>
<p>From C++11 on, an object has 2 extra special member functions: the move constructor and move assignment. The rule of five states to implement these functions as well.</p>
<p>An example with the signatures:</p>
<pre><code>class person
{
std::string name;
int age;
public:
person(const std::string& name, int age); // Ctor
person(const person &) = default; // 1/5: Copy Ctor
person(person &&) noexcept = default; // 4/5: Move Ctor
person& operator=(const person &) = default; // 2/5: Copy Assignment
person& operator=(person &&) noexcept = default; // 5/5: Move Assignment
~person() noexcept = default; // 3/5: Dtor
};
</code></pre>
<h2>The rule of zero</h2>
<p>The rule of 3/5 is also referred to as the rule of 0/3/5. The zero part of the rule states that you are allowed to not write any of the special member functions when creating your class.</p>
<h1>Advice</h1>
<p>Most of the time, you do not need to manage a resource yourself,
because an existing class such as <code>std::string</code> already does it for you.
Just compare the simple code using a <code>std::string</code> member
to the convoluted and error-prone alternative using a <code>char*</code> and you should be convinced.
As long as you stay away from raw pointer members, the rule of three is unlikely to concern your own code.</p> | {
"question_id": 4172722,
"question_date": "2010-11-13T13:27:09.260Z",
"question_score": 2429,
"tags": "c++|copy-constructor|assignment-operator|c++-faq|rule-of-three",
"answer_id": 4172724,
"answer_date": "2010-11-13T13:27:19.090Z",
"answer_score": 2038
} |
Please answer the following Stack Overflow question:
Title: How do I declare and initialize an array in Java?
<p>How do I declare and initialize an array in Java?</p> | <p>You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).</p>
<p>For primitive types:</p>
<pre><code>int[] myIntArray = new int[3];
int[] myIntArray = {1, 2, 3};
int[] myIntArray = new int[]{1, 2, 3};
// Since Java 8. Doc of IntStream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html
int [] myIntArray = IntStream.range(0, 100).toArray(); // From 0 to 99
int [] myIntArray = IntStream.rangeClosed(0, 100).toArray(); // From 0 to 100
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).toArray(); // The order is preserved.
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).sorted().toArray(); // Sort
</code></pre>
<p>For classes, for example <code>String</code>, it's the same:</p>
<pre><code>String[] myStringArray = new String[3];
String[] myStringArray = {"a", "b", "c"};
String[] myStringArray = new String[]{"a", "b", "c"};
</code></pre>
<p>The third way of initializing is useful when you declare an array first and then initialize it, pass an array as a function argument, or return an array. The explicit type is required.</p>
<pre><code>String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};
</code></pre> | {
"question_id": 1200621,
"question_date": "2009-07-29T14:22:27.243Z",
"question_score": 2428,
"tags": "java|arrays",
"answer_id": 1200646,
"answer_date": "2009-07-29T14:25:23.977Z",
"answer_score": 3092
} |
Please answer the following Stack Overflow question:
Title: How do I revert all local changes in Git managed project to previous state?
<p>I ran <code>git status</code> which told me everything was up to date and there were no local changes.</p>
<p>Then I made several consecutive changes and realized I wanted to throw everything away and get back to my original state. Will this command do it for me?</p>
<pre><code>git reset --hard HEAD
</code></pre> | <p>To revert changes made to your working copy, do this:</p>
<pre><code>git checkout .
</code></pre>
<p>Or equivalently, for git version >= 2.23:</p>
<pre><code>git restore .
</code></pre>
<p>To revert changes made to the index (i.e., that you have added), do this. <strong>Warning this will reset all of your unpushed commits to master!</strong>:</p>
<pre><code>git reset
</code></pre>
<p>To revert a change that you have committed:</p>
<pre><code>git revert <commit 1> <commit 2>
</code></pre>
<p>To remove untracked files (e.g., new files, generated files):</p>
<pre><code>git clean -f
</code></pre>
<p>Or untracked directories (e.g., new or automatically generated directories):</p>
<pre><code>git clean -fd
</code></pre> | {
"question_id": 1146973,
"question_date": "2009-07-18T07:52:29.347Z",
"question_score": 2424,
"tags": "git|revert|git-checkout",
"answer_id": 1146981,
"answer_date": "2009-07-18T07:57:46.763Z",
"answer_score": 4252
} |
Please answer the following Stack Overflow question:
Title: How do I delete all Git branches which have been merged?
<p>How do I delete branches which have already been merged? Can I delete them all at once, instead of deleting each branch one-by-one?</p> | <p>NOTE: You can add other branches to exclude like master and dev if your workflow has those as a possible ancestor. Usually I branch off of a "sprint-start" tag and master, dev and qa are not ancestors.</p>
<hr />
<p>First, list locally-tracking branches that were merged in remote (consider using <code>-r</code> flag to list all remote-tracking branches).</p>
<pre><code>git branch --merged
</code></pre>
<p>You might see few branches you don't want to remove. We can add few arguments to skip important branches that we don't want to delete like master or a develop. The following command will skip master branch and anything that has dev in it.</p>
<pre><code>git branch --merged| egrep -v "(^\*|master|main|dev)"
</code></pre>
<p>If you want to skip, you can add it to the egrep command like the following. The branch <code>skip_branch_name</code> will not be deleted.</p>
<pre><code>git branch --merged| egrep -v "(^\*|master|main|dev|skip_branch_name)"
</code></pre>
<p>To delete all local branches that are already merged into the currently checked out branch:</p>
<pre><code>git branch --merged | egrep -v "(^\*|master|main|dev)" | xargs git branch -d
</code></pre>
<p>You can see that master and dev are excluded in case they are an ancestor.</p>
<hr />
<p>You can delete a merged local branch with:</p>
<pre><code>git branch -d branchname
</code></pre>
<p>If it's not merged, use:</p>
<pre><code>git branch -D branchname
</code></pre>
<p>To delete it from the remote use:</p>
<pre><code>git push --delete origin branchname
git push origin :branchname # for really old git
</code></pre>
<p>Once you delete the branch from the remote, you can prune to get rid of remote tracking branches with:</p>
<pre><code>git remote prune origin
</code></pre>
<p>or prune individual remote tracking branches, as the other answer suggests, with:</p>
<pre><code>git branch -dr branchname
</code></pre> | {
"question_id": 6127328,
"question_date": "2011-05-25T15:54:36.060Z",
"question_score": 2421,
"tags": "git|version-control|branch|feature-branch",
"answer_id": 6127884,
"answer_date": "2011-05-25T16:40:19.447Z",
"answer_score": 3725
} |
Please answer the following Stack Overflow question:
Title: See what's in a stash without applying it
<p>How do I see what is inside a <a href="https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning" rel="noreferrer">stash</a> without actually applying it?</p> | <p>From <code>man git-stash</code> (which can also be obtained via <code>git help stash</code>):</p>
<blockquote>
<p>The modifications stashed away by this command can be listed with <code>git stash list</code>, inspected with <code>git stash show</code>, and ...</p>
</blockquote>
<pre><code>show [<stash>]
Show the changes recorded in the stash as a diff between the stashed
state and its original parent. When no <stash> is given, shows the
latest one. By default, the command shows the diffstat, but it will
accept any format known to git diff (e.g., git stash show -p stash@{1}
to view the second most recent stash in patch form).
</code></pre>
<p>Note: the <code>-p</code> option generates a <em>patch</em>, as per <code>git-diff</code> documentation.</p>
<p>List the stashes:</p>
<pre><code>git stash list
</code></pre>
<p>Show the <em>files</em> in the most recent stash:</p>
<pre><code>git stash show
</code></pre>
<p>Show the <em>changes</em> of the most recent stash:</p>
<pre><code>git stash show -p
</code></pre>
<p>Show the <em>changes</em> of the named stash:</p>
<pre><code>git stash show -p stash@{1}
</code></pre>
<p>Or in short:</p>
<pre><code>git stash show -p 1
</code></pre> | {
"question_id": 10725729,
"question_date": "2012-05-23T18:26:39.847Z",
"question_score": 2417,
"tags": "git|git-stash",
"answer_id": 10726185,
"answer_date": "2012-05-23T18:58:49.773Z",
"answer_score": 3352
} |
Please answer the following Stack Overflow question:
Title: How do I parse command line arguments in Bash?
<p>Say, I have a script that gets called with this line:</p>
<pre><code>./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile
</code></pre>
<p>or this one:</p>
<pre><code>./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile
</code></pre>
<p>What's the accepted way of parsing this such that in each case (or some combination of the two) <code>$v</code>, <code>$f</code>, and <code>$d</code> will all be set to <code>true</code> and <code>$outFile</code> will be equal to <code>/fizz/someOtherFile</code>?</p> | <h4>Bash Space-Separated (e.g., <code>--option argument</code>)</h4>
<pre class="lang-sh prettyprint-override"><code>cat >/tmp/demo-space-separated.sh <<'EOF'
#!/bin/bash
POSITIONAL_ARGS=()
while [[ $# -gt 0 ]]; do
case $1 in
-e|--extension)
EXTENSION="$2"
shift # past argument
shift # past value
;;
-s|--searchpath)
SEARCHPATH="$2"
shift # past argument
shift # past value
;;
--default)
DEFAULT=YES
shift # past argument
;;
-*|--*)
echo "Unknown option $1"
exit 1
;;
*)
POSITIONAL_ARGS+=("$1") # save positional arg
shift # past argument
;;
esac
done
set -- "${POSITIONAL_ARGS[@]}" # restore positional parameters
echo "FILE EXTENSION = ${EXTENSION}"
echo "SEARCH PATH = ${SEARCHPATH}"
echo "DEFAULT = ${DEFAULT}"
echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l)
if [[ -n $1 ]]; then
echo "Last line of file specified as non-opt/last argument:"
tail -1 "$1"
fi
EOF
chmod +x /tmp/demo-space-separated.sh
/tmp/demo-space-separated.sh -e conf -s /etc /etc/hosts
</code></pre>
<h5>Output from copy-pasting the block above</h5>
<pre class="lang-sh prettyprint-override"><code>FILE EXTENSION = conf
SEARCH PATH = /etc
DEFAULT =
Number files in SEARCH PATH with EXTENSION: 14
Last line of file specified as non-opt/last argument:
#93.184.216.34 example.com
</code></pre>
<h5>Usage</h5>
<pre class="lang-bash prettyprint-override"><code>demo-space-separated.sh -e conf -s /etc /etc/hosts
</code></pre>
<hr />
<h4>Bash Equals-Separated (e.g., <code>--option=argument</code>)</h4>
<pre class="lang-sh prettyprint-override"><code>cat >/tmp/demo-equals-separated.sh <<'EOF'
#!/bin/bash
for i in "$@"; do
case $i in
-e=*|--extension=*)
EXTENSION="${i#*=}"
shift # past argument=value
;;
-s=*|--searchpath=*)
SEARCHPATH="${i#*=}"
shift # past argument=value
;;
--default)
DEFAULT=YES
shift # past argument with no value
;;
-*|--*)
echo "Unknown option $i"
exit 1
;;
*)
;;
esac
done
echo "FILE EXTENSION = ${EXTENSION}"
echo "SEARCH PATH = ${SEARCHPATH}"
echo "DEFAULT = ${DEFAULT}"
echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l)
if [[ -n $1 ]]; then
echo "Last line of file specified as non-opt/last argument:"
tail -1 $1
fi
EOF
chmod +x /tmp/demo-equals-separated.sh
/tmp/demo-equals-separated.sh -e=conf -s=/etc /etc/hosts
</code></pre>
<h5>Output from copy-pasting the block above</h5>
<pre class="lang-sh prettyprint-override"><code>FILE EXTENSION = conf
SEARCH PATH = /etc
DEFAULT =
Number files in SEARCH PATH with EXTENSION: 14
Last line of file specified as non-opt/last argument:
#93.184.216.34 example.com
</code></pre>
<h5>Usage</h5>
<pre class="lang-bash prettyprint-override"><code>demo-equals-separated.sh -e=conf -s=/etc /etc/hosts
</code></pre>
<hr />
<p>To better understand <code>${i#*=}</code> search for "Substring Removal" in <a href="http://tldp.org/LDP/abs/html/string-manipulation.html" rel="noreferrer">this guide</a>. It is functionally equivalent to <code>`sed 's/[^=]*=//' <<< "$i"`</code> which calls a needless subprocess or <code>`echo "$i" | sed 's/[^=]*=//'`</code> which calls <em>two</em> needless subprocesses.</p>
<hr />
<h4>Using bash with getopt[s]</h4>
<p>getopt(1) limitations (older, relatively-recent <code>getopt</code> versions):</p>
<ul>
<li>can't handle arguments that are empty strings</li>
<li>can't handle arguments with embedded whitespace</li>
</ul>
<p>More recent <code>getopt</code> versions don't have these limitations. For more information, see these <a href="https://mywiki.wooledge.org/BashFAQ/035#getopts" rel="noreferrer">docs</a>.</p>
<hr />
<h4>POSIX getopts</h4>
<p>Additionally, the POSIX shell and others offer <code>getopts</code> which doen't have these limitations. I've included a simplistic <code>getopts</code> example.</p>
<pre class="lang-sh prettyprint-override"><code>cat >/tmp/demo-getopts.sh <<'EOF'
#!/bin/sh
# A POSIX variable
OPTIND=1 # Reset in case getopts has been used previously in the shell.
# Initialize our own variables:
output_file=""
verbose=0
while getopts "h?vf:" opt; do
case "$opt" in
h|\?)
show_help
exit 0
;;
v) verbose=1
;;
f) output_file=$OPTARG
;;
esac
done
shift $((OPTIND-1))
[ "${1:-}" = "--" ] && shift
echo "verbose=$verbose, output_file='$output_file', Leftovers: $@"
EOF
chmod +x /tmp/demo-getopts.sh
/tmp/demo-getopts.sh -vf /etc/hosts foo bar
</code></pre>
<h5>Output from copy-pasting the block above</h5>
<pre class="lang-sh prettyprint-override"><code>verbose=1, output_file='/etc/hosts', Leftovers: foo bar
</code></pre>
<h5>Usage</h5>
<pre class="lang-bash prettyprint-override"><code>demo-getopts.sh -vf /etc/hosts foo bar
</code></pre>
<p>The advantages of <code>getopts</code> are:</p>
<ol>
<li>It's more portable, and will work in other shells like <code>dash</code>.</li>
<li>It can handle multiple single options like <code>-vf filename</code> in the typical Unix way, automatically.</li>
</ol>
<p>The disadvantage of <code>getopts</code> is that it can only handle short options (<code>-h</code>, not <code>--help</code>) without additional code.</p>
<p>There is a <a href="http://wiki.bash-hackers.org/howto/getopts_tutorial" rel="noreferrer">getopts tutorial</a> which explains what all of the syntax and variables mean. In bash, there is also <code>help getopts</code>, which might be informative.</p> | {
"question_id": 192249,
"question_date": "2008-10-10T16:57:19.490Z",
"question_score": 2413,
"tags": "bash|command-line|scripting|arguments|getopts",
"answer_id": 14203146,
"answer_date": "2013-01-07T20:01:05.670Z",
"answer_score": 3360
} |
Please answer the following Stack Overflow question:
Title: Static class variables and methods in Python
<p>How do I create static class variables or methods in Python?</p> | <p>Variables declared inside the class definition, but not inside a method are class or static variables:</p>
<pre><code>>>> class MyClass:
... i = 3
...
>>> MyClass.i
3
</code></pre>
<p>As @<a href="https://stackoverflow.com/questions/68645/static-class-variables-in-python#answer-69067">millerdev</a> points out, this creates a class-level <code>i</code> variable, but this is distinct from any instance-level <code>i</code> variable, so you could have</p>
<pre><code>>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)
</code></pre>
<p>This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.</p>
<p>See <a href="https://docs.python.org/3/tutorial/classes.html#class-objects" rel="noreferrer">what the Python tutorial has to say on the subject of classes and class objects</a>.</p>
<p>@Steve Johnson has already answered regarding <a href="http://web.archive.org/web/20090214211613/http://pyref.infogami.com/staticmethod" rel="noreferrer">static methods</a>, also documented under <a href="https://docs.python.org/3/library/functions.html#staticmethod" rel="noreferrer">"Built-in Functions" in the Python Library Reference</a>.</p>
<pre><code>class C:
@staticmethod
def f(arg1, arg2, ...): ...
</code></pre>
<p>@beidy recommends <a href="https://docs.python.org/3/library/functions.html#classmethod" rel="noreferrer">classmethod</a>s over staticmethod, as the method then receives the class type as the first argument.</p> | {
"question_id": 68645,
"question_date": "2008-09-16T01:46:36.847Z",
"question_score": 2404,
"tags": "python|class|oop|static|class-variables",
"answer_id": 68672,
"answer_date": "2008-09-16T01:51:06.713Z",
"answer_score": 2247
} |
Please answer the following Stack Overflow question:
Title: Why are elementwise additions much faster in separate loops than in a combined loop?
<p>Suppose <code>a1</code>, <code>b1</code>, <code>c1</code>, and <code>d1</code> point to heap memory, and my numerical code has the following core loop.</p>
<pre><code>const int n = 100000;
for (int j = 0; j < n; j++) {
a1[j] += b1[j];
c1[j] += d1[j];
}
</code></pre>
<p>This loop is executed 10,000 times via another outer <code>for</code> loop. To speed it up, I changed the code to:</p>
<pre><code>for (int j = 0; j < n; j++) {
a1[j] += b1[j];
}
for (int j = 0; j < n; j++) {
c1[j] += d1[j];
}
</code></pre>
<p>Compiled on <a href="http://en.wikipedia.org/wiki/Visual_C++#32-bit_versions" rel="noreferrer">Microsoft Visual C++ 10.0</a> with full optimization and <a href="http://en.wikipedia.org/wiki/SSE2" rel="noreferrer">SSE2</a> enabled for 32-bit on a <a href="http://en.wikipedia.org/wiki/Intel_Core_2" rel="noreferrer">Intel Core 2</a> Duo (x64), the first example takes 5.5 seconds and the double-loop example takes only 1.9 seconds.</p>
<p>Disassembly for the first loop basically looks like this (this block is repeated about five times in the full program):</p>
<pre><code>movsd xmm0,mmword ptr [edx+18h]
addsd xmm0,mmword ptr [ecx+20h]
movsd mmword ptr [ecx+20h],xmm0
movsd xmm0,mmword ptr [esi+10h]
addsd xmm0,mmword ptr [eax+30h]
movsd mmword ptr [eax+30h],xmm0
movsd xmm0,mmword ptr [edx+20h]
addsd xmm0,mmword ptr [ecx+28h]
movsd mmword ptr [ecx+28h],xmm0
movsd xmm0,mmword ptr [esi+18h]
addsd xmm0,mmword ptr [eax+38h]
</code></pre>
<p>Each loop of the double loop example produces this code (the following block is repeated about three times):</p>
<pre><code>addsd xmm0,mmword ptr [eax+28h]
movsd mmword ptr [eax+28h],xmm0
movsd xmm0,mmword ptr [ecx+20h]
addsd xmm0,mmword ptr [eax+30h]
movsd mmword ptr [eax+30h],xmm0
movsd xmm0,mmword ptr [ecx+28h]
addsd xmm0,mmword ptr [eax+38h]
movsd mmword ptr [eax+38h],xmm0
movsd xmm0,mmword ptr [ecx+30h]
addsd xmm0,mmword ptr [eax+40h]
movsd mmword ptr [eax+40h],xmm0
</code></pre>
<p>The question turned out to be of no relevance, as the behavior severely depends on the sizes of the arrays (n) and the CPU cache. So if there is further interest, I rephrase the question:</p>
<ul>
<li><p>Could you provide some solid insight into the details that lead to the different cache behaviors as illustrated by the five regions on the following graph?</p>
</li>
<li><p>It might also be interesting to point out the differences between CPU/cache architectures, by providing a similar graph for these CPUs.</p>
</li>
</ul>
<p>Here is the full code. It uses <a href="https://www.threadingbuildingblocks.org/" rel="noreferrer">TBB</a> <code>Tick_Count</code> for higher resolution timing, which can be disabled by not defining the <code>TBB_TIMING</code> Macro:</p>
<pre><code>#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
//#define TBB_TIMING
#ifdef TBB_TIMING
#include <tbb/tick_count.h>
using tbb::tick_count;
#else
#include <time.h>
#endif
using namespace std;
//#define preallocate_memory new_cont
enum { new_cont, new_sep };
double *a1, *b1, *c1, *d1;
void allo(int cont, int n)
{
switch(cont) {
case new_cont:
a1 = new double[n*4];
b1 = a1 + n;
c1 = b1 + n;
d1 = c1 + n;
break;
case new_sep:
a1 = new double[n];
b1 = new double[n];
c1 = new double[n];
d1 = new double[n];
break;
}
for (int i = 0; i < n; i++) {
a1[i] = 1.0;
d1[i] = 1.0;
c1[i] = 1.0;
b1[i] = 1.0;
}
}
void ff(int cont)
{
switch(cont){
case new_sep:
delete[] b1;
delete[] c1;
delete[] d1;
case new_cont:
delete[] a1;
}
}
double plain(int n, int m, int cont, int loops)
{
#ifndef preallocate_memory
allo(cont,n);
#endif
#ifdef TBB_TIMING
tick_count t0 = tick_count::now();
#else
clock_t start = clock();
#endif
if (loops == 1) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++){
a1[j] += b1[j];
c1[j] += d1[j];
}
}
} else {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
a1[j] += b1[j];
}
for (int j = 0; j < n; j++) {
c1[j] += d1[j];
}
}
}
double ret;
#ifdef TBB_TIMING
tick_count t1 = tick_count::now();
ret = 2.0*double(n)*double(m)/(t1-t0).seconds();
#else
clock_t end = clock();
ret = 2.0*double(n)*double(m)/(double)(end - start) *double(CLOCKS_PER_SEC);
#endif
#ifndef preallocate_memory
ff(cont);
#endif
return ret;
}
void main()
{
freopen("C:\\test.csv", "w", stdout);
char *s = " ";
string na[2] ={"new_cont", "new_sep"};
cout << "n";
for (int j = 0; j < 2; j++)
for (int i = 1; i <= 2; i++)
#ifdef preallocate_memory
cout << s << i << "_loops_" << na[preallocate_memory];
#else
cout << s << i << "_loops_" << na[j];
#endif
cout << endl;
long long nmax = 1000000;
#ifdef preallocate_memory
allo(preallocate_memory, nmax);
#endif
for (long long n = 1L; n < nmax; n = max(n+1, long long(n*1.2)))
{
const long long m = 10000000/n;
cout << n;
for (int j = 0; j < 2; j++)
for (int i = 1; i <= 2; i++)
cout << s << plain(n, m, j, i);
cout << endl;
}
}
</code></pre>
<p>It shows FLOP/s for different values of <code>n</code>.</p>
<p><a href="https://i.stack.imgur.com/426bP.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/426bP.gif" alt="Performace chart" /></a></p> | <p>Upon further analysis of this, I believe this is (at least partially) caused by the data alignment of the four-pointers. This will cause some level of cache bank/way conflicts.</p>
<p>If I've guessed correctly on how you are allocating your arrays, they <em><strong>are likely to be aligned to the page line</strong></em>.</p>
<p>This means that all your accesses in each loop will fall on the same cache way. However, Intel processors have had 8-way L1 cache associativity for a while. But in reality, the performance isn't completely uniform. Accessing 4-ways is still slower than say 2-ways.</p>
<p><strong>EDIT: It does in fact look like you are allocating all the arrays separately.</strong>
Usually when such large allocations are requested, the allocator will request fresh pages from the OS. Therefore, there is a high chance that large allocations will appear at the same offset from a page-boundary.</p>
<p><strong>Here's the test code:</strong></p>
<pre><code>int main(){
const int n = 100000;
#ifdef ALLOCATE_SEPERATE
double *a1 = (double*)malloc(n * sizeof(double));
double *b1 = (double*)malloc(n * sizeof(double));
double *c1 = (double*)malloc(n * sizeof(double));
double *d1 = (double*)malloc(n * sizeof(double));
#else
double *a1 = (double*)malloc(n * sizeof(double) * 4);
double *b1 = a1 + n;
double *c1 = b1 + n;
double *d1 = c1 + n;
#endif
// Zero the data to prevent any chance of denormals.
memset(a1,0,n * sizeof(double));
memset(b1,0,n * sizeof(double));
memset(c1,0,n * sizeof(double));
memset(d1,0,n * sizeof(double));
// Print the addresses
cout << a1 << endl;
cout << b1 << endl;
cout << c1 << endl;
cout << d1 << endl;
clock_t start = clock();
int c = 0;
while (c++ < 10000){
#if ONE_LOOP
for(int j=0;j<n;j++){
a1[j] += b1[j];
c1[j] += d1[j];
}
#else
for(int j=0;j<n;j++){
a1[j] += b1[j];
}
for(int j=0;j<n;j++){
c1[j] += d1[j];
}
#endif
}
clock_t end = clock();
cout << "seconds = " << (double)(end - start) / CLOCKS_PER_SEC << endl;
system("pause");
return 0;
}
</code></pre>
<hr />
<p><strong>Benchmark Results:</strong></p>
<h1>EDIT: Results on an <em>actual</em> Core 2 architecture machine:</h1>
<p><strong>2 x Intel Xeon X5482 Harpertown @ 3.2 GHz:</strong></p>
<pre class="lang-none prettyprint-override"><code>#define ALLOCATE_SEPERATE
#define ONE_LOOP
00600020
006D0020
007A0020
00870020
seconds = 6.206
#define ALLOCATE_SEPERATE
//#define ONE_LOOP
005E0020
006B0020
00780020
00850020
seconds = 2.116
//#define ALLOCATE_SEPERATE
#define ONE_LOOP
00570020
00633520
006F6A20
007B9F20
seconds = 1.894
//#define ALLOCATE_SEPERATE
//#define ONE_LOOP
008C0020
00983520
00A46A20
00B09F20
seconds = 1.993
</code></pre>
<p>Observations:</p>
<ul>
<li><p><strong>6.206 seconds</strong> with one loop and <strong>2.116 seconds</strong> with two loops. This reproduces the OP's results exactly.</p>
</li>
<li><p><strong>In the first two tests, the arrays are allocated separately.</strong> You'll notice that they all have the same alignment relative to the page.</p>
</li>
<li><p><strong>In the second two tests, the arrays are packed together to break that alignment.</strong> Here you'll notice both loops are faster. Furthermore, the second (double) loop is now the slower one as you would normally expect.</p>
</li>
</ul>
<p>As @Stephen Cannon points out in the comments, there is a very likely possibility that this alignment causes <em><strong>false aliasing</strong></em> in the load/store units or the cache. I Googled around for this and found that Intel actually has a hardware counter for <em><strong>partial address aliasing</strong></em> stalls:</p>
<p><a href="http://software.intel.com/sites/products/documentation/doclib/stdxe/2013/%7Eamplifierxe/pmw_dp/events/partial_address_alias.html" rel="noreferrer">http://software.intel.com/sites/products/documentation/doclib/stdxe/2013/~amplifierxe/pmw_dp/events/partial_address_alias.html</a></p>
<hr />
<h1>5 Regions - Explanations</h1>
<p><strong>Region 1:</strong></p>
<p>This one is easy. The dataset is so small that the performance is dominated by overhead like looping and branching.</p>
<p><strong>Region 2:</strong></p>
<p><strike>Here, as the data sizes increase, the amount of relative overhead goes down and the performance "saturates". Here two loops is slower because it has twice as much loop and branching overhead.</strike></p>
<p>I'm not sure exactly what's going on here... Alignment could still play an effect as Agner Fog mentions <a href="http://www.agner.org/optimize/blog/read.php?i=142" rel="noreferrer">cache bank conflicts</a>. (That link is about Sandy Bridge, but the idea should still be applicable to Core 2.)</p>
<p><strong>Region 3:</strong></p>
<p>At this point, the data no longer fits in the L1 cache. So performance is capped by the L1 <-> L2 cache bandwidth.</p>
<p><strong>Region 4:</strong></p>
<p>The performance drop in the single-loop is what we are observing. And as mentioned, this is due to the alignment which (most likely) causes <em><strong>false aliasing</strong></em> stalls in the processor load/store units.</p>
<p>However, in order for false aliasing to occur, there must be a large enough stride between the datasets. This is why you don't see this in region 3.</p>
<p><strong>Region 5:</strong></p>
<p>At this point, nothing fits in the cache. So you're bound by memory bandwidth.</p>
<hr />
<p><img src="https://i.stack.imgur.com/ElCGL.png" alt="2 x Intel X5482 Harpertown @ 3.2 GHz" />
<img src="https://i.stack.imgur.com/QMpwj.png" alt="Intel Core i7 870 @ 2.8 GHz" />
<img src="https://i.stack.imgur.com/NpyhG.png" alt="Intel Core i7 2600K @ 4.4 GHz" /></p> | {
"question_id": 8547778,
"question_date": "2011-12-17T20:40:52.030Z",
"question_score": 2402,
"tags": "c++|performance|x86|vectorization|compiler-optimization",
"answer_id": 8547993,
"answer_date": "2011-12-17T21:17:37.143Z",
"answer_score": 1771
} |
Please answer the following Stack Overflow question:
Title: How do I chop/slice/trim off last character in string using Javascript?
<p>I have a string, <code>12345.00</code>, and I would like it to return <code>12345.0</code>.</p>
<p>I have looked at <code>trim</code>, but it looks like it is only trimming whitespace and <code>slice</code> which I don't see how this would work. Any suggestions?</p> | <p>You can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring" rel="noreferrer">substring</a> function:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let str = "12345.00";
str = str.substring(0, str.length - 1);
console.log(str);</code></pre>
</div>
</div>
</p>
<p>This is the accepted answer, but as per the conversations below, the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice" rel="noreferrer">slice</a> syntax is much clearer:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let str = "12345.00";
str = str.slice(0, -1);
console.log(str);</code></pre>
</div>
</div>
</p> | {
"question_id": 952924,
"question_date": "2009-06-04T20:31:53.540Z",
"question_score": 2401,
"tags": "javascript|slice|trim",
"answer_id": 952945,
"answer_date": "2009-06-04T20:35:48.930Z",
"answer_score": 3768
} |
Please answer the following Stack Overflow question:
Title: Generating random whole numbers in JavaScript in a specific range
<p>How can I generate random whole numbers between two specified variables in JavaScript, e.g. <code>x = 4</code> and <code>y = 8</code> would output any of <code>4, 5, 6, 7, 8</code>?</p> | <p>There are some examples on the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random" rel="noreferrer">Mozilla Developer Network</a> page:</p>
<pre><code>/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
/**
* Returns a random integer between min (inclusive) and max (inclusive).
* The value is no lower than min (or the next integer greater than min
* if min isn't an integer) and no greater than max (or the next integer
* lower than max if max isn't an integer).
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
</code></pre>
<hr>
<p>Here's the logic behind it. It's a simple rule of three:</p>
<p><code>Math.random()</code> returns a <code>Number</code> between 0 (inclusive) and 1 (exclusive). So we have an interval like this:</p>
<pre><code>[0 .................................... 1)
</code></pre>
<p>Now, we'd like a number between <code>min</code> (inclusive) and <code>max</code> (exclusive):</p>
<pre><code>[0 .................................... 1)
[min .................................. max)
</code></pre>
<p>We can use the <code>Math.random</code> to get the correspondent in the [min, max) interval. But, first we should factor a little bit the problem by subtracting <code>min</code> from the second interval:</p>
<pre><code>[0 .................................... 1)
[min - min ............................ max - min)
</code></pre>
<p>This gives:</p>
<pre><code>[0 .................................... 1)
[0 .................................... max - min)
</code></pre>
<p>We may now apply <code>Math.random</code> and then calculate the correspondent. Let's choose a random number:</p>
<pre><code> Math.random()
|
[0 .................................... 1)
[0 .................................... max - min)
|
x (what we need)
</code></pre>
<p>So, in order to find <code>x</code>, we would do:</p>
<pre><code>x = Math.random() * (max - min);
</code></pre>
<p>Don't forget to add <code>min</code> back, so that we get a number in the [min, max) interval:</p>
<pre><code>x = Math.random() * (max - min) + min;
</code></pre>
<p>That was the first function from MDN. The second one, returns an integer between <code>min</code> and <code>max</code>, both inclusive.</p>
<p>Now for getting integers, you could use <code>round</code>, <code>ceil</code> or <code>floor</code>.</p>
<p>You could use <code>Math.round(Math.random() * (max - min)) + min</code>, this however gives a non-even distribution. Both, <code>min</code> and <code>max</code> only have approximately half the chance to roll:</p>
<pre><code>min...min+0.5...min+1...min+1.5 ... max-0.5....max
└───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘ ← Math.round()
min min+1 max
</code></pre>
<p>With <code>max</code> excluded from the interval, it has an even less chance to roll than <code>min</code>.</p>
<p>With <code>Math.floor(Math.random() * (max - min +1)) + min</code> you have a perfectly even distribution.</p>
<pre><code>min.... min+1... min+2 ... max-1... max.... max+1 (is excluded from interval)
| | | | | |
└───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘ ← Math.floor()
min min+1 max-1 max
</code></pre>
<p>You can't use <code>ceil()</code> and <code>-1</code> in that equation because <code>max</code> now had a slightly less chance to roll, but you can roll the (unwanted) <code>min-1</code> result too.</p> | {
"question_id": 1527803,
"question_date": "2009-10-06T20:05:41.100Z",
"question_score": 2388,
"tags": "javascript|random|integer",
"answer_id": 1527820,
"answer_date": "2009-10-06T20:08:19.847Z",
"answer_score": 4602
} |
Please answer the following Stack Overflow question:
Title: How do I delete a file from a Git repository?
<p>How can I delete <code>"file1.txt"</code> from my repository?</p> | <p>Use <a href="https://git-scm.com/docs/git-rm" rel="noreferrer"><code>git rm</code></a>.</p>
<p>If you want to remove the file from the Git repository <strong>and the filesystem</strong>, use:</p>
<pre class="lang-sh prettyprint-override"><code>git rm file1.txt
git commit -m "remove file1.txt"
</code></pre>
<p>But if you want to remove the file only from the Git repository and not remove it from the filesystem, use: </p>
<pre class="lang-sh prettyprint-override"><code>git rm --cached file1.txt
git commit -m "remove file1.txt"
</code></pre>
<p>And to push changes to remote repo</p>
<pre class="lang-sh prettyprint-override"><code>git push origin branch_name
</code></pre> | {
"question_id": 2047465,
"question_date": "2010-01-12T07:48:52.400Z",
"question_score": 2384,
"tags": "git|git-rm",
"answer_id": 2047477,
"answer_date": "2010-01-12T07:52:32.037Z",
"answer_score": 3962
} |
Please answer the following Stack Overflow question:
Title: What is JSONP, and why was it created?
<p>I understand JSON, but not JSONP. <a href="http://en.wikipedia.org/wiki/JSON" rel="noreferrer">Wikipedia's document on JSON</a> is (was) the top search result for JSONP. It says this:</p>
<blockquote>
<p>JSONP or "JSON with padding" is a JSON extension wherein a prefix is specified as an input argument of the call itself.</p>
</blockquote>
<p>Huh? What call? That doesn't make any sense to me. JSON is a data format. There's no call.</p>
<p>The <a href="http://remysharp.com/2007/10/08/what-is-jsonp/" rel="noreferrer">2nd search result</a> is from some guy named <a href="https://stackoverflow.com/users/22617/remy-sharp">Remy</a>, who writes this about JSONP:</p>
<blockquote>
<p>JSONP is script tag injection, passing the response from the server in to a user specified function.</p>
</blockquote>
<p>I can sort of understand that, but it's still not making any sense.</p>
<hr>
<p>So what is JSONP? Why was it created (what problem does it solve)? And why would I use it? </p>
<hr>
<p><strong>Addendum</strong>: I've just created <a href="http://en.wikipedia.org/wiki/JSONP" rel="noreferrer">a new page for JSONP</a> on Wikipedia; it now has a clear and thorough description of JSONP, based on <a href="https://stackoverflow.com/users/25330/jvenema">jvenema</a>'s answer.</p> | <p>It's actually not too complicated...</p>
<p>Say you're on domain <strong><code>example.com</code></strong>, and you want to make a request to domain <strong><code>example.net</code></strong>. To do so, you need to <strong>cross domain</strong> boundaries, a <strong>no-no</strong> in most of browserland. </p>
<p>The one item that bypasses this limitation is <code><script></code> tags. When you use a script tag, the domain limitation is ignored, but under normal circumstances, you can't really <strong>do</strong> anything with the results, the script just gets evaluated.</p>
<p>Enter <strong><code>JSONP</code></strong>. When you make your request to a server that is JSONP enabled, you pass a special parameter that tells the server a little bit about your page. That way, the server is able to nicely wrap up its response in a way that your page can handle. </p>
<p>For example, say the server expects a parameter called <strong><code>callback</code></strong> to enable its JSONP capabilities. Then your request would look like:</p>
<pre class="lang-none prettyprint-override"><code>http://www.example.net/sample.aspx?callback=mycallback
</code></pre>
<p>Without JSONP, this might return some basic JavaScript object, like so:</p>
<pre><code>{ foo: 'bar' }
</code></pre>
<p>However, with JSONP, when the server receives the "callback" parameter, it wraps up the result a little differently, returning something like this:</p>
<pre><code>mycallback({ foo: 'bar' });
</code></pre>
<p>As you can see, it will now invoke the method you specified. So, in your page, you define the callback function:</p>
<pre><code>mycallback = function(data){
alert(data.foo);
};
</code></pre>
<p>And now, when the script is loaded, it'll be evaluated, and your function will be executed. Voila, cross-domain requests!</p>
<p>It's also worth noting the one major issue with JSONP: you lose a lot of control of the request. For example, there is no "nice" way to get proper failure codes back. As a result, you end up using timers to monitor the request, etc, which is always a bit suspect. The proposition for <a href="http://www.json.org/JSONRequest.html" rel="noreferrer">JSONRequest</a> is a great solution to allowing cross domain scripting, maintaining security, and allowing proper control of the request.</p>
<p>These days (2015), <a href="http://en.wikipedia.org/wiki/Cross-origin_resource_sharing" rel="noreferrer">CORS</a> is the recommended approach vs. JSONRequest. JSONP is still useful for older browser support, but given the security implications, unless you have no choice CORS is the better choice.</p> | {
"question_id": 2067472,
"question_date": "2010-01-14T20:53:48.287Z",
"question_score": 2376,
"tags": "javascript|json|jsonp|terminology",
"answer_id": 2067584,
"answer_date": "2010-01-14T21:08:08.090Z",
"answer_score": 2237
} |
Please answer the following Stack Overflow question:
Title: How to get the children of the $(this) selector?
<p>I have a layout similar to this:</p>
<pre><code><div id="..."><img src="..."></div>
</code></pre>
<p>and would like to use a jQuery selector to select the child <code>img</code> inside the <code>div</code> on click.</p>
<p>To get the <code>div</code>, I've got this selector:</p>
<pre><code>$(this)
</code></pre>
<p>How can I get the child <code>img</code> using a selector?</p> | <p>The jQuery constructor accepts a 2nd parameter called <a href="http://api.jquery.com/jQuery/#jQuery-selector-context" rel="noreferrer"><code>context</code></a> which can be used to override the context of the selection. </p>
<pre><code>jQuery("img", this);
</code></pre>
<p>Which is the same as using <a href="http://api.jquery.com/find" rel="noreferrer"><code>.find()</code></a> like this:</p>
<pre><code>jQuery(this).find("img");
</code></pre>
<p>If the imgs you desire are <strong>only</strong> direct descendants of the clicked element, you can also use <a href="http://api.jquery.com/children" rel="noreferrer"><code>.children()</code></a>:</p>
<pre><code>jQuery(this).children("img");
</code></pre> | {
"question_id": 306583,
"question_date": "2008-11-20T19:44:05.733Z",
"question_score": 2368,
"tags": "javascript|jquery|jquery-selectors",
"answer_id": 306904,
"answer_date": "2008-11-20T21:27:29.097Z",
"answer_score": 2955
} |
Please answer the following Stack Overflow question:
Title: Branch from a previous commit using Git
<p>If I have <code>N</code> commits, how do I branch from the <code>N-3</code> commit?</p> | <p>Create the branch using a commit hash:</p>
<pre><code>git branch branch_name <commit-hash>
</code></pre>
<p>Or by using a symbolic reference:</p>
<pre><code>git branch branch_name HEAD~3
</code></pre>
<p>To checkout the branch while creating it, use:</p>
<pre><code>git checkout -b branch_name <commit-hash or HEAD~3>
</code></pre> | {
"question_id": 2816715,
"question_date": "2010-05-12T07:21:55.753Z",
"question_score": 2365,
"tags": "git|branch|git-branch",
"answer_id": 2816728,
"answer_date": "2010-05-12T07:24:18.973Z",
"answer_score": 3340
} |
Please answer the following Stack Overflow question:
Title: Make .gitignore ignore everything except a few files
<p>I understand that a <code>.gitignore</code> file cloaks specified files from Git's version control.</p>
<p>How do I tell <code>.gitignore</code> to ignore everything except the files I'm tracking with Git? Something like:</p>
<pre class="lang-bash prettyprint-override"><code># Ignore everything:
*
# Do not ignore these files:
script.pl
template.latex
</code></pre> | <blockquote>
<p>An optional prefix <code>!</code> which negates the pattern; any matching file excluded by
a previous pattern will become included again. If a negated pattern matches,
this will override lower precedence patterns sources.</p>
</blockquote>
<pre class="lang-sh prettyprint-override"><code># Ignore everything
*
# But not these files...
!.gitignore
!script.pl
!template.latex
# etc...
# ...even if they are in subdirectories
!*/
# if the files to be tracked are in subdirectories
!*/a/b/file1.txt
!*/a/b/c/*
</code></pre> | {
"question_id": 987142,
"question_date": "2009-06-12T15:04:49.263Z",
"question_score": 2364,
"tags": "git|gitignore",
"answer_id": 987162,
"answer_date": "2009-06-12T15:07:38.680Z",
"answer_score": 3217
} |
Please answer the following Stack Overflow question:
Title: What's the difference between SCSS and Sass?
<p>From what I've been reading, Sass is a language that makes CSS more powerful with variable and math support. </p>
<p>What's the difference with SCSS? Is it supposed to be the same language? Similar? Different?</p> | <p>Sass is a CSS pre-processor with syntax advancements. Style sheets in the advanced syntax are processed by the program, and turned into regular CSS style sheets. However, they do <strong>not</strong> extend the CSS standard itself.</p>
<p>CSS variables are supported and can be utilized but not as well as pre-processor variables.</p>
<p>For the difference between SCSS and Sass, this text on the <a href="http://sass-lang.com/documentation/file.SASS_REFERENCE.html#syntax" rel="noreferrer">Sass documentation page</a> should answer the question:</p>
<blockquote>
<p>There are two syntaxes available for Sass. The first, known as <strong><code>SCSS (Sassy CSS)</code></strong> and used throughout this reference, is an <strong>extension of the syntax of CSS</strong>. This means that every valid CSS stylesheet is a valid SCSS file with the same meaning. This syntax is enhanced with the Sass features described below. Files using this syntax have the <strong>.scss</strong> extension.</p>
<p>The second and <strong>older syntax</strong>, known as the <strong><code>indented syntax (or sometimes just “Sass”)</code></strong>, provides a more concise way of writing CSS. It <strong>uses indentation rather than brackets</strong> to indicate nesting of selectors, and <strong>newlines rather than semicolons</strong> to separate properties. Files using this syntax have the <strong>.sass</strong> extension.</p>
</blockquote>
<p>However, <strong>all this works only with the Sass pre-compiler</strong> which in the end creates CSS. It is not an extension to the CSS standard itself.</p> | {
"question_id": 5654447,
"question_date": "2011-04-13T19:23:09.870Z",
"question_score": 2361,
"tags": "css|sass",
"answer_id": 5654471,
"answer_date": "2011-04-13T19:25:21.477Z",
"answer_score": 2247
} |
Please answer the following Stack Overflow question:
Title: How can I guarantee that my enums definition doesn't change in JavaScript?
<p>Would the following make the objects fulfil all characteristics that enums have in JavaScript? Something like:</p>
<pre class="lang-js prettyprint-override"><code>my.namespace.ColorEnum = {
RED : 0,
GREEN : 1,
BLUE : 2
}
// later on
if(currentColor == my.namespace.ColorEnum.RED) {
// whatever
}
</code></pre>
<p>Or is there some other way I can do this?</p> | <p>Since 1.8.5 it's possible to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze" rel="noreferrer">seal and freeze the object</a>, so define the above as:</p>
<pre><code>const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})
</code></pre>
<p>or</p>
<pre><code>const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
Object.freeze(DaysEnum)
</code></pre>
<p>and voila! JS enums.</p>
<p>However, this doesn't prevent you from assigning an undesired value to a variable, which is often the main goal of enums:</p>
<pre><code>let day = DaysEnum.tuesday
day = 298832342 // goes through without any errors
</code></pre>
<p>One way to ensure a stronger degree of type safety (with enums or otherwise) is to use a tool like <a href="https://www.typescriptlang.org/" rel="noreferrer">TypeScript</a> or <a href="https://flow.org/" rel="noreferrer">Flow</a>.</p>
<p>Quotes aren't needed but I kept them for consistency.</p> | {
"question_id": 287903,
"question_date": "2008-11-13T19:09:06.620Z",
"question_score": 2360,
"tags": "javascript",
"answer_id": 5040502,
"answer_date": "2011-02-18T11:03:56.883Z",
"answer_score": 1183
} |
Please answer the following Stack Overflow question:
Title: Get the size of the screen, current web page and browser window
<p>How can I get <code>windowWidth</code>, <code>windowHeight</code>, <code>pageWidth</code>, <code>pageHeight</code>, <code>screenWidth</code>, <code>screenHeight</code>, <code>pageX</code>, <code>pageY</code>, <code>screenX</code>, <code>screenY</code> which will work in all major browsers?</p>
<p><img src="https://i.stack.imgur.com/6xPdH.png" alt="screenshot describing which values are wanted"></p> | <p>You can get the size of the window or document with jQuery:</p>
<pre><code>// Size of browser viewport.
$(window).height();
$(window).width();
// Size of HTML document (same as pageHeight/pageWidth in screenshot).
$(document).height();
$(document).width();
</code></pre>
<p>For screen size you can use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/screen" rel="noreferrer"><code>screen</code></a> object:</p>
<pre><code>window.screen.height;
window.screen.width;
</code></pre> | {
"question_id": 3437786,
"question_date": "2010-08-09T06:28:58.150Z",
"question_score": 2350,
"tags": "javascript|html|jquery|layout|cross-browser",
"answer_id": 3437825,
"answer_date": "2010-08-09T06:39:23.750Z",
"answer_score": 1614
} |
Please answer the following Stack Overflow question:
Title: Pull latest changes for all git submodules
<p>We're using git submodules to manage a couple of large projects that have dependencies on many other libraries we've developed. Each library is a separate repo brought into the dependent project as a submodule. During development, we often want to just go grab the latest version of every dependent submodule.</p>
<p>How do I pull the latest changes for all git submodules?</p> | <p>If it's <strong>the first time</strong> you check-out a repo you need to use <code>--init</code> first:</p>
<pre><code>git submodule update --init --recursive
</code></pre>
<p>For <strong>git 1.8.2</strong> or above, the option <code>--remote</code> was added to support updating to latest tips of remote branches:</p>
<pre><code>git submodule update --recursive --remote
</code></pre>
<p>This has the added benefit of respecting any "non default" branches specified in the <code>.gitmodules</code> or <code>.git/config</code> files (if you happen to have any, default is origin/master, in which case some of the other answers here would work as well).</p>
<p>For <strong>git 1.7.3</strong> or above you can use (but the below gotchas around what update does still apply):</p>
<pre><code>git submodule update --recursive
</code></pre>
<p>or:</p>
<pre><code>git pull --recurse-submodules
</code></pre>
<p>if you want to pull your submodules to latest commits instead of the current commit the repo points to.</p>
<p>See <a href="https://www.kernel.org/pub/software/scm/git/docs/git-submodule.html" rel="noreferrer">git-submodule(1)</a> for details</p> | {
"question_id": 1030169,
"question_date": "2009-06-23T01:05:54.157Z",
"question_score": 2350,
"tags": "git|git-submodules",
"answer_id": 1032653,
"answer_date": "2009-06-23T13:42:29.057Z",
"answer_score": 3234
} |
Please answer the following Stack Overflow question:
Title: Difference between decimal, float and double in .NET?
<p>What is the difference between <code>decimal</code>, <code>float</code> and <code>double</code> in .NET?</p>
<p>When would someone use one of these?</p> | <p><code>float</code> and <code>double</code> are <a href="http://csharpindepth.com/Articles/General/FloatingPoint.aspx" rel="noreferrer">floating <em>binary</em> point types</a> (<code>float</code> is 32-bit; <code>double</code> is 64-bit). In other words, they represent a number like this:</p>
<pre><code>10001.10010110011
</code></pre>
<p>The binary number and the location of the binary point are both encoded within the value.</p>
<p><code>decimal</code> is a <a href="http://csharpindepth.com/Articles/General/Decimal.aspx" rel="noreferrer">floating <em>decimal</em> point type</a>. In other words, they represent a number like this:</p>
<pre><code>12345.65789
</code></pre>
<p>Again, the number and the location of the <em>decimal</em> point are both encoded within the value – that's what makes <code>decimal</code> still a floating point type instead of a fixed point type.</p>
<p>The important thing to note is that humans are used to representing non-integers in a decimal form, and expect exact results in decimal representations; not all decimal numbers are exactly representable in binary floating point – 0.1, for example – so if you use a binary floating point value you'll actually get an approximation to 0.1. You'll still get approximations when using a floating decimal point as well – the result of dividing 1 by 3 can't be exactly represented, for example.</p>
<p>As for what to use when:</p>
<ul>
<li><p>For values which are "naturally exact decimals" it's good to use <code>decimal</code>. This is usually suitable for any concepts invented by humans: financial values are the most obvious example, but there are others too. Consider the score given to divers or ice skaters, for example.</p>
</li>
<li><p>For values which are more artefacts of nature which can't really be measured <em>exactly</em> anyway, <code>float</code>/<code>double</code> are more appropriate. For example, scientific data would usually be represented in this form. Here, the original values won't be "decimally accurate" to start with, so it's not important for the expected results to maintain the "decimal accuracy". Floating binary point types are much faster to work with than decimals.</p>
</li>
</ul> | {
"question_id": 618535,
"question_date": "2009-03-06T11:31:23.103Z",
"question_score": 2345,
"tags": ".net|floating-point|double|decimal",
"answer_id": 618596,
"answer_date": "2009-03-06T11:56:02.670Z",
"answer_score": 2503
} |
Please answer the following Stack Overflow question:
Title: Generate random number between two numbers in JavaScript
<p>Is there a way to generate a <em>random number</em> in a <em>specified range</em> with JavaScript ?</p>
<p><strong>For example</strong>: a specified range from <em>1 to 6</em> were the random number could be either <em>1, 2, 3, 4, 5, or 6</em>.</p> | <h3>Important</h3>
The following code works only if the minimum value is `1`. It does not work for minimum values other than `1`.
<p>If you wanted to get a random integer between 1 (<strong>and only 1</strong>) and 6, you would calculate:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> const rndInt = Math.floor(Math.random() * 6) + 1
console.log(rndInt)</code></pre>
</div>
</div>
</p>
<p>Where:</p>
<ul>
<li>1 is the start number</li>
<li>6 is the number of possible results (1 + start <em>(6)</em> - end <em>(1)</em>)</li>
</ul> | {
"question_id": 4959975,
"question_date": "2011-02-10T16:41:22.923Z",
"question_score": 2342,
"tags": "javascript|random",
"answer_id": 4960020,
"answer_date": "2011-02-10T16:45:25.073Z",
"answer_score": 2466
} |
Please answer the following Stack Overflow question:
Title: Indent multiple lines quickly in vi
<p>It should be trivial, and it might even be in the help, but I can't figure out how to navigate it. How do I indent multiple lines quickly in vi?</p> | <p>Use the <kbd>></kbd> command. To indent five lines, <kbd>5</kbd><kbd>></kbd><kbd>></kbd>. To mark a block of lines and indent it, <kbd>V</kbd><kbd>j</kbd><kbd>j</kbd><kbd>></kbd> to indent three lines (Vim only). To indent a curly-braces block, put your cursor on one of the curly braces and use <kbd>></kbd><kbd>%</kbd> or from anywhere inside block use <kbd>></kbd><kbd>i</kbd><kbd>B</kbd>.</p>
<p>If you’re copying blocks of text around and need to align the indent of a block in its new location, use <kbd>]</kbd><kbd>p</kbd> instead of just <kbd>p</kbd>. This aligns the pasted block with the surrounding text.</p>
<p>Also, the <a href="http://vimdoc.sourceforge.net/htmldoc/options.html#'shiftwidth'" rel="noreferrer"><code>shiftwidth</code></a> setting allows you to control how many spaces to indent.</p> | {
"question_id": 235839,
"question_date": "2008-10-25T03:27:28.013Z",
"question_score": 2341,
"tags": "vim|editor|indentation|vi",
"answer_id": 235841,
"answer_date": "2008-10-25T03:28:37.450Z",
"answer_score": 2769
} |
Please answer the following Stack Overflow question:
Title: $(document).ready equivalent without jQuery
<p>I have a script that uses <code>$(document).ready</code>, but it doesn't use anything else from jQuery. I'd like to lighten it up by removing the jQuery dependency.</p>
<p>How can I implement my own <code>$(document).ready</code> functionality without using jQuery? I know that using <code>window.onload</code> will not be the same, as <code>window.onload</code> fires after all images, frames, etc. have been loaded.</p> | <p>There is a standards based replacement,<code>DOMContentLoaded</code> that is supported by over <a href="http://caniuse.com/#search=DOMContentLoaded" rel="noreferrer">99% of browsers</a>, though not IE8:</p>
<pre><code>document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
</code></pre>
<p>jQuery's native function is much more complicated than just window.onload, as depicted below.</p>
<pre><code>function bindReady(){
if ( readyBound ) return;
readyBound = true;
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
jQuery.ready();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
jQuery.ready();
}
});
// If IE and not an iframe
// continually check to see if the document is ready
if ( document.documentElement.doScroll && window == window.top ) (function(){
if ( jQuery.isReady ) return;
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch( error ) {
setTimeout( arguments.callee, 0 );
return;
}
// and execute any waiting functions
jQuery.ready();
})();
}
// A fallback to window.onload, that will always work
jQuery.event.add( window, "load", jQuery.ready );
}
</code></pre> | {
"question_id": 799981,
"question_date": "2009-04-28T21:51:11.640Z",
"question_score": 2334,
"tags": "javascript|jquery|pageload",
"answer_id": 800010,
"answer_date": "2009-04-28T21:59:53.337Z",
"answer_score": 1766
} |
Please answer the following Stack Overflow question:
Title: How do I get a consistent byte representation of strings in C# without manually specifying an encoding?
<p>How do I convert a <code>string</code> to a <code>byte[]</code> in .NET (C#) without manually specifying a specific encoding?</p>
<p>I'm going to encrypt the string. I can encrypt it without converting, but I'd still like to know why encoding comes to play here.</p>
<p>Also, why should encoding even be taken into consideration? Can't I simply get what bytes the string has been stored in? Why is there a dependency on character encodings?</p> | <p><strong>Contrary to the answers here, you DON'T need to worry about encoding <em><strong>if</strong></em> the bytes don't need to be interpreted!</strong></p>
<p>Like you mentioned, your goal is, simply, to <em>"get what bytes the string has been stored in"</em>.<br />
(And, of course, to be able to re-construct the string from the bytes.)</p>
<p><strong>For those goals, I honestly do <em>not</em> understand why people keep telling you that you need the encodings. You certainly do NOT need to worry about encodings for this.</strong></p>
<p>Just do this instead:</p>
<pre><code>static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
// Do NOT use on arbitrary bytes; only use on GetBytes's output on the SAME system
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
</code></pre>
<p>As long as your program (or other programs) don't try to <em>interpret</em> the bytes somehow, which you obviously didn't mention you intend to do, then there is <strong>nothing</strong> wrong with this approach! Worrying about encodings just makes your life more complicated for no real reason.</p>
<p><strong>Additional benefit to this approach: It doesn't matter if the string contains invalid characters, because you can still get the data and reconstruct the original string anyway!</strong></p>
<p>It will be encoded and decoded just the same, because you are <em>just looking at the bytes</em>.</p>
<p>If you used a specific encoding, though, it would've given you trouble with encoding/decoding invalid characters.</p> | {
"question_id": 472906,
"question_date": "2009-01-23T13:39:54.407Z",
"question_score": 2331,
"tags": "c#|.net|string|character-encoding",
"answer_id": 10380166,
"answer_date": "2012-04-30T07:44:22.893Z",
"answer_score": 1927
} |
Please answer the following Stack Overflow question:
Title: Should 'using' directives be inside or outside the namespace?
<p>I have been running <a href="http://en.wikipedia.org/wiki/StyleCop" rel="noreferrer">StyleCop</a> over some C# code, and it keeps reporting that my <code>using</code> directives should be inside the namespace.</p>
<p>Is there a technical reason for putting the <code>using</code> directives inside instead of outside the namespace?</p> | <p>There is actually a (subtle) difference between the two. Imagine you have the following code in File1.cs:</p>
<pre><code>// File1.cs
using System;
namespace Outer.Inner
{
class Foo
{
static void Bar()
{
double d = Math.PI;
}
}
}
</code></pre>
<p>Now imagine that someone adds another file (File2.cs) to the project that looks like this:</p>
<pre><code>// File2.cs
namespace Outer
{
class Math
{
}
}
</code></pre>
<p>The compiler searches <code>Outer</code> before looking at those <code>using</code> directives outside the namespace, so it finds <code>Outer.Math</code> instead of <code>System.Math</code>. Unfortunately (or perhaps fortunately?), <code>Outer.Math</code> has no <code>PI</code> member, so File1 is now broken.</p>
<p>This changes if you put the <code>using</code> inside your namespace declaration, as follows:</p>
<pre><code>// File1b.cs
namespace Outer.Inner
{
using System;
class Foo
{
static void Bar()
{
double d = Math.PI;
}
}
}
</code></pre>
<p>Now the compiler searches <code>System</code> before searching <code>Outer</code>, finds <code>System.Math</code>, and all is well.</p>
<p>Some would argue that <code>Math</code> might be a bad name for a user-defined class, since there's already one in <code>System</code>; the point here is just that there <em>is</em> a difference, and it affects the maintainability of your code.</p>
<p>It's also interesting to note what happens if <code>Foo</code> is in namespace <code>Outer</code>, rather than <code>Outer.Inner</code>. In that case, adding <code>Outer.Math</code> in File2 breaks File1 regardless of where the <code>using</code> goes. This implies that the compiler searches the innermost enclosing namespace before it looks at any <code>using</code> directive.</p> | {
"question_id": 125319,
"question_date": "2008-09-24T03:49:50.173Z",
"question_score": 2329,
"tags": "c#|.net|namespaces|stylecop|code-organization",
"answer_id": 151560,
"answer_date": "2008-09-30T02:33:54.337Z",
"answer_score": 2337
} |
Please answer the following Stack Overflow question:
Title: How to format numbers as currency strings
<p>I would like to format a price in JavaScript. I'd like a function which takes a <code>float</code> as an argument and returns a <code>string</code> formatted like this:</p>
<pre><code>"$ 2,500.00"
</code></pre>
<p>How can I do this?</p> | <p>Ok, based on what you said, I'm using this:</p>
<pre><code>var DecimalSeparator = Number("1.2").toLocaleString().substr(1,1);
var AmountWithCommas = Amount.toLocaleString();
var arParts = String(AmountWithCommas).split(DecimalSeparator);
var intPart = arParts[0];
var decPart = (arParts.length > 1 ? arParts[1] : '');
decPart = (decPart + '00').substr(0,2);
return '£ ' + intPart + DecimalSeparator + decPart;
</code></pre>
<p>I'm open to improvement suggestions (I'd prefer not to include <a href="https://en.wikipedia.org/wiki/Yahoo!_UI_Library" rel="nofollow noreferrer">YUI</a> just to do this :-) )</p>
<p>I already know I should be detecting the "." instead of just using it as the decimal separator...</p> | {
"question_id": 149055,
"question_date": "2008-09-29T15:00:28.963Z",
"question_score": 2327,
"tags": "javascript|formatting|currency",
"answer_id": 149150,
"answer_date": "2008-09-29T15:22:33.140Z",
"answer_score": 30
} |
Please answer the following Stack Overflow question:
Title: What are MVP and MVC and what is the difference?
<p>When looking beyond the <a href="https://en.wikipedia.org/wiki/Rapid_application_development" rel="noreferrer">RAD</a> (drag-drop and configure) way of building user interfaces that many tools encourage you are likely to come across three design patterns called <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="noreferrer">Model-View-Controller</a>, <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter" rel="noreferrer">Model-View-Presenter</a> and <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel" rel="noreferrer">Model-View-ViewModel</a>. My question has three parts to it:</p>
<ol>
<li>What issues do these patterns address?</li>
<li>How are they similar?</li>
<li>How are they different?</li>
</ol> | <h2>Model-View-Presenter</h2>
<p>In <strong>MVP</strong>, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to the Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed.</p>
<p>MVP tends to be a very natural pattern for achieving separated presentation in WebForms. The reason is that the View is always created first by the ASP.NET runtime. You can <a href="https://web.archive.org/web/20071211153445/http://www.codeplex.com/websf/Wiki/View.aspx?title=MVPDocumentation" rel="noreferrer">find out more about both variants</a>.</p>
<h3>Two primary variations</h3>
<p><strong>Passive View:</strong> The View is as dumb as possible and contains almost zero logic. A Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead, the View exposes setter properties that the Presenter uses to set the data. All state is managed in the Presenter and not the View.</p>
<ul>
<li>Pro: maximum testability surface; clean separation of the View and Model</li>
<li>Con: more work (for example all the setter properties) as you are doing all the data binding yourself.</li>
</ul>
<p><strong>Supervising Controller:</strong> The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.</p>
<ul>
<li>Pro: by leveraging data binding the amount of code is reduced.</li>
<li>Con: there's a less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.</li>
</ul>
<h2>Model-View-Controller</h2>
<p>In the <strong>MVC</strong>, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web, each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application:</p>
<pre>
Action in the View
-> Call to Controller
-> Controller Logic
-> Controller returns the View.
</pre>
<p>One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called.</p>
<h2>Presentation Model</h2>
<p>One other pattern to look at is the <strong>Presentation Model</strong> pattern. In this pattern, there is no Presenter. Instead, the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behavior for the view. This pattern is a very strong candidate for use in WPF applications and is also called <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx" rel="noreferrer">Model-View-ViewModel</a>.</p>
<p>There is a <a href="http://msdn.microsoft.com/en-us/library/ff921080.aspx" rel="noreferrer">MSDN article about the Presentation Model</a> and a section in the <a href="http://msdn.microsoft.com/en-us/library/cc707819.aspx" rel="noreferrer">Composite Application Guidance for WPF</a> (former Prism) about <a href="http://msdn.microsoft.com/en-us/library/cc707862.aspx" rel="noreferrer">Separated Presentation Patterns</a></p> | {
"question_id": 2056,
"question_date": "2008-08-05T10:06:33.020Z",
"question_score": 2319,
"tags": "user-interface|model-view-controller|design-patterns|terminology|mvp",
"answer_id": 101561,
"answer_date": "2008-09-19T12:46:52.687Z",
"answer_score": 2109
} |
Please answer the following Stack Overflow question:
Title: JavaScript equivalent to printf/String.Format
<p>I'm looking for a good JavaScript equivalent of the C/PHP <code>printf()</code> or for C#/Java programmers, <code>String.Format()</code> (<code>IFormatProvider</code> for .NET).</p>
<p>My basic requirement is a thousand separator format for numbers for now, but something that handles lots of combinations (including dates) would be good.</p>
<p>I realize Microsoft's <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> library provides a version of <code>String.Format()</code>, but we don't want the entire overhead of that framework.</p> | <h2>Current JavaScript</h2>
<p>From ES6 on you could use template strings:</p>
<pre><code>let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!
</code></pre>
<p>See Kim's <a href="https://stackoverflow.com/a/32202320/2430448">answer</a> below for details.</p>
<hr />
<h2>Older answer</h2>
<p>Try <a href="https://github.com/alexei/sprintf.js" rel="noreferrer">sprintf() for JavaScript</a>.</p>
<hr />
<p>If you really want to do a simple format method on your own, don’t do the replacements successively but do them simultaneously.</p>
<p>Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:</p>
<pre><code>"{0}{1}".format("{1}", "{0}")
</code></pre>
<p>Normally you would expect the output to be <code>{1}{0}</code> but the actual output is <code>{1}{1}</code>. So do a simultaneously replacement instead like in <a href="https://stackoverflow.com/questions/610406/javascript-printf-string-format/4673436#4673436">fearphage’s suggestion</a>.</p> | {
"question_id": 610406,
"question_date": "2009-03-04T12:53:02.017Z",
"question_score": 2318,
"tags": "javascript|printf|string.format",
"answer_id": 610415,
"answer_date": "2009-03-04T12:55:22.293Z",
"answer_score": 1527
} |
Please answer the following Stack Overflow question:
Title: "implements Runnable" vs "extends Thread" in Java
<p>From what time I've spent with threads in <code>Java</code>, I've found these two ways to write threads:</p>
<p>With <strong>implements <code>Runnable</code>:</strong></p>
<pre><code>public class MyRunnable implements Runnable {
public void run() {
//Code
}
}
//Started with a "new Thread(new MyRunnable()).start()" call
</code></pre>
<p>Or, with <strong>extends <code>Thread</code>:</strong></p>
<pre><code>public class MyThread extends Thread {
public MyThread() {
super("MyThread");
}
public void run() {
//Code
}
}
//Started with a "new MyThread().start()" call
</code></pre>
<p>Is there any significant difference in these two blocks of code?</p> | <p>Yes: implements <code>Runnable</code> is the preferred way to do it, IMO. You're not really specialising the thread's behaviour. You're just giving it something to run. That means <a href="http://en.wikipedia.org/wiki/Object_composition" rel="noreferrer">composition</a> is the <em>philosophically</em> "purer" way to go.</p>
<p>In <em>practical</em> terms, it means you can implement <code>Runnable</code> and extend from another class as well... and you can also implement <code>Runnable</code> via a lambda expression as of Java 8.</p> | {
"question_id": 541487,
"question_date": "2009-02-12T14:28:46.393Z",
"question_score": 2309,
"tags": "java|multithreading|runnable|implements|java-threads",
"answer_id": 541506,
"answer_date": "2009-02-12T14:32:54.340Z",
"answer_score": 1793
} |
Please answer the following Stack Overflow question:
Title: How can I save username and password in Git?
<p>I want to use a push and pull automatically in <em><a href="http://gitextensions.github.io/" rel="noreferrer">Git Extensions</a></em>, <em><a href="https://en.wikipedia.org/wiki/Atlassian#Acquisitions_and_product_announcements" rel="noreferrer">Sourcetree</a></em> or any other Git GUI without entering my username and password in a prompt, every time.</p>
<p>So how can I save my credentials in Git?</p> | <p><strong>Attention</strong>: This method saves the credentials in <strong>plaintext</strong> on your PC's disk. Everyone on your computer can access it, e.g. malicious NPM modules.</p>
<p>Run</p>
<pre><code>git config --global credential.helper store
</code></pre>
<p>then</p>
<pre><code>git pull
</code></pre>
<p>provide a username and password and those details will then be remembered later. The credentials are stored in a file on the disk, with the disk permissions of "just user readable/writable" but still in plaintext.</p>
<p>If you want to change the password later</p>
<pre><code>git pull
</code></pre>
<p>Will fail, because the password is incorrect, git then removes the offending user+password from the <code>~/.git-credentials</code> file, so now re-run</p>
<pre><code>git pull
</code></pre>
<p>to provide a new password so it works as earlier.</p> | {
"question_id": 35942754,
"question_date": "2016-03-11T14:29:37.097Z",
"question_score": 2308,
"tags": "git|credentials|git-config|git-extensions",
"answer_id": 35942890,
"answer_date": "2016-03-11T14:36:13.797Z",
"answer_score": 3836
} |
Please answer the following Stack Overflow question:
Title: Vertically align text to top within a UILabel
<p>I have a <code>UILabel</code> with space for two lines of text. Sometimes, when the text is too short, this text is displayed in the vertical center of the label.</p>
<p>How do I vertically align the text to always be at the top of the <code>UILabel</code>?</p>
<p><img src="https://i.stack.imgur.com/TxzmG.jpg" alt="image representing a UILabel with vertically-centered text"></p> | <p>There's no way to set the vertical-align on a <code>UILabel</code>, but you can get the same effect by changing the label's frame. I've made my labels orange so you can see clearly what's happening.</p>
<p>Here's the quick and easy way to do this:</p>
<pre><code> [myLabel sizeToFit];
</code></pre>
<p><img src="https://i.stack.imgur.com/O7JEo.png" alt="sizeToFit to squeeze a label"></p>
<hr>
<p>If you have a label with longer text that will make more than one line, set <code>numberOfLines</code> to <code>0</code> (zero here means an unlimited number of lines).</p>
<pre><code> myLabel.numberOfLines = 0;
[myLabel sizeToFit];
</code></pre>
<p><img src="https://i.stack.imgur.com/08dRM.png" alt="Longer label text with sizeToFit"></p>
<hr>
<p><strong>Longer Version</strong></p>
<p>I'll make my label in code so that you can see what's going on. You can set up most of this in Interface Builder too. My setup is a View-Based App with a background image I made in Photoshop to show margins (20 points). The label is an attractive orange color so you can see what's going on with the dimensions.</p>
<pre><code>- (void)viewDidLoad
{
[super viewDidLoad];
// 20 point top and left margin. Sized to leave 20 pt at right.
CGRect labelFrame = CGRectMake(20, 20, 280, 150);
UILabel *myLabel = [[UILabel alloc] initWithFrame:labelFrame];
[myLabel setBackgroundColor:[UIColor orangeColor]];
NSString *labelText = @"I am the very model of a modern Major-General, I've information vegetable, animal, and mineral";
[myLabel setText:labelText];
// Tell the label to use an unlimited number of lines
[myLabel setNumberOfLines:0];
[myLabel sizeToFit];
[self.view addSubview:myLabel];
}
</code></pre>
<p>Some limitations of using <code>sizeToFit</code> come into play with center- or right-aligned text. Here's what happens:</p>
<pre><code> // myLabel.textAlignment = NSTextAlignmentRight;
myLabel.textAlignment = NSTextAlignmentCenter;
[myLabel setNumberOfLines:0];
[myLabel sizeToFit];
</code></pre>
<p><img src="https://i.stack.imgur.com/DH18q.png" alt="enter image description here"></p>
<p>The label is still sized with a fixed top-left corner. You can save the original label's width in a variable and set it after <code>sizeToFit</code>, or give it a fixed width to counter these problems:</p>
<pre><code> myLabel.textAlignment = NSTextAlignmentCenter;
[myLabel setNumberOfLines:0];
[myLabel sizeToFit];
CGRect myFrame = myLabel.frame;
// Resize the frame's width to 280 (320 - margins)
// width could also be myOriginalLabelFrame.size.width
myFrame = CGRectMake(myFrame.origin.x, myFrame.origin.y, 280, myFrame.size.height);
myLabel.frame = myFrame;
</code></pre>
<p><img src="https://i.stack.imgur.com/gedYP.png" alt="label alignment"></p>
<hr>
<p>Note that <code>sizeToFit</code> will respect your initial label's minimum width. If you start with a label 100 wide and call <code>sizeToFit</code> on it, it will give you back a (possibly very tall) label with 100 (or a little less) width. You might want to set your label to the minimum width you want before resizing.</p>
<p><img src="https://i.stack.imgur.com/RGI6v.png" alt="Correct label alignment by resizing the frame width"></p>
<p>Some other things to note:</p>
<p>Whether <code>lineBreakMode</code> is respected depends on how it's set. <code>NSLineBreakByTruncatingTail</code> (the default) is ignored after <code>sizeToFit</code>, as are the other two truncation modes (head and middle). <code>NSLineBreakByClipping</code> is also ignored. <code>NSLineBreakByCharWrapping</code> works as usual. The frame width is still narrowed to fit to the rightmost letter.</p>
<hr>
<p><strong><a href="https://stackoverflow.com/users/1709587/mark-amery">Mark Amery</a> gave a fix for NIBs and Storyboards using Auto Layout in the comments:</strong></p>
<blockquote>
<p>If your label is included in a nib or storyboard as a subview of the <code>view</code> of a ViewController that uses autolayout, then putting your <code>sizeToFit</code> call into <code>viewDidLoad</code> won't work, because autolayout sizes and positions the subviews after <code>viewDidLoad</code> is called and will immediately undo the effects of your <code>sizeToFit</code> call. However, calling <code>sizeToFit</code> from within <code>viewDidLayoutSubviews</code> <em>will</em> work.</p>
</blockquote>
<p><hr>
<strong>My Original Answer (for posterity/reference):</strong></p>
<p>This uses the <code>NSString</code> method <code>sizeWithFont:constrainedToSize:lineBreakMode:</code> to calculate the frame height needed to fit a string, then sets the origin and width.</p>
<p>Resize the frame for the label using the text you want to insert. That way you can accommodate any number of lines.</p>
<pre><code>CGSize maximumSize = CGSizeMake(300, 9999);
NSString *dateString = @"The date today is January 1st, 1999";
UIFont *dateFont = [UIFont fontWithName:@"Helvetica" size:14];
CGSize dateStringSize = [dateString sizeWithFont:dateFont
constrainedToSize:maximumSize
lineBreakMode:self.dateLabel.lineBreakMode];
CGRect dateFrame = CGRectMake(10, 10, 300, dateStringSize.height);
self.dateLabel.frame = dateFrame;
</code></pre> | {
"question_id": 1054558,
"question_date": "2009-06-28T08:54:03.973Z",
"question_score": 2307,
"tags": "ios|cocoa-touch|uikit|uilabel|text-alignment",
"answer_id": 1054681,
"answer_date": "2009-06-28T10:36:13.627Z",
"answer_score": 2759
} |
Please answer the following Stack Overflow question:
Title: How to print without a newline or space
<p>Example in C:</p>
<pre class="lang-cpp prettyprint-override"><code>for (int i = 0; i < 4; i++)
printf(".");
</code></pre>
<p>Output:</p>
<pre><code>....
</code></pre>
<p>In Python:</p>
<pre class="lang-py prettyprint-override"><code>>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
</code></pre>
<p>In Python, <code>print</code> will add a <code>\n</code> or space. How can I avoid that? I'd like to know how to "append" strings to <code>stdout</code>.</p> | <p>In Python 3, you can use the <code>sep=</code> and <code>end=</code> parameters of the <a href="https://docs.python.org/library/functions.html#print" rel="noreferrer"><code>print</code></a> function:</p>
<p>To not add a newline to the end of the string:</p>
<pre><code>print('.', end='')
</code></pre>
<p>To not add a space between all the function arguments you want to print:</p>
<pre><code>print('a', 'b', 'c', sep='')
</code></pre>
<p>You can pass any string to either parameter, and you can use both parameters at the same time.</p>
<p>If you are having trouble with buffering, you can flush the output by adding <code>flush=True</code> keyword argument:</p>
<pre><code>print('.', end='', flush=True)
</code></pre>
<h2>Python 2.6 and 2.7</h2>
<p>From Python 2.6 you can either import the <code>print</code> function from Python 3 using the <a href="https://docs.python.org/2/library/__future__.html" rel="noreferrer"><code>__future__</code> module</a>:</p>
<pre><code>from __future__ import print_function
</code></pre>
<p>which allows you to use the Python 3 solution above.</p>
<p>However, note that the <code>flush</code> keyword is not available in the version of the <code>print</code> function imported from <code>__future__</code> in Python 2; it only works in Python 3, more specifically 3.3 and later. In earlier versions you'll still need to flush manually with a call to <code>sys.stdout.flush()</code>. You'll also have to rewrite all other print statements in the file where you do this import.</p>
<p>Or you can use <a href="https://docs.python.org/library/sys.html#sys.stdout" rel="noreferrer"><code>sys.stdout.write()</code></a></p>
<pre><code>import sys
sys.stdout.write('.')
</code></pre>
<p>You may also need to call</p>
<pre><code>sys.stdout.flush()
</code></pre>
<p>to ensure <code>stdout</code> is flushed immediately.</p> | {
"question_id": 493386,
"question_date": "2009-01-29T20:58:25.520Z",
"question_score": 2302,
"tags": "python",
"answer_id": 493399,
"answer_date": "2009-01-29T21:01:43.513Z",
"answer_score": 3130
} |
Please answer the following Stack Overflow question:
Title: What is the purpose of .PHONY in a Makefile?
<p>What does <code>.PHONY</code> mean in a Makefile? I have gone through <a href="http://www.gnu.org/software/make/manual/make.html#Phony-Targets" rel="noreferrer">this</a>, but it is too complicated.</p>
<p>Can somebody explain it to me in simple terms?</p> | <p>By default, Makefile targets are "file targets" - they are used to build files from other files. Make assumes its target is a file, and this makes writing Makefiles relatively easy:</p>
<pre><code>foo: bar
create_one_from_the_other foo bar
</code></pre>
<p>However, sometimes you want your Makefile to run commands that do not represent physical files in the file system. Good examples for this are the common targets "clean" and "all". Chances are this isn't the case, but you <em>may</em> potentially have a file named <code>clean</code> in your main directory. In such a case Make will be confused because by default the <code>clean</code> target would be associated with this file and Make will only run it when the file doesn't appear to be up-to-date with regards to its dependencies.</p>
<p>These special targets are called <em>phony</em> and you can explicitly tell Make they're not associated with files, e.g.:</p>
<pre><code>.PHONY: clean
clean:
rm -rf *.o
</code></pre>
<p>Now <code>make clean</code> will run as expected even if you do have a file named <code>clean</code>.</p>
<p>In terms of Make, a phony target is simply a target that is always out-of-date, so whenever you ask <code>make <phony_target></code>, it will run, independent from the state of the file system. Some common <code>make</code> targets that are often phony are: <code>all</code>, <code>install</code>, <code>clean</code>, <code>distclean</code>, <code>TAGS</code>, <code>info</code>, <code>check</code>.</p> | {
"question_id": 2145590,
"question_date": "2010-01-27T09:08:29.730Z",
"question_score": 2301,
"tags": "makefile|phony-target",
"answer_id": 2145605,
"answer_date": "2010-01-27T09:11:10.623Z",
"answer_score": 2606
} |
Please answer the following Stack Overflow question:
Title: What's the simplest way to print a Java array?
<p>In Java, arrays don't override <code>toString()</code>, so if you try to print one directly, you get the <code>className</code> + '@' + the hex of the <a href="https://en.wikipedia.org/wiki/Java_hashCode()" rel="noreferrer"><code>hashCode</code></a> of the array, as defined by <code>Object.toString()</code>:</p>
<pre><code>int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray); // prints something like '[I@3343c8b3'
</code></pre>
<p>But usually, we'd actually want something more like <code>[1, 2, 3, 4, 5]</code>. What's the simplest way of doing that? Here are some example inputs and outputs:</p>
<pre><code>// Array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};
//output: [1, 2, 3, 4, 5]
// Array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};
//output: [John, Mary, Bob]
</code></pre> | <p>Since Java 5 you can use <a href="https://docs.oracle.com/javase/9/docs/api/java/util/Arrays.html#toString-int:A-" rel="noreferrer"><code>Arrays.toString(arr)</code></a> or <a href="https://docs.oracle.com/javase/9/docs/api/java/util/Arrays.html#deepToString-java.lang.Object:A-" rel="noreferrer"><code>Arrays.deepToString(arr)</code></a> for arrays within arrays. Note that the <code>Object[]</code> version calls <code>.toString()</code> on each object in the array. The output is even decorated in the exact way you're asking.</p>
<p>Examples:</p>
<ul>
<li><h3>Simple Array:</h3>
<pre><code>String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));
</code></pre>
<p>Output:</p>
<pre><code>[John, Mary, Bob]
</code></pre>
</li>
<li><h3>Nested Array:</h3>
<pre><code>String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));
</code></pre>
<p>Output:</p>
<pre><code>[[John, Mary], [Alice, Bob]]
</code></pre>
</li>
<li><h3><code>double</code> Array:</h3>
<pre><code>double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
System.out.println(Arrays.toString(doubleArray));
</code></pre>
<p>Output:</p>
<pre><code>[7.0, 9.0, 5.0, 1.0, 3.0 ]
</code></pre>
</li>
<li><h3><code>int</code> Array:</h3>
<pre><code>int[] intArray = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(intArray));
</code></pre>
<p>Output:</p>
<pre><code>[7, 9, 5, 1, 3 ]
</code></pre>
</li>
</ul> | {
"question_id": 409784,
"question_date": "2009-01-03T20:39:39.440Z",
"question_score": 2300,
"tags": "java|arrays|printing",
"answer_id": 409795,
"answer_date": "2009-01-03T20:43:44.893Z",
"answer_score": 3067
} |
Please answer the following Stack Overflow question:
Title: How to replace a character by a newline in Vim
<p>I'm trying to replace each <code>,</code> in the current file by a new line:</p>
<pre><code>:%s/,/\n/g
</code></pre>
<p>But it inserts what looks like a <code>^@</code> instead of an actual newline. The file is not in DOS mode or anything.</p>
<p>What should I do?</p>
<p>If you are curious, like me, check the question <em><a href="https://stackoverflow.com/questions/71417/why-is-r-a-newline-for-vim">Why is \r a newline for Vim?</a></em> as well.</p> | <h2>Use <code>\r</code> instead of <code>\n</code>.</h2>
<p>Substituting by <code>\n</code> inserts a null character into the text. To get a newline, use <code>\r</code>. When <em>searching</em> for a newline, you’d still use <code>\n</code>, however. This asymmetry is due to the fact that <code>\n</code> and <code>\r</code> <a href="http://vim.wikia.com/wiki/Search_and_replace" rel="noreferrer">do slightly different things</a>:</p>
<p><code>\n</code> matches an end of line (newline), whereas <code>\r</code> matches a carriage return. On the other hand, in substitutions <code>\n</code> inserts a null character whereas <code>\r</code> inserts a newline (more precisely, it’s treated as the input <kbd>CR</kbd>). Here’s a small, non-interactive example to illustrate this, using the Vim command line feature (in other words, you can copy and paste the following into a terminal to run it). <code>xxd</code> shows a hexdump of the resulting file.</p>
<pre><code>echo bar > test
(echo 'Before:'; xxd test) > output.txt
vim test '+s/b/\n/' '+s/a/\r/' +wq
(echo 'After:'; xxd test) >> output.txt
more output.txt
</code></pre>
<pre><code>Before:
0000000: 6261 720a bar.
After:
0000000: 000a 720a ..r.
</code></pre>
<p>In other words, <code>\n</code> has inserted the byte 0x00 into the text; <code>\r</code> has inserted the byte 0x0a.</p> | {
"question_id": 71323,
"question_date": "2008-09-16T11:19:39.077Z",
"question_score": 2298,
"tags": "vim|replace|escaping|newline|vi",
"answer_id": 71334,
"answer_date": "2008-09-16T11:21:03.300Z",
"answer_score": 2972
} |
Please answer the following Stack Overflow question:
Title: Finding duplicate values in a SQL table
<p>It's easy to find duplicates with one field:</p>
<pre><code>SELECT email, COUNT(email)
FROM users
GROUP BY email
HAVING COUNT(email) > 1
</code></pre>
<p>So if we have a table</p>
<pre class="lang-none prettyprint-override"><code>ID NAME EMAIL
1 John [email protected]
2 Sam [email protected]
3 Tom [email protected]
4 Bob [email protected]
5 Tom [email protected]
</code></pre>
<p>This query will give us John, Sam, Tom, Tom because they all have the same <code>email</code>.</p>
<p>However, what I want is to get duplicates with the same <code>email</code> <strong>and</strong> <code>name</code>.</p>
<p>That is, I want to get "Tom", "Tom".</p>
<p>The reason I need this: I made a mistake, and allowed inserting duplicate <code>name</code> and <code>email</code> values. Now I need to remove/change the duplicates, so I need to <em>find</em> them first.</p> | <pre><code>SELECT
name, email, COUNT(*)
FROM
users
GROUP BY
name, email
HAVING
COUNT(*) > 1
</code></pre>
<p>Simply group on both of the columns.</p>
<p>Note: the older ANSI standard is to have all non-aggregated columns in the GROUP BY but this has changed with the idea of <a href="https://blog.jooq.org/2015/12/10/sql-group-by-and-functional-dependencies-a-very-useful-feature/" rel="noreferrer">"functional dependency"</a>:</p>
<blockquote>
<p>In relational database theory, a functional dependency is a constraint between two sets of attributes in a relation from a database. In other words, functional dependency is a constraint that describes the relationship between attributes in a relation.</p>
</blockquote>
<p>Support is not consistent:</p>
<ul>
<li>Recent PostgreSQL <a href="https://www.postgresql.org/docs/current/static/sql-select.html#SQL-GROUPBY" rel="noreferrer">supports it</a>.</li>
<li>SQL Server (as at SQL Server 2017) still requires all non-aggregated columns in the GROUP BY.</li>
<li>MySQL is unpredictable and you need <code>sql_mode=only_full_group_by</code>:
<ul>
<li><a href="https://stackoverflow.com/q/10894820/27535">GROUP BY lname ORDER BY showing wrong results</a>;</li>
<li><a href="https://stackoverflow.com/questions/6060241/which-is-the-least-expensive-aggregate-function-in-the-absence-of-any/6060414#6060414">Which is the least expensive aggregate function in the absence of ANY()</a> (see comments in accepted answer).</li>
</ul></li>
<li>Oracle isn't mainstream enough (warning: humour, I don't know about Oracle).</li>
</ul> | {
"question_id": 2594829,
"question_date": "2010-04-07T18:17:29.067Z",
"question_score": 2297,
"tags": "sql|duplicates",
"answer_id": 2594855,
"answer_date": "2010-04-07T18:20:18.513Z",
"answer_score": 3510
} |
Please answer the following Stack Overflow question:
Title: How do I generate a random integer in C#?
<p>How do I generate a random integer in C#?</p> | <p>The <a href="https://docs.microsoft.com/en-us/dotnet/api/system.random" rel="noreferrer"><code>Random</code> class</a> is used to create random numbers. (Pseudo-random that is of course.).</p>
<p>Example:</p>
<pre class="lang-cs prettyprint-override"><code>Random rnd = new Random();
int month = rnd.Next(1, 13); // creates a number between 1 and 12
int dice = rnd.Next(1, 7); // creates a number between 1 and 6
int card = rnd.Next(52); // creates a number between 0 and 51
</code></pre>
<p>If you are going to create more than one random number, you should keep the <code>Random</code> instance and reuse it. If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.</p> | {
"question_id": 2706500,
"question_date": "2010-04-24T23:09:11.523Z",
"question_score": 2293,
"tags": "c#|random",
"answer_id": 2706537,
"answer_date": "2010-04-24T23:19:07.210Z",
"answer_score": 2900
} |
Please answer the following Stack Overflow question:
Title: What does the ??!??! operator do in C?
<p>I saw a line of C that looked like this:</p>
<pre><code>!ErrorHasOccured() ??!??! HandleError();
</code></pre>
<p>It compiled correctly and seems to run ok. It seems like it's checking if an error has occurred, and if it has, it handles it. But I'm not really sure what it's actually doing or how it's doing it. It does look like the programmer is trying express their feelings about errors.</p>
<p>I have never seen the <code>??!??!</code> before in any programming language, and I can't find documentation for it anywhere. (Google doesn't help with search terms like <code>??!??!</code>). What does it do and how does the code sample work?</p> | <p><code>??!</code> is a <a href="https://en.wikipedia.org/wiki/Digraphs_and_trigraphs#C" rel="noreferrer">trigraph</a> that translates to <code>|</code>. So it says:</p>
<pre><code>!ErrorHasOccured() || HandleError();
</code></pre>
<p>which, due to short circuiting, is equivalent to:</p>
<pre><code>if (ErrorHasOccured())
HandleError();
</code></pre>
<p><a href="http://www.gotw.ca/gotw/086.htm" rel="noreferrer">Guru of the Week</a> (deals with C++ but relevant here), where I picked this up.</p>
<p><a href="https://web.archive.org/web/20170502193704/http://www.archivum.info/comp.std.c/2007-11/00083/Re-extended-operators.html" rel="noreferrer">Possible origin of trigraphs</a> or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). <a href="https://web.archive.org/web/20191226092436/https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014505842#77777777-0000-0000-0000-000014505849" rel="noreferrer">This</a> discussion on the IBM developerworks board seems to support that theory.</p>
<p>From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t <a href="https://stackoverflow.com/q/7825055#comment9538582_7825075">@Random832</a>):</p>
<blockquote>
<p>The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as
described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.</p>
</blockquote> | {
"question_id": 7825055,
"question_date": "2011-10-19T16:56:59.617Z",
"question_score": 2292,
"tags": "c|operators|trigraphs",
"answer_id": 7825075,
"answer_date": "2011-10-19T16:58:44.797Z",
"answer_score": 1813
} |
Please answer the following Stack Overflow question:
Title: Showing which files have changed between two revisions
<p>I want to merge two branches that have been separated for a while and wanted to know which files have been modified.</p>
<p>Came across this link: <a href="https://web.archive.org/web/20180830081303/http://linux.yyz.us/git-howto.html" rel="noreferrer">http://linux.yyz.us/git-howto.html</a> which was quite useful.</p>
<p>The tools to compare branches I've come across are:</p>
<ul>
<li><code>git diff master..branch</code></li>
<li><code>git log master..branch</code></li>
<li><code>git shortlog master..branch</code></li>
</ul>
<p>Was wondering if there's something like "git status master..branch" to only see those files that are different between the two branches.</p>
<p>Without creating a new tool, I think this is the closest you can get to do that now (which of course will show repeats if a file was modified more than once):</p>
<ul>
<li><code>git diff master..branch | grep "^diff"</code></li>
</ul>
<p>Was wondering if there's something I missed...</p> | <p>To compare the current branch against <code>main</code> branch:</p>
<pre><code>$ git diff --name-status main
</code></pre>
<p>To compare any two branches:</p>
<pre><code>$ git diff --name-status firstbranch..yourBranchName
</code></pre>
<p>There is more options to <code>git diff</code> in the <a href="https://git-scm.com/docs/git-diff" rel="noreferrer">official documentation</a> (and specifically <a href="https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---name-status" rel="noreferrer"><code>--name-status</code></a> option).</p> | {
"question_id": 822811,
"question_date": "2009-05-05T00:47:59.573Z",
"question_score": 2285,
"tags": "git|branch|git-branch|git-diff",
"answer_id": 822859,
"answer_date": "2009-05-05T01:04:38.473Z",
"answer_score": 2809
} |
Please answer the following Stack Overflow question:
Title: What is the copy-and-swap idiom?
<p>What is the copy-and-swap idiom and when should it be used? What problems does it solve? Does it change for C++11?</p>
<p>Related:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/276173/what-are-your-favorite-c-coding-style-idioms/2034447#2034447">What are your favorite C++ Coding Style idioms: Copy-swap</a></li>
<li><a href="https://stackoverflow.com/questions/1734628/copy-constructor-and-operator-overload-in-c-is-a-common-function-possible/1734640#1734640">Copy constructor and = operator overload in C++: is a common function possible?</a></li>
<li><a href="https://stackoverflow.com/questions/2143787/what-is-copy-elision-and-how-it-optimizes-copy-and-swap-idiom">What is copy elision and how it optimizes copy-and-swap idiom</a></li>
<li><a href="https://stackoverflow.com/questions/255612/c-dynamically-allocating-an-array-of-objects/255744#255744">C++: dynamically allocating an array of objects?</a></li>
</ul> | <h1>Overview</h1>
<h3>Why do we need the copy-and-swap idiom?</h3>
<p>Any class that manages a resource (a <em>wrapper</em>, like a smart pointer) needs to implement <a href="https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three">The Big Three</a>. While the goals and implementation of the copy-constructor and destructor are straightforward, the copy-assignment operator is arguably the most nuanced and difficult. How should it be done? What pitfalls need to be avoided?</p>
<p>The <em>copy-and-swap idiom</em> is the solution, and elegantly assists the assignment operator in achieving two things: avoiding <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="noreferrer">code duplication</a>, and providing a <a href="http://en.wikipedia.org/wiki/Exception_guarantees" rel="noreferrer">strong exception guarantee</a>.</p>
<h3>How does it work?</h3>
<p><a href="https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom/3279616#3279616">Conceptually</a>, it works by using the copy-constructor's functionality to create a local copy of the data, then takes the copied data with a <code>swap</code> function, swapping the old data with the new data. The temporary copy then destructs, taking the old data with it. We are left with a copy of the new data.</p>
<p>In order to use the copy-and-swap idiom, we need three things: a working copy-constructor, a working destructor (both are the basis of any wrapper, so should be complete anyway), and a <code>swap</code> function.</p>
<p>A swap function is a <em>non-throwing</em> function that swaps two objects of a class, member for member. We might be tempted to use <code>std::swap</code> instead of providing our own, but this would be impossible; <code>std::swap</code> uses the copy-constructor and copy-assignment operator within its implementation, and we'd ultimately be trying to define the assignment operator in terms of itself!</p>
<p>(Not only that, but unqualified calls to <code>swap</code> will use our custom swap operator, skipping over the unnecessary construction and destruction of our class that <code>std::swap</code> would entail.)</p>
<hr />
<h1>An in-depth explanation</h1>
<h3>The goal</h3>
<p>Let's consider a concrete case. We want to manage, in an otherwise useless class, a dynamic array. We start with a working constructor, copy-constructor, and destructor:</p>
<pre><code>#include <algorithm> // std::copy
#include <cstddef> // std::size_t
class dumb_array
{
public:
// (default) constructor
dumb_array(std::size_t size = 0)
: mSize(size),
mArray(mSize ? new int[mSize]() : nullptr)
{
}
// copy-constructor
dumb_array(const dumb_array& other)
: mSize(other.mSize),
mArray(mSize ? new int[mSize] : nullptr)
{
// note that this is non-throwing, because of the data
// types being used; more attention to detail with regards
// to exceptions must be given in a more general case, however
std::copy(other.mArray, other.mArray + mSize, mArray);
}
// destructor
~dumb_array()
{
delete [] mArray;
}
private:
std::size_t mSize;
int* mArray;
};
</code></pre>
<p>This class almost manages the array successfully, but it needs <code>operator=</code> to work correctly.</p>
<h3>A failed solution</h3>
<p>Here's how a naive implementation might look:</p>
<pre><code>// the hard part
dumb_array& operator=(const dumb_array& other)
{
if (this != &other) // (1)
{
// get rid of the old data...
delete [] mArray; // (2)
mArray = nullptr; // (2) *(see footnote for rationale)
// ...and put in the new
mSize = other.mSize; // (3)
mArray = mSize ? new int[mSize] : nullptr; // (3)
std::copy(other.mArray, other.mArray + mSize, mArray); // (3)
}
return *this;
}
</code></pre>
<p>And we say we're finished; this now manages an array, without leaks. However, it suffers from three problems, marked sequentially in the code as <code>(n)</code>.</p>
<ol>
<li><p>The first is the self-assignment test.<br />
This check serves two purposes: it's an easy way to prevent us from running needless code on self-assignment, and it protects us from subtle bugs (such as deleting the array only to try and copy it). But in all other cases it merely serves to slow the program down, and act as noise in the code; self-assignment rarely occurs, so most of the time this check is a waste.<br />
It would be better if the operator could work properly without it.</p>
</li>
<li><p>The second is that it only provides a basic exception guarantee. If <code>new int[mSize]</code> fails, <code>*this</code> will have been modified. (Namely, the size is wrong and the data is gone!)<br />
For a strong exception guarantee, it would need to be something akin to:</p>
<pre><code> dumb_array& operator=(const dumb_array& other)
{
if (this != &other) // (1)
{
// get the new data ready before we replace the old
std::size_t newSize = other.mSize;
int* newArray = newSize ? new int[newSize]() : nullptr; // (3)
std::copy(other.mArray, other.mArray + newSize, newArray); // (3)
// replace the old data (all are non-throwing)
delete [] mArray;
mSize = newSize;
mArray = newArray;
}
return *this;
}
</code></pre>
</li>
<li><p>The code has expanded! Which leads us to the third problem: code duplication.</p>
</li>
</ol>
<p>Our assignment operator effectively duplicates all the code we've already written elsewhere, and that's a terrible thing.</p>
<p>In our case, the core of it is only two lines (the allocation and the copy), but with more complex resources this code bloat can be quite a hassle. We should strive to never repeat ourselves.</p>
<p>(One might wonder: if this much code is needed to manage one resource correctly, what if my class manages more than one?<br />
While this may seem to be a valid concern, and indeed it requires non-trivial <code>try</code>/<code>catch</code> clauses, this is a non-issue.<br />
That's because a class should manage <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" rel="noreferrer"><em>one resource only</em></a>!)</p>
<h3>A successful solution</h3>
<p>As mentioned, the copy-and-swap idiom will fix all these issues. But right now, we have all the requirements except one: a <code>swap</code> function. While The Rule of Three successfully entails the existence of our copy-constructor, assignment operator, and destructor, it should really be called "The Big Three and A Half": any time your class manages a resource it also makes sense to provide a <code>swap</code> function.</p>
<p>We need to add swap functionality to our class, and we do that as follows†:</p>
<pre><code>class dumb_array
{
public:
// ...
friend void swap(dumb_array& first, dumb_array& second) // nothrow
{
// enable ADL (not necessary in our case, but good practice)
using std::swap;
// by swapping the members of two objects,
// the two objects are effectively swapped
swap(first.mSize, second.mSize);
swap(first.mArray, second.mArray);
}
// ...
};
</code></pre>
<p>(<a href="https://stackoverflow.com/questions/5695548/public-friend-swap-member-function">Here</a> is the explanation why <code>public friend swap</code>.) Now not only can we swap our <code>dumb_array</code>'s, but swaps in general can be more efficient; it merely swaps pointers and sizes, rather than allocating and copying entire arrays. Aside from this bonus in functionality and efficiency, we are now ready to implement the copy-and-swap idiom.</p>
<p>Without further ado, our assignment operator is:</p>
<pre><code>dumb_array& operator=(dumb_array other) // (1)
{
swap(*this, other); // (2)
return *this;
}
</code></pre>
<p>And that's it! With one fell swoop, all three problems are elegantly tackled at once.</p>
<h3>Why does it work?</h3>
<p>We first notice an important choice: the parameter argument is taken <em>by-value</em>. While one could just as easily do the following (and indeed, many naive implementations of the idiom do):</p>
<pre><code>dumb_array& operator=(const dumb_array& other)
{
dumb_array temp(other);
swap(*this, temp);
return *this;
}
</code></pre>
<p>We lose an <a href="https://web.archive.org/web/20140113221447/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/" rel="noreferrer">important optimization opportunity</a>. Not only that, but this choice is critical in C++11, which is discussed later. (On a general note, a remarkably useful guideline is as follows: if you're going to make a copy of something in a function, let the compiler do it in the parameter list.‡)</p>
<p>Either way, this method of obtaining our resource is the key to eliminating code duplication: we get to use the code from the copy-constructor to make the copy, and never need to repeat any bit of it. Now that the copy is made, we are ready to swap.</p>
<p>Observe that upon entering the function that all the new data is already allocated, copied, and ready to be used. This is what gives us a strong exception guarantee for free: we won't even enter the function if construction of the copy fails, and it's therefore not possible to alter the state of <code>*this</code>. (What we did manually before for a strong exception guarantee, the compiler is doing for us now; how kind.)</p>
<p>At this point we are home-free, because <code>swap</code> is non-throwing. We swap our current data with the copied data, safely altering our state, and the old data gets put into the temporary. The old data is then released when the function returns. (Where upon the parameter's scope ends and its destructor is called.)</p>
<p>Because the idiom repeats no code, we cannot introduce bugs within the operator. Note that this means we are rid of the need for a self-assignment check, allowing a single uniform implementation of <code>operator=</code>. (Additionally, we no longer have a performance penalty on non-self-assignments.)</p>
<p>And that is the copy-and-swap idiom.</p>
<h2>What about C++11?</h2>
<p>The next version of C++, C++11, makes one very important change to how we manage resources: the Rule of Three is now <strong>The Rule of Four</strong> (and a half). Why? Because not only do we need to be able to copy-construct our resource, <a href="https://stackoverflow.com/questions/3106110/can-someone-please-explain-move-semantics-to-me">we need to move-construct it as well</a>.</p>
<p>Luckily for us, this is easy:</p>
<pre><code>class dumb_array
{
public:
// ...
// move constructor
dumb_array(dumb_array&& other) noexcept ††
: dumb_array() // initialize via default constructor, C++11 only
{
swap(*this, other);
}
// ...
};
</code></pre>
<p>What's going on here? Recall the goal of move-construction: to take the resources from another instance of the class, leaving it in a state guaranteed to be assignable and destructible.</p>
<p>So what we've done is simple: initialize via the default constructor (a C++11 feature), then swap with <code>other</code>; we know a default constructed instance of our class can safely be assigned and destructed, so we know <code>other</code> will be able to do the same, after swapping.</p>
<p>(Note that some compilers do not support constructor delegation; in this case, we have to manually default construct the class. This is an unfortunate but luckily trivial task.)</p>
<h3>Why does that work?</h3>
<p>That is the only change we need to make to our class, so why does it work? Remember the ever-important decision we made to make the parameter a value and not a reference:</p>
<pre><code>dumb_array& operator=(dumb_array other); // (1)
</code></pre>
<p>Now, if <code>other</code> is being initialized with an rvalue, <em>it will be move-constructed</em>. Perfect. In the same way C++03 let us re-use our copy-constructor functionality by taking the argument by-value, C++11 will <em>automatically</em> pick the move-constructor when appropriate as well. (And, of course, as mentioned in previously linked article, the copying/moving of the value may simply be elided altogether.)</p>
<p>And so concludes the copy-and-swap idiom.</p>
<hr />
<h3>Footnotes</h3>
<p>*Why do we set <code>mArray</code> to null? Because if any further code in the operator throws, the destructor of <code>dumb_array</code> might be called; and if that happens without setting it to null, we attempt to delete memory that's already been deleted! We avoid this by setting it to null, as deleting null is a no-operation.</p>
<p>†There are other claims that we should specialize <code>std::swap</code> for our type, provide an in-class <code>swap</code> along-side a free-function <code>swap</code>, etc. But this is all unnecessary: any proper use of <code>swap</code> will be through an unqualified call, and our function will be found through <a href="http://en.wikipedia.org/wiki/Argument-dependent_name_lookup" rel="noreferrer">ADL</a>. One function will do.</p>
<p>‡The reason is simple: once you have the resource to yourself, you may swap and/or move it (C++11) anywhere it needs to be. And by making the copy in the parameter list, you maximize optimization.</p>
<p>††The move constructor should generally be <code>noexcept</code>, otherwise some code (e.g. <code>std::vector</code> resizing logic) will use the copy constructor even when a move would make sense. Of course, only mark it noexcept if the code inside doesn't throw exceptions.</p> | {
"question_id": 3279543,
"question_date": "2010-07-19T08:42:09.907Z",
"question_score": 2283,
"tags": "c++|copy-constructor|assignment-operator|c++-faq|copy-and-swap",
"answer_id": 3279550,
"answer_date": "2010-07-19T08:43:14.240Z",
"answer_score": 2464
} |
Please answer the following Stack Overflow question:
Title: How to get an enum value from a string value in Java
<p>Say I have an enum which is just</p>
<pre><code>public enum Blah {
A, B, C, D
}
</code></pre>
<p>and I would like to find the enum value of a string, for example <code>"A"</code> which would be <code>Blah.A</code>. How would it be possible to do this?</p>
<p>Is the <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Enum.html#valueOf(java.lang.Class,java.lang.String)" rel="noreferrer"><code>Enum.valueOf()</code></a> the method I need? If so, how would I use this?</p> | <p>Yes, <code>Blah.valueOf("A")</code> will give you <code>Blah.A</code>.</p>
<p>Note that the name must be an <em>exact</em> match, including case: <code>Blah.valueOf("a")</code> and <code>Blah.valueOf("A ")</code> both throw an <code>IllegalArgumentException</code>.</p>
<p>The static methods <code>valueOf()</code> and <code>values()</code> are created at compile time and do not appear in source code. They do appear in Javadoc, though; for example, <a href="http://docs.oracle.com/javase/7/docs/api/java/awt/Dialog.ModalityType.html" rel="noreferrer"><code>Dialog.ModalityType</code></a> shows both methods.</p> | {
"question_id": 604424,
"question_date": "2009-03-02T22:56:34.750Z",
"question_score": 2281,
"tags": "java|enums",
"answer_id": 604426,
"answer_date": "2009-03-02T22:57:44.217Z",
"answer_score": 2544
} |
Please answer the following Stack Overflow question:
Title: Calling a function of a module by using its name (a string)
<p>How do I call a function, using a string with the function's name? For example:</p>
<pre><code>import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
</code></pre> | <p>Given a module <code>foo</code> with method <code>bar</code>:</p>
<pre><code>import foo
bar = getattr(foo, 'bar')
result = bar()
</code></pre>
<p><a href="https://docs.python.org/library/functions.html#getattr" rel="noreferrer"><code>getattr</code></a> can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.</p> | {
"question_id": 3061,
"question_date": "2008-08-06T03:36:08.627Z",
"question_score": 2277,
"tags": "python|object|reflection",
"answer_id": 3071,
"answer_date": "2008-08-06T03:57:16.820Z",
"answer_score": 2727
} |
Please answer the following Stack Overflow question:
Title: How to concatenate text from multiple rows into a single text string in SQL Server
<p>Consider a database table holding names, with three rows:</p>
<pre><code>Peter
Paul
Mary
</code></pre>
<p>Is there an easy way to turn this into a single string of <code>Peter, Paul, Mary</code>?</p> | <p>If you are on SQL Server 2017 or Azure, see <a href="https://stackoverflow.com/a/42778050/1178676">Mathieu Renda answer</a>.</p>
<p>I had a similar issue when I was trying to join two tables with one-to-many relationships. In SQL 2005 I found that <code>XML PATH</code> method can handle the concatenation of the rows very easily.</p>
<p>If there is a table called <code>STUDENTS</code></p>
<pre><code>SubjectID StudentName
---------- -------------
1 Mary
1 John
1 Sam
2 Alaina
2 Edward
</code></pre>
<p>Result I expected was:</p>
<pre><code>SubjectID StudentName
---------- -------------
1 Mary, John, Sam
2 Alaina, Edward
</code></pre>
<p>I used the following <code>T-SQL</code>:</p>
<pre><code>SELECT Main.SubjectID,
LEFT(Main.Students,Len(Main.Students)-1) As "Students"
FROM
(
SELECT DISTINCT ST2.SubjectID,
(
SELECT ST1.StudentName + ',' AS [text()]
FROM dbo.Students ST1
WHERE ST1.SubjectID = ST2.SubjectID
ORDER BY ST1.SubjectID
FOR XML PATH (''), TYPE
).value('text()[1]','nvarchar(max)') [Students]
FROM dbo.Students ST2
) [Main]
</code></pre>
<p>You can do the same thing in a more compact way if you can concat the commas at the beginning and use <code>substring</code> to skip the first one so you don't need to do a sub-query:</p>
<pre><code>SELECT DISTINCT ST2.SubjectID,
SUBSTRING(
(
SELECT ','+ST1.StudentName AS [text()]
FROM dbo.Students ST1
WHERE ST1.SubjectID = ST2.SubjectID
ORDER BY ST1.SubjectID
FOR XML PATH (''), TYPE
).value('text()[1]','nvarchar(max)'), 2, 1000) [Students]
FROM dbo.Students ST2
</code></pre> | {
"question_id": 194852,
"question_date": "2008-10-11T23:49:59.470Z",
"question_score": 2271,
"tags": "sql|sql-server|csv|string-concatenation|group-concat",
"answer_id": 545672,
"answer_date": "2009-02-13T11:53:52.437Z",
"answer_score": 1610
} |
Please answer the following Stack Overflow question:
Title: How do I break a string in YAML over multiple lines?
<p>In YAML, I have a string that's very long. I want to keep this within the 80-column (or so) view of my editor, so I'd like to break the string. What's the syntax for this?</p>
<p>In other words, I have this:</p>
<pre><code>Key: 'this is my very very very very very very long string'
</code></pre>
<p>and I'd like to have this (or something to this effect):</p>
<pre><code>Key: 'this is my very very very ' +
'long string'
</code></pre>
<p>I'd like to use quotes as above, so I don't need to escape anything within the string.</p> | <p>Using yaml folded style. The indention in each line will be ignored. A line break will be inserted at the end.</p>
<pre><code>Key: >
This is a very long sentence
that spans several lines in the YAML
but which will be rendered as a string
with only a single carriage return appended to the end.
</code></pre>
<p><a href="http://symfony.com/doc/current/components/yaml/yaml_format.html" rel="noreferrer">http://symfony.com/doc/current/components/yaml/yaml_format.html</a></p>
<p>You can use the "block chomping indicator" to eliminate the trailing line break, as follows:</p>
<pre><code>Key: >-
This is a very long sentence
that spans several lines in the YAML
but which will be rendered as a string
with NO carriage returns.
</code></pre>
<p>In either case, each line break is replaced by a space.</p>
<p>There are other control tools available as well (for controlling indentation for example).</p>
<p>See <a href="https://yaml-multiline.info/" rel="noreferrer">https://yaml-multiline.info/</a></p> | {
"question_id": 3790454,
"question_date": "2010-09-24T19:47:10.497Z",
"question_score": 2269,
"tags": "string|syntax|yaml|newline",
"answer_id": 3790497,
"answer_date": "2010-09-24T19:54:30.460Z",
"answer_score": 1384
} |
Please answer the following Stack Overflow question:
Title: How do you parse and process HTML/XML in PHP?
<p>How can one parse HTML/XML and extract information from it?</p> | <h2>Native XML Extensions</h2>
<p>I prefer using one of the <a href="https://php.net/manual/en/refs.xml.php" rel="noreferrer">native XML extensions</a> since they come bundled with PHP, are usually faster than all the 3rd party libs and give me all the control I need over the markup.</p>
<h3><a href="https://php.net/manual/en/book.dom.php" rel="noreferrer">DOM</a></h3>
<blockquote>
<p>The DOM extension allows you to operate on XML documents through the DOM API with PHP 5. It is an implementation of the W3C's Document Object Model Core Level 3, a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure and style of documents.</p>
</blockquote>
<p>DOM is capable of parsing and modifying real world (broken) HTML and it can do <a href="http://schlitt.info/opensource/blog/0704_xpath.html" rel="noreferrer">XPath queries</a>. It is based on <a href="http://xmlsoft.org/html/libxml-HTMLparser.html" rel="noreferrer">libxml</a>.</p>
<p>It takes some time to get productive with DOM, but that time is well worth it IMO. Since DOM is a language-agnostic interface, you'll find implementations in many languages, so if you need to change your programming language, chances are you will already know how to use that language's DOM API then.</p>
<p>How to use the DOM extension has been <a href="https://stackoverflow.com/search?q=DOM+HTML+%5BPHP%5D&submit=search">covered extensively</a> on StackOverflow, so if you choose to use it, you can be sure most of the issues you run into can be solved by searching/browsing Stack Overflow.</p>
<p>A <a href="https://stackoverflow.com/a/3820783">basic usage example</a> and a <a href="https://stackoverflow.com/a/4983721">general conceptual overview</a> are available in other answers.</p>
<h3><a href="https://php.net/manual/en/book.xmlreader.php" rel="noreferrer">XMLReader</a></h3>
<blockquote>
<p>The XMLReader extension is an XML pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.</p>
</blockquote>
<p>XMLReader, like DOM, is based on libxml. I am not aware of how to trigger the HTML Parser Module, so chances are using XMLReader for parsing broken HTML might be less robust than using DOM where you can explicitly tell it to use libxml's HTML Parser Module.</p>
<p>A <a href="https://stackoverflow.com/a/3299140">basic usage example</a> is available in another answer.</p>
<h3><a href="https://php.net/manual/en/book.xml.php" rel="noreferrer">XML Parser</a></h3>
<blockquote>
<p>This extension lets you create XML parsers and then define handlers for different XML events. Each XML parser also has a few parameters you can adjust.</p>
</blockquote>
<p>The XML Parser library is also based on libxml, and implements a <a href="http://en.wikipedia.org/wiki/Simple_API_for_XML" rel="noreferrer">SAX</a> style XML push parser. It may be a better choice for memory management than DOM or SimpleXML, but will be more difficult to work with than the pull parser implemented by XMLReader.</p>
<h3><a href="https://php.net/manual/en/book.simplexml.php" rel="noreferrer">SimpleXml</a></h3>
<blockquote>
<p>The SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.</p>
</blockquote>
<p>SimpleXML is an option when you know the HTML is valid XHTML. If you need to parse broken HTML, don't even consider SimpleXml because it will choke.</p>
<p>A <a href="https://stackoverflow.com/a/4906459">basic usage example</a> is available, and there are <a href="https://php.net/manual/en/simplexml.examples-basic.php" rel="noreferrer">lots of additional examples in the PHP Manual</a>.</p>
<hr />
<h2>3rd Party Libraries (libxml based)</h2>
<p>If you prefer to use a 3rd-party lib, I'd suggest using a lib that actually uses <a href="http://php.net/manual/en/book.dom.php" rel="noreferrer">DOM</a>/<a href="http://xmlsoft.org/" rel="noreferrer">libxml</a> underneath instead of string parsing.</p>
<h3><a href="https://github.com/ThomasWeinert/FluentDOM" rel="noreferrer">FluentDom</a></h3>
<blockquote>
<p>FluentDOM provides a jQuery-like fluent XML interface for the DOMDocument in PHP. Selectors are written in XPath or CSS (using a CSS to XPath converter). Current versions extend the DOM implementing standard interfaces and add features from the DOM Living Standard. FluentDOM can load formats like JSON, CSV, JsonML, RabbitFish and others. Can be installed via Composer.</p>
</blockquote>
<h3><a href="https://github.com/wasinger/htmlpagedom" rel="noreferrer">HtmlPageDom</a></h3>
<blockquote>
<p><code>Wa72\HtmlPageDom</code> is a PHP library for easy manipulation of HTML
documents using DOM. It requires <a href="https://github.com/symfony/DomCrawler" rel="noreferrer">DomCrawler from Symfony2
components</a> for traversing
the DOM tree and extends it by adding methods for manipulating the
DOM tree of HTML documents.</p>
</blockquote>
<h3><a href="https://github.com/electrolinux/phpquery" rel="noreferrer">phpQuery</a></h3>
<blockquote>
<p>phpQuery is a server-side, chainable, CSS3 selector driven Document Object Model (DOM) API based on jQuery JavaScript Library.
The library is written in PHP5 and provides additional Command Line Interface (CLI).</p>
</blockquote>
<p>This is described as "abandonware and buggy: use at your own risk" but does appear to be minimally maintained.</p>
<h3><a href="https://docs.laminas.dev/laminas-dom/" rel="noreferrer">laminas-dom</a></h3>
<blockquote>
<p>The Laminas\Dom component (formerly Zend_DOM) provides tools for working with DOM documents and structures. Currently, we offer <code>Laminas\Dom\Query</code>, which provides a unified interface for querying DOM documents utilizing both XPath and CSS selectors.</p>
<p>This package is considered feature-complete, and is now in security-only maintenance mode.</p>
</blockquote>
<h3><a href="http://github.com/theseer/fDOMDocument" rel="noreferrer">fDOMDocument</a></h3>
<blockquote>
<p>fDOMDocument extends the standard DOM to use exceptions at all occasions of errors instead of PHP warnings or notices. They also add various custom methods and shortcuts for convenience and to simplify the usage of DOM.</p>
</blockquote>
<h3><a href="http://sabre.io/xml/" rel="noreferrer">sabre/xml</a></h3>
<blockquote>
<p>sabre/xml is a library that wraps and extends the XMLReader and XMLWriter classes to create a simple "xml to object/array" mapping system and design pattern. Writing and reading XML is single-pass and can therefore be fast and require low memory on large xml files.</p>
</blockquote>
<h3><a href="https://github.com/servo-php/fluidxml" rel="noreferrer">FluidXML</a></h3>
<blockquote>
<p>FluidXML is a PHP library for manipulating XML with a concise and fluent API.
It leverages XPath and the fluent programming pattern to be fun and effective.</p>
</blockquote>
<hr />
<h2>3rd-Party (not libxml-based)</h2>
<p>The benefit of building upon DOM/libxml is that you get good performance out of the box because you are based on a native extension. However, not all 3rd-party libs go down this route. Some of them listed below</p>
<h3><a href="https://simplehtmldom.sourceforge.io/docs/1.9/index.html" rel="noreferrer">PHP Simple HTML DOM Parser</a></h3>
<blockquote>
<ul>
<li>An HTML DOM parser written in PHP5+ lets you manipulate HTML in a very easy way!</li>
<li>Require PHP 5+.</li>
<li>Supports invalid HTML.</li>
<li>Find tags on an HTML page with selectors just like jQuery.</li>
<li>Extract contents from HTML in a single line.</li>
</ul>
</blockquote>
<p>I generally do not recommend this parser. The codebase is horrible and the parser itself is rather slow and memory hungry. Not all jQuery Selectors (such as <a href="https://api.jquery.com/child-selector/" rel="noreferrer">child selectors</a>) are possible. Any of the libxml based libraries should outperform this easily.</p>
<h3><a href="https://github.com/paquettg/php-html-parser" rel="noreferrer">PHP Html Parser</a></h3>
<blockquote>
<p>PHPHtmlParser is a simple, flexible, html parser which allows you to select tags using any css selector, like jQuery. The goal is to assiste in the development of tools which require a quick, easy way to scrape html, whether it's valid or not! This project was original supported by sunra/php-simple-html-dom-parser but the support seems to have stopped so this project is my adaptation of his previous work.</p>
</blockquote>
<p>Again, I would not recommend this parser. It is rather slow with high CPU usage. There is also no function to clear memory of created DOM objects. These problems scale particularly with nested loops. The documentation itself is inaccurate and misspelled, with no responses to fixes since 14 Apr 16.</p>
<hr />
<h2>HTML 5</h2>
<p>You can use the above for parsing HTML5, but <a href="https://stackoverflow.com/q/4029341">there can be quirks</a> due to the markup HTML5 allows. So for HTML5 you may want to consider using a dedicated parser. Note that these are written in PHP, so suffer from slower performance and increased memory usage compared to a compiled extension in a lower-level language.</p>
<h3><a href="https://github.com/ivopetkov/html5-dom-document-php/" rel="noreferrer">HTML5DomDocument</a></h3>
<blockquote>
<p>HTML5DOMDocument extends the native DOMDocument library. It fixes some bugs and adds some new functionality.</p>
<ul>
<li>Preserves html entities (DOMDocument does not)</li>
<li>Preserves void tags (DOMDocument does not)</li>
<li>Allows inserting HTML code that moves the correct parts to their proper places (head elements are inserted in the head, body elements in the body)</li>
<li>Allows querying the DOM with CSS selectors (currently available: <code>*</code>, <code>tagname</code>, <code>tagname#id</code>, <code>#id</code>, <code>tagname.classname</code>, <code>.classname</code>, <code>tagname.classname.classname2</code>, <code>.classname.classname2</code>, <code>tagname[attribute-selector]</code>, <code>[attribute-selector]</code>, <code>div, p</code>, <code>div p</code>, <code>div > p</code>, <code>div + p</code>, and <code>p ~ ul</code>.)</li>
<li>Adds support for element->classList.</li>
<li>Adds support for element->innerHTML.</li>
<li>Adds support for element->outerHTML.</li>
</ul>
</blockquote>
<h3><a href="https://github.com/Masterminds/html5-php" rel="noreferrer">HTML5</a></h3>
<blockquote>
<p>HTML5 is a standards-compliant HTML5 parser and writer written entirely in PHP. It is stable and used in many production websites, and has well over five million downloads.</p>
<p>HTML5 provides the following features.</p>
</blockquote>
<blockquote>
<ul>
<li>An HTML5 serializer</li>
<li>Support for PHP namespaces</li>
<li>Composer support</li>
<li>Event-based (SAX-like) parser</li>
<li>A DOM tree builder</li>
<li>Interoperability with QueryPath</li>
<li>Runs on PHP 5.3.0 or newer</li>
</ul>
</blockquote>
<hr />
<h2>Regular Expressions</h2>
<p>Last and <strong>least recommended</strong>, you can extract data from HTML with <a href="https://stackoverflow.com/search?q=regular%20expression%20tutorials">regular expressions</a>. In general using Regular Expressions on HTML is discouraged.</p>
<p>Most of the snippets you will find on the web to match markup are brittle. In most cases they are only working for a very particular piece of HTML. Tiny markup changes, like adding whitespace somewhere, or adding, or changing attributes in a tag, can make the RegEx fails when it's not properly written. You should know what you are doing before using RegEx on HTML.</p>
<p>HTML parsers already know the syntactical rules of HTML. Regular expressions have to be taught for each new RegEx you write. RegEx are fine in some cases, but it really depends on your use-case.</p>
<p>You <a href="https://stackoverflow.com/a/4234491">can write more reliable parsers</a>, but writing a <em>complete and reliable</em> custom parser with regular expressions is a waste of time when the aforementioned libraries already exist and do a much better job on this.</p>
<p>Also see <a href="http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html" rel="noreferrer">Parsing Html The Cthulhu Way</a></p>
<hr />
<h2>Books</h2>
<p>If you want to spend some money, have a look at</p>
<ul>
<li><a href="http://www.phparch.com/books/phparchitects-guide-to-web-scraping-with-php" rel="noreferrer">PHP Architect's Guide to Webscraping with PHP</a></li>
</ul>
<p>I am not affiliated with PHP Architect or the authors.</p> | {
"question_id": 3577641,
"question_date": "2010-08-26T17:17:19.417Z",
"question_score": 2267,
"tags": "php|html|xml|xml-parsing|html-parsing",
"answer_id": 3577662,
"answer_date": "2010-08-26T17:19:41.690Z",
"answer_score": 1983
} |
Please answer the following Stack Overflow question:
Title: Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?
<p>I am doing some numerical optimization on a scientific application. One thing I noticed is that GCC will optimize the call <code>pow(a,2)</code> by compiling it into <code>a*a</code>, but the call <code>pow(a,6)</code> is not optimized and will actually call the library function <code>pow</code>, which greatly slows down the performance. (In contrast, <a href="http://en.wikipedia.org/wiki/Intel_C++_Compiler">Intel C++ Compiler</a>, executable <code>icc</code>, will eliminate the library call for <code>pow(a,6)</code>.) </p>
<p>What I am curious about is that when I replaced <code>pow(a,6)</code> with <code>a*a*a*a*a*a</code> using GCC 4.5.1 and options "<code>-O3 -lm -funroll-loops -msse4</code>", it uses 5 <code>mulsd</code> instructions:</p>
<pre><code>movapd %xmm14, %xmm13
mulsd %xmm14, %xmm13
mulsd %xmm14, %xmm13
mulsd %xmm14, %xmm13
mulsd %xmm14, %xmm13
mulsd %xmm14, %xmm13
</code></pre>
<p>while if I write <code>(a*a*a)*(a*a*a)</code>, it will produce</p>
<pre><code>movapd %xmm14, %xmm13
mulsd %xmm14, %xmm13
mulsd %xmm14, %xmm13
mulsd %xmm13, %xmm13
</code></pre>
<p>which reduces the number of multiply instructions to 3. <code>icc</code> has similar behavior.</p>
<p>Why do compilers not recognize this optimization trick?</p> | <p>Because <a href="http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems" rel="noreferrer">Floating Point Math is not Associative</a>. The way you group the operands in floating point multiplication has an effect on the numerical accuracy of the answer.</p>
<p>As a result, most compilers are very conservative about reordering floating point calculations unless they can be sure that the answer will stay the same, or unless you tell them you don't care about numerical accuracy. For example: <a href="http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html" rel="noreferrer">the <code>-fassociative-math</code> option</a> of gcc which allows gcc to reassociate floating point operations, or even the <code>-ffast-math</code> option which allows even more aggressive tradeoffs of accuracy against speed.</p> | {
"question_id": 6430448,
"question_date": "2011-06-21T18:49:55.103Z",
"question_score": 2266,
"tags": "gcc|assembly|floating-point|compiler-optimization|fast-math",
"answer_id": 6430525,
"answer_date": "2011-06-21T18:56:51.430Z",
"answer_score": 2876
} |
Please answer the following Stack Overflow question:
Title: How do I recover a dropped stash in Git?
<p>I frequently use <code>git stash</code> and <code>git stash pop</code> to save and restore changes in my working tree. Yesterday, I had some changes in my working tree that I had stashed and popped, and then I made more changes to my working tree. I'd like to go back and review yesterday's stashed changes, but <code>git stash pop</code> appears to remove all references to the associated commit.</p>
<p>I know that if I use <code>git stash</code> then <em>.git/refs/stash contains</em> the reference of the commit used to create the stash. And <em>.git/logs/refs/stash contains</em> the whole stash. But those references are gone after <code>git stash pop</code>. I know that the commit is still in my repository somewhere, but I don't know what it was.</p>
<p>Is there an easy way to recover yesterday's stash commit reference?</p> | <p>Once you know the hash of the stash commit you dropped, you can apply it as a stash:</p>
<pre class="lang-bash prettyprint-override"><code>git stash apply $stash_hash
</code></pre>
<p>Or, you can create a separate branch for it with</p>
<pre class="lang-bash prettyprint-override"><code>git branch recovered $stash_hash
</code></pre>
<p>After that, you can do whatever you want with all the normal tools. When you’re done, just blow the branch away.</p>
<h1>Finding the hash</h1>
<p>If you have only just popped it and the terminal is still open, you will <a href="https://stackoverflow.com/questions/89332/recover-dropped-stash-in-git/7844566#7844566">still have the hash value printed by <code>git stash pop</code> on screen</a> (thanks, Dolda).</p>
<p>Otherwise, you can find it using this for Linux, Unix or Git Bash for Windows:</p>
<pre class="lang-bash prettyprint-override"><code>git fsck --no-reflog | awk '/dangling commit/ {print $3}'
</code></pre>
<p>...or using PowerShell for Windows:</p>
<pre><code>git fsck --no-reflog | select-string 'dangling commit' | foreach { $_.ToString().Split(" ")[2] }
</code></pre>
<p>This will show you all the commits at the tips of your commit graph which are no longer referenced from any branch or tag – every lost commit, including every stash commit you’ve ever created, will be somewhere in that graph.</p>
<p>The easiest way to find the stash commit you want is probably to pass that list to <code>gitk</code>:</p>
<pre class="lang-bash prettyprint-override"><code>gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' )
</code></pre>
<p>...or see <a href="https://stackoverflow.com/questions/89332#34666995">the answer from emragins</a> if using PowerShell for Windows.</p>
<p>This will launch a repository browser showing you <em>every single commit in the repository ever</em>, regardless of whether it is reachable or not.</p>
<p>You can replace <code>gitk</code> there with something like <code>git log --graph --oneline --decorate</code> if you prefer a nice graph on the console over a separate GUI app.</p>
<p>To spot stash commits, look for commit messages of this form:</p>
<p> WIP on <i>somebranch</i>: <i>commithash Some old commit message</i></p>
<p><em>Note</em>: The commit message will only be in this form (starting with "WIP on") if you did not supply a message when you did <code>git stash</code>.</p> | {
"question_id": 89332,
"question_date": "2008-09-18T01:59:06.160Z",
"question_score": 2265,
"tags": "git|recovery|git-stash",
"answer_id": 91795,
"answer_date": "2008-09-18T11:38:25.550Z",
"answer_score": 3619
} |
Please answer the following Stack Overflow question:
Title: How do I center text horizontally and vertically in a TextView?
<p>How do I center the text horizontally and vertically in a <code>TextView</code>, so that it appears exactly in the middle of the <code>TextView</code> in <code>Android</code>?</p> | <p>I'm assuming you're using XML layout.</p>
<pre><code><TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/**yourtextstring**"
/>
</code></pre>
<p>You can also use gravity <code>center_vertical</code> or <code>center_horizontal</code> according to your need.</p>
<p>As @stealthcopter commented, in java: <code>.setGravity(Gravity.CENTER);</code>.</p>
<p>And for Kotlin users, <code>.gravity = Gravity.CENTER</code></p> | {
"question_id": 432037,
"question_date": "2009-01-11T00:27:55.617Z",
"question_score": 2263,
"tags": "android|textview",
"answer_id": 432155,
"answer_date": "2009-01-11T01:53:17.393Z",
"answer_score": 3363
} |
Please answer the following Stack Overflow question:
Title: What is a non-capturing group in regular expressions?
<p>How are non-capturing groups, i.e., <code>(?:)</code>, used in regular expressions and what are they good for?</p> | <p>Let me try to explain this with an example.</p>
<p>Consider the following text:</p>
<pre class="lang-none prettyprint-override"><code>http://stackoverflow.com/
https://stackoverflow.com/questions/tagged/regex
</code></pre>
<p>Now, if I apply the regex below over it...</p>
<pre class="lang-regex prettyprint-override"><code>(https?|ftp)://([^/\r\n]+)(/[^\r\n]*)?
</code></pre>
<p>... I would get the following result:</p>
<pre><code>Match "http://stackoverflow.com/"
Group 1: "http"
Group 2: "stackoverflow.com"
Group 3: "/"
Match "https://stackoverflow.com/questions/tagged/regex"
Group 1: "https"
Group 2: "stackoverflow.com"
Group 3: "/questions/tagged/regex"
</code></pre>
<p>But I don't care about the protocol -- I just want the host and path of the URL. So, I change the regex to include the non-capturing group <code>(?:)</code>.</p>
<pre class="lang-regex prettyprint-override"><code>(?:https?|ftp)://([^/\r\n]+)(/[^\r\n]*)?
</code></pre>
<p>Now, my result looks like this:</p>
<pre><code>Match "http://stackoverflow.com/"
Group 1: "stackoverflow.com"
Group 2: "/"
Match "https://stackoverflow.com/questions/tagged/regex"
Group 1: "stackoverflow.com"
Group 2: "/questions/tagged/regex"
</code></pre>
<p>See? The first group has not been captured. The parser uses it to match the text, but ignores it later, in the final result.</p>
<hr>
<h2>EDIT:</h2>
<p>As requested, let me try to explain groups too.</p>
<p>Well, groups serve many purposes. They can help you to extract exact information from a bigger match (which can also be named), they let you rematch a previous matched group, and can be used for substitutions. Let's try some examples, shall we?</p>
<p>Imagine you have some kind of XML or HTML (be aware that <a href="https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags">regex may not be the best tool for the job</a>, but it is nice as an example). You want to parse the tags, so you could do something like this (I have added spaces to make it easier to understand):</p>
<pre class="lang-none prettyprint-override"><code> \<(?<TAG>.+?)\> [^<]*? \</\k<TAG>\>
or
\<(.+?)\> [^<]*? \</\1\>
</code></pre>
<p>The first regex has a named group (TAG), while the second one uses a common group. Both regexes do the same thing: they use the value from the first group (the name of the tag) to match the closing tag. The difference is that the first one uses the name to match the value, and the second one uses the group index (which starts at 1).</p>
<p>Let's try some substitutions now. Consider the following text:</p>
<pre class="lang-none prettyprint-override"><code>Lorem ipsum dolor sit amet consectetuer feugiat fames malesuada pretium egestas.
</code></pre>
<p>Now, let's use this dumb regex over it:</p>
<pre class="lang-regex prettyprint-override"><code>\b(\S)(\S)(\S)(\S*)\b
</code></pre>
<p>This regex matches words with at least 3 characters, and uses groups to separate the first three letters. The result is this:</p>
<pre><code>Match "Lorem"
Group 1: "L"
Group 2: "o"
Group 3: "r"
Group 4: "em"
Match "ipsum"
Group 1: "i"
Group 2: "p"
Group 3: "s"
Group 4: "um"
...
Match "consectetuer"
Group 1: "c"
Group 2: "o"
Group 3: "n"
Group 4: "sectetuer"
...
</code></pre>
<p>So, if we apply the substitution string:</p>
<pre class="lang-none prettyprint-override"><code>$1_$3$2_$4
</code></pre>
<p>... over it, we are trying to use the first group, add an underscore, use the third group, then the second group, add another underscore, and then the fourth group. The resulting string would be like the one below.</p>
<pre class="lang-none prettyprint-override"><code>L_ro_em i_sp_um d_lo_or s_ti_ a_em_t c_no_sectetuer f_ue_giat f_ma_es m_la_esuada p_er_tium e_eg_stas.
</code></pre>
<p>You can use named groups for substitutions too, using <code>${name}</code>.</p>
<p>To play around with regexes, I recommend <a href="http://regex101.com/" rel="noreferrer">http://regex101.com/</a>, which offers a good amount of details on how the regex works; it also offers a few regex engines to choose from.</p> | {
"question_id": 3512471,
"question_date": "2010-08-18T13:17:47.447Z",
"question_score": 2262,
"tags": "regex|capturing-group|regex-group",
"answer_id": 3513858,
"answer_date": "2010-08-18T15:39:32.567Z",
"answer_score": 2835
} |
Please answer the following Stack Overflow question:
Title: How to change the cursor into a hand when a user hovers over a list item?
<p>I've got a list, and I have a click handler for its items:</p>
<pre><code><ul>
<li>foo</li>
<li>goo</li>
</ul>
</code></pre>
<p>How can I change the mouse pointer into a hand pointer (like when hovering over a button)? Right now the pointer turns into a text selection pointer when I hover over the list items.</p> | <p>In light of the passage of time, as people have mentioned, you can now safely just use:</p>
<pre class="lang-css prettyprint-override"><code>li { cursor: pointer; }
</code></pre> | {
"question_id": 3087975,
"question_date": "2010-06-21T19:45:44.983Z",
"question_score": 2257,
"tags": "css|hover|mouse-cursor",
"answer_id": 3088012,
"answer_date": "2010-06-21T19:50:20.947Z",
"answer_score": 3679
} |
Please answer the following Stack Overflow question:
Title: PostgreSQL: Show tables in PostgreSQL
<p>What's the equivalent to <code>show tables</code> (from MySQL) in PostgreSQL?</p> | <p>From the <code>psql</code> command line interface,</p>
<p>First, choose your database</p>
<pre><code>\c database_name
</code></pre>
<p>Then, this shows all tables in the current schema:</p>
<pre><code>\dt
</code></pre>
<hr>
<p>Programmatically (or from the <code>psql</code> interface too, of course):</p>
<pre><code>SELECT * FROM pg_catalog.pg_tables;
</code></pre>
<p>The system tables live in the <code>pg_catalog</code> database.</p> | {
"question_id": 769683,
"question_date": "2009-04-20T19:07:39.210Z",
"question_score": 2255,
"tags": "postgresql",
"answer_id": 769706,
"answer_date": "2009-04-20T19:12:57.420Z",
"answer_score": 3222
} |
Please answer the following Stack Overflow question:
Title: How to leave/exit/deactivate a Python virtualenv
<p>I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the <code>workon</code> command.</p>
<pre><code>me@mymachine:~$ workon env1
(env1)me@mymachine:~$ workon env2
(env2)me@mymachine:~$ workon env1
(env1)me@mymachine:~$
</code></pre>
<p>How do I exit all virtual environments and work on my system environment again? Right now, the only way I have of getting back to <code>me@mymachine:~$</code> is to exit the shell and start a new one. That's kind of annoying. Is there a command to work on "nothing", and if so, what is it? If such a command does not exist, how would I go about creating it?</p> | <p>Usually, activating a virtualenv gives you a shell function named:</p>
<pre><code>$ deactivate
</code></pre>
<p>which puts things back to normal.</p>
<p>I have just looked specifically again at the code for <code>virtualenvwrapper</code>, and, yes, it too supports <code>deactivate</code> as the way to escape from all virtualenvs.</p>
<p>If you are trying to leave an <a href="https://en.wikipedia.org/wiki/Anaconda_(Python_distribution)" rel="noreferrer"><em>Anaconda</em></a> environment, the command depends upon your version of <code>conda</code>. Recent versions (like 4.6) install a <code>conda</code> function directly in your shell, in which case you run:</p>
<pre><code>conda deactivate
</code></pre>
<p>Older conda versions instead implement deactivation using a stand-alone script:</p>
<pre><code>source deactivate
</code></pre> | {
"question_id": 990754,
"question_date": "2009-06-13T14:15:36.753Z",
"question_score": 2249,
"tags": "python|virtualenv|exit|virtualenvwrapper",
"answer_id": 990779,
"answer_date": "2009-06-13T14:31:00.867Z",
"answer_score": 3615
} |
Please answer the following Stack Overflow question:
Title: How to write a switch statement in Ruby
<p>How do I write a <code>switch</code> statement in Ruby?</p> | <p>Ruby uses the <a href="http://ruby-doc.com/docs/ProgrammingRuby/html/tut_expressions.html#S5" rel="noreferrer"><code>case</code> expression</a> instead.</p>
<pre><code>case x
when 1..5
"It's between 1 and 5"
when 6
"It's 6"
when "foo", "bar"
"It's either foo or bar"
when String
"You passed a string"
else
"You gave me #{x} -- I have no idea what to do with that."
end
</code></pre>
<p>Ruby compares the object in the <code>when</code> clause with the object in the <code>case</code> clause using the <code>===</code> operator. For example, <code>1..5 === x</code>, and not <code>x === 1..5</code>. </p>
<p>This allows for sophisticated <code>when</code> clauses as seen above. Ranges, classes and all sorts of things can be tested for rather than just equality.</p>
<p>Unlike <code>switch</code> statements in many other languages, Ruby’s <code>case</code> does not have <a href="https://en.wikipedia.org/wiki/Switch_statement#Fallthrough" rel="noreferrer">fall-through</a>, so there is no need to end each <code>when</code> with a <code>break</code>. You can also specify multiple matches in a single <code>when</code> clause like <code>when "foo", "bar"</code>.</p> | {
"question_id": 948135,
"question_date": "2009-06-04T01:18:00.793Z",
"question_score": 2249,
"tags": "ruby|switch-statement|conditional-statements",
"answer_id": 948157,
"answer_date": "2009-06-04T01:22:57.180Z",
"answer_score": 2903
} |
Please answer the following Stack Overflow question:
Title: How do I determine if an object has an attribute in Python?
<p>How do I determine if an object has some attribute? For example:</p>
<pre><code>>>> a = SomeClass()
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
</code></pre>
<p>How do I tell if <code>a</code> has the attribute <code>property</code> before using it?</p> | <p>Try <a href="https://docs.python.org/3/library/functions.html#hasattr" rel="noreferrer"><code>hasattr()</code></a>:</p>
<pre><code>if hasattr(a, 'property'):
a.property
</code></pre>
<p>See <a href="https://stackoverflow.com/a/610923/117030">zweiterlinde's answer</a> below, who offers good advice about asking forgiveness! A very pythonic approach!</p>
<p>The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than <code>hasattr</code>. If the property is likely to not be there most of the time, or you're not sure, using <code>hasattr</code> will probably be faster than repeatedly falling into an exception block.</p> | {
"question_id": 610883,
"question_date": "2009-03-04T14:45:59.233Z",
"question_score": 2240,
"tags": "python|attributes",
"answer_id": 610893,
"answer_date": "2009-03-04T14:48:43.737Z",
"answer_score": 3156
} |
Please answer the following Stack Overflow question:
Title: What is the best way to give a C# auto-property an initial value?
<p>How do you give a C# auto-property an initial value?</p>
<p>I either use the constructor, or revert to the old syntax. </p>
<p><strong> Using the Constructor:</strong></p>
<pre><code>class Person
{
public Person()
{
Name = "Initial Name";
}
public string Name { get; set; }
}
</code></pre>
<p><strong>Using normal property syntax</strong> (with an initial value)</p>
<pre><code>private string name = "Initial Name";
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
</code></pre>
<p>Is there a better way?</p> | <p>In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor.</p>
<p>Since C# 6.0, you can specify initial value in-line. The syntax is:</p>
<pre><code>public int X { get; set; } = x; // C# 6 or higher
</code></pre>
<p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.defaultvalueattribute?view=netframework-4.8" rel="noreferrer"><code>DefaultValueAttribute</code></a> is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value).</p>
<p>At compile time <code>DefaultValueAttribute</code> will not impact the generated IL and it will not be read to initialize the property to that value (see <a href="https://stackoverflow.com/questions/1980520/defaultvalue-attribute-is-not-working-with-my-auto-property">DefaultValue attribute is not working with my Auto Property</a>).</p>
<p>Example of attributes that impact the IL are <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threadstaticattribute?view=netframework-4.8" rel="noreferrer"><code>ThreadStaticAttribute</code></a>, <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute?view=netframework-4.8" rel="noreferrer"><code>CallerMemberNameAttribute</code></a>, ...</p> | {
"question_id": 40730,
"question_date": "2008-09-02T21:29:41.227Z",
"question_score": 2237,
"tags": "c#|constructor|getter|setter|automatic-properties",
"answer_id": 40754,
"answer_date": "2008-09-02T21:46:23.683Z",
"answer_score": 2849
} |
Please answer the following Stack Overflow question:
Title: Get selected value in dropdown list using JavaScript
<p>How do I get the selected value from a dropdown list using JavaScript?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
</form></code></pre>
</div>
</div>
</p> | <p>Given a select element that looks like this:</p>
<pre class="lang-html prettyprint-override"><code><select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
</code></pre>
<p>Running this code:</p>
<pre class="lang-js prettyprint-override"><code>var e = document.getElementById("ddlViewBy");
var value = e.value;
var text = e.options[e.selectedIndex].text;
</code></pre>
<p>Results in:</p>
<pre><code>value == 2
text == "test2"
</code></pre>
<hr />
<p>Interactive example:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var e = document.getElementById("ddlViewBy");
function onChange() {
var value = e.value;
var text = e.options[e.selectedIndex].text;
console.log(value, text);
}
e.onchange = onChange;
onChange();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
</form></code></pre>
</div>
</div>
</p> | {
"question_id": 1085801,
"question_date": "2009-07-06T07:25:06.597Z",
"question_score": 2235,
"tags": "javascript|html-select",
"answer_id": 1085810,
"answer_date": "2009-07-06T07:29:43.937Z",
"answer_score": 3542
} |
Please answer the following Stack Overflow question:
Title: How can I randomly select an item from a list?
<p>How do I retrieve an item at random from the following list?</p>
<pre><code>foo = ['a', 'b', 'c', 'd', 'e']
</code></pre> | <p>Use <a href="https://docs.python.org/library/random.html#random.choice" rel="noreferrer"><code>random.choice()</code></a>:</p>
<pre><code>import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
</code></pre>
<p>For <a href="https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator" rel="noreferrer">cryptographically secure</a> random choices (e.g., for generating a passphrase from a wordlist), use <a href="https://docs.python.org/library/secrets.html#secrets.choice" rel="noreferrer"><code>secrets.choice()</code></a>:</p>
<pre><code>import secrets
foo = ['battery', 'correct', 'horse', 'staple']
print(secrets.choice(foo))
</code></pre>
<p><code>secrets</code> is new in Python 3.6. On older versions of Python you can use the <a href="https://docs.python.org/library/random.html#random.SystemRandom" rel="noreferrer"><code>random.SystemRandom</code></a> class:</p>
<pre><code>import random
secure_random = random.SystemRandom()
print(secure_random.choice(foo))
</code></pre> | {
"question_id": 306400,
"question_date": "2008-11-20T18:42:21.817Z",
"question_score": 2232,
"tags": "python|list|random",
"answer_id": 306417,
"answer_date": "2008-11-20T18:46:39.470Z",
"answer_score": 3261
} |
Please answer the following Stack Overflow question:
Title: Vim clear last search highlighting
<p>After doing a search in Vim, I get all the occurrences highlighted. How can I disable that? I now do another search for something gibberish that can't be found.</p>
<p>Is there a way to just temporarily disable the highlight and then re-enable it when needed again?</p> | <p>To turn off highlighting until the next search:</p>
<pre><code>:noh
</code></pre>
<p>Or turn off highlighting completely:</p>
<pre><code>set nohlsearch
</code></pre>
<p>Or, to toggle it:</p>
<pre><code>set hlsearch!
nnoremap <F3> :set hlsearch!<CR>
</code></pre> | {
"question_id": 657447,
"question_date": "2009-03-18T09:00:32.310Z",
"question_score": 2232,
"tags": "vim|full-text-search|highlight",
"answer_id": 657457,
"answer_date": "2009-03-18T09:02:47.920Z",
"answer_score": 1955
} |
Please answer the following Stack Overflow question:
Title: JavaScript check if variable exists (is defined/initialized)
<p>Which method of checking if a variable has been initialized is better/correct?
(Assuming the variable could hold anything (string, int, object, function, etc.))</p>
<pre><code>if (elem) { // or !elem
</code></pre>
<p>or</p>
<pre><code>if (typeof elem !== 'undefined') {
</code></pre>
<p>or</p>
<pre><code>if (elem != null) {
</code></pre> | <p>The <code>typeof</code> operator will check if the variable is really undefined.</p>
<pre><code>if (typeof variable === 'undefined') {
// variable is undefined
}
</code></pre>
<p>The <code>typeof</code> operator, unlike the other operators, doesn't throw a <em>ReferenceError</em> exception when used with an undeclared variable.</p>
<p>However, do note that <code>typeof null</code> will return <code>"object"</code>. We have to be careful to avoid the mistake of initializing a variable to <code>null</code>. To be safe, this is what we could use instead:</p>
<pre><code>if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
</code></pre>
<hr>
<p>For more info on using strict comparison <code>===</code> instead of simple equality <code>==</code>, see:<br><a href="https://stackoverflow.com/q/359494/584192">Which equals operator (== vs ===) should be used in JavaScript comparisons?</a></p> | {
"question_id": 5113374,
"question_date": "2011-02-25T03:44:47.660Z",
"question_score": 2229,
"tags": "javascript|function|variables|initialization|undefined",
"answer_id": 6509422,
"answer_date": "2011-06-28T16:00:11.260Z",
"answer_score": 1046
} |
Please answer the following Stack Overflow question:
Title: How do I set a variable to the output of a command in Bash?
<p>I have a pretty simple script that is something like the following:</p>
<pre><code>#!/bin/bash
VAR1="$1"
MOREF='sudo run command against $VAR1 | grep name | cut -c7-'
echo $MOREF
</code></pre>
<p>When I run this script from the command line and pass it the arguments, I am not getting any output. However, when I run the commands contained within the <code>$MOREF</code> variable, I am able to get output.</p>
<p>How can one take the results of a command that needs to be run within a script, save it to a variable, and then output that variable on the screen?</p> | <p>In addition to backticks <code>`command`</code>, <a href="http://www.gnu.org/software/bash/manual/bashref.html#Command-Substitution" rel="noreferrer">command substitution</a> can be done with <code>$(command)</code> or <code>"$(command)"</code>, which I find easier to read, and allows for nesting.</p>
<pre><code>OUTPUT=$(ls -1)
echo "${OUTPUT}"
MULTILINE=$(ls \
-1)
echo "${MULTILINE}"
</code></pre>
<p>Quoting (<code>"</code>) does matter to preserve <strong>multi-line variable values</strong>; it is optional on the right-hand side of an assignment, as <a href="https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Shell-Parameters" rel="noreferrer">word splitting is not performed</a>, so <code>OUTPUT=$(ls -1)</code> would work fine.</p> | {
"question_id": 4651437,
"question_date": "2011-01-10T20:58:02.093Z",
"question_score": 2228,
"tags": "bash|shell|command-line",
"answer_id": 4651495,
"answer_date": "2011-01-10T21:04:18.747Z",
"answer_score": 2986
} |
Please answer the following Stack Overflow question:
Title: What is a JavaBean exactly?
<p>I understood, I think, that a "Bean" is a Java-class with properties and getters/setters. <br />
As much as I understand, it is the equivalent of a C <code>struct</code>. Is that true?</p>
<p>Also, is there a real <em>syntactic</em> difference between a <code>JavaBean</code> and a regular <code>class</code>? <br />
Is there any special definition or an <code>Interface</code>?</p>
<p>Basically, why is there a term for this?</p>
<p>Also what does the <code>Serializable</code> interface mean?</p> | <p>A JavaBean is just a <a href="http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html" rel="noreferrer">standard</a>. It is a regular Java <code>class</code>, except it follows certain conventions:</p>
<ol>
<li>All properties are private (use <a href="http://en.wikipedia.org/wiki/Mutator_method" rel="noreferrer">getters/setters</a>)</li>
<li>A public <a href="http://en.wikipedia.org/wiki/Nullary_constructor" rel="noreferrer">no-argument constructor</a></li>
<li>Implements <a href="http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html" rel="noreferrer"><code>Serializable</code></a>.</li>
</ol>
<p>That's it. It's just a convention. Lots of libraries depend on it though.</p>
<p>With respect to <code>Serializable</code>, from the <a href="http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html" rel="noreferrer">API documentation</a>:</p>
<blockquote>
<p>Serializability of a class is enabled by the class implementing the
java.io.Serializable interface. Classes that do not implement this
interface will not have any of their state serialized or deserialized.
All subtypes of a serializable class are themselves serializable. The
serialization interface has no methods or fields and serves only to
identify the semantics of being serializable.</p>
</blockquote>
<p>In other words, serializable objects can be written to streams, and hence files, object databases, anything really.</p>
<p>Also, there is no syntactic difference between a JavaBean and another class -- a class is a JavaBean if it follows the standards.</p>
<p>There is a term for it, because the standard allows libraries to programmatically do things with class instances you define in a predefined way. For example, if a library wants to stream any object you pass into it, it knows it can because your object is serializable (assuming the library requires your objects be proper JavaBeans).</p> | {
"question_id": 3295496,
"question_date": "2010-07-21T00:41:11.187Z",
"question_score": 2228,
"tags": "java|dependency-injection|inversion-of-control|javabeans|serializable",
"answer_id": 3295517,
"answer_date": "2010-07-21T00:45:24.297Z",
"answer_score": 2547
} |
Please answer the following Stack Overflow question:
Title: How to copy files from host to Docker container?
<p>I am trying to build a backup and restore solution for the Docker containers that we work with.</p>
<p>I have Docker base image that I have created, <code>ubuntu:base</code>, and do not want have to rebuild it each time with a Docker file to add files to it.</p>
<p>I want to create a script that runs from the host machine and creates a new container using the <code>ubuntu:base</code> Docker image and then copies files into that container.</p>
<p>How can I copy files from the host to the container?</p> | <p>The <code>cp</code> command can be used to copy files.</p>
<p>One specific file can be copied TO the container like:</p>
<pre><code>docker cp foo.txt container_id:/foo.txt
</code></pre>
<p>One specific file can be copied FROM the container like:</p>
<pre><code>docker cp container_id:/foo.txt foo.txt
</code></pre>
<p>For emphasis, <code>container_id</code> is a <em>container</em> ID, <strong>not</strong> an <em>image</em> ID. (Use <code>docker ps</code> to view listing which includes <code>container_id</code>s.)</p>
<p>Multiple files contained by the folder <code>src</code> can be copied into the <code>target</code> folder using:</p>
<pre><code>docker cp src/. container_id:/target
docker cp container_id:/src/. target
</code></pre>
<p>Reference: <a href="https://docs.docker.com/engine/reference/commandline/cp/" rel="noreferrer">Docker CLI docs for <code>cp</code></a></p>
<p>In Docker versions prior to 1.8 it was only possible to copy files from a container to the host. Not from the host to a container.</p> | {
"question_id": 22907231,
"question_date": "2014-04-07T08:28:55.613Z",
"question_score": 2227,
"tags": "docker|docker-container",
"answer_id": 31971697,
"answer_date": "2015-08-12T17:25:00.957Z",
"answer_score": 3691
} |
Please answer the following Stack Overflow question:
Title: When should I use double or single quotes in JavaScript?
<p><code>console.log("double");</code> vs. <code>console.log('single');</code></p>
<p>I see more and more JavaScript libraries out there using single quotes when handling strings. What are the reasons to use one over the other?</p>
<p>I thought they're pretty much interchangeable.</p> | <p>The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string.</p>
<p>Using the other type of quote as a literal:</p>
<pre><code>alert('Say "Hello"');
alert("Say 'Hello'");
</code></pre>
<p>This can get complicated:</p>
<pre><code>alert("It's \"game\" time.");
alert('It\'s "game" time.');
</code></pre>
<p>Another option, new in ECMAScript 6, is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals" rel="noreferrer">template literals</a> which use the <em>backtick</em> character:</p>
<pre><code>alert(`Use "double" and 'single' quotes in the same string`);
alert(`Escape the \` back-tick character and the \${ dollar-brace sequence in a string`);
</code></pre>
<p>Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.</p>
<p>Note that <a href="https://jsonlint.com/" rel="noreferrer">JSON</a> is formally specified to use double quotes, which may be worth considering depending on system requirements.</p> | {
"question_id": 242813,
"question_date": "2008-10-28T10:34:35.097Z",
"question_score": 2225,
"tags": "javascript|string|conventions",
"answer_id": 242833,
"answer_date": "2008-10-28T10:40:18.597Z",
"answer_score": 1388
} |
Please answer the following Stack Overflow question:
Title: How can I select an element with multiple classes in jQuery?
<p>I want to select all the elements that have the two classes <code>a</code> and <code>b</code>.</p>
<pre><code><element class="a b">
</code></pre>
<p>So, only the elements that have <em>both</em> classes.</p>
<p>When I use <code>$(".a, .b")</code> it gives me the union, but I want the intersection.</p> | <p>If you want to match only elements with <strong>both</strong> classes (an intersection, like a logical AND), just write the selectors together <strong>without spaces</strong> in between:</p>
<pre><code>$('.a.b')
</code></pre>
<p>The order is not relevant, so you can also swap the classes:</p>
<pre><code>$('.b.a')
</code></pre>
<p>So to match a <code>div</code> element that has an ID of <code>a</code> with classes <code>b</code> and <code>c</code>, you would write:</p>
<pre><code>$('div#a.b.c')
</code></pre>
<p>(In practice, you most likely don't need to get that specific, and an ID or class selector by itself is usually enough: <code>$('#a')</code>.)</p> | {
"question_id": 1041344,
"question_date": "2009-06-24T22:28:58.530Z",
"question_score": 2224,
"tags": "html|jquery|css|jquery-selectors|htmlelements",
"answer_id": 1041352,
"answer_date": "2009-06-24T22:30:43.800Z",
"answer_score": 2817
} |
Please answer the following Stack Overflow question:
Title: What are valid values for the id attribute in HTML?
<p>When creating the <code>id</code> attributes for HTML elements, what rules are there for the value?</p> | <p>For <a href="http://www.w3.org/TR/html4/types.html#type-id" rel="noreferrer">HTML 4</a>, the answer is technically:</p>
<blockquote>
<p>ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").</p>
</blockquote>
<p><a href="https://www.w3.org/TR/html5/dom.html#the-id-attribute" rel="noreferrer">HTML 5</a> is even more permissive, saying only that an id must contain at least one character and may not contain any space characters.</p>
<p>The id attribute is case sensitive in <a href="https://www.w3.org/TR/xhtml1/diffs.html#h-4.2" rel="noreferrer">XHTML</a>.</p>
<p>As a purely practical matter, you may want to avoid certain characters. Periods, colons and '#' have special meaning in CSS selectors, so you will have to escape those characters using a <a href="http://www.w3.org/TR/CSS2/syndata.html#value-def-identifier" rel="noreferrer">backslash in CSS</a> or a double backslash in a <a href="http://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/" rel="noreferrer">selector string passed to jQuery</a>. Think about how often you will have to escape a character in your stylesheets or code before you go crazy with periods and colons in ids.</p>
<p>For example, the HTML declaration <code><div id="first.name"></div></code> is valid. You can select that element in CSS as <code>#first\.name</code> and in jQuery like so: <code>$('#first\\.name').</code> But if you forget the backslash, <code>$('#first.name')</code>, you will have a perfectly valid selector looking for an element with id <code>first</code> and also having class <code>name</code>. This is a bug that is easy to overlook. You might be happier in the long run choosing the id <code>first-name</code> (a hyphen rather than a period), instead.</p>
<p>You can simplify your development tasks by strictly sticking to a naming convention. For example, if you limit yourself entirely to lower-case characters and always separate words with either hyphens or underscores (but not both, pick one and never use the other), then you have an easy-to-remember pattern. You will never wonder "was it <code>firstName</code> or <code>FirstName</code>?" because you will always know that you should type <code>first_name</code>. Prefer camel case? Then limit yourself to that, no hyphens or underscores, and always, consistently use either upper-case or lower-case for the first character, don't mix them.</p>
<hr>
<p>A now very obscure problem was that at least one browser, Netscape 6, <a href="https://developer.mozilla.org/en-US/docs/Case_Sensitivity_in_class_and_id_Names" rel="noreferrer">incorrectly treated id attribute values as case-sensitive</a>. That meant that if you had typed <code>id="firstName"</code> in your HTML (lower-case 'f') and <code>#FirstName { color: red }</code> in your CSS (upper-case 'F'), that buggy browser would have failed to set the element's color to red. At the time of this edit, April 2015, I hope you aren't being asked to support Netscape 6. Consider this a historical footnote.</p> | {
"question_id": 70579,
"question_date": "2008-09-16T09:08:52.527Z",
"question_score": 2215,
"tags": "html",
"answer_id": 79022,
"answer_date": "2008-09-17T01:42:42.433Z",
"answer_score": 1843
} |
Please answer the following Stack Overflow question:
Title: Get int value from enum in C#
<p>I have a class called <code>Questions</code> (plural). In this class there is an enum called <code>Question</code> (singular) which looks like this.</p>
<pre><code>public enum Question
{
Role = 2,
ProjectFunding = 3,
TotalEmployee = 4,
NumberOfServers = 5,
TopBusinessConcern = 6
}
</code></pre>
<p>In the <code>Questions</code> class I have a <code>get(int foo)</code> function that returns a <code>Questions</code> object for that <code>foo</code>. Is there an easy way to get the integer value off the enum so I can do something like this <code>Questions.Get(Question.Role)</code>?</p> | <p>Just cast the enum, e.g.</p>
<pre><code>int something = (int) Question.Role;
</code></pre>
<p>The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is <code>int</code>.</p>
<p>However, as <a href="https://stackoverflow.com/users/333082/cecilphillip">cecilphillip</a> points out, enums can have different underlying types.
If an enum is declared as a <code>uint</code>, <code>long</code>, or <code>ulong</code>, it should be cast to the type of the enum; e.g. for</p>
<pre><code>enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};
</code></pre>
<p>you should use</p>
<pre><code>long something = (long)StarsInMilkyWay.Wolf424B;
</code></pre> | {
"question_id": 943398,
"question_date": "2009-06-03T06:46:39.357Z",
"question_score": 2212,
"tags": "c#|enums|casting|int",
"answer_id": 943407,
"answer_date": "2009-06-03T06:49:18.553Z",
"answer_score": 2801
} |
Please answer the following Stack Overflow question:
Title: How do you assert that a certain exception is thrown in JUnit tests?
<p>How can I use JUnit idiomatically to test that some code throws an exception?</p>
<p>While I can certainly do something like this:</p>
<pre><code>@Test
public void testFooThrowsIndexOutOfBoundsException() {
boolean thrown = false;
try {
foo.doStuff();
} catch (IndexOutOfBoundsException e) {
thrown = true;
}
assertTrue(thrown);
}
</code></pre>
<p>I recall that there is an annotation or an Assert.xyz or <em>something</em> that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.</p> | <p>It depends on the JUnit version and what assert libraries you use.</p>
<ul>
<li>For JUnit5 and 4.13 see answer <a href="https://stackoverflow.com/a/2935935/2986984">https://stackoverflow.com/a/2935935/2986984</a></li>
<li>If you use assertJ or google-truth, see answer <a href="https://stackoverflow.com/a/41019785/2986984">https://stackoverflow.com/a/41019785/2986984</a></li>
</ul>
<p>The original answer for <code>JUnit <= 4.12</code> was:</p>
<pre><code>@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
</code></pre>
<p>Though answer <a href="https://stackoverflow.com/a/31826781/2986984">https://stackoverflow.com/a/31826781/2986984</a> has more options for JUnit <= 4.12.</p>
<p>Reference : </p>
<ul>
<li><a href="https://junit.org/junit4/faq.html#atests_7" rel="noreferrer">JUnit Test-FAQ</a></li>
</ul> | {
"question_id": 156503,
"question_date": "2008-10-01T06:56:08.127Z",
"question_score": 2212,
"tags": "java|exception|junit|junit4|assert",
"answer_id": 156528,
"answer_date": "2008-10-01T07:12:13.440Z",
"answer_score": 2518
} |
Please answer the following Stack Overflow question:
Title: Do I commit the package-lock.json file created by npm 5?
<p><a href="http://blog.npmjs.org/post/161081169345/v500" rel="noreferrer">npm 5 was released today</a> and one of the new features include deterministic installs with the creation of a <code>package-lock.json</code> file.</p>
<p>Is this file supposed to be kept in source control?</p>
<p>I'm assuming it's similar to <a href="https://stackoverflow.com/questions/39990017/should-i-commit-the-yarn-lock-file-and-what-is-it-for"><code>yarn.lock</code></a> and <a href="https://stackoverflow.com/questions/12896780/should-composer-lock-be-committed-to-version-control"><code>composer.lock</code></a>, both of which are supposed to be kept in source control. </p> | <p>Yes, <code>package-lock.json</code> is intended to be checked into source control. If you're using npm 5+, you may see this notice on the command line: <code>created a lockfile as package-lock.json. You should commit this file.</code> According to <a href="https://docs.npmjs.com/cli/v8/configuring-npm/package-lock-json" rel="noreferrer"><code>npm help package-lock.json</code></a>:</p>
<blockquote>
<p><code>package-lock.json</code> is automatically generated for any operations where npm
modifies either the <code>node_modules</code> tree, or <code>package.json</code>. It describes the
exact tree that was generated, such that subsequent installs are able to
generate identical trees, regardless of intermediate dependency updates.</p>
<p><strong>This file is intended to be committed into source repositories</strong>, and serves
various purposes:</p>
<ul>
<li><p>Describe a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.</p>
</li>
<li><p>Provide a facility for users to "time-travel" to previous states of <code>node_modules</code> without having to commit the directory itself.</p>
</li>
<li><p>To facilitate greater visibility of tree changes through readable source control diffs.</p>
</li>
<li><p>And optimize the installation process by allowing npm to skip repeated metadata resolutions for previously-installed packages.</p>
</li>
</ul>
<p>One key detail about <code>package-lock.json</code> is that it cannot be published, and it
will be ignored if found in any place other than the toplevel package. It shares
a format with npm-shrinkwrap.json, which is essentially the same file, but
allows publication. This is not recommended unless deploying a CLI tool or
otherwise using the publication process for producing production packages.</p>
<p>If both <code>package-lock.json</code> and <code>npm-shrinkwrap.json</code> are present in the root of
a package, <code>package-lock.json</code> will be completely ignored.</p>
</blockquote> | {
"question_id": 44206782,
"question_date": "2017-05-26T17:03:32.577Z",
"question_score": 2212,
"tags": "node.js|git|npm|version-control|lockfile",
"answer_id": 44210813,
"answer_date": "2017-05-26T22:16:32.407Z",
"answer_score": 2394
} |
Please answer the following Stack Overflow question:
Title: What is Inversion of Control?
<p>Inversion of Control (IoC) can be quite confusing when it is first encountered.</p>
<ol>
<li>What is it?</li>
<li>Which problem does it solve?</li>
<li>When is it appropriate to use and when not?</li>
</ol> | <p>The <strong><code>Inversion-of-Control</code> (IoC)</strong> pattern, is about providing <em>any kind</em> of <code>callback</code> (which controls reaction), instead of acting ourself directly (in other words, inversion and/or redirecting control to external handler/controller). The <strong><code>Dependency-Injection</code> (DI)</strong> pattern is a more specific version of IoC pattern, and is all about removing dependencies from your code.</p>
<blockquote>
<p>Every <code>DI</code> implementation can be considered <code>IoC</code>, but one should not call it <code>IoC</code>, because implementing Dependency-Injection is harder than callback (Don't lower your product's worth by using general term "IoC" instead).</p>
</blockquote>
<p>For DI example, say your application has a text-editor component, and you want to provide spell checking. Your standard code would look something like this:</p>
<pre class="lang-cs prettyprint-override"><code>public class TextEditor {
private SpellChecker checker;
public TextEditor() {
this.checker = new SpellChecker();
}
}
</code></pre>
<p>What we've done here creates a dependency between the <code>TextEditor</code> and the <code>SpellChecker</code>.
In an IoC scenario we would instead do something like this:</p>
<pre class="lang-cs prettyprint-override"><code>public class TextEditor {
private IocSpellChecker checker;
public TextEditor(IocSpellChecker checker) {
this.checker = checker;
}
}
</code></pre>
<p>In the first code example we are instantiating <code>SpellChecker</code> (<code>this.checker = new SpellChecker();</code>), which means the <code>TextEditor</code> class directly depends on the <code>SpellChecker</code> class.</p>
<p>In the second code example we are creating an abstraction by having the <code>SpellChecker</code> dependency class in <code>TextEditor</code>'s constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so:</p>
<pre class="lang-cs prettyprint-override"><code>SpellChecker sc = new SpellChecker(); // dependency
TextEditor textEditor = new TextEditor(sc);
</code></pre>
<p>Now the client creating the <code>TextEditor</code> class has control over which <code>SpellChecker</code> implementation to use because we're injecting the dependency into the <code>TextEditor</code> signature.</p> | {
"question_id": 3058,
"question_date": "2008-08-06T03:35:27.380Z",
"question_score": 2207,
"tags": "oop|design-patterns|inversion-of-control",
"answer_id": 3140,
"answer_date": "2008-08-06T07:22:09.513Z",
"answer_score": 1900
} |
Please answer the following Stack Overflow question:
Title: HTML 5: Is it <br>, <br/>, or <br />?
<p>I've tried checking <a href="https://stackoverflow.com/questions/1659208/why-br-and-not-br">other answers</a>, but I'm still confused — especially after seeing <a href="http://www.w3schools.com/tags/tag_img.asp" rel="noreferrer">W3schools HTML 5 reference</a>.</p>
<p>I thought HTML 4.01 was supposed to "allow" single-tags to just be <code><img></code> and <code><br></code>. Then XHTML came along with <code><img /></code> and <code><br /></code> (<a href="https://stackoverflow.com/questions/462741/space-before-closing-slash/463692#463692">where someone said that the space is there for older browsers</a>).</p>
<p>Now I'm wondering how I'm supposed to format my code when practicing HTML 5. </p>
<p>Is it <code><br></code>, <code><br/></code> or <code><br /></code>?</p> | <p>Simply <code><br></code> is sufficient.</p>
<p>The other forms are there for compatibility with XHTML; to make it possible to write the same code as XHTML, and have it also work as HTML. Some systems that generate HTML may be based on XML generators, and thus do not have the ability to output just a bare <code><br></code> tag; if you're using such a system, it's fine to use <code><br/></code>, it's just not necessary if you don't need to do it.</p>
<p>Very few people actually use XHTML, however. You need to serve your content as <code>application/xhtml+xml</code> for it to be interpreted as XHTML, and that will not work in old versions of IE - it will also mean that any small error you make will prevent your page from being displayed in browsers that do support XHTML. So, most of what looks like XHTML on the web is actually being served, and interpreted, as HTML. See <a href="http://hixie.ch/advocacy/xhtml" rel="noreferrer">Serving XHTML as text/html Considered Harmful</a> for some more information.</p> | {
"question_id": 1946426,
"question_date": "2009-12-22T13:39:08.033Z",
"question_score": 2203,
"tags": "html",
"answer_id": 1946446,
"answer_date": "2009-12-22T13:42:26.910Z",
"answer_score": 1764
} |
Please answer the following Stack Overflow question:
Title: What is 'Context' on Android?
<p>In Android programming, what exactly is a <code>Context</code> class and what is it used for?</p>
<p>I read about it on the <a href="https://d.android.com/reference/android/content/Context" rel="noreferrer">developer site</a>, but I am unable to understand it clearly.</p> | <p>Putting it simply:</p>
<p>As the name suggests, it's the context of the current state of the application/object. It lets newly-created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity and package/application).</p>
<p>You can get the context by invoking <code>getApplicationContext()</code>, <code>getContext()</code>, <code>getBaseContext()</code> or <code>this</code> (when in a class that extends from <code>Context</code>, such as the Application, Activity, Service and IntentService classes).</p>
<p>Typical uses of context:</p>
<ul>
<li><p><strong>Creating new objects</strong>:
Creating new views, adapters, listeners:</p>
<pre><code> TextView tv = new TextView(getContext());
ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);
</code></pre>
</li>
<li><p><strong>Accessing standard common resources</strong>:
Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:</p>
<pre><code> context.getSystemService(LAYOUT_INFLATER_SERVICE)
getApplicationContext().getSharedPreferences(*name*, *mode*);
</code></pre>
</li>
<li><p><strong>Accessing components implicitly</strong>:
Regarding content providers, broadcasts, intent</p>
<pre><code> getApplicationContext().getContentResolver().query(uri, ...);
</code></pre>
</li>
</ul> | {
"question_id": 3572463,
"question_date": "2010-08-26T06:12:00.683Z",
"question_score": 2199,
"tags": "android|android-context",
"answer_id": 3572553,
"answer_date": "2010-08-26T06:32:42.717Z",
"answer_score": 1677
} |
Please answer the following Stack Overflow question:
Title: How do I get the number of elements in a list in Python?
<p>How do I get the number of elements in the list <code>items</code>?</p>
<pre><code>items = ["apple", "orange", "banana"]
# There are 3 items.
</code></pre> | <p>The <a href="https://docs.python.org/3/library/functions.html#len" rel="noreferrer"><code>len()</code></a> function can be used with several different types in Python - both built-in types and library types. For example:</p>
<pre><code>>>> len([1, 2, 3])
3
</code></pre> | {
"question_id": 1712227,
"question_date": "2009-11-11T00:30:54.670Z",
"question_score": 2197,
"tags": "python|list",
"answer_id": 1712236,
"answer_date": "2009-11-11T00:33:22.983Z",
"answer_score": 2885
} |
Please answer the following Stack Overflow question:
Title: How to delete from a text file, all lines that contain a specific string?
<p>How would I use sed to delete all lines in a text file that contain a specific string?</p> | <p>To remove the line and print the output to standard out:</p>
<pre><code>sed '/pattern to match/d' ./infile
</code></pre>
<p>To directly modify the file – does not work with BSD sed:</p>
<pre><code>sed -i '/pattern to match/d' ./infile
</code></pre>
<p>Same, but for BSD sed (Mac OS X and FreeBSD) – does not work with GNU sed:</p>
<pre><code>sed -i '' '/pattern to match/d' ./infile
</code></pre>
<p>To directly modify the file (and create a backup) – works with BSD and GNU sed:</p>
<pre><code>sed -i.bak '/pattern to match/d' ./infile
</code></pre> | {
"question_id": 5410757,
"question_date": "2011-03-23T19:46:07.297Z",
"question_score": 2197,
"tags": "shell|sed|text-parsing|in-place",
"answer_id": 5410784,
"answer_date": "2011-03-23T19:48:46.250Z",
"answer_score": 3357
} |
Please answer the following Stack Overflow question:
Title: How do I empty an array in JavaScript?
<p>Is there a way to empty an array and if so possibly with <code>.remove()</code>?</p>
<p>For instance, </p>
<pre><code>A = [1,2,3,4];
</code></pre>
<p>How can I empty that?</p> | <p>Ways to clear an existing array <code>A</code>:</p>
<p><strong>Method 1</strong></p>
<p>(this was my original answer to the question)</p>
<pre><code>A = [];
</code></pre>
<p>This code will set the variable <code>A</code> to a new empty array. This is perfect if you don't have <strong>references to the original array <code>A</code></strong> anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable <code>A</code>.</p>
<p>This is also the fastest solution.</p>
<p>This code sample shows the issue you can encounter when using this method:</p>
<pre><code>var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1; // Reference arr1 by another variable
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']
</code></pre>
<p><strong>Method 2</strong> (as <a href="https://stackoverflow.com/a/1234337/113570">suggested</a> by <a href="https://stackoverflow.com/users/2214/matthew-crumley">Matthew Crumley</a>)</p>
<pre><code>A.length = 0
</code></pre>
<p>This will clear the existing array by setting its length to 0. Some have argued that this may not work in all implementations of JavaScript, but it turns out that this is not the case. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.</p>
<p><strong>Method 3</strong> (as <a href="https://stackoverflow.com/a/8134354/113570">suggested</a> by <a href="https://stackoverflow.com/users/1047275/anthony">Anthony</a>)</p>
<pre><code>A.splice(0,A.length)
</code></pre>
<p>Using <code>.splice()</code> will work perfectly, but since the <code>.splice()</code> function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.</p>
<p><strong>Method 4</strong> (as <a href="https://stackoverflow.com/a/17306971/113570">suggested</a> by <a href="https://stackoverflow.com/users/990356/tanguy-k">tanguy_k</a>)</p>
<pre><code>while(A.length > 0) {
A.pop();
}
</code></pre>
<p>This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.</p>
<p><strong>Performance</strong></p>
<p>Of all the methods of clearing an <em><strong>existing array</strong></em>, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this <a href="http://jsben.ch/#/hyj65" rel="noreferrer">benchmark</a>.</p>
<p>As pointed out by <a href="https://stackoverflow.com/users/47401/diadistis">Diadistis</a> in their <a href="https://stackoverflow.com/a/28548360/113570">answer</a> below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty.</p>
<p>The following benchmark fixes this flaw: <a href="http://jsben.ch/#/hyj65" rel="noreferrer">http://jsben.ch/#/hyj65</a>. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array).</p>
<hr/>
<p>This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here.</p> | {
"question_id": 1232040,
"question_date": "2009-08-05T09:08:39.340Z",
"question_score": 2195,
"tags": "javascript|arrays",
"answer_id": 1232046,
"answer_date": "2009-08-05T09:10:00.727Z",
"answer_score": 5327
} |
Please answer the following Stack Overflow question:
Title: How to decide when to use Node.js?
<p>I am new to this kind of stuff, but lately I've been hearing a lot about how good <a href="http://en.wikipedia.org/wiki/Node.js" rel="nofollow noreferrer">Node.js</a> is. Considering how much I love working with jQuery and JavaScript in general, I can't help but wonder how to decide when to use Node.js. The web application I have in mind is something like <a href="https://en.wikipedia.org/wiki/Bitly" rel="nofollow noreferrer">Bitly</a> - takes some content, archives it. </p>
<p>From all the homework I have been doing in the last few days, I obtained the following information. Node.js </p>
<ul>
<li>is a command-line tool that can be run as a regular web server and lets one run JavaScript programs</li>
<li>utilizes the great <a href="http://en.wikipedia.org/wiki/V8_%28JavaScript_engine%29" rel="nofollow noreferrer">V8 JavaScript engine</a></li>
<li>is very good when you need to do several things at the same time</li>
<li>is event-based so all the wonderful <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="nofollow noreferrer">Ajax</a>-like stuff can be done on the server side</li>
<li>lets us share code between the browser and the backend</li>
<li>lets us talk with MySQL</li>
</ul>
<p>Some of the sources that I have come across are:</p>
<ul>
<li><a href="http://www.stoimen.com/blog/2010/11/16/diving-into-node-js-introduction-and-installation/" rel="nofollow noreferrer">Diving into Node.js – Introduction and Installation</a></li>
<li><a href="http://debuggable.com/posts/understanding-node-js:4bd98440-45e4-4a9a-8ef7-0f7ecbdd56cb" rel="nofollow noreferrer">Understanding NodeJS</a></li>
<li><a href="http://blog.osbutler.com/categories/node-by-example/?page=3" rel="nofollow noreferrer">Node by Example</a> (<a href="http://archive.is/exhaR" rel="nofollow noreferrer">Archive.is</a>)</li>
<li><a href="http://dailyjs.com/2010/11/01/node-tutorial/" rel="nofollow noreferrer">Let’s Make a Web App: NodePad</a></li>
</ul>
<p>Considering that Node.js can be run almost out-of-the-box on <a href="http://en.wikipedia.org/wiki/Amazon_Elastic_Compute_Cloud" rel="nofollow noreferrer">Amazon's EC2</a> instances, I am trying to understand what type of problems require Node.js as opposed to any of the mighty kings out there like <a href="http://en.wikipedia.org/wiki/PHP" rel="nofollow noreferrer">PHP</a>, <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="nofollow noreferrer">Python</a> and <a href="http://en.wikipedia.org/wiki/Ruby_%28programming_language%29" rel="nofollow noreferrer">Ruby</a>. I understand that it really depends on the expertise one has on a language, but my question falls more into the general category of: When to use a particular framework and what type of problems is it particularly suited for?</p> | <p>You did a great job of summarizing what's awesome about Node.js. My feeling is that Node.js is especially suited for applications where you'd like to maintain a persistent connection from the browser back to the server. Using a technique known as <a href="http://en.wikipedia.org/wiki/Push_technology#Long_polling" rel="noreferrer">"long-polling"</a>, you can write an application that sends updates to the user in real time. Doing long polling on many of the web's giants, like <a href="http://en.wikipedia.org/wiki/Ruby_on_Rails" rel="noreferrer">Ruby on Rails</a> or <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="noreferrer">Django</a>, would create immense load on the server, because each active client eats up one server process. This situation amounts to a <a href="http://en.wikipedia.org/wiki/Tarpit_(networking)" rel="noreferrer">tarpit</a> attack. When you use something like Node.js, the server has no need of maintaining separate threads for each open connection. </p>
<p>This means you can create a <a href="https://github.com/rivalslayer/node_chat" rel="noreferrer">browser-based chat application</a> in Node.js that takes almost no system resources to serve a great many clients. Any time you want to do this sort of long-polling, Node.js is a great option. </p>
<p>It's worth mentioning that Ruby and Python both have tools to do this sort of thing (<a href="http://rubyeventmachine.com/" rel="noreferrer">eventmachine</a> and <a href="https://twistedmatrix.com/trac/" rel="noreferrer">twisted</a>, respectively), but that Node.js does it exceptionally well, and from the ground up. JavaScript is exceptionally well situated to a callback-based concurrency model, and it excels here. Also, being able to serialize and deserialize with JSON native to both the client and the server is pretty nifty. </p>
<p>I look forward to reading other answers here, this is a fantastic question. </p>
<p>It's worth pointing out that Node.js is also great for situations in which you'll be reusing a lot of code across the client/server gap. The <a href="http://meteor.com" rel="noreferrer">Meteor framework</a> makes this really easy, and a lot of folks are suggesting this might be the future of web development. I can say from experience that it's a whole lot of fun to write code in Meteor, and a big part of this is spending less time thinking about how you're going to restructure your data, so the code that runs in the browser can easily manipulate it and pass it back. </p>
<p>Here's an article on Pyramid and long-polling, which turns out to be very easy to set up with a little help from gevent: <a href="http://michael.merickel.org/2011/6/21/tictactoe-and-long-polling-with-pyramid/" rel="noreferrer"><em>TicTacToe and Long Polling with Pyramid</em></a>.</p> | {
"question_id": 5062614,
"question_date": "2011-02-21T05:20:51.360Z",
"question_score": 2192,
"tags": "javascript|node.js|web-applications",
"answer_id": 5062670,
"answer_date": "2011-02-21T05:30:51.750Z",
"answer_score": 1354
} |
Please answer the following Stack Overflow question:
Title: Vertically align text next to an image?
<p>Why won't <code>vertical-align: middle</code> work? And yet, <code>vertical-align: top</code> <em>does</em> work.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>span{
vertical-align: middle;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<img src="https://via.placeholder.com/30" alt="small img" />
<span>Doesn't work.</span>
</div></code></pre>
</div>
</div>
</p> | <p>Actually, in this case it's quite simple: apply the vertical align to the image. Since it's all in one line, it's really the image you want aligned, not the text.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- moved "vertical-align:middle" style from span to img -->
<div>
<img style="vertical-align:middle" src="https://via.placeholder.com/60x60" alt="A grey image showing text 60 x 60">
<span style="">Works.</span>
</div></code></pre>
</div>
</div>
</p>
<p>Tested in FF3.</p>
<p>Now you can use flexbox for this type of layout.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
display: flex;
align-items:center;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
<img src="https://via.placeholder.com/60x60">
<span style="">Works.</span>
</div></code></pre>
</div>
</div>
</p> | {
"question_id": 489340,
"question_date": "2009-01-28T21:01:50.337Z",
"question_score": 2190,
"tags": "html|css|alignment|vertical-alignment",
"answer_id": 489394,
"answer_date": "2009-01-28T21:10:50.180Z",
"answer_score": 2513
} |
Please answer the following Stack Overflow question:
Title: How to check if a variable is set in Bash
<p>How do I know if a variable is set in Bash?</p>
<p>For example, how do I check if the user gave the first parameter to a function?</p>
<pre><code>function a {
# if $1 is set ?
}
</code></pre> | <h2>(Usually) The right way</h2>
<pre><code>if [ -z ${var+x} ]; then echo "var is unset"; else echo "var is set to '$var'"; fi
</code></pre>
<p>where <code>${var+x}</code> is a <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02" rel="noreferrer">parameter expansion</a> which evaluates to nothing if <code>var</code> is unset, and substitutes the string <code>x</code> otherwise.</p>
<h3>Quotes Digression</h3>
<p>Quotes can be omitted (so we can say <code>${var+x}</code> instead of <code>"${var+x}"</code>) because this syntax & usage guarantees this will only expand to something that does not require quotes (since it either expands to <code>x</code> (which contains no word breaks so it needs no quotes), or to nothing (which results in <code>[ -z ]</code>, which conveniently evaluates to the same value (true) that <code>[ -z "" ]</code> does as well)).</p>
<p>However, while quotes can be safely omitted, and it was not immediately obvious to all (it wasn't even apparent to <a href="https://stackoverflow.com/users/2255628/destiny-architect">the first author of this quotes explanation</a> who is also a major Bash coder), it would sometimes be better to write the solution with quotes as <code>[ -z "${var+x}" ]</code>, at the very small possible cost of an O(1) speed penalty. The first author also added this as a comment next to the code using this solution giving the URL to this answer, which now also includes the explanation for why the quotes can be safely omitted.</p>
<h2>(Often) The wrong way</h2>
<pre><code>if [ -z "$var" ]; then echo "var is blank"; else echo "var is set to '$var'"; fi
</code></pre>
<p>This is often wrong because it doesn't distinguish between a variable that is unset and a variable that is set to the empty string. That is to say, if <code>var=''</code>, then the above solution will output "var is blank".</p>
<p>The distinction between unset and "set to the empty string" is essential in situations where the user has to specify an extension, or additional list of properties, and that not specifying them defaults to a non-empty value, whereas specifying the empty string should make the script use an empty extension or list of additional properties.</p>
<p>The distinction may not be essential in every scenario though. In those cases <code>[ -z "$var" ]</code> will be just fine.</p> | {
"question_id": 3601515,
"question_date": "2010-08-30T14:54:38.197Z",
"question_score": 2184,
"tags": "bash|shell|variables",
"answer_id": 13864829,
"answer_date": "2012-12-13T17:04:53.047Z",
"answer_score": 3083
} |
Please answer the following Stack Overflow question:
Title: How do I print curly-brace characters in a string while using .format?
<p>Non-working example:</p>
<pre><code>print(" \{ Hello \} {0} ".format(42))
</code></pre>
<p>Desired output:</p>
<pre class="lang-none prettyprint-override"><code> {Hello} 42
</code></pre> | <p>You need to double the <code>{{</code> and <code>}}</code>:</p>
<pre><code>>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '
</code></pre>
<p>Here's the relevant part of the <a href="https://docs.python.org/library/string.html#formatstrings" rel="noreferrer">Python documentation for format string syntax</a>:</p>
<blockquote>
<p>Format strings contain “replacement fields” surrounded by curly braces <code>{}</code>. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: <code>{{</code> and <code>}}</code>.</p>
</blockquote> | {
"question_id": 5466451,
"question_date": "2011-03-29T00:04:53.057Z",
"question_score": 2182,
"tags": "python|string|format|string-formatting|curly-braces",
"answer_id": 5466478,
"answer_date": "2011-03-29T00:08:55.973Z",
"answer_score": 2980
} |
Please answer the following Stack Overflow question:
Title: When should I use 'self' over '$this'?
<p>In PHP 5, what is the difference between using <code>self</code> and <code>$this</code>?</p>
<p>When is each appropriate?</p> | <h1>Short Answer</h1>
<blockquote>
<p>Use <code>$this</code> to refer to the current
object. Use <code>self</code> to refer to the
current class. In other words, use
<code>$this->member</code> for non-static members,
use <code>self::$member</code> for static members.</p>
</blockquote>
<h1>Full Answer</h1>
<p>Here is an example of <strong>correct</strong> usage of <code>$this</code> and <code>self</code> for non-static and static member variables:</p>
<pre><code><?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo $this->non_static_member . ' '
. self::$static_member;
}
}
new X();
?>
</code></pre>
<p>Here is an example of <strong>incorrect</strong> usage of <code>$this</code> and <code>self</code> for non-static and static member variables:</p>
<pre><code><?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo self::$non_static_member . ' '
. $this->static_member;
}
}
new X();
?>
</code></pre>
<p>Here is an example of <strong>polymorphism</strong> with <code>$this</code> for member functions:</p>
<pre><code><?php
class X {
function foo() {
echo 'X::foo()';
}
function bar() {
$this->foo();
}
}
class Y extends X {
function foo() {
echo 'Y::foo()';
}
}
$x = new Y();
$x->bar();
?>
</code></pre>
<p>Here is an example of <strong>suppressing polymorphic behaviour</strong> by using <code>self</code> for member functions:</p>
<pre><code><?php
class X {
function foo() {
echo 'X::foo()';
}
function bar() {
self::foo();
}
}
class Y extends X {
function foo() {
echo 'Y::foo()';
}
}
$x = new Y();
$x->bar();
?>
</code></pre>
<blockquote>
<p>The idea is that <code>$this->foo()</code> calls the <code>foo()</code> member function of whatever is the exact type of the current object. If the object is of <code>type X</code>, it thus calls <code>X::foo()</code>. If the object is of <code>type Y</code>, it calls <code>Y::foo()</code>. But with self::foo(), <code>X::foo()</code> is always called.</p>
</blockquote>
<p>From <a href="http://www.phpbuilder.com/board/showthread.php?t=10354489" rel="noreferrer">http://www.phpbuilder.com/board/showthread.php?t=10354489</a>:</p>
<p>By <a href="http://board.phpbuilder.com/member.php?145249-laserlight" rel="noreferrer">http://board.phpbuilder.com/member.php?145249-laserlight</a></p> | {
"question_id": 151969,
"question_date": "2008-09-30T06:23:06.343Z",
"question_score": 2181,
"tags": "php|class|oop|scope",
"answer_id": 151976,
"answer_date": "2008-09-30T06:29:25.627Z",
"answer_score": 1897
} |
Please answer the following Stack Overflow question:
Title: Should I use Vagrant or Docker for creating an isolated environment?
<p>I use Ubuntu for development and deployment and have a need for creating an isolated environment. </p>
<p>I am considering either Vagrant or Docker for this purpose. What are the pros and cons, or how do these solutions compare?</p> | <p>If your purpose is the isolation, I think Docker is what you want.</p>
<p>Vagrant is a virtual machine manager. It allows you to script the virtual machine configuration as well as the provisioning. However, it is still a virtual machine depending on <a href="http://en.wikipedia.org/wiki/VirtualBox">VirtualBox</a> (or others) with a huge overhead. It requires you to have a hard drive file that can be huge, it takes a lot of ram, and performance may be not very good.</p>
<p>Docker on the other hand uses kernel cgroup and namespacing via <a href="https://en.wikipedia.org/wiki/LXC">LXC</a>. It means that you are using the same kernel as the host and the same file system.
You can use Dockerfile with the <code>docker build</code> command in order to handle the provisioning and configuration of your container. You have an example at <a href="https://docs.docker.com/">docs.docker.com</a> on how to make your Dockerfile; it is very intuitive.</p>
<p>The only reason you could want to use Vagrant is if you need to do BSD, Windows or other non-Linux development on your Ubuntu box. Otherwise, go for Docker.</p> | {
"question_id": 16647069,
"question_date": "2013-05-20T10:05:25.017Z",
"question_score": 2172,
"tags": "vagrant|docker",
"answer_id": 16761439,
"answer_date": "2013-05-26T16:46:10.097Z",
"answer_score": 1186
} |
Please answer the following Stack Overflow question:
Title: How to convert a string to an integer in JavaScript?
<p>How do I convert a string to an integer in JavaScript?</p> | <p>The simplest way would be to use the native <code>Number</code> function:</p>
<pre><code>var x = Number("1000")
</code></pre>
<p>If that doesn't work for you, then there are the <strong>parseInt</strong>, <strong>unary plus</strong>, <strong>parseFloat with floor</strong>, and <strong>Math.round</strong> methods.</p>
<p>parseInt:</p>
<pre><code>var x = parseInt("1000", 10); // you want to use radix 10
// so you get a decimal number even with a leading 0 and an old browser ([IE8, Firefox 20, Chrome 22 and older][1])
</code></pre>
<p>unary plus
if your string is already in the form of an integer:</p>
<pre><code>var x = +"1000";
</code></pre>
<p>if your string is or might be a float and you want an integer:</p>
<pre><code>var x = Math.floor("1000.01"); //floor automatically converts string to number
</code></pre>
<p>or, if you're going to be using Math.floor several times:</p>
<pre><code>var floor = Math.floor;
var x = floor("1000.01");
</code></pre>
<p>If you're the type who forgets to put the radix in when you call parseInt, you can use parseFloat and round it however you like. Here I use floor.</p>
<pre><code>var floor = Math.floor;
var x = floor(parseFloat("1000.01"));
</code></pre>
<p>Interestingly, Math.round (like Math.floor) will do a string to number conversion, so if you want the number rounded (or if you have an integer in the string), this is a great way, maybe my favorite:</p>
<pre><code>var round = Math.round;
var x = round("1000"); //equivalent to round("1000",0)
</code></pre> | {
"question_id": 1133770,
"question_date": "2009-07-15T20:22:48.227Z",
"question_score": 2168,
"tags": "javascript|string|integer|data-conversion",
"answer_id": 1133814,
"answer_date": "2009-07-15T20:28:48.790Z",
"answer_score": 2626
} |
Please answer the following Stack Overflow question:
Title: How to exit in Node.js
<p>What is the command that is used to exit? (i.e terminate the Node.js process)</p> | <p>Call the global <a href="http://nodejs.org/api/process.html" rel="noreferrer"><code>process</code></a> object's <a href="https://nodejs.org/api/process.html#process_process_exit_code" rel="noreferrer"><code>exit</code></a> method:</p>
<pre><code>process.exit()
</code></pre>
<p><a href="https://nodejs.org/api/process.html#process_exit_codes" rel="noreferrer">From the docs:</a></p>
<blockquote>
<h2><code>process.exit([exitcode])</code></h2>
<p>Ends the process with the specified <code>code</code>. If omitted, exit with a 'success' code <code>0</code>.</p>
<p>To exit with a 'failure' code:</p>
<pre><code>process.exit(1);
</code></pre>
<p>The shell that executed node should see the exit code as <code>1</code>.</p>
</blockquote> | {
"question_id": 5266152,
"question_date": "2011-03-10T21:30:05.660Z",
"question_score": 2167,
"tags": "node.js",
"answer_id": 5266239,
"answer_date": "2011-03-10T21:38:47.003Z",
"answer_score": 2688
} |
Please answer the following Stack Overflow question:
Title: How do I calculate someone's age based on a DateTime type birthday?
<p>Given a <code>DateTime</code> representing a person's birthday, how do I calculate their age in years?</p> | <p>An easy to understand and simple solution.</p>
<pre class="lang-cs prettyprint-override"><code>// Save today's date.
var today = DateTime.Today;
// Calculate the age.
var age = today.Year - birthdate.Year;
// Go back to the year in which the person was born in case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;
</code></pre>
<p>However, this assumes you are looking for the <em>western</em> idea of the age and not using <a href="https://en.wikipedia.org/wiki/East_Asian_age_reckoning" rel="noreferrer"><em>East Asian reckoning</em></a>.</p> | {
"question_id": 9,
"question_date": "2008-07-31T23:40:59.743Z",
"question_score": 2161,
"tags": "c#|.net|datetime",
"answer_id": 1404,
"answer_date": "2008-08-04T16:50:06.170Z",
"answer_score": 2359
} |
Please answer the following Stack Overflow question:
Title: How does JavaScript .prototype work?
<p>I'm not that into dynamic programming languages but I've written my fair share of JavaScript code. I never really got my head around this prototype-based programming, does any one know how this works?</p>
<pre><code>var obj = new Object();
obj.prototype.test = function() { alert('Hello?'); };
var obj2 = new obj();
obj2.test();
</code></pre>
<p>I remember a lot discussion I had with people a while back (I'm not exactly sure what I'm doing) but as I understand it, there's no concept of a class. It's just an object, and instances of those objects are clones of the original, right?</p>
<p>But what is the exact purpose of this ".prototype" property in JavaScript? How does it relate to instantiating objects?</p>
<h3>Update: correct way</h3>
<pre><code>var obj = new Object(); // not a functional object
obj.prototype.test = function() { alert('Hello?'); }; // this is wrong!
function MyObject() {} // a first class functional object
MyObject.prototype.test = function() { alert('OK'); } // OK
</code></pre>
<p>Also these <a href="http://ejohn.org/apps/learn/#64" rel="noreferrer">slides</a> really helped a lot.</p> | <p>Every JavaScript object <a href="https://www.ecma-international.org/ecma-262/10.0/index.html#sec-ordinary-object-internal-methods-and-internal-slots" rel="noreferrer">has an internal "slot"</a> called <code>[[Prototype]]</code> whose value is either <code>null</code> or an <code>object</code>. You can think of a slot as a property on an object, internal to the JavaScript engine, hidden from the code you write. The square brackets around <code>[[Prototype]]</code> are deliberate, and are an ECMAScript specification convention to denote internal slots. </p>
<p>The value pointed at by the <code>[[Prototype]]</code> of an object, is colloquially known as "the prototype of that object." </p>
<p>If you access a property via the dot (<code>obj.propName</code>) or bracket (<code>obj['propName']</code>) notation, and the object does not directly have such a property (ie. an <em>own property</em>, checkable via <code>obj.hasOwnProperty('propName')</code>), the runtime looks for a property with that name on the object referenced by the <code>[[Prototype]]</code> instead. If the <code>[[Prototype]]</code> <em>also</em> does not have such a property, its <code>[[Prototype]]</code> is checked in turn, and so on. In this way, the original object's <em>prototype chain</em> is walked until a match is found, or its end is reached. At the top of the prototype chain is the <code>null</code> value.</p>
<p>Modern JavaScript implementations allow read and/or write access to the <code>[[Prototype]]</code> in the following ways:</p>
<ol>
<li>The <code>new</code> operator (configures the prototype chain on the default object returned from a constructor function),</li>
<li>The <code>extends</code> keyword (configures the prototype chain when using the class syntax),</li>
<li><code>Object.create</code> will set the supplied argument as the <code>[[Prototype]]</code> of the resulting object,</li>
<li><code>Object.getPrototypeOf</code> and <code>Object.setPrototypeOf</code> (get/set the <code>[[Prototype]]</code> <em>after</em> object creation), and</li>
<li>The standardized accessor (ie. getter/setter) property named <code>__proto__</code> (similar to 4.)</li>
</ol>
<p><code>Object.getPrototypeOf</code> and <code>Object.setPrototypeOf</code> are preferred over <code>__proto__</code>, in part because the behavior of <code>o.__proto__</code> <a href="https://stackoverflow.com/a/35458348/38522">is unusual</a> when an object has a prototype of <code>null</code>.</p>
<p>An object's <code>[[Prototype]]</code> is initially set during object creation.</p>
<p>If you create a new object via <code>new Func()</code>, the object's <code>[[Prototype]]</code> will, by default, be set to the object referenced by <code>Func.prototype</code>.</p>
<p>Note that, therefore, <strong>all classes, and all functions that can be used with the <code>new</code> operator, have a property named <code>.prototype</code> in addition to their own <code>[[Prototype]]</code> internal slot.</strong> This dual use of the word "prototype" is the source of endless confusion amongst newcomers to the language.</p>
<p>Using <code>new</code> with constructor functions allows us to simulate classical inheritance in JavaScript; although JavaScript's inheritance system is - as we have seen - prototypical, and not class-based.</p>
<p>Prior to the introduction of class syntax to JavaScript, constructor functions were the only way to simulate classes. We can think of properties of the object referenced by the constructor function's <code>.prototype</code> property as shared members; ie. members which are the same for each instance. In class-based systems, methods are implemented the same way for each instance, so methods are conceptually added to the <code>.prototype</code> property; an object's fields, however, are instance-specific and are therefore added to the object itself during construction.</p>
<p>Without the class syntax, developers had to manually configure the prototype chain to achieve similar functionality to classical inheritance. This led to a preponderance of different ways to achieve this. </p>
<p>Here's one way:</p>
<pre class="lang-js prettyprint-override"><code>function Child() {}
function Parent() {}
Parent.prototype.inheritedMethod = function () { return 'this is inherited' }
function inherit(child, parent) {
child.prototype = Object.create(parent.prototype)
child.prototype.constructor = child
return child;
}
Child = inherit(Child, Parent)
const o = new Child
console.log(o.inheritedMethod()) // 'this is inherited'
</code></pre>
<p>...and here's another way:</p>
<pre class="lang-js prettyprint-override"><code>function Child() {}
function Parent() {}
Parent.prototype.inheritedMethod = function () { return 'this is inherited' }
function inherit(child, parent) {
function tmp() {}
tmp.prototype = parent.prototype
const proto = new tmp()
proto.constructor = child
child.prototype = proto
return child
}
Child = inherit(Child, Parent)
const o = new Child
console.log(o.inheritedMethod()) // 'this is inherited'
</code></pre>
<p>The class syntax introduced in ES2015 simplifies things, by providing <code>extends</code> as the "one true way" to configure the prototype chain in order to simulate classical inheritance in JavaScript.</p>
<p>So, similar to the code above, if you use the class syntax to create a new object like so:</p>
<pre class="lang-js prettyprint-override"><code>class Parent { inheritedMethod() { return 'this is inherited' } }
class Child extends Parent {}
const o = new Child
console.log(o.inheritedMethod()) // 'this is inherited'
</code></pre>
<p>...the resulting object's <code>[[Prototype]]</code> will be set to an instance of <code>Parent</code>, whose <code>[[Prototype]]</code>, in turn, is <code>Parent.prototype</code>.</p>
<p>Finally, if you create a new object via <code>Object.create(foo)</code>, the resulting object's <code>[[Prototype]]</code> will be set to <code>foo</code>.</p> | {
"question_id": 572897,
"question_date": "2009-02-21T12:31:18.370Z",
"question_score": 2153,
"tags": "javascript|dynamic-languages|prototype-oriented",
"answer_id": 572996,
"answer_date": "2009-02-21T13:33:54.193Z",
"answer_score": 1056
} |
Please answer the following Stack Overflow question:
Title: Viewing unpushed Git commits
<p>How can I view any local commits I've made, that haven't yet been pushed to the remote repository? Occasionally, <code>git status</code> will print out that my branch is X commits ahead of <code>origin/master</code>, but not always.</p>
<p>Is this a bug with my install of Git, or am I missing something?</p> | <p>This gives a log of all commits between origin/master and HEAD:</p>
<pre><code>git log origin/master..HEAD
</code></pre>
<p>When HEAD is on the master branch, this gives a log of unpushed commits.</p>
<hr />
<p>Similarly, to view the diff:</p>
<pre><code>git diff origin/master..HEAD
</code></pre> | {
"question_id": 2016901,
"question_date": "2010-01-06T22:41:15.013Z",
"question_score": 2152,
"tags": "git|git-diff|git-log",
"answer_id": 2016954,
"answer_date": "2010-01-06T22:50:30.377Z",
"answer_score": 2169
} |
Please answer the following Stack Overflow question:
Title: How do I change permissions for a folder and its subfolders/files?
<p>How do I change the permissions of a folder and all its subfolders and files?</p>
<p>This only applies to the <code>/opt/lampp/htdocs</code> folder, not its contents:</p>
<pre><code>chmod 775 /opt/lampp/htdocs
</code></pre>
<p>How do I set <code>chmod 755</code> for all of the <code>/opt/lampp/htdocs</code> folder's current contents, as well as automatically in the future for new folders/files created under it?</p>
<p>Related: <em><a href="http://stackoverflow.com/questions/3740187/how-to-set-default-chmod-in-linux-terminal">How can I set a default 'chmod' in a Linux terminal?</a></em></p> | <p>The other answers are correct, in that <code>chmod -R 755</code> will set these permissions to all files and subfolders in the tree. <strong>But why on earth would you want to</strong>? It might make sense for the directories, but why set the execute bit on all the files?</p>
<p>I suspect what you really want to do is set the directories to 755 and either leave the files alone or set them to 644. For this, you can use the <code>find</code> command. For example:</p>
<p>To change all the directories to 755 (<code>drwxr-xr-x</code>):</p>
<pre><code>find /opt/lampp/htdocs -type d -exec chmod 755 {} \;
</code></pre>
<p>To change all the files to 644 (<code>-rw-r--r--</code>):</p>
<pre><code>find /opt/lampp/htdocs -type f -exec chmod 644 {} \;
</code></pre>
<p>Some splainin': <sup>(thanks @<a href="https://stackoverflow.com/q/3740152/673991#comment22305809_11512211">tobbez</a>)</sup></p>
<ul>
<li><code>chmod 755 {}</code> specifies the command that will be executed by <code>find</code> for each directory</li>
<li><code>chmod 644 {}</code> specifies the command that will be executed by <code>find</code> for each file</li>
<li><code>{}</code> is replaced by the path</li>
<li><code>;</code> the semicolon tells <code>find</code> that this is the end of the command it's supposed to execute</li>
<li><code>\;</code> the semicolon is <a href="https://stackoverflow.com/a/26439638/673991">escaped</a>, otherwise it would be interpreted by the shell instead of <code>find</code></li>
</ul> | {
"question_id": 3740152,
"question_date": "2010-09-18T02:31:58.987Z",
"question_score": 2147,
"tags": "linux|permissions|directory|chmod",
"answer_id": 11512211,
"answer_date": "2012-07-16T20:42:23.790Z",
"answer_score": 3401
} |
Please answer the following Stack Overflow question:
Title: How can I symlink a file in Linux?
<p>I want to make a symbolic link in Linux. I have written this Bash command where the first path is the folder I want link into and the second path is the compiled source. </p>
<pre><code>ln -s '+basebuild+'/IpDome-kernel/kernel /home/build/sandbox/gen2/basebuild/IpDome-kernel/kernal
</code></pre>
<p>Is this correct?</p> | <p>To create a new symlink (will fail if symlink exists already):</p>
<pre><code>ln -s /path/to/file /path/to/symlink
</code></pre>
<p>To create or update a symlink:</p>
<pre><code>ln -sf /path/to/file /path/to/symlink
</code></pre> | {
"question_id": 1951742,
"question_date": "2009-12-23T09:50:39.187Z",
"question_score": 2147,
"tags": "linux|symlink",
"answer_id": 1951752,
"answer_date": "2009-12-23T09:52:24.627Z",
"answer_score": 3965
} |
Please answer the following Stack Overflow question:
Title: How do I format a Microsoft JSON date?
<p>I'm taking my first crack at <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> with jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON data that is returned for Date data types. Basically, I'm getting a string back that looks like this:</p>
<pre><code>/Date(1224043200000)/
</code></pre>
<p>From someone totally new to JSON - How do I format this to a short date format? Should this be handled somewhere in the jQuery code? I've tried the <code>jQuery.UI.datepicker</code> plugin using <code>$.datepicker.formatDate()</code> without any success.</p>
<p>FYI: Here's the solution I came up with using a combination of the answers here:</p>
<pre><code>function getMismatch(id) {
$.getJSON("Main.aspx?Callback=GetMismatch",
{ MismatchId: id },
function (result) {
$("#AuthMerchId").text(result.AuthorizationMerchantId);
$("#SttlMerchId").text(result.SettlementMerchantId);
$("#CreateDate").text(formatJSONDate(Date(result.AppendDts)));
$("#ExpireDate").text(formatJSONDate(Date(result.ExpiresDts)));
$("#LastUpdate").text(formatJSONDate(Date(result.LastUpdateDts)));
$("#LastUpdatedBy").text(result.LastUpdateNt);
$("#ProcessIn").text(result.ProcessIn);
}
);
return false;
}
function formatJSONDate(jsonDate) {
var newDate = dateFormat(jsonDate, "mm/dd/yyyy");
return newDate;
}
</code></pre>
<p>This solution got my object from the callback method and displayed the dates on the page properly using the date format library.</p> | <p><code>eval()</code> is not necessary. This will work fine:</p>
<pre><code>var date = new Date(parseInt(jsonDate.substr(6)));
</code></pre>
<p>The <code>substr()</code> function takes out the <code>/Date(</code> part, and the <code>parseInt()</code> function gets the integer and ignores the <code>)/</code> at the end. The resulting number is passed into the <code>Date</code> constructor.</p>
<hr />
<p>I have intentionally left out the radix (the 2nd argument to <code>parseInt</code>); see <a href="https://stackoverflow.com/questions/206384/how-to-format-a-microsoft-json-date#comment19286516_2316066">my comment below</a>.</p>
<p>Also, I completely agree with <a href="https://stackoverflow.com/questions/206384/how-to-format-a-microsoft-json-date#comment20315450_2316066">Rory's comment</a>: ISO-8601 dates are preferred over this old format - so this format generally shouldn't be used for new development.</p>
<p>For ISO-8601 formatted JSON dates, just pass the string into the <code>Date</code> constructor:</p>
<pre><code>var date = new Date(jsonDate); //no ugly parsing needed; full timezone support
</code></pre> | {
"question_id": 206384,
"question_date": "2008-10-15T20:43:41.077Z",
"question_score": 2135,
"tags": "jquery|asp.net|ajax|json",
"answer_id": 2316066,
"answer_date": "2010-02-23T04:15:09.440Z",
"answer_score": 1754
} |
Please answer the following Stack Overflow question:
Title: C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?
<p>C++11 introduced a standardized memory model, but what exactly does that mean? And how is it going to affect C++ programming?</p>
<p><a href="http://www.theregister.co.uk/2011/06/11/herb_sutter_next_c_plus_plus/page2.html" rel="noreferrer">This article</a> (by <strong>Gavin Clarke</strong> who quotes <strong><a href="https://en.wikipedia.org/wiki/Herb_Sutter" rel="noreferrer">Herb Sutter</a></strong>) says that,</p>
<blockquote>
<p>The memory model means that C++ code
now has a standardized library to call
regardless of who made the compiler
and on what platform it's running.
There's a standard way to control how
different threads talk to the
processor's memory.</p>
<p>"When you are talking about splitting
[code] across different cores that's
in the standard, we are talking about
the memory model. We are going to
optimize it without breaking the
following assumptions people are going
to make in the code," <strong>Sutter</strong> said.</p>
</blockquote>
<p>Well, I can <em>memorize</em> this and similar paragraphs available online (as I've had my own memory model since birth :P) and can even post as an answer to questions asked by others, but to be honest, I don't exactly understand this.</p>
<p>C++ programmers used to develop multi-threaded applications even before, so how does it matter if it's POSIX threads, or Windows threads, or C++11 threads? What are the benefits? I want to understand the low-level details.</p>
<p>I also get this feeling that the C++11 memory model is somehow related to C++11 multi-threading support, as I often see these two together. If it is, how exactly? Why should they be related?</p>
<p>I don't know how the internals of multi-threading work, and what memory model means in general.</p> | <p>First, you have to learn to think like a Language Lawyer.</p>
<p>The C++ specification does not make reference to any particular compiler, operating system, or CPU. It makes reference to an <em>abstract machine</em> that is a generalization of actual systems. In the Language Lawyer world, the job of the programmer is to write code for the abstract machine; the job of the compiler is to actualize that code on a concrete machine. By coding rigidly to the spec, you can be certain that your code will compile and run without modification on any system with a compliant C++ compiler, whether today or 50 years from now.</p>
<p>The abstract machine in the C++98/C++03 specification is fundamentally single-threaded. So it is not possible to write multi-threaded C++ code that is "fully portable" with respect to the spec. The spec does not even say anything about the <em>atomicity</em> of memory loads and stores or the <em>order</em> in which loads and stores might happen, never mind things like mutexes.</p>
<p>Of course, you can write multi-threaded code in practice for particular concrete systems – like pthreads or Windows. But there is no <em>standard</em> way to write multi-threaded code for C++98/C++03.</p>
<p>The abstract machine in C++11 is multi-threaded by design. It also has a well-defined <em>memory model</em>; that is, it says what the compiler may and may not do when it comes to accessing memory.</p>
<p>Consider the following example, where a pair of global variables are accessed concurrently by two threads:</p>
<pre><code> Global
int x, y;
Thread 1 Thread 2
x = 17; cout << y << " ";
y = 37; cout << x << endl;
</code></pre>
<p>What might Thread 2 output?</p>
<p>Under C++98/C++03, this is not even Undefined Behavior; the question itself is <em>meaningless</em> because the standard does not contemplate anything called a "thread".</p>
<p>Under C++11, the result is Undefined Behavior, because loads and stores need not be atomic in general. Which may not seem like much of an improvement... And by itself, it's not.</p>
<p>But with C++11, you can write this:</p>
<pre><code> Global
atomic<int> x, y;
Thread 1 Thread 2
x.store(17); cout << y.load() << " ";
y.store(37); cout << x.load() << endl;
</code></pre>
<p>Now things get much more interesting. First of all, the behavior here is <em>defined</em>. Thread 2 could now print <code>0 0</code> (if it runs before Thread 1), <code>37 17</code> (if it runs after Thread 1), or <code>0 17</code> (if it runs after Thread 1 assigns to x but before it assigns to y).</p>
<p>What it cannot print is <code>37 0</code>, because the default mode for atomic loads/stores in C++11 is to enforce <em>sequential consistency</em>. This just means all loads and stores must be "as if" they happened in the order you wrote them within each thread, while operations among threads can be interleaved however the system likes. So the default behavior of atomics provides both <em>atomicity</em> and <em>ordering</em> for loads and stores.</p>
<p>Now, on a modern CPU, ensuring sequential consistency can be expensive. In particular, the compiler is likely to emit full-blown memory barriers between every access here. But if your algorithm can tolerate out-of-order loads and stores; i.e., if it requires atomicity but not ordering; i.e., if it can tolerate <code>37 0</code> as output from this program, then you can write this:</p>
<pre><code> Global
atomic<int> x, y;
Thread 1 Thread 2
x.store(17,memory_order_relaxed); cout << y.load(memory_order_relaxed) << " ";
y.store(37,memory_order_relaxed); cout << x.load(memory_order_relaxed) << endl;
</code></pre>
<p>The more modern the CPU, the more likely this is to be faster than the previous example.</p>
<p>Finally, if you just need to keep particular loads and stores in order, you can write:</p>
<pre><code> Global
atomic<int> x, y;
Thread 1 Thread 2
x.store(17,memory_order_release); cout << y.load(memory_order_acquire) << " ";
y.store(37,memory_order_release); cout << x.load(memory_order_acquire) << endl;
</code></pre>
<p>This takes us back to the ordered loads and stores – so <code>37 0</code> is no longer a possible output – but it does so with minimal overhead. (In this trivial example, the result is the same as full-blown sequential consistency; in a larger program, it would not be.)</p>
<p>Of course, if the only outputs you want to see are <code>0 0</code> or <code>37 17</code>, you can just wrap a mutex around the original code. But if you have read this far, I bet you already know how that works, and this answer is already longer than I intended :-).</p>
<p>So, bottom line. Mutexes are great, and C++11 standardizes them. But sometimes for performance reasons you want lower-level primitives (e.g., the classic <a href="http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-6-double-checked-locking.html" rel="noreferrer">double-checked locking pattern</a>). The new standard provides high-level gadgets like mutexes and condition variables, and it also provides low-level gadgets like atomic types and the various flavors of memory barrier. So now you can write sophisticated, high-performance concurrent routines entirely within the language specified by the standard, and you can be certain your code will compile and run unchanged on both today's systems and tomorrow's.</p>
<p>Although to be frank, unless you are an expert and working on some serious low-level code, you should probably stick to mutexes and condition variables. That's what I intend to do.</p>
<p>For more on this stuff, see <a href="http://bartoszmilewski.wordpress.com/2008/12/01/c-atomics-and-memory-ordering/" rel="noreferrer">this blog post</a>.</p> | {
"question_id": 6319146,
"question_date": "2011-06-11T23:30:14.617Z",
"question_score": 2133,
"tags": "c++|multithreading|c++11|language-lawyer|memory-model",
"answer_id": 6319356,
"answer_date": "2011-06-12T00:23:46.617Z",
"answer_score": 2490
} |
Please answer the following Stack Overflow question:
Title: Why can templates only be implemented in the header file?
<p>Quote from <a href="http://books.google.com/books?id=n9VEG2Gp5pkC&pg=PA10&lpg=PA10&dq=%22The%20only%20portable%20way%20of%20using%20templates%20at%20the%20moment%20is%20to%20implement%20them%20in%20header%20files%20by%20using%20inline%20functions.%22&source=bl&ots=Ref8pl8dPX&sig=t4K5gvxtBblpcujNxodpwMfei8I&hl=en&ei=qkR6TvbiGojE0AHq4IzqAg&sa=X&oi=book_result&ct=result&resnum=3&ved=0CC8Q6AEwAg#v=onepage&q=%22The%20only%20portable%20way%20of%20using%20templates%20at%20the%20moment%20is%20to%20implement%20them%20in%20header%20files%20by%20using%20inline%20functions.%22&f=false" rel="noreferrer">The C++ standard library: a tutorial and handbook</a>:</p>
<blockquote>
<p>The only portable way of using templates at the moment is to implement them in header files by using inline functions.</p>
</blockquote>
<p>Why is this?</p>
<p>(Clarification: header files are not the <em>only</em> portable solution. But they are the most convenient portable solution.)</p> | <p>Caveat: It is <em>not</em> necessary to put the implementation in the header file, see the alternative solution at the end of this answer.</p>
<p>Anyway, the reason your code is failing is that, when instantiating a template, the compiler creates a new class with the given template argument. For example:</p>
<pre><code>template<typename T>
struct Foo
{
T bar;
void doSomething(T param) {/* do stuff using T */}
};
// somewhere in a .cpp
Foo<int> f;
</code></pre>
<p>When reading this line, the compiler will create a new class (let's call it <code>FooInt</code>), which is equivalent to the following:</p>
<pre><code>struct FooInt
{
int bar;
void doSomething(int param) {/* do stuff using int */}
}
</code></pre>
<p>Consequently, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case <code>int</code>). If these implementations were not in the header, they wouldn't be accessible, and therefore the compiler wouldn't be able to instantiate the template.</p>
<p>A common solution to this is to write the template declaration in a header file, then implement the class in an implementation file (for example .tpp), and include this implementation file at the end of the header.</p>
<p>Foo.h</p>
<pre><code>template <typename T>
struct Foo
{
void doSomething(T param);
};
#include "Foo.tpp"
</code></pre>
<p>Foo.tpp</p>
<pre><code>template <typename T>
void Foo<T>::doSomething(T param)
{
//implementation
}
</code></pre>
<p>This way, implementation is still separated from declaration, but is accessible to the compiler.</p>
<h1>Alternative solution</h1>
<p>Another solution is to keep the implementation separated, and explicitly instantiate all the template instances you'll need:</p>
<p>Foo.h</p>
<pre><code>// no implementation
template <typename T> struct Foo { ... };
</code></pre>
<p>Foo.cpp</p>
<pre><code>// implementation of Foo's methods
// explicit instantiations
template class Foo<int>;
template class Foo<float>;
// You will only be able to use Foo with int or float
</code></pre>
<p>If my explanation isn't clear enough, you can have a look at the <a href="https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl" rel="noreferrer">C++ Super-FAQ on this subject</a>.</p> | {
"question_id": 495021,
"question_date": "2009-01-30T10:06:50.997Z",
"question_score": 2131,
"tags": "c++|templates|undefined-reference|c++-faq",
"answer_id": 495056,
"answer_date": "2009-01-30T10:26:41.987Z",
"answer_score": 1874
} |
Please answer the following Stack Overflow question:
Title: Remove duplicate values from JS array
<p>I have a very simple JavaScript array that may or may not contain duplicates.</p>
<pre><code>var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
</code></pre>
<p>I need to remove the duplicates and put the unique values in a new array.</p>
<p>I could point to all the codes that I've tried but I think it's useless because they don't work. I accept jQuery solutions too.</p>
<h3>Similar question:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/840781">Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array</a></li>
</ul> | <p>Quick and dirty using jQuery:</p>
<pre><code>var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
</code></pre> | {
"question_id": 9229645,
"question_date": "2012-02-10T14:53:22.713Z",
"question_score": 2127,
"tags": "javascript|jquery|arrays|duplicates|unique",
"answer_id": 9229932,
"answer_date": "2012-02-10T15:13:22.277Z",
"answer_score": 511
} |
Please answer the following Stack Overflow question:
Title: What are drawbacks or disadvantages of singleton pattern?
<p>The <a href="https://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">singleton pattern</a> is a fully paid up member of the <a href="https://en.wikipedia.org/wiki/Design_Patterns" rel="noreferrer">GoF</a>'s <a href="https://rads.stackoverflow.com/amzn/click/com/0201633612" rel="noreferrer" rel="nofollow noreferrer">patterns book</a>, but it lately seems rather orphaned by the developer world. I still use quite a lot of singletons, especially for <a href="https://en.wikipedia.org/wiki/Factory_method_pattern" rel="noreferrer">factory classes</a>, and while you have to be a bit careful about multithreading issues (like any class actually), I fail to see why they are so awful.</p>
<p>Stack Overflow especially seems to assume that everyone agrees that Singletons are evil. Why?</p>
<p>Please support your answers with "<em>facts, references, or specific expertise</em>"</p> | <p>Paraphrased from Brian Button:</p>
<ol>
<li><p>They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a <a href="https://en.wikipedia.org/wiki/Code_smell" rel="noreferrer">code smell</a>.</p></li>
<li><p>They violate the <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle" rel="noreferrer">single responsibility principle</a>: by virtue of the fact that they control their own creation and lifecycle.</p></li>
<li><p>They inherently cause code to be tightly <a href="https://en.wikipedia.org/wiki/Coupling_%28computer_programming%29" rel="noreferrer">coupled</a>. This makes faking them out under test rather difficult in many cases.</p></li>
<li><p>They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.</p></li>
</ol> | {
"question_id": 137975,
"question_date": "2008-09-26T06:02:00.727Z",
"question_score": 2124,
"tags": "design-patterns|singleton",
"answer_id": 138012,
"answer_date": "2008-09-26T06:13:44.630Z",
"answer_score": 1400
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.