input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: Make an existing Git branch track a remote branch?
<p>I know how to make a new branch that tracks remote branches, but <strong>how do I make an existing branch track a remote branch?</strong></p>
<p>I know I can just edit the <code>.git/config</code> file, but it seems there should be an easier way.</p> | <p>Given a branch <code>foo</code> and a remote <code>upstream</code>:</p>
<p><strong>As of Git 1.8.0:</strong></p>
<pre><code>git branch -u upstream/foo
</code></pre>
<p>Or, if local branch <code>foo</code> is not the current branch:</p>
<pre><code>git branch -u upstream/foo foo
</code></pre>
<p>Or, if you like to type longer commands, these are equivalent to the above two:</p>
<pre><code>git branch --set-upstream-to=upstream/foo
git branch --set-upstream-to=upstream/foo foo
</code></pre>
<p><strong>As of Git 1.7.0 (before 1.8.0):</strong></p>
<pre><code>git branch --set-upstream foo upstream/foo
</code></pre>
<p><strong>Notes:</strong></p>
<ul>
<li>All of the above commands will cause local branch <code>foo</code> to track remote branch <code>foo</code> from remote <code>upstream</code>.</li>
<li>The old (1.7.x) syntax is deprecated in favor of the new (1.8+) syntax. The new syntax is intended to be more intuitive and easier to remember.</li>
<li>Defining an upstream branch will fail when run against newly-created remotes that have not already been fetched. In that case, run <code>git fetch upstream</code> beforehand.</li>
</ul>
<hr />
<p>See also: <a href="https://stackoverflow.com/q/6089294/95706">Why do I need to do `--set-upstream` all the time?</a></p> | {
"question_id": 520650,
"question_date": "2009-02-06T15:14:04.757Z",
"question_score": 3887,
"tags": "git|branch|git-branch",
"answer_id": 2286030,
"answer_date": "2010-02-18T03:06:52.900Z",
"answer_score": 4676
} |
Please answer the following Stack Overflow question:
Title: Is there a CSS parent selector?
<p>How do I select the <code><li></code> element that is a direct parent of the anchor element?</p>
<p>As an example, my CSS would be something like this:</p>
<pre><code>li < a.active {
property: value;
}
</code></pre>
<p>Obviously there are ways of doing this with JavaScript, but I'm hoping that there is some sort of workaround that exists native to CSS Level 2.</p>
<p>The menu that I am trying to style is being spewed out by a CMS, so I can't move the active element to the <code><li></code> element... (unless I theme the menu creation module which I'd rather not do).</p> | <p>There is currently no way to select the parent of an element in CSS in a way that works across all browsers.</p>
<p>That said, the <a href="https://dev.w3.org/csswg/selectors4/#relational" rel="noreferrer">Selectors Level 4 Working Draft</a> includes a <code>:has()</code> pseudo-class that will provide this capability. It will be similar to the <a href="https://api.jquery.com/has-selector/" rel="noreferrer">jQuery implementation</a>.</p>
<pre class="lang-css prettyprint-override"><code>li:has(> a.active) { /* styles to apply to the li tag */ }
</code></pre>
<p>As of 2022, <strong><a href="https://caniuse.com/css-has" rel="noreferrer">it is only supported by Safari, and by Chromium browsers behind a flag</a></strong>.</p>
<p>In the meantime, you'll have to resort to JavaScript if you need to select a parent element with full cross-browser support.</p> | {
"question_id": 1014861,
"question_date": "2009-06-18T19:59:36.653Z",
"question_score": 3870,
"tags": "css|css-selectors",
"answer_id": 1014958,
"answer_date": "2009-06-18T20:16:50.707Z",
"answer_score": 3160
} |
Please answer the following Stack Overflow question:
Title: How do I efficiently iterate over each entry in a Java Map?
<p>If I have an object implementing the <code>Map</code> interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?</p>
<p>Will the ordering of elements depend on the specific map implementation that I have for the interface?</p> | <pre class="lang-java prettyprint-override"><code>Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
</code></pre>
<p>On Java 10+:</p>
<pre class="lang-java prettyprint-override"><code>for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
</code></pre> | {
"question_id": 46898,
"question_date": "2008-09-05T21:12:48.370Z",
"question_score": 3829,
"tags": "java|dictionary|collections|iteration",
"answer_id": 46908,
"answer_date": "2008-09-05T21:15:52.713Z",
"answer_score": 5721
} |
Please answer the following Stack Overflow question:
Title: Why don't Java's +=, -=, *=, /= compound assignment operators require casting?
<p>Until today, I thought that for example:</p>
<pre><code>i += j;
</code></pre>
<p>Was just a shortcut for:</p>
<pre><code>i = i + j;
</code></pre>
<p>But if we try this:</p>
<pre><code>int i = 5;
long j = 8;
</code></pre>
<p>Then <code>i = i + j;</code> will not compile but <code>i += j;</code> will compile fine.</p>
<p>Does it mean that in fact <code>i += j;</code> is a shortcut for something like this
<code>i = (type of i) (i + j)</code>?</p> | <p>As always with these questions, the JLS holds the answer. In this case <a href="http://docs.oracle.com/javase/specs/jls/se14/html/jls-15.html#jls-15.26.2" rel="noreferrer">§15.26.2 Compound Assignment Operators</a>. An extract:</p>
<blockquote>
<p>A compound assignment expression of the form <code>E1 op= E2</code> is equivalent to <code>E1 = (T)((E1) op (E2))</code>, where <code>T</code> is the type of <code>E1</code>, except that <code>E1</code> is evaluated only once.</p>
</blockquote>
<p>An example cited from <a href="http://docs.oracle.com/javase/specs/jls/se14/html/jls-15.html#jls-15.26.2" rel="noreferrer">§15.26.2</a></p>
<blockquote>
<p>[...] the following code is correct:</p>
<pre><code>short x = 3;
x += 4.6;
</code></pre>
<p>and results in x having the value 7 because it is equivalent to:</p>
<pre><code>short x = 3;
x = (short)(x + 4.6);
</code></pre>
</blockquote>
<p>In other words, your assumption is correct.</p> | {
"question_id": 8710619,
"question_date": "2012-01-03T10:10:32.037Z",
"question_score": 3799,
"tags": "java|casting|operators|variable-assignment|assignment-operator",
"answer_id": 8710685,
"answer_date": "2012-01-03T10:15:23.400Z",
"answer_score": 2542
} |
Please answer the following Stack Overflow question:
Title: Checking if a key exists in a JavaScript object?
<p>How do I check if a particular key exists in a JavaScript object or array?</p>
<p>If a key doesn't exist, and I try to access it, will it return false? Or throw an error?</p> | <p>Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually <code>undefined</code>?</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>var obj = { key: undefined };
console.log(obj["key"] !== undefined); // false, but the key exists!</code></pre>
</div>
</div>
</p>
<p>You should instead use the <code>in</code> operator:</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>var obj = { key: undefined };
console.log("key" in obj); // true, regardless of the actual value</code></pre>
</div>
</div>
</p>
<p>If you want to check if a key doesn't exist, remember to use parenthesis:</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>var obj = { not_key: undefined };
console.log(!("key" in obj)); // true if "key" doesn't exist in object
console.log(!"key" in obj); // Do not do this! It is equivalent to "false in obj"</code></pre>
</div>
</div>
</p>
<p>Or, if you want to particularly test for properties of the object instance (and not inherited properties), use <code>hasOwnProperty</code>:</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>var obj = { key: undefined };
console.log(obj.hasOwnProperty("key")); // true</code></pre>
</div>
</div>
</p>
<p>For performance comparison between the methods that are <code>in</code>, <code>hasOwnProperty</code> and key is <code>undefined</code>, see <a href="https://jsben.ch/WqlIl" rel="noreferrer">this <strong>benchmark</strong></a>:</p>
<p><a href="https://i.stack.imgur.com/PEuZT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PEuZT.png" alt="Benchmark results" /></a></p> | {
"question_id": 1098040,
"question_date": "2009-07-08T13:21:32.833Z",
"question_score": 3797,
"tags": "javascript|arrays|object",
"answer_id": 1098955,
"answer_date": "2009-07-08T15:51:10.257Z",
"answer_score": 5211
} |
Please answer the following Stack Overflow question:
Title: How do I tell if a file does not exist in Bash?
<p>This checks if a file exists:</p>
<pre><code>#!/bin/bash
FILE=$1
if [ -f $FILE ]; then
echo "File $FILE exists."
else
echo "File $FILE does not exist."
fi
</code></pre>
<p>How do I only check if the file does <strong>not</strong> exist?</p> | <p>The <a href="http://man7.org/linux/man-pages/man1/test.1.html" rel="noreferrer"><code>test</code></a> command (written as <code>[</code> here) has a "not" logical operator, <code>!</code> (exclamation mark):</p>
<pre><code>if [ ! -f /tmp/foo.txt ]; then
echo "File not found!"
fi
</code></pre> | {
"question_id": 638975,
"question_date": "2009-03-12T14:48:43.340Z",
"question_score": 3796,
"tags": "bash|file-io|scripting",
"answer_id": 638980,
"answer_date": "2009-03-12T14:50:01.093Z",
"answer_score": 5158
} |
Please answer the following Stack Overflow question:
Title: Sort array of objects by string property value
<p>I have an array of JavaScript objects:</p>
<pre><code>var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
</code></pre>
<p>How can I sort them by the value of <code>last_nom</code> in JavaScript?</p>
<p>I know about <code>sort(a,b)</code>, but that only seems to work on strings and numbers. Do I need to add a <code>toString()</code> method to my objects?</p> | <p>It's easy enough to write your own comparison function:</p>
<pre><code>function compare( a, b ) {
if ( a.last_nom < b.last_nom ){
return -1;
}
if ( a.last_nom > b.last_nom ){
return 1;
}
return 0;
}
objs.sort( compare );
</code></pre>
<p>Or inline (c/o Marco Demaio):</p>
<pre class="lang-js prettyprint-override"><code>objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))
</code></pre>
<p>Or simplified for numeric (c/o Andre Figueiredo):</p>
<pre class="lang-js prettyprint-override"><code>objs.sort((a,b) => a.last_nom - b.last_nom); // b - a for reverse sort
</code></pre> | {
"question_id": 1129216,
"question_date": "2009-07-15T03:17:47.440Z",
"question_score": 3796,
"tags": "javascript|arrays|sorting|comparison",
"answer_id": 1129270,
"answer_date": "2009-07-15T03:35:51.443Z",
"answer_score": 5244
} |
Please answer the following Stack Overflow question:
Title: How to round to at most 2 decimal places, if necessary
<p>I'd like to round at most two decimal places, but <em>only if necessary</em>.</p>
<p>Input:</p>
<pre><code>10
1.7777777
9.1
</code></pre>
<p>Output:</p>
<pre><code>10
1.78
9.1
</code></pre>
<p>How can I do this in JavaScript?</p> | <p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round" rel="noreferrer"><code>Math.round()</code></a> :</p>
<pre><code>Math.round(num * 100) / 100
</code></pre>
<p>Or to be more specific and to ensure things like 1.005 round correctly, use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON" rel="noreferrer">Number.EPSILON </a> :</p>
<pre><code>Math.round((num + Number.EPSILON) * 100) / 100
</code></pre> | {
"question_id": 11832914,
"question_date": "2012-08-06T17:17:48.293Z",
"question_score": 3761,
"tags": "javascript|rounding|decimal-point",
"answer_id": 11832950,
"answer_date": "2012-08-06T17:20:31.017Z",
"answer_score": 4928
} |
Please answer the following Stack Overflow question:
Title: Why is char[] preferred over String for passwords?
<p>In Swing, the password field has a <code>getPassword()</code> (returns <code>char[]</code>) method instead of the usual <code>getText()</code> (returns <code>String</code>) method. Similarly, I have come across a suggestion not to use <code>String</code> to handle passwords.</p>
<p>Why does <code>String</code> pose a threat to security when it comes to passwords?
It feels inconvenient to use <code>char[]</code>.</p> | <p><strong>Strings are immutable</strong>. That means once you've created the <code>String</code>, if another process can dump memory, there's no way (aside from <a href="https://en.wikipedia.org/wiki/Reflection_%28computer_programming%29" rel="noreferrer">reflection</a>) you can get rid of the data before <a href="https://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29" rel="noreferrer">garbage collection</a> kicks in.</p>
<p>With an array, you can explicitly wipe the data after you're done with it. You can overwrite the array with anything you like, and the password won't be present anywhere in the system, even before garbage collection.</p>
<p>So yes, this <em>is</em> a security concern - but even using <code>char[]</code> only reduces the window of opportunity for an attacker, and it's only for this specific type of attack.</p>
<p>As noted in the comments, it's possible that arrays being moved by the garbage collector will leave stray copies of the data in memory. I believe this is implementation-specific - the garbage collector <em>may</em> clear all memory as it goes, to avoid this sort of thing. Even if it does, there's still the time during which the <code>char[]</code> contains the actual characters as an attack window.</p> | {
"question_id": 8881291,
"question_date": "2012-01-16T14:20:42.473Z",
"question_score": 3748,
"tags": "java|string|security|passwords|char",
"answer_id": 8881376,
"answer_date": "2012-01-16T14:26:16.390Z",
"answer_score": 4647
} |
Please answer the following Stack Overflow question:
Title: Using global variables in a function
<p>How do I create or use a global variable inside a function?</p>
<p>How do I use a global variable that was defined in one function inside other functions?</p>
<hr />
<p><sub>Failing to use the <code>global</code> keyword where appropriate often causes <code>UnboundLocalError</code>. The precise rules for this are explained at <a href="https://stackoverflow.com/questions/370357">UnboundLocalError on local variable when reassigned after first use</a>. Generally, please close other questions as a duplicate of <em>that</em> question when an explanation is sought, and <em>this</em> question when someone simply needs to know the <code>global</code> keyword.</sub></p> | <p>You can use a global variable within other functions by declaring it as <code>global</code> within each function that assigns a value to it:</p>
<pre><code>globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1
def print_globvar():
print(globvar) # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1
</code></pre>
<p>Since it's unclear whether <code>globvar = 1</code> is creating a local variable or changing a global variable, Python defaults to creating a local variable, and makes you explicitly choose the other behavior with the <code>global</code> keyword.</p>
<p>See other answers if you want to share a global variable across modules.</p> | {
"question_id": 423379,
"question_date": "2009-01-08T05:45:02.847Z",
"question_score": 3737,
"tags": "python|global-variables|scope",
"answer_id": 423596,
"answer_date": "2009-01-08T08:39:44.023Z",
"answer_score": 4953
} |
Please answer the following Stack Overflow question:
Title: How do I cast int to enum in C#?
<p>How do I cast an <code>int</code> to an <code>enum</code> in C#?</p> | <p>From an int:</p>
<pre><code>YourEnum foo = (YourEnum)yourInt;
</code></pre>
<p>From a string:</p>
<pre><code>YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
// The foo.ToString().Contains(",") check is necessary for
// enumerations marked with a [Flags] attribute.
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
throw new InvalidOperationException(
$"{yourString} is not an underlying value of the YourEnum enumeration."
);
}
</code></pre>
<p>From a number:</p>
<pre><code>YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum), yourInt);
</code></pre> | {
"question_id": 29482,
"question_date": "2008-08-27T03:58:21.253Z",
"question_score": 3725,
"tags": "c#|enums|casting|integer",
"answer_id": 29485,
"answer_date": "2008-08-27T03:59:42.483Z",
"answer_score": 4469
} |
Please answer the following Stack Overflow question:
Title: How do I clone a specific Git branch?
<p>Git clone will clone remote branch into local.</p>
<p>Is there any way to clone a specific branch by myself without switching branches on the remote repository?</p> | <pre><code>git clone --single-branch --branch <branchname> <remote-repo>
</code></pre>
<p>The <code>--single-branch</code> option is valid from version <a href="https://github.com/git/git/blob/master/Documentation/RelNotes/1.7.10.txt" rel="noreferrer">1.7.10</a> and later.</p>
<p>Please see also the <a href="https://stackoverflow.com/a/4568323/134077">other answer</a> which many people prefer.</p>
<p>You may also want to make sure you understand the difference. And the difference is: by invoking <code>git clone --branch <branchname> url</code> you're fetching <em>all</em> the branches and checking out one. That may, for instance, mean that your repository has a 5kB documentation or wiki branch and 5GB data branch. And whenever you want to edit your frontpage, you may end up cloning 5GB of data.</p>
<p>Again, that is not to say <code>git clone --branch</code> is not the way to accomplish that, it's just that it's not <em>always</em> what you want to accomplish, when you're asking about cloning a specific branch.</p> | {
"question_id": 1911109,
"question_date": "2009-12-15T23:06:50.437Z",
"question_score": 3721,
"tags": "git|git-branch|git-clone",
"answer_id": 1911126,
"answer_date": "2009-12-15T23:09:29.470Z",
"answer_score": 2299
} |
Please answer the following Stack Overflow question:
Title: Is floating point math broken?
<p>Consider the following code:
</p>
<pre><code>0.1 + 0.2 == 0.3 -> false
</code></pre>
<pre class="lang-js prettyprint-override"><code>0.1 + 0.2 -> 0.30000000000000004
</code></pre>
<p>Why do these inaccuracies happen?</p> | <p>Binary <a href="https://en.wikipedia.org/wiki/Double-precision_floating-point_format" rel="noreferrer">floating point</a> math is like this. In most programming languages, it is based on the <a href="https://en.wikipedia.org/wiki/IEEE_754#Basic_and_interchange_formats" rel="noreferrer">IEEE 754 standard</a>. The crux of the problem is that numbers are represented in this format as a whole number times a power of two; rational numbers (such as <code>0.1</code>, which is <code>1/10</code>) whose denominator is not a power of two cannot be exactly represented.</p>
<p>For <code>0.1</code> in the standard <code>binary64</code> format, the representation can be written exactly as</p>
<ul>
<li><code>0.1000000000000000055511151231257827021181583404541015625</code> in decimal, or</li>
<li><code>0x1.999999999999ap-4</code> in <a href="http://www.exploringbinary.com/hexadecimal-floating-point-constants/" rel="noreferrer">C99 hexfloat notation</a>.</li>
</ul>
<p>In contrast, the rational number <code>0.1</code>, which is <code>1/10</code>, can be written exactly as</p>
<ul>
<li><code>0.1</code> in decimal, or</li>
<li><code>0x1.99999999999999...p-4</code> in an analogue of C99 hexfloat notation, where the <code>...</code> represents an unending sequence of 9's.</li>
</ul>
<p>The constants <code>0.2</code> and <code>0.3</code> in your program will also be approximations to their true values. It happens that the closest <code>double</code> to <code>0.2</code> is larger than the rational number <code>0.2</code> but that the closest <code>double</code> to <code>0.3</code> is smaller than the rational number <code>0.3</code>. The sum of <code>0.1</code> and <code>0.2</code> winds up being larger than the rational number <code>0.3</code> and hence disagreeing with the constant in your code.</p>
<p>A fairly comprehensive treatment of floating-point arithmetic issues is <a href="http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html" rel="noreferrer"><em>What Every Computer Scientist Should Know About Floating-Point Arithmetic</em></a>. For an easier-to-digest explanation, see <a href="http://floating-point-gui.de" rel="noreferrer">floating-point-gui.de</a>.</p>
<p><strong>Side Note: All positional (base-N) number systems share this problem with precision</strong></p>
<p>Plain old decimal (base 10) numbers have the same issues, which is why numbers like 1/3 end up as 0.333333333...</p>
<p>You've just stumbled on a number (3/10) that happens to be easy to represent with the decimal system, but doesn't fit the binary system. It goes both ways (to some small degree) as well: 1/16 is an ugly number in decimal (0.0625), but in binary it looks as neat as a 10,000th does in decimal (0.0001)** - if we were in the habit of using a base-2 number system in our daily lives, you'd even look at that number and instinctively understand you could arrive there by halving something, halving it again, and again and again.</p>
<p>** Of course, that's not exactly how floating-point numbers are stored in memory (they use a form of scientific notation). However, it does illustrate the point that binary floating-point precision errors tend to crop up because the "real world" numbers we are usually interested in working with are so often powers of ten - but only because we use a decimal number system day-to-day. This is also why we'll say things like 71% instead of "5 out of every 7" (71% is an approximation, since 5/7 can't be represented exactly with any decimal number).</p>
<p>So no: binary floating point numbers are not broken, they just happen to be as imperfect as every other base-N number system :)</p>
<p><strong>Side Side Note: Working with Floats in Programming</strong></p>
<p>In practice, this problem of precision means you need to use rounding functions to round your floating point numbers off to however many decimal places you're interested in before you display them.</p>
<p>You also need to replace equality tests with comparisons that allow some amount of tolerance, which means:</p>
<p>Do <em>not</em> do <code>if (x == y) { ... }</code></p>
<p>Instead do <code>if (abs(x - y) < myToleranceValue) { ... }</code>.</p>
<p>where <code>abs</code> is the absolute value. <code>myToleranceValue</code> needs to be chosen for your particular application - and it will have a lot to do with how much "wiggle room" you are prepared to allow, and what the largest number you are going to be comparing may be (due to loss of precision issues). Beware of "epsilon" style constants in your language of choice. These are <em>not</em> to be used as tolerance values.</p> | {
"question_id": 588004,
"question_date": "2009-02-25T21:39:02.343Z",
"question_score": 3709,
"tags": "math|language-agnostic|floating-point|floating-accuracy",
"answer_id": 588014,
"answer_date": "2009-02-25T21:40:32.900Z",
"answer_score": 2777
} |
Please answer the following Stack Overflow question:
Title: Move existing, uncommitted work to a new branch in Git
<p>I started some work on a new feature and after coding for a bit, I decided this feature should be on its own branch. </p>
<p>How do I move the existing uncommitted changes to a new branch and reset my current one?</p>
<p>I want to reset my current branch while preserving existing work on the new feature.</p> | <h3>Update 2020 / Git 2.23</h3>
<p>Git 2.23 adds the new <a href="https://git-scm.com/docs/git-switch" rel="noreferrer"><code>switch</code></a> subcommand in an attempt to clear some of the confusion that comes from the overloaded usage of <a href="https://git-scm.com/docs/git-checkout" rel="noreferrer"><code>checkout</code></a> (switching branches, restoring files, detaching HEAD, etc.)</p>
<p>Starting with this version of Git, replace the checkout command with:</p>
<pre><code>git switch -c <new-branch>
</code></pre>
<p>The behavior is identical and remains unchanged.</p>
<hr />
<h3>Before Update 2020 / Git 2.23</h3>
<p>Use the following:</p>
<pre><code>git checkout -b <new-branch>
</code></pre>
<p>This will leave your current branch as it is, create and checkout a new branch and keep all your changes. You can then stage changes in files to commit with:</p>
<pre><code>git add <files>
</code></pre>
<p>and commit to your <em>new branch</em> with:</p>
<pre><code>git commit -m "<Brief description of this commit>"
</code></pre>
<p>The changes in the working directory and changes staged in index <em>do not belong to any branch</em> yet. This changes the branch where those modifications would end in.</p>
<p>You don't <em>reset</em> your original branch, it stays as it is. The last commit on <code><old-branch></code> will still be the same. Therefore you <code>checkout -b</code> and then commit.</p> | {
"question_id": 1394797,
"question_date": "2009-09-08T15:57:05.377Z",
"question_score": 3694,
"tags": "git|git-branch|git-stash|git-reset",
"answer_id": 1394804,
"answer_date": "2009-09-08T15:59:03.267Z",
"answer_score": 4322
} |
Please answer the following Stack Overflow question:
Title: Iterate through a HashMap
<p>What's the best way to iterate over the items in a <a href="https://docs.oracle.com/javase/10/docs/api/java/util/HashMap.html" rel="noreferrer"><code>HashMap</code></a>?</p> | <p>Iterate through the <a href="http://www.java2s.com/Code/JavaAPI/java.util/HashtableentrySet.htm" rel="noreferrer"><code>entrySet()</code></a> like so:</p>
<pre><code>public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
</code></pre>
<p>Read more about <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Map.html" rel="noreferrer"><code>Map</code></a>.</p> | {
"question_id": 1066589,
"question_date": "2009-06-30T23:24:14.333Z",
"question_score": 3693,
"tags": "java|loops|hashmap|iteration",
"answer_id": 1066603,
"answer_date": "2009-06-30T23:27:25.700Z",
"answer_score": 3440
} |
Please answer the following Stack Overflow question:
Title: How do I check for an empty/undefined/null string in JavaScript?
<p>Is there a <code>string.Empty</code> in JavaScript, or is it just a case of checking for <code>""</code>?</p> | <h3>Empty string, undefined, null, ...</h3>
<p>To check for a <a href="https://developer.mozilla.org/en-US/docs/Glossary/Truthy" rel="noreferrer">truthy value</a>:</p>
<pre><code>if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
</code></pre>
<p>To check for a <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy" rel="noreferrer">falsy value</a>:</p>
<pre><code>if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
</code></pre>
<hr />
<h3>Empty string (only!)</h3>
<p>To check for exactly an empty string, compare for strict equality against <code>""</code> using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality" rel="noreferrer"><code>===</code> operator</a>:</p>
<pre><code>if (strValue === "") {
// strValue was empty string
}
</code></pre>
<p>To check for not an empty string strictly, use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality" rel="noreferrer"><code>!==</code> operator</a>:</p>
<pre><code>if (strValue !== "") {
// strValue was not an empty string
}
</code></pre> | {
"question_id": 154059,
"question_date": "2008-09-30T17:17:45.273Z",
"question_score": 3692,
"tags": "javascript|null|is-empty",
"answer_id": 154068,
"answer_date": "2008-09-30T17:20:14.207Z",
"answer_score": 4535
} |
Please answer the following Stack Overflow question:
Title: How can I create a memory leak in Java?
<p>I just had an interview where I was asked to create a <em><strong>memory leak</strong></em> with Java.</p>
<p>Needless to say, I felt pretty dumb having no clue on how to even start creating one.</p>
<p>What would an example be?</p> | <p>Here's a good way to create a true memory leak (objects inaccessible by running code but still stored in memory) in pure Java:</p>
<ol>
<li>The application creates a long-running thread (or use a thread pool to leak even faster).</li>
<li>The thread loads a class via an (optionally custom) <code>ClassLoader</code>.</li>
<li>The class allocates a large chunk of memory (e.g. <code>new byte[1000000]</code>), stores a strong reference to it in a static field, and then stores a reference to itself in a <code>ThreadLocal</code>. Allocating the extra memory is optional (leaking the class instance is enough), but it will make the leak work that much faster.</li>
<li>The application clears all references to the custom class or the <code>ClassLoader</code> it was loaded from.</li>
<li>Repeat.</li>
</ol>
<p>Due to the way <code>ThreadLocal</code> is implemented in Oracle's JDK, this creates a memory leak:</p>
<ul>
<li>Each <code>Thread</code> has a private field <code>threadLocals</code>, which actually stores the thread-local values.</li>
<li>Each <em>key</em> in this map is a weak reference to a <code>ThreadLocal</code> object, so after that <code>ThreadLocal</code> object is garbage-collected, its entry is removed from the map.</li>
<li>But each <em>value</em> is a strong reference, so when a value (directly or indirectly) points to the <code>ThreadLocal</code> object that is its <em>key</em>, that object will neither be garbage-collected nor removed from the map as long as the thread lives.</li>
</ul>
<p>In this example, the chain of strong references looks like this:</p>
<p><code>Thread</code> object → <code>threadLocals</code> map → instance of example class → example class → static <code>ThreadLocal</code> field → <code>ThreadLocal</code> object.</p>
<p>(The <code>ClassLoader</code> doesn't really play a role in creating the leak, it just makes the leak worse because of this additional reference chain: example class → <code>ClassLoader</code> → all the classes it has loaded. It was even worse in many JVM implementations, especially prior to Java 7, because classes and <code>ClassLoader</code>s were allocated straight into permgen and were never garbage-collected at all.)</p>
<p>A variation on this pattern is why application containers (like Tomcat) can leak memory like a sieve if you frequently redeploy applications which happen to use <code>ThreadLocal</code>s that in some way point back to themselves. This can happen for a number of subtle reasons and is often hard to debug and/or fix.</p>
<p><strong>Update</strong>: Since lots of people keep asking for it, <a href="https://gist.github.com/dpryden/b2bb29ee2d146901b4ae" rel="noreferrer">here's some example code that shows this behavior in action</a>.</p> | {
"question_id": 6470651,
"question_date": "2011-06-24T16:11:52.227Z",
"question_score": 3620,
"tags": "java|memory|memory-leaks",
"answer_id": 6471947,
"answer_date": "2011-06-24T18:05:10.123Z",
"answer_score": 2539
} |
Please answer the following Stack Overflow question:
Title: Set cellpadding and cellspacing in CSS?
<p>In an HTML table, the <code>cellpadding</code> and <code>cellspacing</code> can be set like this:</p>
<pre class="lang-html prettyprint-override"><code><table cellspacing="1" cellpadding="1">
</code></pre>
<p>How can the same be accomplished using CSS?</p> | <p><strong>Basics</strong></p>
<p>For controlling "cellpadding" in CSS, you can simply use <code>padding</code> on table cells. E.g. for 10px of "cellpadding":</p>
<pre class="lang-css prettyprint-override"><code>td {
padding: 10px;
}
</code></pre>
<p>For "cellspacing", you can apply the <code>border-spacing</code> CSS property to your table. E.g. for 10px of "cellspacing":</p>
<pre class="lang-css prettyprint-override"><code>table {
border-spacing: 10px;
border-collapse: separate;
}
</code></pre>
<p>This property will even allow separate horizontal and vertical spacing, something you couldn't do with old-school "cellspacing".</p>
<p><strong>Issues in IE ≤ 7</strong></p>
<p>This will work in almost all popular browsers except for Internet Explorer up through Internet Explorer 7, where you're almost out of luck. I say "almost" because these browsers still support the <code>border-collapse</code> property, which merges the borders of adjoining table cells. If you're trying to eliminate cellspacing (that is, <code>cellspacing="0"</code>) then <code>border-collapse:collapse</code> should have the same effect: no space between table cells. This support is buggy, though, as it does not override an existing <code>cellspacing</code> HTML attribute on the table element.</p>
<p>In short: for non-Internet Explorer 5-7 browsers, <code>border-spacing</code> handles you. For Internet Explorer, if your situation is just right (you want 0 cellspacing and your table doesn't have it defined already), you can use <code>border-collapse:collapse</code>.</p>
<pre class="lang-css prettyprint-override"><code>table {
border-spacing: 0;
border-collapse: collapse;
}
</code></pre>
<p>Note: For a great overview of CSS properties that one can apply to tables and for which browsers, see this <a href="http://www.quirksmode.org/css/tables.html" rel="noreferrer">fantastic Quirksmode page</a>.</p> | {
"question_id": 339923,
"question_date": "2008-12-04T08:45:47.323Z",
"question_score": 3605,
"tags": "html|css|html-table|alignment",
"answer_id": 3209434,
"answer_date": "2010-07-09T02:34:02.337Z",
"answer_score": 3816
} |
Please answer the following Stack Overflow question:
Title: View the change history of a file using Git versioning
<p>How do I view the history of an individual file with complete details of what has changed?</p>
<p><code>git log -- [filename]</code> shows me the commit history of a file, but how do I see the file content that changed?</p> | <p>For a graphical view, use <a href="https://git-scm.com/docs/gitk/" rel="noreferrer"><code>gitk</code></a>:</p>
<pre><code>gitk [filename]
</code></pre>
<p>To follow the file across file renames:</p>
<pre><code>gitk --follow [filename]
</code></pre> | {
"question_id": 278192,
"question_date": "2008-11-10T15:42:32.737Z",
"question_score": 3602,
"tags": "git|git-log",
"answer_id": 1321962,
"answer_date": "2009-08-24T12:05:51.537Z",
"answer_score": 2653
} |
Please answer the following Stack Overflow question:
Title: Remove a file from a Git repository without deleting it from the local filesystem
<p>I want to remove a file from my repository.</p>
<pre><code>git rm file_to_remove.txt
</code></pre>
<p>will remove the file from the repository, but it will also remove the file from the local file system. How do I remove this file from the repo <strong>without</strong> deleting my local copy of the file?</p> | <p>The <a href="https://git-scm.com/docs/git-rm" rel="noreferrer"><code>git rm</code></a> documentation states:</p>
<blockquote>
<p>When <code>--cached</code> is given, the staged content has to match either the tip of the branch or the file on disk, allowing the file to be removed from just the index.</p>
</blockquote>
<p>So, for a single file:</p>
<pre><code>git rm --cached file_to_remove.txt
</code></pre>
<p>and for a single directory:</p>
<pre><code>git rm --cached -r directory_to_remove
</code></pre> | {
"question_id": 1143796,
"question_date": "2009-07-17T14:56:43.597Z",
"question_score": 3601,
"tags": "git|repository|remote-server|delete-file|git-rm",
"answer_id": 1143800,
"answer_date": "2009-07-17T14:57:26.933Z",
"answer_score": 5067
} |
Please answer the following Stack Overflow question:
Title: How do I get the current time?
<p>How do I get the current time?</p> | <p>Use <a href="https://docs.python.org/3/library/datetime.html" rel="noreferrer"><code>datetime</code></a>:</p>
<pre><code>>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)
>>> print(now)
2009-01-06 15:08:24.789150
</code></pre>
<p>For just the clock time without the date:</p>
<pre><code>>>> now.time()
datetime.time(15, 8, 24, 78915)
>>> print(now.time())
15:08:24.789150
</code></pre>
<hr />
<p>To save typing, you can import the <code>datetime</code> object from the <a href="https://docs.python.org/3/library/datetime.html" rel="noreferrer"><code>datetime</code></a> module:</p>
<pre><code>>>> from datetime import datetime
</code></pre>
<p>Then remove the prefix <code>datetime.</code> from all of the above.</p> | {
"question_id": 415511,
"question_date": "2009-01-06T04:54:23.530Z",
"question_score": 3600,
"tags": "python|datetime|time",
"answer_id": 415519,
"answer_date": "2009-01-06T04:57:05.317Z",
"answer_score": 3683
} |
Please answer the following Stack Overflow question:
Title: How to iterate over rows in a DataFrame in Pandas
<p>I have a pandas dataframe, <code>df</code>:</p>
<pre><code> c1 c2
0 10 100
1 11 110
2 12 120
</code></pre>
<p>How do I iterate over the rows of this dataframe? For every row, I want to be able to access its elements (values in cells) by the name of the columns. For example:</p>
<pre><code>for row in df.rows:
print(row['c1'], row['c2'])
</code></pre>
<hr />
<p>I found a <a href="https://stackoverflow.com/questions/7837722/what-is-the-most-efficient-way-to-loop-through-dataframes-with-pandas">similar question</a> which suggests using either of these:</p>
<pre><code>for date, row in df.T.iteritems():
</code></pre>
<pre><code>for row in df.iterrows():
</code></pre>
<p>But I do not understand what the <code>row</code> object is and how I can work with it.</p> | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html#pandas-dataframe-iterrows" rel="noreferrer"><code>DataFrame.iterrows</code></a> is a generator which yields both the index and row (as a Series):</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]})
df = df.reset_index() # make sure indexes pair with number of rows
for index, row in df.iterrows():
print(row['c1'], row['c2'])
</code></pre>
<pre><code>10 100
11 110
12 120
</code></pre> | {
"question_id": 16476924,
"question_date": "2013-05-10T07:04:49.897Z",
"question_score": 3594,
"tags": "python|pandas|dataframe",
"answer_id": 16476974,
"answer_date": "2013-05-10T07:07:58.523Z",
"answer_score": 4726
} |
Please answer the following Stack Overflow question:
Title: Does Python have a string 'contains' substring method?
<p>I'm looking for a <code>string.contains</code> or <code>string.indexof</code> method in Python.</p>
<p>I want to do:</p>
<pre><code>if not somestring.contains("blah"):
continue
</code></pre> | <p>Use the <a href="https://docs.python.org/reference/expressions.html#membership-test-details" rel="noreferrer"><code>in</code> operator</a>:</p>
<pre><code>if "blah" not in somestring:
continue
</code></pre> | {
"question_id": 3437059,
"question_date": "2010-08-09T02:52:50.963Z",
"question_score": 3588,
"tags": "python|string|substring|contains",
"answer_id": 3437070,
"answer_date": "2010-08-09T02:56:21.017Z",
"answer_score": 7962
} |
Please answer the following Stack Overflow question:
Title: How do I stash only one file out of multiple files that have changed?
<p>How do I stash only one of the multiple changed files on my branch?</p> | <pre><code>git stash push -p -m "my commit message"
</code></pre>
<p><code>-p</code> let's you select the hunks that should be stashed; whole files can be selected as well.</p>
<p>You'll be prompted with a few actions for each hunk:</p>
<pre><code> y - stash this hunk
n - do not stash this hunk
q - quit; do not stash this hunk or any of the remaining ones
a - stash this hunk and all later hunks in the file
d - do not stash this hunk or any of the later hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help
</code></pre> | {
"question_id": 3040833,
"question_date": "2010-06-14T20:52:33.507Z",
"question_score": 3584,
"tags": "git|git-stash",
"answer_id": 17969785,
"answer_date": "2013-07-31T11:59:56.827Z",
"answer_score": 3427
} |
Please answer the following Stack Overflow question:
Title: Catch multiple exceptions in one line (except block)
<p>I know that I can do:</p>
<pre><code>try:
# do something that may fail
except:
# do this if ANYTHING goes wrong
</code></pre>
<p>I can also do this:</p>
<pre><code>try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreTooShortException:
# stand on a ladder
</code></pre>
<p>But if I want to do the same thing inside two different exceptions, the best I can think of right now is to do this:</p>
<pre><code>try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreBeingMeanException:
# say please
</code></pre>
<p>Is there any way that I can do something like this (since the action to take in both exceptions is to <code>say please</code>):</p>
<pre><code>try:
# do something that may fail
except IDontLikeYouException, YouAreBeingMeanException:
# say please
</code></pre>
<p>Now this really won't work, as it matches the syntax for:</p>
<pre><code>try:
# do something that may fail
except Exception, e:
# say please
</code></pre>
<p>So, my effort to catch the two distinct exceptions doesn't exactly come through.</p>
<p>Is there a way to do this?</p> | <p>From <a href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions" rel="noreferrer">Python Documentation</a>:</p>
<blockquote>
<p>An except clause may name multiple exceptions as a parenthesized tuple, for example</p>
</blockquote>
<pre><code>except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
</code></pre>
<p>Or, for Python 2 only:</p>
<pre><code>except (IDontLikeYouException, YouAreBeingMeanException), e:
pass
</code></pre>
<p>Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using <code>as</code>.</p> | {
"question_id": 6470428,
"question_date": "2011-06-24T15:55:08.617Z",
"question_score": 3580,
"tags": "python|exception|exception-handling",
"answer_id": 6470452,
"answer_date": "2011-06-24T15:56:34.030Z",
"answer_score": 4779
} |
Please answer the following Stack Overflow question:
Title: How do I create a remote Git branch?
<p>I created a local branch. How do I push it to the remote server?</p>
<p><strong>UPDATE: I have written a <a href="https://stackoverflow.com/a/27185855/109305">simpler answer for Git 2.0 here</a>.</strong></p> | <h2>Simple Git 2.0+ solution:</h2>
<p>As of <strong>Git 2.0, the behavior has become simpler</strong>:</p>
<p>You can configure git with <strong><code>push.default = current</code></strong> to make life easier:</p>
<p>I added this so now I can just push a new branch upstream with</p>
<pre><code>$ git push -u
</code></pre>
<p><code>-u</code> will track remote branch of the same name. Now with this configuration, you will auto-guess the remote reference to git push. From <a href="http://git-scm.com/docs/git-config" rel="noreferrer">git.config documentation</a>:</p>
<blockquote>
<p><strong>push.default</strong></p>
<p>Defines the action git push should take if no refspec is explicitly given.</p>
<p><strong><code>push.default = current</code></strong> - push the current branch to update a branch with the
same name on the receiving end. Works in both central and non-central workflows.</p>
</blockquote>
<p>For me, this is a good simplification of my day-to-day Git workflow. The configuration setting takes care of the 'usual' use case where you add a branch locally and want to create it remotely. Also, I can just as easily create local branches from remotes by just doing <code>git co remote_branch_name</code> (as opposed to using <code>--set-upstream-to</code> flag).</p>
<p>I know this question and the accepted answers are rather old, but the behavior has changed so that now configuration options exist to make your workflow simpler.</p>
<p>To add to your global Git configuration, run this on the command line:</p>
<pre><code>$ git config --global push.default current
</code></pre> | {
"question_id": 1519006,
"question_date": "2009-10-05T09:21:04.187Z",
"question_score": 3578,
"tags": "git|branch|git-branch",
"answer_id": 27185855,
"answer_date": "2014-11-28T09:46:01.427Z",
"answer_score": 395
} |
Please answer the following Stack Overflow question:
Title: How do I get the current branch name in Git?
<p>How do I get the name of the current branch in Git?</p> | <pre><code>git branch
</code></pre>
<p>should show all the local branches of your repo. The starred branch is your current branch.</p>
<hr />
<p>To retrieve only the name of the branch you are on:</p>
<pre><code>git rev-parse --abbrev-ref HEAD
</code></pre>
<p>or with Git 2.22 and above:</p>
<pre><code>git branch --show-current
</code></pre> | {
"question_id": 6245570,
"question_date": "2011-06-05T20:13:43.930Z",
"question_score": 3567,
"tags": "git|branch|git-branch",
"answer_id": 6245587,
"answer_date": "2011-06-05T20:17:04.933Z",
"answer_score": 3737
} |
Please answer the following Stack Overflow question:
Title: How do I correctly clone a JavaScript object?
<p>I have an object <code>x</code>. I'd like to copy it as object <code>y</code>, such that changes to <code>y</code> do not modify <code>x</code>. I realized that copying objects derived from built-in JavaScript objects will result in extra, unwanted properties. This isn't a problem, since I'm copying one of my own literal-constructed objects.</p>
<p>How do I correctly clone a JavaScript object?</p> | <h3>2022 update</h3>
<p>There's a new JS standard called <a href="https://developer.mozilla.org/en-US/docs/Web/API/structuredClone" rel="noreferrer">structured cloning</a>. It works on all browsers:</p>
<pre class="lang-js prettyprint-override"><code>const clone = structuredClone(object);
</code></pre>
<h2>Old answer</h2>
<p>To do this for any object in JavaScript will not be simple or straightforward. You will run into the problem of erroneously picking up attributes from the object's prototype that should be left in the prototype and not copied to the new instance. If, for instance, you are adding a <code>clone</code> method to <code>Object.prototype</code>, as some answers depict, you will need to explicitly skip that attribute. But what if there are other additional methods added to <code>Object.prototype</code>, or other intermediate prototypes, that you don't know about? In that case, you will copy attributes you shouldn't, so you need to detect unforeseen, non-local attributes with the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty" rel="noreferrer" title="Mozilla JavaScript Reference: Object.hasOwnProperty"><code>hasOwnProperty</code></a> method.</p>
<p>In addition to non-enumerable attributes, you'll encounter a tougher problem when you try to copy objects that have hidden properties. For example, <code>prototype</code> is a hidden property of a function. Also, an object's prototype is referenced with the attribute <code>__proto__</code>, which is also hidden, and will not be copied by a for/in loop iterating over the source object's attributes. I think <code>__proto__</code> might be specific to Firefox's JavaScript interpreter and it may be something different in other browsers, but you get the picture. Not everything is enumerable. You can copy a hidden attribute if you know its name, but I don't know of any way to discover it automatically.</p>
<p>Yet another snag in the quest for an elegant solution is the problem of setting up the prototype inheritance correctly. If your source object's prototype is <code>Object</code>, then simply creating a new general object with <code>{}</code> will work, but if the source's prototype is some descendant of <code>Object</code>, then you are going to be missing the additional members from that prototype which you skipped using the <code>hasOwnProperty</code> filter, or which were in the prototype, but weren't enumerable in the first place. One solution might be to call the source object's <code>constructor</code> property to get the initial copy object and then copy over the attributes, but then you still will not get non-enumerable attributes. For example, a <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date" rel="noreferrer" title="Mozilla JavaScript Reference: Date"><code>Date</code></a> object stores its data as a hidden member:</p>
<pre><code>function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
var d1 = new Date();
/* Executes function after 5 seconds. */
setTimeout(function(){
var d2 = clone(d1);
alert("d1 = " + d1.toString() + "\nd2 = " + d2.toString());
}, 5000);
</code></pre>
<p>The date string for <code>d1</code> will be 5 seconds behind that of <code>d2</code>. A way to make one <code>Date</code> the same as another is by calling the <code>setTime</code> method, but that is specific to the <code>Date</code> class. I don't think there is a bullet-proof general solution to this problem, though I would be happy to be wrong!</p>
<p>When I had to implement general deep copying I ended up compromising by assuming that I would only need to copy a plain <code>Object</code>, <code>Array</code>, <code>Date</code>, <code>String</code>, <code>Number</code>, or <code>Boolean</code>. The last 3 types are immutable, so I could perform a shallow copy and not worry about it changing. I further assumed that any elements contained in <code>Object</code> or <code>Array</code> would also be one of the 6 simple types in that list. This can be accomplished with code like the following:</p>
<pre><code>function clone(obj) {
var copy;
// Handle the 3 simple types, and null or undefined
if (null == obj || "object" != typeof obj) return obj;
// Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
</code></pre>
<p>The above function will work adequately for the 6 simple types I mentioned, as long as the data in the objects and arrays form a tree structure. That is, there isn't more than one reference to the same data in the object. For example:</p>
<pre><code>// This would be cloneable:
var tree = {
"left" : { "left" : null, "right" : null, "data" : 3 },
"right" : null,
"data" : 8
};
// This would kind-of work, but you would get 2 copies of the
// inner node instead of 2 references to the same copy
var directedAcylicGraph = {
"left" : { "left" : null, "right" : null, "data" : 3 },
"data" : 8
};
directedAcyclicGraph["right"] = directedAcyclicGraph["left"];
// Cloning this would cause a stack overflow due to infinite recursion:
var cyclicGraph = {
"left" : { "left" : null, "right" : null, "data" : 3 },
"data" : 8
};
cyclicGraph["right"] = cyclicGraph;
</code></pre>
<p>It will not be able to handle any JavaScript object, but it may be sufficient for many purposes as long as you don't assume that it will just work for anything you throw at it.</p> | {
"question_id": 728360,
"question_date": "2009-04-08T03:01:06.323Z",
"question_score": 3566,
"tags": "javascript|clone|javascript-objects",
"answer_id": 728694,
"answer_date": "2009-04-08T05:58:23.557Z",
"answer_score": 1773
} |
Please answer the following Stack Overflow question:
Title: How do I POST JSON data with cURL?
<p>I use Ubuntu and installed <a href="https://en.wikipedia.org/wiki/CURL" rel="noreferrer">cURL</a> on it. I want to test my Spring REST application with cURL. I wrote my POST code at the Java side. However, I want to test it with cURL. I am trying to post a JSON data. Example data is like this:</p>
<pre><code>{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}
</code></pre>
<p>I use this command:</p>
<pre><code>curl -i \
-H "Accept: application/json" \
-H "X-HTTP-Method-Override: PUT" \
-X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true \
http://localhost:8080/xx/xxx/xxxx
</code></pre>
<p>It returns this error:</p>
<pre><code>HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT
</code></pre>
<p>The error description is this:</p>
<blockquote>
<p><em>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().</em></p>
</blockquote>
<p>Tomcat log:
"POST /ui/webapp/conf/clear HTTP/1.1" 415 1051</p>
<p>What is the right format of the cURL command?</p>
<p>This is my Java side <code>PUT</code> code (I have tested GET and DELETE and they work):</p>
<pre><code>@RequestMapping(method = RequestMethod.PUT)
public Configuration updateConfiguration(HttpServletResponse response, @RequestBody Configuration configuration) { //consider @Valid tag
configuration.setName("PUT worked");
//todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND);
return configuration;
}
</code></pre> | <p>You need to set your content-type to application/json. But <a href="https://curl.haxx.se/docs/manpage.html#-d" rel="noreferrer"><code>-d</code></a> (or <code>--data</code>) sends the Content-Type <code>application/x-www-form-urlencoded</code>, which is not accepted on Spring's side.</p>
<p>Looking at the <a href="https://curl.haxx.se/docs/manpage.html" rel="noreferrer">curl man page</a>, I think you can use <a href="https://curl.haxx.se/docs/manpage.html#-H" rel="noreferrer"><code>-H</code></a> (or <code>--header</code>):</p>
<pre><code>-H "Content-Type: application/json"
</code></pre>
<p>Full example:</p>
<pre><code>curl --header "Content-Type: application/json" \
--request POST \
--data '{"username":"xyz","password":"xyz"}' \
http://localhost:3000/api/login
</code></pre>
<p>(<code>-H</code> is short for <code>--header</code>, <code>-d</code> for <code>--data</code>)</p>
<p>Note that <code>-request POST</code> is <em>optional</em> if you use <code>-d</code>, as the <code>-d</code> flag implies a POST request.</p>
<hr />
<p>On Windows, things are slightly different. See the comment thread.</p> | {
"question_id": 7172784,
"question_date": "2011-08-24T08:51:11.793Z",
"question_score": 3564,
"tags": "json|rest|spring-mvc|curl|http-headers",
"answer_id": 7173011,
"answer_date": "2011-08-24T09:12:29.297Z",
"answer_score": 5354
} |
Please answer the following Stack Overflow question:
Title: Get the current URL with JavaScript?
<p>All I want is to get the website URL. Not the URL as taken from a link. On the page loading I need to be able to grab the full, current URL of the website and set it as a variable to do with as I please.</p> | <p>Use:</p>
<pre><code>window.location.href
</code></pre>
<p>As noted in the comments, the line below works, but it is bugged for Firefox.</p>
<pre><code>document.URL
</code></pre>
<p>See <strong><a href="https://web.archive.org/web/20170327080647/http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-46183437" rel="noreferrer">URL of type DOMString, readonly</a></strong>.</p> | {
"question_id": 1034621,
"question_date": "2009-06-23T19:26:45.823Z",
"question_score": 3536,
"tags": "javascript|url",
"answer_id": 1034642,
"answer_date": "2009-06-23T19:29:00.920Z",
"answer_score": 4264
} |
Please answer the following Stack Overflow question:
Title: What is the difference between public, protected, package-private and private in Java?
<p>In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), <code>public</code>, <code>protected</code> and <code>private</code>, while making <code>class</code> and <code>interface</code> and dealing with inheritance?</p> | <p><a href="http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html" rel="noreferrer">The official tutorial</a> may be of some use to you.</p>
<hr />
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>Class</th>
<th>Package</th>
<th>Subclass<br/>(same pkg)</th>
<th>Subclass<br/>(diff pkg)</th>
<th>World</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>public</code></td>
<td>+</td>
<td>+</td>
<td>+</td>
<td>+</td>
<td>+</td>
</tr>
<tr>
<td><code>protected</code></td>
<td>+</td>
<td>+</td>
<td>+</td>
<td>+</td>
<td></td>
</tr>
<tr>
<td><em>no modifier</em></td>
<td>+</td>
<td>+</td>
<td>+</td>
<td></td>
<td></td>
</tr>
<tr>
<td><code>private</code></td>
<td>+</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>+ : accessible<br/>
blank : not accessible</p> | {
"question_id": 215497,
"question_date": "2008-10-18T19:53:12.187Z",
"question_score": 3536,
"tags": "java|private|public|protected|access-modifiers",
"answer_id": 215505,
"answer_date": "2008-10-18T19:57:50.150Z",
"answer_score": 6172
} |
Please answer the following Stack Overflow question:
Title: When to use LinkedList over ArrayList in Java?
<p>I've always been one to simply use:</p>
<pre><code>List<String> names = new ArrayList<>();
</code></pre>
<p>I use the interface as the type name for <em>portability</em>, so that when I ask questions such as this, I can rework my code.</p>
<p>When should <a href="https://docs.oracle.com/javase/9/docs/api/java/util/LinkedList.html" rel="noreferrer"><code>LinkedList</code></a> be used over <a href="https://docs.oracle.com/javase/9/docs/api/java/util/ArrayList.html" rel="noreferrer"><code>ArrayList</code></a> and vice-versa?</p> | <p><strong>Summary</strong> <code>ArrayList</code> with <code>ArrayDeque</code> are preferable in <em>many</em> more use-cases than <code>LinkedList</code>. If you're not sure — just start with <code>ArrayList</code>.</p>
<hr />
<p>TLDR, in <code>ArrayList</code> accessing an element takes constant time [O(1)] and adding an element takes O(n) time [worst case]. In <code>LinkedList</code> inserting an element takes O(n) time and accessing also takes O(n) time but <code>LinkedList</code> uses more memory than <code>ArrayList</code>.</p>
<p><code>LinkedList</code> and <code>ArrayList</code> are two different implementations of the <code>List</code> interface. <code>LinkedList</code> implements it with a doubly-linked list. <code>ArrayList</code> implements it with a dynamically re-sizing array.</p>
<p>As with standard linked list and array operations, the various methods will have different algorithmic runtimes.</p>
<p>For <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/LinkedList.html" rel="noreferrer"><code>LinkedList<E></code></a></p>
<ul>
<li><code>get(int index)</code> is <em>O(n)</em> (with <em>n/4</em> steps on average), but <em>O(1)</em> when <code>index = 0</code> or <code>index = list.size() - 1</code> (in this case, you can also use <code>getFirst()</code> and <code>getLast()</code>). <strong>One of the main benefits of</strong> <code>LinkedList<E></code></li>
<li><code>add(int index, E element)</code> is <em>O(n)</em> (with <em>n/4</em> steps on average), but <em>O(1)</em> when <code>index = 0</code> or <code>index = list.size() - 1</code> (in this case, you can also use <code>addFirst()</code> and <code>addLast()</code>/<code>add()</code>). <strong>One of the main benefits of</strong> <code>LinkedList<E></code></li>
<li><code>remove(int index)</code> is <em>O(n)</em> (with <em>n/4</em> steps on average), but <em>O(1)</em> when <code>index = 0</code> or <code>index = list.size() - 1</code> (in this case, you can also use <code>removeFirst()</code> and <code>removeLast()</code>). <strong>One of the main benefits of</strong> <code>LinkedList<E></code></li>
<li><code>Iterator.remove()</code> is <em>O(1)</em>. <strong>One of the main benefits of</strong> <code>LinkedList<E></code></li>
<li><code>ListIterator.add(E element)</code> is <em>O(1)</em>. <strong>One of the main benefits of</strong> <code>LinkedList<E></code></li>
</ul>
<p><sup>Note: Many of the operations need <em>n/4</em> steps on average, <em>constant</em> number of steps in the best case (e.g. index = 0), and <em>n/2</em> steps in worst case (middle of list)</sup></p>
<p>For <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html" rel="noreferrer"><code>ArrayList<E></code></a></p>
<ul>
<li><code>get(int index)</code> is <em>O(1)</em>. <strong>Main benefit of</strong> <code>ArrayList<E></code></li>
<li><code>add(E element)</code> is <em>O(1)</em> amortized, but <em>O(n)</em> worst-case since the array must be resized and copied</li>
<li><code>add(int index, E element)</code> is <em>O(n)</em> (with <em>n/2</em> steps on average)</li>
<li><code>remove(int index)</code> is <em>O(n)</em> (with <em>n/2</em> steps on average)</li>
<li><code>Iterator.remove()</code> is <em>O(n)</em> (with <em>n/2</em> steps on average)</li>
<li><code>ListIterator.add(E element)</code> is <em>O(n)</em> (with <em>n/2</em> steps on average)</li>
</ul>
<p><sup>Note: Many of the operations need <em>n/2</em> steps on average, <em>constant</em> number of steps in the best case (end of list), <em>n</em> steps in the worst case (start of list)</sup></p>
<p><code>LinkedList<E></code> allows for constant-time insertions or removals <em>using iterators</em>, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but finding a position in the list takes time proportional to the size of the list. Javadoc says <em>"operations that index into the list will traverse the list from the beginning or the end, whichever is closer"</em>, so those methods are <em>O(n)</em> (<em>n/4</em> steps) on average, though <em>O(1)</em> for <code>index = 0</code>.</p>
<p><code>ArrayList<E></code>, on the other hand, allow fast random read access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap. Also, if you add more elements than the capacity of the underlying array, a new array (1.5 times the size) is allocated, and the old array is copied to the new one, so adding to an <code>ArrayList</code> is <em>O(n)</em> in the worst case but constant on average.</p>
<p>So depending on the operations you intend to do, you should choose the implementations accordingly. Iterating over either kind of List is practically equally cheap. (Iterating over an <code>ArrayList</code> is technically faster, but unless you're doing something really performance-sensitive, you shouldn't worry about this -- they're both constants.)</p>
<p>The main benefits of using a <code>LinkedList</code> arise when you re-use existing iterators to insert and remove elements. These operations can then be done in <em>O(1)</em> by changing the list locally only. In an array list, the remainder of the array needs to be <em>moved</em> (i.e. copied). On the other side, seeking in a <code>LinkedList</code> means following the links in <em>O(n)</em> (<em>n/2</em> steps) for worst case, whereas in an <code>ArrayList</code> the desired position can be computed mathematically and accessed in <em>O(1)</em>.</p>
<p>Another benefit of using a <code>LinkedList</code> arises when you add or remove from the head of the list, since those operations are <em>O(1)</em>, while they are <em>O(n)</em> for <code>ArrayList</code>. Note that <code>ArrayDeque</code> may be a good alternative to <code>LinkedList</code> for adding and removing from the head, but it is not a <code>List</code>.</p>
<p>Also, if you have large lists, keep in mind that memory usage is also different. Each element of a <code>LinkedList</code> has more overhead since pointers to the next and previous elements are also stored. <code>ArrayLists</code> don't have this overhead. However, <code>ArrayLists</code> take up as much memory as is allocated for the capacity, regardless of whether elements have actually been added.</p>
<p>The default initial capacity of an <code>ArrayList</code> is pretty small (10 from Java 1.4 - 1.8). But since the underlying implementation is an array, the array must be resized if you add a lot of elements. To avoid the high cost of resizing when you know you're going to add a lot of elements, construct the <code>ArrayList</code> with a higher initial capacity.</p>
<p>If the data structures perspective is used to understand the two structures, a LinkedList is basically a sequential data structure which contains a head Node. The Node is a wrapper for two components : a value of type T [accepted through generics] and another reference to the Node linked to it. So, we can assert it is a recursive data structure (a Node contains another Node which has another Node and so on...). Addition of elements takes linear time in LinkedList as stated above.</p>
<p>An ArrayList is a growable array. It is just like a regular array. Under the hood, when an element is added, and the ArrayList is already full to capacity, it creates another array with a size which is greater than previous size. The elements are then copied from previous array to new one and the elements that are to be added are also placed at the specified indices.</p> | {
"question_id": 322715,
"question_date": "2008-11-27T01:36:35.567Z",
"question_score": 3495,
"tags": "java|arraylist|collections|linked-list",
"answer_id": 322742,
"answer_date": "2008-11-27T01:49:42.357Z",
"answer_score": 3781
} |
Please answer the following Stack Overflow question:
Title: What is dependency injection?
<p>There have been several questions already posted with specific questions about <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer">dependency injection</a>, such as when to use it and what frameworks are there for it. However,</p>
<p><strong>What is dependency injection and when/why should or shouldn't it be used?</strong></p> | <p><strong>Dependency Injection</strong> is passing dependency to other <strong>objects</strong> or <strong>framework</strong>( dependency injector).</p>
<p>Dependency injection makes testing easier. The injection can be done through <strong>constructor</strong>. </p>
<p><code>SomeClass()</code> has its constructor as following:</p>
<pre class="lang-csh prettyprint-override"><code>public SomeClass() {
myObject = Factory.getObject();
}
</code></pre>
<p><strong>Problem</strong>:
If <code>myObject</code> involves complex tasks such as disk access or network access, it is <strong>hard</strong> to do unit test on <code>SomeClass()</code>. Programmers have to mock <code>myObject</code> and might <strong>intercept</strong> the factory call.</p>
<p><strong>Alternative solution</strong>: </p>
<ul>
<li>Passing <code>myObject</code> in as an argument to the constructor</li>
</ul>
<pre class="lang-csh prettyprint-override"><code>public SomeClass (MyClass myObject) {
this.myObject = myObject;
}
</code></pre>
<p><code>myObject</code> can be passed directly which makes testing easier. </p>
<ul>
<li>One common alternative is defining a <strong>do-nothing constructor</strong>. Dependency injection can be done through setters. (h/t @MikeVella). </li>
<li><a href="http://martinfowler.com/articles/injection.html#InterfaceInjection" rel="noreferrer">Martin Fowler</a> documents a third alternative (h/t @MarcDix), where <strong>classes explicitly implement an interface</strong> for the dependencies programmers wish injected.</li>
</ul>
<p>It is harder to isolate components in unit testing without dependency injection. </p>
<p>In 2013, when I wrote this answer, this was a major theme on the <a href="http://googletesting.blogspot.com/" rel="noreferrer">Google Testing Blog</a>. It remains the biggest advantage to me, as programmers not always need the extra flexibility in their run-time design (for instance, for service locator or similar patterns). Programmers often need to isolate the classes during testing.</p> | {
"question_id": 130794,
"question_date": "2008-09-25T00:28:40.600Z",
"question_score": 3490,
"tags": "design-patterns|language-agnostic|dependency-injection|terminology",
"answer_id": 130862,
"answer_date": "2008-09-25T00:49:32.063Z",
"answer_score": 2119
} |
Please answer the following Stack Overflow question:
Title: What does the explicit keyword mean?
<p>What does the <code>explicit</code> keyword mean in C++?</p> | <p>The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a <strong>single parameter</strong> to convert from one type to another in order to get the right type for a parameter.</p>
<p>Here's an example class with a constructor that can be used for implicit conversions:</p>
<pre><code>class Foo
{
private:
int m_foo;
public:
// single parameter constructor, can be used as an implicit conversion
Foo (int foo) : m_foo (foo) {}
int GetFoo () { return m_foo; }
};
</code></pre>
<p>Here's a simple function that takes a <code>Foo</code> object:</p>
<pre><code>void DoBar (Foo foo)
{
int i = foo.GetFoo ();
}
</code></pre>
<p>and here's where the <code>DoBar</code> function is called:</p>
<pre><code>int main ()
{
DoBar (42);
}
</code></pre>
<p>The argument is not a <code>Foo</code> object, but an <code>int</code>. However, there exists a constructor for <code>Foo</code> that takes an <code>int</code> so this constructor can be used to convert the parameter to the correct type.</p>
<p>The compiler is allowed to do this once for each parameter.</p>
<p>Prefixing the <code>explicit</code> keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call <code>DoBar (42)</code>. It is now necessary to call for conversion explicitly with <code>DoBar (Foo (42))</code></p>
<p>The reason you might want to do this is to avoid accidental construction that can hide bugs.<br />
Contrived example:</p>
<ul>
<li>You have a <code>MyString</code> class with a constructor that constructs a string of the given size. You have a function <code>print(const MyString&)</code> (as well as an overload <code>print (char *string)</code>), and you call <code>print(3)</code> (when you <em>actually</em> intended to call <code>print("3")</code>). You expect it to print "3", but it prints an empty string of length 3 instead.</li>
</ul> | {
"question_id": 121162,
"question_date": "2008-09-23T13:58:45.630Z",
"question_score": 3483,
"tags": "c++|constructor|explicit|c++-faq|explicit-constructor",
"answer_id": 121163,
"answer_date": "2008-09-23T13:59:04.413Z",
"answer_score": 3970
} |
Please answer the following Stack Overflow question:
Title: What is the difference between __str__ and __repr__?
<p>What is the difference between <a href="https://docs.python.org/3/reference/datamodel.html#object.__str__" rel="noreferrer"><code>__str__</code></a> and <a href="https://docs.python.org/3/reference/datamodel.html#object.__repr__" rel="noreferrer"><code>__repr__</code></a> in Python?</p> | <p><a href="https://stackoverflow.com/users/95810/alex-martelli">Alex</a> summarized well but, surprisingly, was too succinct.</p>
<p>First, let me reiterate the main points in <a href="https://stackoverflow.com/a/1436756/3798217">Alex’s post</a>:</p>
<ul>
<li>The default implementation is useless (it’s hard to think of one which wouldn’t be, but yeah)</li>
<li><code>__repr__</code> goal is to be unambiguous</li>
<li><code>__str__</code> goal is to be readable</li>
<li>Container’s <code>__str__</code> uses contained objects’ <code>__repr__</code></li>
</ul>
<p><strong>Default implementation is useless</strong></p>
<p>This is mostly a surprise because Python’s defaults tend to be fairly useful. However, in this case, having a default for <code>__repr__</code> which would act like:</p>
<pre><code>return "%s(%r)" % (self.__class__, self.__dict__)
</code></pre>
<p>would have been too dangerous (for example, too easy to get into infinite recursion if objects reference each other). So Python cops out. Note that there is one default which is true: if <code>__repr__</code> is defined, and <code>__str__</code> is not, the object will behave as though <code>__str__=__repr__</code>.</p>
<p>This means, in simple terms: almost every object you implement should have a functional <code>__repr__</code> that’s usable for understanding the object. Implementing <code>__str__</code> is optional: do that if you need a “pretty print” functionality (for example, used by a report generator).</p>
<p><strong>The goal of <code>__repr__</code> is to be unambiguous</strong></p>
<p>Let me come right out and say it — I do not believe in debuggers. I don’t really know how to use any debugger, and have never used one seriously. Furthermore, I believe that the big fault in debuggers is their basic nature — most failures I debug happened a long long time ago, in a galaxy far far away. This means that I do believe, with religious fervor, in logging. Logging is the lifeblood of any decent fire-and-forget server system. Python makes it easy to log: with maybe some project specific wrappers, all you need is a</p>
<pre><code>log(INFO, "I am in the weird function and a is", a, "and b is", b, "but I got a null C — using default", default_c)
</code></pre>
<p>But you have to do the last step — make sure every object you implement has a useful repr, so code like that can just work. This is why the “eval” thing comes up: if you have enough information so <code>eval(repr(c))==c</code>, that means you know everything there is to know about <code>c</code>. If that’s easy enough, at least in a fuzzy way, do it. If not, make sure you have enough information about <code>c</code> anyway. I usually use an eval-like format: <code>"MyClass(this=%r,that=%r)" % (self.this,self.that)</code>. It does not mean that you can actually construct MyClass, or that those are the right constructor arguments — but it is a useful form to express “this is everything you need to know about this instance”.</p>
<p>Note: I used <code>%r</code> above, not <code>%s</code>. You always want to use <code>repr()</code> [or <code>%r</code> formatting character, equivalently] inside <code>__repr__</code> implementation, or you’re defeating the goal of repr. You want to be able to differentiate <code>MyClass(3)</code> and <code>MyClass("3")</code>.</p>
<p><strong>The goal of <code>__str__</code> is to be readable</strong></p>
<p>Specifically, it is not intended to be unambiguous — notice that <code>str(3)==str("3")</code>. Likewise, if you implement an IP abstraction, having the str of it look like 192.168.1.1 is just fine. When implementing a date/time abstraction, the str can be "2010/4/12 15:35:22", etc. The goal is to represent it in a way that a user, not a programmer, would want to read it. Chop off useless digits, pretend to be some other class — as long is it supports readability, it is an improvement.</p>
<p><strong>Container’s <code>__str__</code> uses contained objects’ <code>__repr__</code></strong></p>
<p>This seems surprising, doesn’t it? It is a little, but how readable would it be if it used their <code>__str__</code>?</p>
<pre><code>[moshe is, 3, hello
world, this is a list, oh I don't know, containing just 4 elements]
</code></pre>
<p>Not very. Specifically, the strings in a container would find it way too easy to disturb its string representation. In the face of ambiguity, remember, Python resists the temptation to guess. If you want the above behavior when you’re printing a list, just</p>
<pre><code>print("[" + ", ".join(l) + "]")
</code></pre>
<p>(you can probably also figure out what to do about dictionaries.</p>
<p><strong>Summary</strong></p>
<p>Implement <code>__repr__</code> for any class you implement. This should be second nature. Implement <code>__str__</code> if you think it would be useful to have a string version which errs on the side of readability.</p> | {
"question_id": 1436703,
"question_date": "2009-09-17T04:27:45.907Z",
"question_score": 3461,
"tags": "python|magic-methods|repr",
"answer_id": 2626364,
"answer_date": "2010-04-13T00:56:52.533Z",
"answer_score": 3293
} |
Please answer the following Stack Overflow question:
Title: Convert bytes to a string
<p>I captured the standard output of an external program into a <code>bytes</code> object:</p>
<pre class="lang-none prettyprint-override"><code>>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>>
>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
</code></pre>
<p>I want to convert that to a normal Python string, so that I can print it like this:</p>
<pre class="lang-none prettyprint-override"><code>>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
</code></pre>
<p>I tried the <a href="http://docs.python.org/3.0/library/binascii.html?highlight=b2a#binascii.b2a_qp" rel="nofollow noreferrer"><code>binascii.b2a_qp()</code></a> method, but got the same <code>bytes</code> object again:</p>
<pre class="lang-none prettyprint-override"><code>>>> binascii.b2a_qp(command_stdout)
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
</code></pre>
<p>How do I convert the <code>bytes</code> object to a <code>str</code> with Python 3?</p> | <p><a href="https://docs.python.org/3/library/stdtypes.html#bytes.decode" rel="noreferrer">Decode the <code>bytes</code> object</a> to produce a string:</p>
<pre><code>>>> b"abcde".decode("utf-8")
'abcde'
</code></pre>
<p>The above example <em>assumes</em> that the <code>bytes</code> object is in UTF-8, because it is a common encoding. However, you should use the encoding your data is actually in!</p> | {
"question_id": 606191,
"question_date": "2009-03-03T12:23:01.583Z",
"question_score": 3455,
"tags": "python|string|python-3.x",
"answer_id": 606199,
"answer_date": "2009-03-03T12:26:18.313Z",
"answer_score": 5291
} |
Please answer the following Stack Overflow question:
Title: How do I loop through or enumerate a JavaScript object?
<p>I have a JavaScript object like the following:</p>
<pre><code>var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
</code></pre>
<p>How do I loop through all of <code>p</code>'s elements (<code>p1</code>, <code>p2</code>, <code>p3</code>...) and get their keys and values?</p> | <p>You can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in" rel="noreferrer"><code>for-in</code></a> loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.</p>
<p><strong>Here is the snippet:</strong>
<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>var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}</code></pre>
</div>
</div>
</p>
<p><strong>For-of with Object.keys() alternative:</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>var p = {
0: "value1",
"b": "value2",
key: "value3"
};
for (var key of Object.keys(p)) {
console.log(key + " -> " + p[key])
}</code></pre>
</div>
</div>
</p>
<p>Notice the use of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of" rel="noreferrer"><code>for-of</code></a> instead of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in" rel="noreferrer"><code>for-in</code></a>, if not used it will return undefined on named properties, and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys" rel="noreferrer"><code>Object.keys()</code></a> ensures the use of only the object's own properties without the whole prototype-chain properties</p>
<p><strong>Using the new <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries" rel="noreferrer"><code>Object.entries()</code></a> method:</strong></p>
<p><strong>Note:</strong> This method is not supported natively by Internet Explorer. You may consider using a Polyfill for older browsers.</p>
<pre class="lang-js prettyprint-override"><code>const p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (let [key, value] of Object.entries(p)) {
console.log(`${key}: ${value}`);
}
</code></pre> | {
"question_id": 684672,
"question_date": "2009-03-26T06:01:47.873Z",
"question_score": 3443,
"tags": "javascript|loops|for-loop|each",
"answer_id": 684692,
"answer_date": "2009-03-26T06:12:13.807Z",
"answer_score": 5012
} |
Please answer the following Stack Overflow question:
Title: How do I sort a dictionary by value?
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p>
<p>I can sort on the keys, but how can I sort based on the values?</p>
<p>Note: I have read Stack Overflow question here <em><a href="https://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by a value of the dictionary?</a></em> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution to sort either in ascending or descending order.</p> | <h3>Python 3.7+ or CPython 3.6</h3>
<p>Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but <a href="https://stackoverflow.com/q/39980323/4518341">it's an implementation detail</a>.</p>
<pre><code>>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
</code></pre>
<p>or</p>
<pre><code>>>> dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
</code></pre>
<h3>Older Python</h3>
<p>It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.</p>
<p>For instance,</p>
<pre><code>import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
</code></pre>
<p><code>sorted_x</code> will be a list of tuples sorted by the second element in each tuple. <code>dict(sorted_x) == x</code>.</p>
<p>And for those wishing to sort on keys instead of values:</p>
<pre><code>import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
</code></pre>
<p>In Python3 since <a href="https://stackoverflow.com/a/15712231/4293057">unpacking is not allowed</a> we can use</p>
<pre><code>x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])
</code></pre>
<p>If you want the output as a dict, you can use <a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict" rel="noreferrer"><code>collections.OrderedDict</code></a>:</p>
<pre><code>import collections
sorted_dict = collections.OrderedDict(sorted_x)
</code></pre> | {
"question_id": 613183,
"question_date": "2009-03-05T00:49:05.383Z",
"question_score": 3416,
"tags": "python|sorting|dictionary",
"answer_id": 613218,
"answer_date": "2009-03-05T00:59:34.143Z",
"answer_score": 6560
} |
Please answer the following Stack Overflow question:
Title: How to copy files?
<p>How do I copy a file in Python?</p> | <p><a href="http://docs.python.org/3/library/shutil.html" rel="noreferrer"><code>shutil</code></a> has many methods you can use. One of which is:</p>
<pre><code>import shutil
shutil.copyfile(src, dst)
# 2nd option
shutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp
</code></pre>
<ul>
<li>Copy the contents of the file named <code>src</code> to a file named <code>dst</code>. Both <code>src</code> and <code>dst</code> need to be the entire filename of the files, including path.</li>
<li>The destination location must be writable; otherwise, an <code>IOError</code> exception will be raised.</li>
<li>If <code>dst</code> already exists, it will be replaced.</li>
<li>Special files such as character or block devices and pipes cannot be copied with this function.</li>
<li>With <code>copy</code>, <code>src</code> and <code>dst</code> are path names given as <code>str</code>s.</li>
</ul>
<p>Another <code>shutil</code> method to look at is <a href="https://docs.python.org/3/library/shutil.html#shutil.copy2" rel="noreferrer"><code>shutil.copy2()</code></a>. It's similar but preserves more metadata (e.g. time stamps).</p>
<p>If you use <code>os.path</code> operations, use <code>copy</code> rather than <code>copyfile</code>. <code>copyfile</code> will only accept strings.</p> | {
"question_id": 123198,
"question_date": "2008-09-23T19:23:48.643Z",
"question_score": 3416,
"tags": "python|file|copy|filesystems|file-copying",
"answer_id": 123212,
"answer_date": "2008-09-23T19:25:35.393Z",
"answer_score": 4244
} |
Please answer the following Stack Overflow question:
Title: How do I convert a String to an int in Java?
<p>How can I convert a <code>String</code> to an <code>int</code>?</p>
<pre><code>"1234" → 1234
</code></pre> | <pre><code>String myString = "1234";
int foo = Integer.parseInt(myString);
</code></pre>
<p>If you look at the <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Integer.html#parseInt(java.lang.String)" rel="noreferrer">Java documentation</a> you'll notice the "catch" is that this function can throw a <code>NumberFormatException</code>, which you can handle:</p>
<pre><code>int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e) {
foo = 0;
}
</code></pre>
<p>(This treatment defaults a malformed number to <code>0</code>, but you can do something else if you like.)</p>
<p>Alternatively, you can use an <code>Ints</code> method from the Guava library, which in combination with Java 8's <code>Optional</code>, makes for a powerful and concise way to convert a string into an int:</p>
<pre><code>import com.google.common.primitives.Ints;
int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)
</code></pre> | {
"question_id": 5585779,
"question_date": "2011-04-07T18:27:54.270Z",
"question_score": 3402,
"tags": "java|string|type-conversion|integer",
"answer_id": 5585800,
"answer_date": "2011-04-07T18:29:41.110Z",
"answer_score": 4438
} |
Please answer the following Stack Overflow question:
Title: AngularJS: Service vs provider vs factory
<p>What are the differences between a <code>Service</code>, <code>Provider</code> and <code>Factory</code> in AngularJS?</p> | <p>From the AngularJS mailing list I got <a href="https://groups.google.com/forum/#!msg/angular/56sdORWEoqg/HuZsOsMvKv4J" rel="noreferrer">an amazing thread</a> that explains service vs factory vs provider and their injection usage. Compiling the answers:</p>
<h1>Services</h1>
<p>Syntax: <code>module.service( 'serviceName', function );</code> <br/>
Result: When declaring serviceName as an injectable argument <strong>you will be provided with an instance of the function. In other words</strong> <code>new FunctionYouPassedToService()</code>.</p>
<h1>Factories</h1>
<p>Syntax: <code>module.factory( 'factoryName', function );</code> <br/>
Result: When declaring factoryName as an injectable argument you will be provided with <strong>the value that is returned by invoking the function reference passed to module.factory</strong>.</p>
<h1>Providers</h1>
<p>Syntax: <code>module.provider( 'providerName', function );</code> <br/>
Result: When declaring providerName as an injectable argument <strong>you will be provided with</strong> <code>(new ProviderFunction()).$get()</code>. The constructor function is instantiated before the $get method is called - <code>ProviderFunction</code> is the function reference passed to module.provider.</p>
<p>Providers have the advantage that they can be configured during the module configuration phase.</p>
<p>See <a href="http://jsbin.com/ohamub/1/edit" rel="noreferrer">here</a> for the provided code.</p>
<p>Here's a great further explanation by Misko:</p>
<pre><code>provide.value('a', 123);
function Controller(a) {
expect(a).toEqual(123);
}
</code></pre>
<p>In this case the injector simply returns the value as is. But what if you want to compute the value? Then use a factory</p>
<pre><code>provide.factory('b', function(a) {
return a*2;
});
function Controller(b) {
expect(b).toEqual(246);
}
</code></pre>
<p>So <code>factory</code> is a function which is responsible for creating the value. Notice that the factory function can ask for other dependencies.</p>
<p>But what if you want to be more OO and have a class called Greeter?</p>
<pre><code>function Greeter(a) {
this.greet = function() {
return 'Hello ' + a;
}
}
</code></pre>
<p>Then to instantiate you would have to write</p>
<pre><code>provide.factory('greeter', function(a) {
return new Greeter(a);
});
</code></pre>
<p>Then we could ask for 'greeter' in controller like this</p>
<pre><code>function Controller(greeter) {
expect(greeter instanceof Greeter).toBe(true);
expect(greeter.greet()).toEqual('Hello 123');
}
</code></pre>
<p>But that is way too wordy. A shorter way to write this would be <code>provider.service('greeter', Greeter);</code></p>
<p>But what if we wanted to configure the <code>Greeter</code> class before the injection? Then we could write</p>
<pre><code>provide.provider('greeter2', function() {
var salutation = 'Hello';
this.setSalutation = function(s) {
salutation = s;
}
function Greeter(a) {
this.greet = function() {
return salutation + ' ' + a;
}
}
this.$get = function(a) {
return new Greeter(a);
};
});
</code></pre>
<p>Then we can do this:</p>
<pre><code>angular.module('abc', []).config(function(greeter2Provider) {
greeter2Provider.setSalutation('Halo');
});
function Controller(greeter2) {
expect(greeter2.greet()).toEqual('Halo 123');
}
</code></pre>
<p>As a side note, <code>service</code>, <code>factory</code>, and <code>value</code> are all derived from provider.</p>
<pre><code>provider.service = function(name, Class) {
provider.provide(name, function() {
this.$get = function($injector) {
return $injector.instantiate(Class);
};
});
}
provider.factory = function(name, factory) {
provider.provide(name, function() {
this.$get = function($injector) {
return $injector.invoke(factory);
};
});
}
provider.value = function(name, value) {
provider.factory(name, function() {
return value;
});
};
</code></pre> | {
"question_id": 15666048,
"question_date": "2013-03-27T17:59:46.853Z",
"question_score": 3390,
"tags": "angularjs|dependency-injection|angularjs-service|angularjs-factory|angularjs-provider",
"answer_id": 15666049,
"answer_date": "2013-03-27T17:59:46.853Z",
"answer_score": 2903
} |
Please answer the following Stack Overflow question:
Title: 403 Forbidden vs 401 Unauthorized HTTP responses
<p>For a web page that exists, but for which a user does not have sufficient privileges (they are not logged in or do not belong to the proper user group), what is the proper HTTP response to serve?</p>
<p><code>401 Unauthorized</code>?<br>
<code>403 Forbidden</code>?<br>
Something else?</p>
<p>What I've read on each so far isn't very clear on the difference between the two. What use cases are appropriate for each response?</p> | <p>A clear explanation from <a href="http://web.archive.org/web/20190904190534/https://www.dirv.me/blog/2011/07/18/understanding-403-forbidden/index.html" rel="noreferrer">Daniel Irvine</a> <sup>[<a href="http://www.dirv.me/blog/2011/07/18/understanding-403-forbidden/index.html" rel="noreferrer">original link</a>]</sup>:</p>
<blockquote>
<p>There's a problem with <em>401 Unauthorized</em>, the HTTP status code for authentication errors. And that’s just it: it’s for authentication, not authorization.
Receiving a 401 response is the server telling you, “you aren’t
authenticated–either not authenticated at all or authenticated
incorrectly–but please reauthenticate and try again.” To help you out,
it will always include a <em>WWW-Authenticate</em> header that describes how
to authenticate.</p>
<p>This is a response generally returned by your web server, not your web
application.</p>
<p>It’s also something very temporary; the server is asking you to try
again.</p>
<p>So, for authorization I use the <em>403 Forbidden</em> response. It’s
permanent, it’s tied to my application logic, and it’s a more concrete
response than a 401.</p>
<p>Receiving a 403 response is the server telling you, “I’m sorry. I know
who you are–I believe who you say you are–but you just don’t have
permission to access this resource. Maybe if you ask the system
administrator nicely, you’ll get permission. But please don’t bother
me again until your predicament changes.”</p>
<p>In summary, a <em>401 Unauthorized</em> response should be used for missing
or bad authentication, and a <em>403 Forbidden</em> response should be used
afterwards, when the user is authenticated but isn’t authorized to
perform the requested operation on the given resource.</p>
</blockquote>
<p>Another <a href="https://www.loggly.com/blog/http-status-code-diagram/" rel="noreferrer">nice pictorial format</a> of how http status codes should be used.</p> | {
"question_id": 3297048,
"question_date": "2010-07-21T07:21:58.080Z",
"question_score": 3377,
"tags": "http-headers|http-status-code-403|http-status-codes|http-status-code-401|http-response-codes",
"answer_id": 6937030,
"answer_date": "2011-08-04T06:24:41.817Z",
"answer_score": 4850
} |
Please answer the following Stack Overflow question:
Title: How can I add new keys to a dictionary?
<p>How do I add a key to an existing dictionary? It doesn't have an <code>.add()</code> method.</p> | <p>You create a new key/value pair on a dictionary by assigning a value to that key</p>
<pre><code>d = {'key': 'value'}
print(d) # {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
</code></pre>
<p>If the key doesn't exist, it's added and points to that value. If it exists, the current value it points to is overwritten.</p> | {
"question_id": 1024847,
"question_date": "2009-06-21T22:07:39.587Z",
"question_score": 3369,
"tags": "python|dictionary|lookup",
"answer_id": 1024851,
"answer_date": "2009-06-21T22:09:06.870Z",
"answer_score": 4256
} |
Please answer the following Stack Overflow question:
Title: What is the difference between call and apply?
<p>What is the difference between using <code>Function.prototype.apply()</code> and <code>Function.prototype.call()</code> to invoke a function?</p>
<pre><code>var func = function() {
alert('hello!');
};
</code></pre>
<p><code>func.apply();</code> vs <code>func.call();</code></p>
<p>Are there performance differences between the two aforementioned methods? When is it best to use <code>call</code> over <code>apply</code> and vice versa?</p> | <p>The difference is that <code>apply</code> lets you invoke the function with <code>arguments</code> as an array; <code>call</code> requires the parameters be listed explicitly. A useful mnemonic is <em>"<strong>A</strong> for <strong>a</strong>rray and <strong>C</strong> for <strong>c</strong>omma."</em></p>
<p>See MDN's documentation on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply" rel="noreferrer">apply</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" rel="noreferrer">call</a>.</p>
<p>Pseudo syntax:</p>
<p><code>theFunction.apply(valueForThis, arrayOfArgs)</code></p>
<p><code>theFunction.call(valueForThis, arg1, arg2, ...)</code></p>
<p>There is also, as of ES6, the possibility to <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator" rel="noreferrer"><code>spread</code></a> the array for use with the <code>call</code> function, you can see the compatibilities <a href="http://kangax.github.io/compat-table/es6/" rel="noreferrer">here</a>.</p>
<p>Sample code:</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>function theFunction(name, profession) {
console.log("My name is " + name + " and I am a " + profession +".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");
theFunction.call(undefined, ...["Matthew", "physicist"]); // used with the spread operator</code></pre>
</div>
</div>
</p> | {
"question_id": 1986896,
"question_date": "2009-12-31T19:56:25.510Z",
"question_score": 3369,
"tags": "javascript|performance|function|dynamic",
"answer_id": 1986909,
"answer_date": "2009-12-31T20:00:42.070Z",
"answer_score": 3917
} |
Please answer the following Stack Overflow question:
Title: How do I list all the files in a commit?
<p>How can I print a plain list of all files that were part of a given commit?</p>
<p>Although the following lists the files, it also includes unwanted diff information for each:</p>
<pre><code>git show a303aa90779efdd2f6b9d90693e2cbbbe4613c1d
</code></pre> | <p><strong>Preferred Way</strong> (because it's a <em>plumbing</em> command; meant to be programmatic):</p>
<pre><code>$ git diff-tree --no-commit-id --name-only -r bd61ad98
index.html
javascript/application.js
javascript/ie6.js
</code></pre>
<p><strong>Another Way</strong> (less preferred for scripts, because it's a <em>porcelain</em> command; meant to be user-facing)</p>
<pre><code>$ git show --pretty="" --name-only bd61ad98
index.html
javascript/application.js
javascript/ie6.js
</code></pre>
<hr>
<ul>
<li>The <code>--no-commit-id</code> suppresses the commit ID output.</li>
<li>The <code>--pretty</code> argument specifies an empty format string to avoid the cruft at the beginning.</li>
<li>The <code>--name-only</code> argument shows only the file names that were affected (Thanks Hank). Use <code>--name-status</code> instead, if you want to see what happened to each file (<strong>D</strong>eleted, <strong>M</strong>odified, <strong>A</strong>dded)</li>
<li>The <code>-r</code> argument is to recurse into sub-trees</li>
</ul> | {
"question_id": 424071,
"question_date": "2009-01-08T12:26:32.570Z",
"question_score": 3363,
"tags": "git|git-show",
"answer_id": 424142,
"answer_date": "2009-01-08T13:02:22.590Z",
"answer_score": 4507
} |
Please answer the following Stack Overflow question:
Title: What is the JavaScript version of sleep()?
<p>Is there a better way to engineer a <code>sleep</code> in JavaScript than the following <code>pausecomp</code> function (<a href="http://www.sean.co.uk/a/webdesign/javascriptdelay.shtm" rel="noreferrer">taken from here</a>)?</p>
<pre><code>function pausecomp(millis)
{
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < millis);
}
</code></pre>
<p>This is not a duplicate of <a href="https://stackoverflow.com/questions/758688/sleep-in-javascript-delay-between-actions">Sleep in JavaScript - delay between actions</a>; I want a <em>real sleep</em> in the middle of a function, and not a delay before a piece of code executes.</p> | <h2>2017 — 2021 update</h2>
<p>Since 2009 when this question was asked, JavaScript has evolved significantly. All other answers are now obsolete or overly complicated. Here is the current best practice:</p>
<pre><code>function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
</code></pre>
<p>Or as a one-liner:</p>
<pre><code>await new Promise(r => setTimeout(r, 2000));
</code></pre>
<p>As a function:</p>
<pre><code>const sleep = ms => new Promise(r => setTimeout(r, ms));
</code></pre>
<p>or in Typescript:</p>
<pre><code>const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
</code></pre>
<p>use it as:</p>
<pre><code>await sleep(<duration>);
</code></pre>
<h3>Demo:</h3>
<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>function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
for (let i = 0; i < 5; i++) {
console.log(`Waiting ${i} seconds...`);
await sleep(i * 1000);
}
console.log('Done');
}
demo();</code></pre>
</div>
</div>
</p>
<p>Note that,</p>
<ol>
<li><code>await</code> can only be executed in functions prefixed with the <code>async</code> keyword, or at the top level of your script in <a href="https://stackoverflow.com/questions/46515764/how-can-i-use-async-await-at-the-top-level/56590390#56590390">an increasing number of environments</a>.</li>
<li><code>await</code> only pauses the current <code>async</code> function. This means it does not block the execution of the rest of the script, which is what you want in the vast majority of the cases. If you do want a blocking construct, see <a href="https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep/56406126#56406126">this answer</a> using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics" rel="noreferrer"><code>Atomics</code></a><code>.wait</code>, but note that most browsers will not allow it on the browser's main thread.</li>
</ol>
<p>Two new JavaScript features (as of 2017) helped write this "sleep" function:</p>
<ul>
<li><a href="https://ponyfoo.com/articles/es6-promises-in-depth" rel="noreferrer">Promises, a native feature of ES2015</a> (aka ES6). We also use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions" rel="noreferrer">arrow functions</a> in the definition of the sleep function.</li>
<li>The <a href="https://ponyfoo.com/articles/understanding-javascript-async-await" rel="noreferrer"><code>async/await</code></a> feature lets the code explicitly wait for a promise to settle (resolve or reject).</li>
</ul>
<h2>Compatibility</h2>
<ul>
<li>promises are supported <a href="http://node.green/#Promise" rel="noreferrer">in Node v0.12+</a> and <a href="http://caniuse.com/#feat=promises" rel="noreferrer">widely supported in browsers</a>, except IE</li>
<li><code>async</code>/<code>await</code> landed in V8 and has been <a href="https://developers.google.com/web/fundamentals/getting-started/primers/async-functions" rel="noreferrer">enabled by default since Chrome 55</a> (released in Dec 2016)
<ul>
<li>it landed <a href="https://blog.risingstack.com/async-await-node-js-7-nightly/" rel="noreferrer">in Node 7 in October 2016</a></li>
<li>and also landed <a href="https://blog.nightly.mozilla.org/2016/11/01/async-await-support-in-firefox/" rel="noreferrer">in Firefox Nightly in November 2016</a></li>
</ul>
</li>
</ul>
<p>If for some reason you're using Node older than 7 (which reached <a href="https://github.com/nodejs/Release#end-of-life-releases" rel="noreferrer">end of life in 2017</a>), or are targeting old browsers, <code>async</code>/<code>await</code> can still be used via <a href="https://babeljs.io/" rel="noreferrer">Babel</a> (a tool that will <a href="https://www.stevefenton.co.uk/2012/11/compiling-vs-transpiling/" rel="noreferrer">transpile</a> JavaScript + new features into plain old JavaScript), with the <a href="https://babeljs.io/docs/en/babel-plugin-transform-async-to-generator" rel="noreferrer"><code>transform-async-to-generator</code></a> plugin.</p> | {
"question_id": 951021,
"question_date": "2009-06-04T14:41:10.240Z",
"question_score": 3342,
"tags": "javascript|sleep",
"answer_id": 39914235,
"answer_date": "2016-10-07T09:44:56.400Z",
"answer_score": 4520
} |
Please answer the following Stack Overflow question:
Title: What is __init__.py for?
<p>What is <a href="https://docs.python.org/3/tutorial/modules.html#packages" rel="noreferrer"><code>__init__.py</code></a> for in a Python source directory?</p> | <p>It used to be a required part of a package (<a href="https://docs.python.org/3/reference/import.html#regular-packages" rel="noreferrer">old, pre-3.3 "regular package"</a>, not <a href="https://docs.python.org/3/reference/import.html#namespace-packages" rel="noreferrer">newer 3.3+ "namespace package"</a>).</p>
<p><a href="https://docs.python.org/3/reference/import.html#regular-packages" rel="noreferrer">Here's the documentation.</a></p>
<blockquote>
<p>Python defines two types of packages, regular packages and namespace packages. Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an <code>__init__.py</code> file. When a regular package is imported, this <code>__init__.py</code> file is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The <code>__init__.py</code> file can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported.</p>
</blockquote>
<p>But just click the link, it contains an example, more information, and an explanation of namespace packages, the kind of packages without <code>__init__.py</code>.</p> | {
"question_id": 448271,
"question_date": "2009-01-15T20:09:09.707Z",
"question_score": 3338,
"tags": "python|module|package|python-packaging",
"answer_id": 448279,
"answer_date": "2009-01-15T20:13:24.987Z",
"answer_score": 1874
} |
Please answer the following Stack Overflow question:
Title: Commit only part of a file in Git
<p>When I make changes to a file in Git, how can I commit only some of the changes?</p>
<p>For example, how could I commit only 15 lines out of 30 lines that have been changed in a file?</p> | <p>You can use:</p>
<pre class="lang-bash prettyprint-override"><code>git add --patch <filename>
</code></pre>
<p>or for short:</p>
<pre class="lang-bash prettyprint-override"><code>git add -p <filename>
</code></pre>
<p>Git will break down your file into what it thinks are sensible "hunks" (portions of the file). It will then prompt you with this question:</p>
<pre><code>Stage this hunk [y,n,q,a,d,/,j,J,g,s,e,?]?
</code></pre>
<p>Here is a description of each option:</p>
<ul>
<li><kbd>y</kbd> stage this hunk for the next commit</li>
<li><kbd>n</kbd> do not stage this hunk for the next commit</li>
<li><kbd>q</kbd> quit; do not stage this hunk or any of the remaining hunks</li>
<li><kbd>a</kbd> stage this hunk and all later hunks in the file</li>
<li><kbd>d</kbd> do not stage this hunk or any of the later hunks in the file</li>
<li><kbd>g</kbd> select a hunk to go to</li>
<li><kbd>/</kbd> search for a hunk matching the given regex</li>
<li><kbd>j</kbd> leave this hunk undecided, see next undecided hunk</li>
<li><kbd>J</kbd> leave this hunk undecided, see next hunk</li>
<li><kbd>k</kbd> leave this hunk undecided, see previous undecided hunk</li>
<li><kbd>K</kbd> leave this hunk undecided, see previous hunk</li>
<li><kbd>s</kbd> split the current hunk into smaller hunks</li>
<li><kbd>e</kbd> manually edit the current hunk
<ul>
<li>You can then edit the hunk manually by replacing <code>+</code>/<code>-</code> by <code>#</code> (thanks <a href="https://stackoverflow.com/users/1732521/veksen">veksen</a>)</li>
</ul>
</li>
<li><kbd>?</kbd> print hunk help</li>
</ul>
<p>If the file is not in the repository yet, you can first do <code>git add -N <filename></code>. Afterwards you can go on with <code>git add -p <filename></code>.</p>
<p>Afterwards, you can use:</p>
<ul>
<li><code>git diff --staged</code> to check that you staged the correct changes</li>
<li><code>git reset -p</code> to unstage mistakenly added hunks</li>
<li><code>git commit -v</code> to view your commit while you edit the commit message.</li>
</ul>
<p>Note this is far different than the <code>git format-patch</code> command, whose purpose is to parse commit data into a <code>.patch</code> files.</p>
<p>Reference for future: <a href="https://git-scm.com/book/en/v2/Git-Tools-Interactive-Staging" rel="noreferrer">Git Tools - Interactive Staging</a></p> | {
"question_id": 1085162,
"question_date": "2009-07-06T02:25:02.390Z",
"question_score": 3336,
"tags": "git|git-commit",
"answer_id": 1085191,
"answer_date": "2009-07-06T02:36:42.233Z",
"answer_score": 4526
} |
Please answer the following Stack Overflow question:
Title: How to concatenate string variables in Bash
<p>In PHP, strings are concatenated together as follows:</p>
<pre><code>$foo = "Hello";
$foo .= " World";
</code></pre>
<p>Here, <code>$foo</code> becomes <code>"Hello World"</code>.</p>
<p>How is this accomplished in Bash?</p> | <pre><code>foo="Hello"
foo="${foo} World"
echo "${foo}"
> Hello World
</code></pre>
<p>In general to concatenate two variables you can just write them one after another:</p>
<pre><code>a='Hello'
b='World'
c="${a} ${b}"
echo "${c}"
> Hello World
</code></pre> | {
"question_id": 4181703,
"question_date": "2010-11-15T05:38:35.240Z",
"question_score": 3325,
"tags": "bash|shell|syntax|concatenation|string-concatenation",
"answer_id": 4181721,
"answer_date": "2010-11-15T05:41:36.770Z",
"answer_score": 4537
} |
Please answer the following Stack Overflow question:
Title: What is a serialVersionUID and why should I use it?
<p>Eclipse issues warnings when a <code>serialVersionUID</code> is missing. </p>
<blockquote>
<p>The serializable class Foo does not declare a static final
serialVersionUID field of type long</p>
</blockquote>
<p>What is <code>serialVersionUID</code> and why is it important? Please show an example where missing <code>serialVersionUID</code> will cause a problem.</p> | <p>The docs for <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/Serializable.html" rel="noreferrer"><code>java.io.Serializable</code></a> are probably about as good an explanation as you'll get:</p>
<blockquote>
<p>The serialization runtime associates with each serializable class a version number, called a <code>serialVersionUID</code>, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different <code>serialVersionUID</code> than that of the corresponding sender's class, then deserialization will result in an
<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/InvalidClassException.html" rel="noreferrer"><code>InvalidClassException</code></a>. A serializable class can declare its own <code>serialVersionUID</code> explicitly by declaring a field named <code>serialVersionUID</code> that must be static, final, and of type <code>long</code>:</p>
</blockquote>
<blockquote>
<pre><code>ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
</code></pre>
</blockquote>
<blockquote>
<p>If a serializable class does not explicitly declare a <code>serialVersionUID</code>, then the serialization runtime will calculate a default <code>serialVersionUID</code> value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is <em>strongly recommended</em> that all serializable classes explicitly declare <code>serialVersionUID</code> values, since the default <code>serialVersionUID</code> computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected <code>InvalidClassExceptions</code> during deserialization. Therefore, to guarantee a consistent <code>serialVersionUID</code> value across different java compiler implementations, a serializable class must declare an explicit <code>serialVersionUID</code> value. It is also strongly advised that explicit <code>serialVersionUID</code> declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class — <code>serialVersionUID</code> fields are not useful as inherited members.</p>
</blockquote> | {
"question_id": 285793,
"question_date": "2008-11-12T23:24:56.797Z",
"question_score": 3324,
"tags": "java|serialization|serialversionuid",
"answer_id": 285809,
"answer_date": "2008-11-12T23:30:15.710Z",
"answer_score": 2514
} |
Please answer the following Stack Overflow question:
Title: Difference between "git add -A" and "git add ."
<p>What is the difference between <a href="https://git-scm.com/docs/git-add#Documentation/git-add.txt--A" rel="noreferrer"><code>git add [--all | -A]</code></a> and <a href="https://git-scm.com/docs/git-add" rel="noreferrer"><code>git add .</code></a>?</p> | <p><em>This answer only applies to <strong>Git version 1.x</strong>. For Git version 2.x, see other answers.</em></p>
<hr />
<p><strong>Summary:</strong></p>
<ul>
<li><p><code>git add -A</code> stages <strong>all changes</strong></p>
</li>
<li><p><code>git add .</code> stages new files and modifications, <strong>without deletions</strong> (on the current directory and its subdirectories).</p>
</li>
<li><p><code>git add -u</code> stages modifications and deletions, <strong>without new files</strong></p>
</li>
</ul>
<hr />
<p><strong>Detail:</strong></p>
<p><code>git add -A</code> is equivalent to <code>git add .; git add -u</code>.</p>
<p>The important point about <code>git add .</code> is that it looks at the working tree and adds all those paths to the staged changes if they are either changed or are new and not ignored, it does not stage any 'rm' actions.</p>
<p><code>git add -u</code> looks at all the <em>already</em> tracked files and stages the changes to those files if they are different or if they have been removed. It does not add any new files, it only stages changes to already tracked files.</p>
<p><code>git add -A</code> is a handy shortcut for doing both of those.</p>
<p>You can test the differences out with something like this (note that for Git version 2.x your output for <code>git add .</code> <code>git status</code> <strong>will</strong> be different):</p>
<pre class="lang-sh prettyprint-override"><code>git init
echo Change me > change-me
echo Delete me > delete-me
git add change-me delete-me
git commit -m initial
echo OK >> change-me
rm delete-me
echo Add me > add-me
git status
# Changed but not updated:
# modified: change-me
# deleted: delete-me
# Untracked files:
# add-me
git add .
git status
# Changes to be committed:
# new file: add-me
# modified: change-me
# Changed but not updated:
# deleted: delete-me
git reset
git add -u
git status
# Changes to be committed:
# modified: change-me
# deleted: delete-me
# Untracked files:
# add-me
git reset
git add -A
git status
# Changes to be committed:
# new file: add-me
# modified: change-me
# deleted: delete-me
</code></pre> | {
"question_id": 572549,
"question_date": "2009-02-21T06:51:06.767Z",
"question_score": 3315,
"tags": "git|git-add",
"answer_id": 572660,
"answer_date": "2009-02-21T09:00:04.930Z",
"answer_score": 4723
} |
Please answer the following Stack Overflow question:
Title: Case insensitive 'Contains(string)'
<p>Is there a way to make the following return true?</p>
<pre><code>string title = "ASTRINGTOTEST";
title.Contains("string");
</code></pre>
<p>There doesn't seem to be an overload that allows me to set the case sensitivity. Currently I UPPERCASE them both, but that's just silly (by which I am referring to the <a href="http://en.wikipedia.org/wiki/Internationalization_and_localization" rel="noreferrer">i18n</a> issues that come with up- and down casing).</p>
<p><strong>UPDATE</strong></p>
<p>This question is ancient and since then I have realized I asked for a simple answer for a really vast and difficult topic if you care to investigate it fully.</p>
<p>For most cases, in mono-lingual, English code bases <a href="https://stackoverflow.com/a/444818/11333">this</a> answer will suffice. I'm suspecting because most people coming here fall in this category this is the most popular answer.</p>
<p><a href="https://stackoverflow.com/a/15464440/11333">This</a> answer however brings up the inherent problem that we can't compare text case insensitive until we know both texts are the same culture and we know what that culture is. This is maybe a less popular answer, but I think it is more correct and that's why I marked it as such.</p> | <p>To test if the string <code>paragraph</code> contains the string <code>word</code> (thanks @QuarterMeister)</p>
<pre><code>culture.CompareInfo.IndexOf(paragraph, word, CompareOptions.IgnoreCase) >= 0
</code></pre>
<p>Where <code>culture</code> is the instance of <a href="http://msdn.microsoft.com/en-gb/library/system.globalization.cultureinfo(v=vs.110).aspx" rel="noreferrer"><code>CultureInfo</code></a> describing the language that the text is written in.</p>
<p>This solution is transparent about <strong>the definition of case-insensitivity, which is language dependent</strong>. For example, the English language uses the characters <code>I</code> and <code>i</code> for the upper and lower case versions of the ninth letter, whereas the Turkish language uses these characters for the <a href="http://en.wikipedia.org/wiki/Dotted_and_dotless_I" rel="noreferrer">eleventh and twelfth letters</a> of its 29 letter-long alphabet. The Turkish upper case version of 'i' is the unfamiliar character 'İ'.</p>
<p>Thus the strings <code>tin</code> and <code>TIN</code> are the same word <em>in English</em>, but different words <em>in Turkish</em>. As I understand, one means 'spirit' and the other is an onomatopoeia word. (Turks, please correct me if I'm wrong, or suggest a better example)</p>
<p>To summarise, you can only answer the question 'are these two strings the same but in different cases' <em>if you know what language the text is in</em>. If you don't know, you'll have to take a punt. Given English's hegemony in software, you should probably resort to <a href="https://stackoverflow.com/questions/9760237/what-does-cultureinfo-invariantculture-mean"><code>CultureInfo.InvariantCulture</code></a>, because it will be wrong in familiar ways.</p> | {
"question_id": 444798,
"question_date": "2009-01-14T21:39:46.670Z",
"question_score": 3290,
"tags": "c#|string|contains|case-insensitive",
"answer_id": 15464440,
"answer_date": "2013-03-17T18:22:11.727Z",
"answer_score": 1553
} |
Please answer the following Stack Overflow question:
Title: How do I iterate over the words of a string?
<p>How do I iterate over the words of a string composed of words separated by whitespace?</p>
<p>Note that I'm not interested in C string functions or that kind of character manipulation/access. I prefer elegance over efficiency. My current solution:</p>
<pre><code>#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string s = "Somewhere down the road";
istringstream iss(s);
do {
string subs;
iss >> subs;
cout << "Substring: " << subs << endl;
} while (iss);
}
</code></pre> | <p>For what it's worth, here's another way to extract tokens from an input string, relying only on standard library facilities. It's an example of the power and elegance behind the design of the STL.</p>
<pre><code>#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
int main() {
using namespace std;
string sentence = "And I feel fine...";
istringstream iss(sentence);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
ostream_iterator<string>(cout, "\n"));
}
</code></pre>
<p>Instead of copying the extracted tokens to an output stream, one could insert them into a container, using the same generic <a href="https://en.cppreference.com/w/cpp/algorithm/copy" rel="noreferrer"><code>copy</code></a> algorithm.</p>
<pre><code>vector<string> tokens;
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(tokens));
</code></pre>
<p>... or create the <code>vector</code> directly:</p>
<pre><code>vector<string> tokens{istream_iterator<string>{iss},
istream_iterator<string>{}};
</code></pre> | {
"question_id": 236129,
"question_date": "2008-10-25T08:58:21.013Z",
"question_score": 3285,
"tags": "c++|string|split",
"answer_id": 237280,
"answer_date": "2008-10-26T00:43:09.317Z",
"answer_score": 1491
} |
Please answer the following Stack Overflow question:
Title: How can I convert a string to boolean in JavaScript?
<p>Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?</p>
<p>I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.</p>
<p>The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.</p>
<pre><code>var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';
</code></pre>
<p>Is there a better way to accomplish this?</p> | <h1>Do:</h1>
<pre><code>var isTrueSet = (myValue === 'true');
</code></pre>
<p>using the identity operator (<code>===</code>), which doesn't make any implicit type conversions when the compared variables have different types.</p>
<p>This will set <code>isTrueSet</code> to a boolean <code>true</code> if the string is "true" and boolean <code>false</code> if it is string "false" or not set at all.</p>
<hr />
<h2>Don't:</h2>
<p>You should probably <strong>be cautious about using these two methods</strong> for your specific needs:</p>
<pre><code>var myBool = Boolean("false"); // == true
var myBool = !!"false"; // == true
</code></pre>
<p>Any string which isn't the empty string will evaluate to <code>true</code> by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.</p> | {
"question_id": 263965,
"question_date": "2008-11-05T00:13:08.963Z",
"question_score": 3267,
"tags": "javascript|boolean-expression|boolean-operations|string-conversion",
"answer_id": 264037,
"answer_date": "2008-11-05T00:51:02.193Z",
"answer_score": 4599
} |
Please answer the following Stack Overflow question:
Title: How to check if a string contains a substring in Bash
<p>I have a string in Bash:</p>
<pre class="lang-sh prettyprint-override"><code>string="My string"
</code></pre>
<p>How can I test if it contains another string?</p>
<pre class="lang-sh prettyprint-override"><code>if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
</code></pre>
<p>Where <code>??</code> is my unknown operator. Do I use <code>echo</code> and <code>grep</code>?</p>
<pre class="lang-sh prettyprint-override"><code>if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
</code></pre>
<p>That looks a bit clumsy.</p> | <p>You can use <a href="https://stackoverflow.com/a/229585/3755692">Marcus's answer (* wildcards)</a> outside a case statement, too, if you use double brackets:</p>
<pre><code>string='My long string'
if [[ $string == *"My long"* ]]; then
echo "It's there!"
fi
</code></pre>
<p>Note that spaces in the needle string need to be placed between double quotes, and the <code>*</code> wildcards should be outside. Also note that a simple comparison operator is used (i.e. <code>==</code>), not the regex operator <code>=~</code>.</p> | {
"question_id": 229551,
"question_date": "2008-10-23T12:37:31.787Z",
"question_score": 3256,
"tags": "string|bash|shell|substring|sh",
"answer_id": 229606,
"answer_date": "2008-10-23T12:55:24.963Z",
"answer_score": 4536
} |
Please answer the following Stack Overflow question:
Title: Creating multiline strings in JavaScript
<p>I have the following code in Ruby. I want to convert this code into JavaScript. What is the equivalent code in JS?</p>
<pre><code>text = <<"HERE"
This
Is
A
Multiline
String
HERE
</code></pre> | <h3>Update:</h3>
<p>ECMAScript 6 (ES6) introduces a new type of literal, namely <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings" rel="noreferrer"><strong>template literals</strong></a>. They have many features, variable interpolation among others, but most importantly for this question, they can be multiline.</p>
<p>A template literal is delimited by <em>backticks</em>:</p>
<pre><code>var html = `
<div>
<span>Some HTML here</span>
</div>
`;
</code></pre>
<p>(Note: I'm not advocating to use HTML in strings)</p>
<p><a href="https://kangax.github.io/compat-table/es6/#test-template_literals" rel="noreferrer">Browser support is OK</a>, but you can use <a href="https://babeljs.io/" rel="noreferrer">transpilers</a> to be more compatible.</p>
<hr>
<h3>Original ES5 answer:</h3>
<p>Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close:</p>
<pre><code>"foo \
bar"
</code></pre> | {
"question_id": 805107,
"question_date": "2009-04-30T02:11:55.560Z",
"question_score": 3256,
"tags": "javascript|string|multiline|heredoc",
"answer_id": 805113,
"answer_date": "2009-04-30T02:15:20.593Z",
"answer_score": 4238
} |
Please answer the following Stack Overflow question:
Title: How can I change an element's class with JavaScript?
<p>How can I change the class of an HTML element in response to an <code>onclick</code> or any other events using JavaScript?</p> | <h2>Modern HTML5 Techniques for changing classes</h2>
<p>Modern browsers have added <a href="https://developer.mozilla.org/en-US/docs/DOM/element.classList" rel="noreferrer"><strong>classList</strong></a> which provides methods to make it easier to manipulate classes without needing a library:</p>
<pre><code>document.getElementById("MyElement").classList.add('MyClass');
document.getElementById("MyElement").classList.remove('MyClass');
if ( document.getElementById("MyElement").classList.contains('MyClass') )
document.getElementById("MyElement").classList.toggle('MyClass');
</code></pre>
<p>Unfortunately, these do not work in Internet Explorer prior to v10, though there is a <a href="http://en.wikipedia.org/wiki/Shim_(computing)" rel="noreferrer">shim</a> to add support for it to IE8 and IE9, available from <a href="https://developer.mozilla.org/en-US/docs/DOM/element.classList" rel="noreferrer">this page</a>. It is, though, getting more and more <a href="http://caniuse.com/#feat=classlist" rel="noreferrer">supported</a>.</p>
<h2>Simple cross-browser solution</h2>
<p>The standard JavaScript way to select an element is using <a href="https://developer.mozilla.org/en-US/docs/DOM/document.getElementById" rel="noreferrer"><code>document.getElementById("Id")</code></a>, which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use <code>this</code> instead - however, going into detail on this is beyond the scope of the answer.</p>
<h3>To change all classes for an element:</h3>
<p>To replace all existing classes with one or more new classes, set the className attribute:</p>
<pre><code>document.getElementById("MyElement").className = "MyClass";
</code></pre>
<p>(You can use a space-delimited list to apply multiple classes.)</p>
<h3>To add an additional class to an element:</h3>
<p>To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:</p>
<pre><code>document.getElementById("MyElement").className += " MyClass";
</code></pre>
<h3>To remove a class from an element:</h3>
<p>To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:</p>
<pre><code>document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace
( /(?:^|\s)MyClass(?!\S)/g , '' )
/* Code wrapped for readability - above is all one statement */
</code></pre>
<p>An explanation of this regex is as follows:</p>
<pre><code>(?:^|\s) # Match the start of the string or any single whitespace character
MyClass # The literal text for the classname to remove
(?!\S) # Negative lookahead to verify the above is the whole classname
# Ensures there is no non-space character following
# (i.e. must be the end of the string or space)
</code></pre>
<p>The <code>g</code> flag tells the replace to repeat as required, in case the class name has been added multiple times.</p>
<h3>To check if a class is already applied to an element:</h3>
<p>The same regex used above for removing a class can also be used as a check as to whether a particular class exists:</p>
<pre><code>if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )
</code></pre>
<br/>
### Assigning these actions to onclick events:
<p>Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as <code>onclick="this.className+=' MyClass'"</code>) this is not recommended behaviour. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.</p>
<p>The first step to achieving this is by creating a function, and calling the function in the onclick attribute, for example:</p>
<pre><code><script type="text/javascript">
function changeClass(){
// Code examples from above
}
</script>
...
<button onclick="changeClass()">My Button</button>
</code></pre>
<p><sub><em>(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)</em></sub></p>
<p>The second step is to move the onclick event out of the HTML and into JavaScript, for example using <a href="https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener" rel="noreferrer">addEventListener</a></p>
<pre><code><script type="text/javascript">
function changeClass(){
// Code examples from above
}
window.onload = function(){
document.getElementById("MyElement").addEventListener( 'click', changeClass);
}
</script>
...
<button id="MyElement">My Button</button>
</code></pre>
<p>(Note that the window.onload part is required so that the contents of that function are executed <em>after</em> the HTML has finished loading - without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)</p>
<br/>
<h2>JavaScript Frameworks and Libraries</h2>
<p>The above code is all in standard JavaScript, however, it is common practice to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.</p>
<p>Whilst some people consider it overkill to add a ~50 KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work or anything that might have unusual cross-browser behavior, it is well worth considering.</p>
<p><em>(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)</em></p>
<p>The examples above have been reproduced below using <a href="http://jquery.com" rel="noreferrer">jQuery</a>, probably the most commonly used JavaScript library (though there are others worth investigating too).</p>
<p>(Note that <code>$</code> here is the jQuery object.)</p>
<h3>Changing Classes with jQuery:</h3>
<pre><code>$('#MyElement').addClass('MyClass');
$('#MyElement').removeClass('MyClass');
if ( $('#MyElement').hasClass('MyClass') )
</code></pre>
<p>In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:</p>
<pre><code>$('#MyElement').toggleClass('MyClass');
</code></pre>
<br/>
### Assigning a function to a click event with jQuery:
<pre><code>$('#MyElement').click(changeClass);
</code></pre>
<p>or, without needing an id:</p>
<pre><code>$(':button:contains(My Button)').click(changeClass);
</code></pre>
<br/> | {
"question_id": 195951,
"question_date": "2008-10-12T20:06:43.663Z",
"question_score": 3252,
"tags": "javascript|html|dom",
"answer_id": 196038,
"answer_date": "2008-10-12T20:45:36.347Z",
"answer_score": 4430
} |
Please answer the following Stack Overflow question:
Title: How can I check if an object is an array?
<p>I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item so I can loop over it without fear of an error.</p>
<p>So how do I check if the variable is an array?</p> | <p>In modern browsers you can do:</p>
<pre><code>Array.isArray(obj)
</code></pre>
<p>(<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray" rel="noreferrer">Supported by</a> Chrome 5, Firefox 4.0, Internet Explorer 9, <a href="https://en.wikipedia.org/wiki/Opera_%28web_browser%29" rel="noreferrer">Opera</a> 10.5 and Safari 5)</p>
<p>For backward compatibility you can add the following:</p>
<pre><code>// Only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
Array.isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
};
</code></pre>
<p>If you use jQuery you can use <code>jQuery.isArray(obj)</code> or <code>$.isArray(obj)</code>. If you use <a href="https://en.wikipedia.org/wiki/Underscore.js" rel="noreferrer">Underscore.js</a> you can use <code>_.isArray(obj)</code>.</p>
<p>If you don't need to detect arrays created in different frames you can also just use <code>instanceof</code>:</p>
<pre><code>obj instanceof Array
</code></pre> | {
"question_id": 4775722,
"question_date": "2011-01-23T18:53:04.733Z",
"question_score": 3251,
"tags": "javascript|arrays|javascript-objects",
"answer_id": 20956445,
"answer_date": "2014-01-06T18:11:55.180Z",
"answer_score": 1514
} |
Please answer the following Stack Overflow question:
Title: How do I concatenate two lists in Python?
<p>How do I concatenate two lists in Python?</p>
<p>Example:</p>
<pre><code>listone = [1, 2, 3]
listtwo = [4, 5, 6]
</code></pre>
<p>Expected outcome:</p>
<pre><code>>>> joinedlist
[1, 2, 3, 4, 5, 6]
</code></pre> | <p>Use the <code>+</code> operator to combine the lists:</p>
<pre><code>listone = [1, 2, 3]
listtwo = [4, 5, 6]
joinedlist = listone + listtwo
</code></pre>
<p>Output:</p>
<pre><code>>>> joinedlist
[1, 2, 3, 4, 5, 6]
</code></pre> | {
"question_id": 1720421,
"question_date": "2009-11-12T07:04:09.050Z",
"question_score": 3246,
"tags": "python|list|concatenation",
"answer_id": 1720432,
"answer_date": "2009-11-12T07:07:06.253Z",
"answer_score": 5098
} |
Please answer the following Stack Overflow question:
Title: How do I check if a list is empty?
<p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p> | <pre><code>if not a:
print("List is empty")
</code></pre>
<p>Using the <a href="https://docs.python.org/library/stdtypes.html#truth-value-testing" rel="noreferrer">implicit booleanness</a> of the empty <code>list</code> is quite Pythonic.</p> | {
"question_id": 53513,
"question_date": "2008-09-10T06:20:11Z",
"question_score": 3230,
"tags": "python|list",
"answer_id": 53522,
"answer_date": "2008-09-10T06:28:05.147Z",
"answer_score": 6873
} |
Please answer the following Stack Overflow question:
Title: Echo newline in Bash prints literal \n
<p>How do I print a newline? This merely prints <code>\n</code>:</p>
<pre><code>$ echo -e "Hello,\nWorld!"
Hello,\nWorld!
</code></pre> | <p>Use <code>printf</code> instead:</p>
<pre><code>printf "hello\nworld\n"
</code></pre>
<p><code>printf</code> behaves more consistently across different environments than <code>echo</code>.</p> | {
"question_id": 8467424,
"question_date": "2011-12-11T21:01:54.900Z",
"question_score": 3211,
"tags": "bash|echo|newline",
"answer_id": 8467449,
"answer_date": "2011-12-11T21:04:56.710Z",
"answer_score": 3826
} |
Please answer the following Stack Overflow question:
Title: "Least Astonishment" and the Mutable Default Argument
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p>
<pre><code>def foo(a=[]):
a.append(5)
return a
</code></pre>
<p>Python novices would expect this function called with no parameter to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p>
<pre><code>>>> foo()
[5]
>>> foo()
[5, 5]
>>> foo()
[5, 5, 5]
>>> foo()
[5, 5, 5, 5]
>>> foo()
</code></pre>
<p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p>
<p><strong>Edit</strong>:</p>
<p><a href="https://stackoverflow.com/a/1137164/7487335">Baczek made an interesting example</a>. Together with most of your comments and <a href="https://stackoverflow.com/a/1134623/7487335">Utaal's in particular</a>, I elaborated further:</p>
<pre><code>>>> def a():
... print("a executed")
... return []
...
>>>
>>> def b(x=a()):
... x.append(5)
... print(x)
...
a executed
>>> b()
[5]
>>> b()
[5, 5]
</code></pre>
<p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function, or "together" with it?</p>
<p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p>
<p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p> | <p>Actually, this is not a design flaw, and it is not because of internals or performance. It comes simply from the fact that functions in Python are first-class objects, and not only a piece of code.</p>
<p>As soon as you think of it this way, then it completely makes sense: a function is an object being evaluated on its definition; default parameters are kind of "member data" and therefore their state may change from one call to the other - exactly as in any other object.</p>
<p>In any case, the effbot (Fredrik Lundh) has a very nice explanation of the reasons for this behavior in <a href="https://web.archive.org/web/20200221224620id_/http://effbot.org/zone/default-values.htm" rel="noreferrer">Default Parameter Values in Python</a>.
I found it very clear, and I really suggest reading it for a better knowledge of how function objects work.</p> | {
"question_id": 1132941,
"question_date": "2009-07-15T18:00:37.467Z",
"question_score": 3206,
"tags": "python|language-design|default-parameters|least-astonishment",
"answer_id": 1145781,
"answer_date": "2009-07-17T21:29:39.827Z",
"answer_score": 1843
} |
Please answer the following Stack Overflow question:
Title: How do I format a date in JavaScript?
<p>How do I format a <code>Date</code> object to a string?</p> | <p>For custom-delimited date formats, you have to pull out the date (or time)
components from a <a href="//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat" rel="noreferrer"><code>DateTimeFormat</code></a> object (which is part of the
<a href="//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl" rel="noreferrer">ECMAScript Internationalization API</a>), and then manually create a string
with the delimiters you want.</p>
<p>To do this, you can use <a href="//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts" rel="noreferrer"><code>DateTimeFormat#formatToParts</code></a>. You could
destructure the array, but that is not ideal, as the array output depends on the
locale:</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>{ // example 1
let f = new Intl.DateTimeFormat('en');
let a = f.formatToParts();
console.log(a);
}
{ // example 2
let f = new Intl.DateTimeFormat('hi');
let a = f.formatToParts();
console.log(a);
}</code></pre>
</div>
</div>
</p>
<p>Better would be to map a format array to resultant strings:</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>function join(t, a, s) {
function format(m) {
let f = new Intl.DateTimeFormat('en', m);
return f.format(t);
}
return a.map(format).join(s);
}
let a = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}];
let s = join(new Date, a, '-');
console.log(s);</code></pre>
</div>
</div>
</p>
<p>You can also pull out the parts of a <code>DateTimeFormat</code> one-by-one using
<a href="//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/format" rel="noreferrer"><code>DateTimeFormat#format</code></a>, but note that when using this method, as of March
2020, there is <a href="//stackoverflow.com/questions/60544534#60545316">a bug</a> in the ECMAScript implementation when it comes to
leading zeros on minutes and seconds (this bug is circumvented by the approach
above).</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 d = new Date(2010, 7, 5);
let ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
let mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d);
let da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
console.log(`${da}-${mo}-${ye}`);</code></pre>
</div>
</div>
</p>
<p>When working with dates and times, it is usually worth using a library (eg. <a href="//moment.github.io/luxon" rel="noreferrer">luxon</a>, <a href="https://date-fns.org/" rel="noreferrer">date-fns</a>, <a href="https://momentjs.com/docs/#/-project-status/recommendations/" rel="noreferrer"><del>moment.js</del> is not recommended for new projects</a>) because of the many hidden complexities of the field.</p>
<p>Note that the ECMAScript Internationalization API, used in the solutions above
is not supported <a href="//caniuse.com#search=datetimeformat" rel="noreferrer">in IE10</a> (<a href="//gs.statcounter.com/browser-version-market-share" rel="noreferrer">0.03%</a> global browser market share in Feb
2020).</p> | {
"question_id": 3552461,
"question_date": "2010-08-23T23:28:26.650Z",
"question_score": 3191,
"tags": "javascript|date|date-formatting",
"answer_id": 3552493,
"answer_date": "2010-08-23T23:35:17.063Z",
"answer_score": 1671
} |
Please answer the following Stack Overflow question:
Title: Initialization of an ArrayList in one line
<p>I wanted to create a list of options for testing purposes. At first, I did this:</p>
<pre><code>ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");
</code></pre>
<p>Then, I refactored the code as follows:</p>
<pre><code>ArrayList<String> places = new ArrayList<String>(
Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
</code></pre>
<p>Is there a better way to do this?</p> | <p>Actually, probably the "best" way to initialize the <code>ArrayList</code> is the method you wrote, as it does not need to create a new <code>List</code> in any way:</p>
<pre><code>ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
</code></pre>
<p>The catch is that there is quite a bit of typing required to refer to that <code>list</code> instance.</p>
<p>There are alternatives, such as making an anonymous inner class with an instance initializer (also known as an "double brace initialization"):</p>
<pre><code>ArrayList<String> list = new ArrayList<String>() {{
add("A");
add("B");
add("C");
}};
</code></pre>
<p>However, I'm not too fond of that method because what you end up with is a subclass of <code>ArrayList</code> which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.</p>
<p>What would have been nice was if the <a href="http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/001193.html" rel="noreferrer">Collection Literals proposal</a> for <a href="http://openjdk.java.net/projects/coin" rel="noreferrer">Project Coin</a> was accepted (it was slated to be introduced in Java 7, but it's not likely to be part of Java 8 either.):</p>
<pre><code>List<String> list = ["A", "B", "C"];
</code></pre>
<p>Unfortunately it won't help you here, as it will initialize an immutable <code>List</code> rather than an <code>ArrayList</code>, and furthermore, it's not available yet, if it ever will be.</p> | {
"question_id": 1005073,
"question_date": "2009-06-17T04:10:20Z",
"question_score": 3191,
"tags": "java|collections|arraylist|initialization",
"answer_id": 1005083,
"answer_date": "2009-06-17T04:13:36.023Z",
"answer_score": 2206
} |
Please answer the following Stack Overflow question:
Title: event.preventDefault() vs. return false
<p>When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques. I'll use jQuery in the examples, but this applies to plain-JS as well:</p>
<h3>1. <code>event.preventDefault()</code></h3>
<pre><code>$('a').click(function (e) {
// custom handling here
e.preventDefault();
});
</code></pre>
<h3>2. <code>return false</code></h3>
<pre><code>$('a').click(function () {
// custom handling here
return false;
});
</code></pre>
<p>Is there any significant difference between those two methods of stopping event propagation?</p>
<p>For me, <code>return false;</code> is simpler, shorter and probably less error prone than executing a method. With the method, you have to remember about correct casing, parenthesis, etc. </p>
<p>Also, I have to define the first parameter in callback to be able to call the method. Perhaps, there are some reasons why I should avoid doing it like this and use <code>preventDefault</code> instead? What's the better way?</p> | <p><code>return false</code> from <em>within a jQuery event handler</em> is effectively the same as calling both <code>e.preventDefault</code> and <code>e.stopPropagation</code> on the passed <a href="http://api.jquery.com/category/events/event-object/" rel="noreferrer">jQuery.Event object.</a></p>
<p><code>e.preventDefault()</code> will prevent the default event from occuring, <code>e.stopPropagation()</code> will prevent the event from bubbling up and <code>return false</code> will do both. Note that this behaviour differs from <em>normal</em> (non-jQuery) event handlers, in which, notably, <code>return false</code> does <em>not</em> stop the event from bubbling up.</p>
<p>Source: <a href="http://ejohn.org/" rel="noreferrer">John Resig</a></p>
<p><a href="http://www.mail-archive.com/[email protected]/msg71371.html" rel="noreferrer"><strong>Any benefit to using event.preventDefault() over "return false" to cancel out an href click?</strong></a></p> | {
"question_id": 1357118,
"question_date": "2009-08-31T11:58:31.807Z",
"question_score": 3185,
"tags": "javascript|jquery|event-handling|dom-events|event-propagation",
"answer_id": 1357151,
"answer_date": "2009-08-31T12:05:19.110Z",
"answer_score": 2950
} |
Please answer the following Stack Overflow question:
Title: Why is "using namespace std;" considered bad practice?
<p>I have heard <code>using namespace std;</code> is bad practice, and that I should use <code>std::cout</code> and <code>std::cin</code> directly instead.
Why is this? Does it risk declaring variables that share the same name as something in the <code>std</code> namespace?</p> | <p>Consider two libraries called Foo and Bar:</p>
<pre><code>using namespace foo;
using namespace bar;
</code></pre>
<p>Everything works fine, and you can call <code>Blah()</code> from Foo and <code>Quux()</code> from Bar without problems. But one day you upgrade to a new version of Foo 2.0, which now offers a function called <code>Quux()</code>. Now you've got a conflict: Both Foo 2.0 and Bar import <code>Quux()</code> into your global namespace. This is going to take some effort to fix, especially if the function parameters happen to match.</p>
<p>If you had used <code>foo::Blah()</code> and <code>bar::Quux()</code>, then the introduction of <code>foo::Quux()</code> would have been a non-event.</p> | {
"question_id": 1452721,
"question_date": "2009-09-21T03:08:23.280Z",
"question_score": 3178,
"tags": "c++|namespaces|std|using-directives|c++-faq",
"answer_id": 1452738,
"answer_date": "2009-09-21T03:13:50.933Z",
"answer_score": 2692
} |
Please answer the following Stack Overflow question:
Title: How do I copy a folder from remote to local using scp?
<p>How do I copy a folder from remote to local host using <code>scp</code>?</p>
<p>I use <code>ssh</code> to log in to my server.<br />
Then, I would like to copy the remote folder <code>foo</code> to local <code>/home/user/Desktop</code>.</p>
<p>How do I achieve this?</p> | <pre><code>scp -r [email protected]:/path/to/foo /home/user/Desktop/
</code></pre>
<p>By not including the trailing '/' at the end of foo, you will copy the directory itself (including contents), rather than only the contents of the directory.</p>
<p>From <code>man scp</code> (See <a href="http://man7.org/linux/man-pages/man1/scp.1.html" rel="noreferrer">online manual</a>)</p>
<blockquote>
<p>-r Recursively copy entire directories</p>
</blockquote> | {
"question_id": 11304895,
"question_date": "2012-07-03T05:17:58.003Z",
"question_score": 3166,
"tags": "shell|ssh|command-line|copy|scp",
"answer_id": 11304926,
"answer_date": "2012-07-03T05:21:39.313Z",
"answer_score": 5741
} |
Please answer the following Stack Overflow question:
Title: pretty-print JSON using JavaScript
<p>How can I display JSON in an easy-to-read (for human readers) format? I'm looking primarily for indentation and whitespace, with perhaps even colors / font-styles / etc.</p> | <p><strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify" rel="noreferrer">Pretty-printing is implemented natively in <code>JSON.stringify()</code></a></strong>. The third argument enables pretty printing and sets the spacing to use:</p>
<pre><code>var str = JSON.stringify(obj, null, 2); // spacing level = 2
</code></pre>
<p>If you need syntax highlighting, you might use some regex magic like so:</p>
<pre><code>function syntaxHighlight(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
</code></pre>
<p>See in action here: <a href="http://jsfiddle.net/KJQ9K/554/" rel="noreferrer">jsfiddle</a></p>
<p><strong>Or a full snippet provided below:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function output(inp) {
document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}
function syntaxHighlight(json) {
json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
var obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]};
var str = JSON.stringify(obj, undefined, 4);
output(str);
output(syntaxHighlight(str));</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }</code></pre>
</div>
</div>
</p> | {
"question_id": 4810841,
"question_date": "2011-01-26T22:33:53.733Z",
"question_score": 3151,
"tags": "javascript|json|pretty-print",
"answer_id": 7220510,
"answer_date": "2011-08-28T10:56:51.043Z",
"answer_score": 6345
} |
Please answer the following Stack Overflow question:
Title: JavaScript closure inside loops – simple practical example
<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>var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
// and store them in funcs
funcs[i] = function() {
// each should log its value.
console.log("My value: " + i);
};
}
for (var j = 0; j < 3; j++) {
// and now let's run each one to see
funcs[j]();
}</code></pre>
</div>
</div>
</p>
<p>It outputs this:</p>
<blockquote>
<p>My value: 3<br />
My value: 3<br />
My value: 3</p>
</blockquote>
<p>Whereas I'd like it to output:</p>
<blockquote>
<p>My value: 0<br />
My value: 1<br />
My value: 2</p>
</blockquote>
<hr />
<p>The same problem occurs when the delay in running the function is caused by using event listeners:</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>var buttons = document.getElementsByTagName("button");
// let's create 3 functions
for (var i = 0; i < buttons.length; i++) {
// as event listeners
buttons[i].addEventListener("click", function() {
// each should log its value.
console.log("My value: " + i);
});
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>0</button>
<br />
<button>1</button>
<br />
<button>2</button></code></pre>
</div>
</div>
</p>
<p>… or asynchronous code, e.g. using Promises:</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>// Some async wait function
const wait = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms));
for (var i = 0; i < 3; i++) {
// Log `i` as soon as each promise resolves.
wait(i * 100).then(() => console.log(i));
}</code></pre>
</div>
</div>
</p>
<p>It is also apparent in <code>for in</code> and <code>for of</code> loops:</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 arr = [1,2,3];
const fns = [];
for(var i in arr){
fns.push(() => console.log(`index: ${i}`));
}
for(var v of arr){
fns.push(() => console.log(`value: ${v}`));
}
for(var f of fns){
f();
}</code></pre>
</div>
</div>
</p>
<p>What’s the solution to this basic problem?</p> | <p>Well, the problem is that the variable <code>i</code>, within each of your anonymous functions, is bound to the same variable outside of the function.</p>
<h1>ES6 solution: <code>let</code></h1>
<p>ECMAScript 6 (ES6) introduces new <code>let</code> and <code>const</code> keywords that are scoped differently than <code>var</code>-based variables. For example, in a loop with a <code>let</code>-based index, each iteration through the loop will have a new variable <code>i</code> with loop scope, so your code would work as you expect. There are many resources, but I'd recommend <a href="http://www.2ality.com/2015/02/es6-scoping.html" rel="noreferrer">2ality's block-scoping post</a> as a great source of information.</p>
<pre><code>for (let i = 0; i < 3; i++) {
funcs[i] = function() {
console.log("My value: " + i);
};
}
</code></pre>
<p>Beware, though, that IE9-IE11 and Edge prior to Edge 14 support <code>let</code> but get the above wrong (they don't create a new <code>i</code> each time, so all the functions above would log 3 like they would if we used <code>var</code>). Edge 14 finally gets it right.</p>
<hr />
<h1>ES5.1 solution: forEach</h1>
<p>With the relatively widespread availability of the <code>Array.prototype.forEach</code> function (in 2015), it's worth noting that in those situations involving iteration primarily over an array of values, <code>.forEach()</code> provides a clean, natural way to get a distinct closure for every iteration. That is, assuming you've got some sort of array containing values (DOM references, objects, whatever), and the problem arises of setting up callbacks specific to each element, you can do this:</p>
<pre><code>var someArray = [ /* whatever */ ];
// ...
someArray.forEach(function(arrayElement) {
// ... code code code for this one element
someAsynchronousFunction(arrayElement, function() {
arrayElement.doSomething();
});
});
</code></pre>
<p>The idea is that each invocation of the callback function used with the <code>.forEach</code> loop will be its own closure. The parameter passed in to that handler is the array element specific to that particular step of the iteration. If it's used in an asynchronous callback, it won't collide with any of the other callbacks established at other steps of the iteration.</p>
<p>If you happen to be working in jQuery, the <code>$.each()</code> function gives you a similar capability.</p>
<hr />
<h1>Classic solution: Closures</h1>
<p>What you want to do is bind the variable within each function to a separate, unchanging value outside of the 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>var funcs = [];
function createfunc(i) {
return function() {
console.log("My value: " + i);
};
}
for (var i = 0; i < 3; i++) {
funcs[i] = createfunc(i);
}
for (var j = 0; j < 3; j++) {
// and now let's run each one to see
funcs[j]();
}</code></pre>
</div>
</div>
</p>
<p>Since there is no block scope in JavaScript - only function scope - by wrapping the function creation in a new function, you ensure that the value of "i" remains as you intended.</p> | {
"question_id": 750486,
"question_date": "2009-04-15T06:06:20.460Z",
"question_score": 3149,
"tags": "javascript|loops|closures",
"answer_id": 750506,
"answer_date": "2009-04-15T06:18:17.527Z",
"answer_score": 2358
} |
Please answer the following Stack Overflow question:
Title: Detecting an undefined object property
<p>How do I check if an object property in JavaScript is undefined?</p> | <p>The usual way to check if the value of a property is the special value <code>undefined</code>, is:</p>
<pre class="lang-js prettyprint-override"><code>if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}
</code></pre>
<p>To check if an object does not actually have such a property, and will therefore return <code>undefined</code> by default when you try to access it:</p>
<pre class="lang-js prettyprint-override"><code>if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}
</code></pre>
<p>To check if the value associated with an identifier is the special value <code>undefined</code>, <em>or</em> if that identifier has not been declared:</p>
<pre class="lang-js prettyprint-override"><code>if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
</code></pre>
<p>Note: this last method is the only way to refer to an <strong>undeclared</strong> identifier without an early error, which is different from having a value of <code>undefined</code>.</p>
<p>In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check <code>foo === undefined</code> might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.</p>
<p>However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.</p>
<p>If you are worried about this (unlikely) edge case, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void" rel="noreferrer">the void operator</a> to get at the special <code>undefined</code> value itself:</p>
<pre class="lang-js prettyprint-override"><code>if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}
</code></pre> | {
"question_id": 27509,
"question_date": "2008-08-26T07:25:08.083Z",
"question_score": 3141,
"tags": "javascript|object|undefined|object-property",
"answer_id": 416327,
"answer_date": "2009-01-06T12:27:41.587Z",
"answer_score": 2886
} |
Please answer the following Stack Overflow question:
Title: How do I pass a variable by reference?
<p>Are parameters passed by reference or by value? How do I pass by reference so that the code below outputs <code>'Changed'</code> instead of <code>'Original'</code>?</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.change(self.variable)
print(self.variable)
def change(self, var):
var = 'Changed'
</code></pre> | <p>Arguments are <a href="http://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference" rel="noreferrer">passed by assignment</a>. The rationale behind this is twofold:</p>
<ol>
<li>the parameter passed in is actually a <em>reference</em> to an object (but the reference is passed by value)</li>
<li>some data types are mutable, but others aren't</li>
</ol>
<p>So:</p>
<ul>
<li><p>If you pass a <em>mutable</em> object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object. </p></li>
<li><p>If you pass an <em>immutable</em> object to a method, you still can't rebind the outer reference, and you can't even mutate the object.</p></li>
</ul>
<p>To make it even more clear, let's have some examples. </p>
<h2>List - a mutable type</h2>
<p><strong>Let's try to modify the list that was passed to a method:</strong></p>
<pre><code>def try_to_change_list_contents(the_list):
print('got', the_list)
the_list.append('four')
print('changed to', the_list)
outer_list = ['one', 'two', 'three']
print('before, outer_list =', outer_list)
try_to_change_list_contents(outer_list)
print('after, outer_list =', outer_list)
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>before, outer_list = ['one', 'two', 'three']
got ['one', 'two', 'three']
changed to ['one', 'two', 'three', 'four']
after, outer_list = ['one', 'two', 'three', 'four']
</code></pre>
<p>Since the parameter passed in is a reference to <code>outer_list</code>, not a copy of it, we can use the mutating list methods to change it and have the changes reflected in the outer scope.</p>
<p><strong>Now let's see what happens when we try to change the reference that was passed in as a parameter:</strong></p>
<pre><code>def try_to_change_list_reference(the_list):
print('got', the_list)
the_list = ['and', 'we', 'can', 'not', 'lie']
print('set to', the_list)
outer_list = ['we', 'like', 'proper', 'English']
print('before, outer_list =', outer_list)
try_to_change_list_reference(outer_list)
print('after, outer_list =', outer_list)
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>before, outer_list = ['we', 'like', 'proper', 'English']
got ['we', 'like', 'proper', 'English']
set to ['and', 'we', 'can', 'not', 'lie']
after, outer_list = ['we', 'like', 'proper', 'English']
</code></pre>
<p>Since the <code>the_list</code> parameter was passed by value, assigning a new list to it had no effect that the code outside the method could see. The <code>the_list</code> was a copy of the <code>outer_list</code> reference, and we had <code>the_list</code> point to a new list, but there was no way to change where <code>outer_list</code> pointed.</p>
<h2>String - an immutable type</h2>
<p><strong>It's immutable, so there's nothing we can do to change the contents of the string</strong></p>
<p><strong>Now, let's try to change the reference</strong></p>
<pre><code>def try_to_change_string_reference(the_string):
print('got', the_string)
the_string = 'In a kingdom by the sea'
print('set to', the_string)
outer_string = 'It was many and many a year ago'
print('before, outer_string =', outer_string)
try_to_change_string_reference(outer_string)
print('after, outer_string =', outer_string)
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>before, outer_string = It was many and many a year ago
got It was many and many a year ago
set to In a kingdom by the sea
after, outer_string = It was many and many a year ago
</code></pre>
<p>Again, since the <code>the_string</code> parameter was passed by value, assigning a new string to it had no effect that the code outside the method could see. The <code>the_string</code> was a copy of the <code>outer_string</code> reference, and we had <code>the_string</code> point to a new string, but there was no way to change where <code>outer_string</code> pointed.</p>
<p>I hope this clears things up a little.</p>
<p><strong>EDIT:</strong> It's been noted that this doesn't answer the question that @David originally asked, "Is there something I can do to pass the variable by actual reference?". Let's work on that.</p>
<h2>How do we get around this?</h2>
<p>As @Andrea's answer shows, you could return the new value. This doesn't change the way things are passed in, but does let you get the information you want back out:</p>
<pre><code>def return_a_whole_new_string(the_string):
new_string = something_to_do_with_the_old_string(the_string)
return new_string
# then you could call it like
my_string = return_a_whole_new_string(my_string)
</code></pre>
<p>If you really wanted to avoid using a return value, you could create a class to hold your value and pass it into the function or use an existing class, like a list:</p>
<pre><code>def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change):
new_string = something_to_do_with_the_old_string(stuff_to_change[0])
stuff_to_change[0] = new_string
# then you could call it like
wrapper = [my_string]
use_a_wrapper_to_simulate_pass_by_reference(wrapper)
do_something_with(wrapper[0])
</code></pre>
<p>Although this seems a little cumbersome.</p> | {
"question_id": 986006,
"question_date": "2009-06-12T10:23:51.560Z",
"question_score": 3136,
"tags": "python|reference|parameter-passing|pass-by-reference",
"answer_id": 986145,
"answer_date": "2009-06-12T11:18:27.077Z",
"answer_score": 3383
} |
Please answer the following Stack Overflow question:
Title: How do I select rows from a DataFrame based on column values?
<p>How can I select rows from a DataFrame based on values in some column in Pandas?</p>
<p>In SQL, I would use:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM table
WHERE column_name = some_value
</code></pre> | <p>To select rows whose column value equals a scalar, <code>some_value</code>, use <code>==</code>:</p>
<pre><code>df.loc[df['column_name'] == some_value]
</code></pre>
<p>To select rows whose column value is in an iterable, <code>some_values</code>, use <code>isin</code>:</p>
<pre><code>df.loc[df['column_name'].isin(some_values)]
</code></pre>
<p>Combine multiple conditions with <code>&</code>: </p>
<pre><code>df.loc[(df['column_name'] >= A) & (df['column_name'] <= B)]
</code></pre>
<p>Note the parentheses. Due to Python's <a href="https://docs.python.org/3/reference/expressions.html#operator-precedence" rel="noreferrer">operator precedence rules</a>, <code>&</code> binds more tightly than <code><=</code> and <code>>=</code>. Thus, the parentheses in the last example are necessary. Without the parentheses </p>
<pre><code>df['column_name'] >= A & df['column_name'] <= B
</code></pre>
<p>is parsed as </p>
<pre><code>df['column_name'] >= (A & df['column_name']) <= B
</code></pre>
<p>which results in a <a href="https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o">Truth value of a Series is ambiguous error</a>.</p>
<hr>
<p>To select rows whose column value <em>does not equal</em> <code>some_value</code>, use <code>!=</code>:</p>
<pre><code>df.loc[df['column_name'] != some_value]
</code></pre>
<p><code>isin</code> returns a boolean Series, so to select rows whose value is <em>not</em> in <code>some_values</code>, negate the boolean Series using <code>~</code>:</p>
<pre><code>df.loc[~df['column_name'].isin(some_values)]
</code></pre>
<hr>
<p>For example,</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
# A B C D
# 0 foo one 0 0
# 1 bar one 1 2
# 2 foo two 2 4
# 3 bar three 3 6
# 4 foo two 4 8
# 5 bar two 5 10
# 6 foo one 6 12
# 7 foo three 7 14
print(df.loc[df['A'] == 'foo'])
</code></pre>
<p>yields</p>
<pre><code> A B C D
0 foo one 0 0
2 foo two 2 4
4 foo two 4 8
6 foo one 6 12
7 foo three 7 14
</code></pre>
<hr>
<p>If you have multiple values you want to include, put them in a
list (or more generally, any iterable) and use <code>isin</code>:</p>
<pre><code>print(df.loc[df['B'].isin(['one','three'])])
</code></pre>
<p>yields</p>
<pre><code> A B C D
0 foo one 0 0
1 bar one 1 2
3 bar three 3 6
6 foo one 6 12
7 foo three 7 14
</code></pre>
<hr>
<p>Note, however, that if you wish to do this many times, it is more efficient to
make an index first, and then use <code>df.loc</code>:</p>
<pre><code>df = df.set_index(['B'])
print(df.loc['one'])
</code></pre>
<p>yields</p>
<pre><code> A C D
B
one foo 0 0
one bar 1 2
one foo 6 12
</code></pre>
<p>or, to include multiple values from the index use <code>df.index.isin</code>:</p>
<pre><code>df.loc[df.index.isin(['one','two'])]
</code></pre>
<p>yields</p>
<pre><code> A C D
B
one foo 0 0
one bar 1 2
two foo 2 4
two foo 4 8
two bar 5 10
one foo 6 12
</code></pre> | {
"question_id": 17071871,
"question_date": "2013-06-12T17:42:05.903Z",
"question_score": 3134,
"tags": "python|pandas|dataframe",
"answer_id": 17071908,
"answer_date": "2013-06-12T17:44:20.483Z",
"answer_score": 5865
} |
Please answer the following Stack Overflow question:
Title: How do I clone a list so that it doesn't change unexpectedly after assignment?
<p>While using <code>new_list = my_list</code>, any modifications to <code>new_list</code> changes <code>my_list</code> every time. Why is this, and how can I clone or copy the list to prevent it?</p> | <p><code>new_list = my_list</code> doesn't actually create a second list. The assignment just copies the reference to the list, not the actual list, so both <code>new_list</code> and <code>my_list</code> refer to the same list after the assignment.</p>
<p>To actually copy the list, you have several options:</p>
<ul>
<li><p>You can use the builtin <a href="https://docs.python.org/library/stdtypes.html#mutable-sequence-types" rel="noreferrer"><code>list.copy()</code></a> method (available since Python 3.3):</p>
<pre><code>new_list = old_list.copy()
</code></pre>
</li>
<li><p>You can slice it:</p>
<pre><code>new_list = old_list[:]
</code></pre>
<p><a href="https://en.wikipedia.org/wiki/Alex_Martelli" rel="noreferrer">Alex Martelli</a>'s opinion (at least <a href="https://www.youtube.com/watch?v=g7V89K8QfgQ" rel="noreferrer">back in 2007</a>) about this is, that <em>it is a weird syntax and it does not make sense to use it ever</em>. ;) (In his opinion, the next one is more readable).</p>
</li>
<li><p>You can use the built in <a href="https://docs.python.org/library/stdtypes.html#list" rel="noreferrer"><code>list()</code></a> constructor:</p>
<pre><code>new_list = list(old_list)
</code></pre>
</li>
<li><p>You can use generic <a href="https://docs.python.org/library/copy.html#copy.copy" rel="noreferrer"><code>copy.copy()</code></a>:</p>
<pre><code>import copy
new_list = copy.copy(old_list)
</code></pre>
<p>This is a little slower than <code>list()</code> because it has to find out the datatype of <code>old_list</code> first.</p>
</li>
<li><p>If you need to copy the elements of the list as well, use generic <a href="https://docs.python.org/library/copy.html#copy.deepcopy" rel="noreferrer"><code>copy.deepcopy()</code></a>:</p>
<pre><code>import copy
new_list = copy.deepcopy(old_list)
</code></pre>
<p>Obviously the slowest and most memory-needing method, but sometimes unavoidable. This operates recursively; it will handle any number of levels of nested lists (or other containers).</p>
</li>
</ul>
<p><strong>Example:</strong></p>
<pre><code>import copy
class Foo(object):
def __init__(self, val):
self.val = val
def __repr__(self):
return f'Foo({self.val!r})'
foo = Foo(1)
a = ['foo', foo]
b = a.copy()
c = a[:]
d = list(a)
e = copy.copy(a)
f = copy.deepcopy(a)
# edit orignal list and instance
a.append('baz')
foo.val = 5
print(f'original: {a}\nlist.copy(): {b}\nslice: {c}\nlist(): {d}\ncopy: {e}\ndeepcopy: {f}')
</code></pre>
<p>Result:</p>
<pre><code>original: ['foo', Foo(5), 'baz']
list.copy(): ['foo', Foo(5)]
slice: ['foo', Foo(5)]
list(): ['foo', Foo(5)]
copy: ['foo', Foo(5)]
deepcopy: ['foo', Foo(1)]
</code></pre> | {
"question_id": 2612802,
"question_date": "2010-04-10T08:49:46.673Z",
"question_score": 3132,
"tags": "python|list|reference|copy|clone",
"answer_id": 2612815,
"answer_date": "2010-04-10T08:55:21.393Z",
"answer_score": 3892
} |
Please answer the following Stack Overflow question:
Title: How do you disable browser autocomplete on web form field / input tags?
<p>How do you disable autocomplete in the major browsers for a specific input (or form field)?</p> | <p>Firefox 30 ignores <code>autocomplete="off"</code> for passwords, opting to prompt the user instead whether the password should be stored on the client. Note the following <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=956906#c100" rel="noreferrer">commentary</a> from May 5, 2014:</p>
<blockquote>
<ul>
<li>The password manager <em>always</em> prompts if it wants to save a password. Passwords are not saved without permission from the user.</li>
<li>We are the third browser to implement this change, after IE and Chrome.</li>
</ul>
</blockquote>
<p>According to the <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion" rel="noreferrer">Mozilla Developer Network</a> documentation, the Boolean form element attribute <code>autocomplete</code> prevents form data from being cached in older browsers.</p>
<pre><code><input type="text" name="foo" autocomplete="off" />
</code></pre> | {
"question_id": 2530,
"question_date": "2008-08-05T16:22:32.603Z",
"question_score": 3130,
"tags": "html|forms|browser|autocomplete",
"answer_id": 2531,
"answer_date": "2008-08-05T16:24:53.380Z",
"answer_score": 2835
} |
Please answer the following Stack Overflow question:
Title: How do I disable the resizable property of a textarea?
<p>I want to disable the resizable property of a <code>textarea</code>.</p>
<p>Currently, I can resize a <code>textarea</code> by clicking on the bottom right corner of the <code>textarea</code> and dragging the mouse. How can I disable this?</p>
<p><a href="https://i.stack.imgur.com/xrfWQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xrfWQ.png" alt="Enter image description here"></a></p> | <p>The following CSS rule disables resizing behavior for <a href="http://www.w3.org/wiki/HTML/Elements/textarea" rel="noreferrer"><code>textarea</code></a> elements:</p>
<pre class="lang-css prettyprint-override"><code>textarea {
resize: none;
}
</code></pre>
<p>To disable it for some (but not all) <code>textarea</code>s, there are a <a href="http://www.electrictoolbox.com/disable-textarea-resizing-safari-chrome/" rel="noreferrer">couple of options</a>.</p>
<p>You can use <code>class</code> attribute in your tag(<code><textarea class="textarea1"></code>):</p>
<pre class="lang-css prettyprint-override"><code>.textarea1 {
resize: none;
}
</code></pre>
<p>To disable a specific <code>textarea</code> with the <code>name</code> attribute set to <code>foo</code> (i.e., <code><textarea name="foo"></textarea></code>):</p>
<pre class="lang-css prettyprint-override"><code>textarea[name=foo] {
resize: none;
}
</code></pre>
<p>Or, using an <code>id</code> attribute (i.e., <code><textarea id="foo"></textarea></code>):</p>
<pre class="lang-css prettyprint-override"><code>#foo {
resize: none;
}
</code></pre>
<p>The <a href="http://www.w3.org/TR/css3-ui/#resize" rel="noreferrer">W3C page</a> lists possible values for resizing restrictions: none, both, horizontal, vertical, and inherit:</p>
<pre class="lang-css prettyprint-override"><code>textarea {
resize: vertical; /* user can resize vertically, but width is fixed */
}
</code></pre>
<p>Review a decent <a href="http://quirksmode.org/css/user-interface/" rel="noreferrer">compatibility page</a> to see what browsers currently support this feature. As Jon Hulka has commented, the dimensions can be <a href="http://davidwalsh.name/textarea-resize" rel="noreferrer">further restrained</a> in CSS using max-width, max-height, min-width, and min-height.</p>
<blockquote>
<h3>Super important to know:</h3>
<p>This property does nothing unless the overflow property is something other than visible, which is the default for most elements. So generally to use this, you'll have to set something like overflow: scroll;</p>
<p>Quote by Sara Cope,
<a href="http://css-tricks.com/almanac/properties/r/resize/" rel="noreferrer">http://css-tricks.com/almanac/properties/r/resize/</a></p>
</blockquote> | {
"question_id": 5235142,
"question_date": "2011-03-08T16:15:40.497Z",
"question_score": 3124,
"tags": "html|css",
"answer_id": 5235160,
"answer_date": "2011-03-08T16:17:12.397Z",
"answer_score": 4142
} |
Please answer the following Stack Overflow question:
Title: Add a column with a default value to an existing table in SQL Server
<p>How can I add a column with a default value to an existing table in <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#Genesis" rel="noreferrer">SQL Server 2000</a> / <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005" rel="noreferrer">SQL Server 2005</a>?</p> | <h2>Syntax:</h2>
<pre><code>ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
WITH VALUES
</code></pre>
<h2>Example:</h2>
<pre><code>ALTER TABLE SomeTable
ADD SomeCol Bit NULL --Or NOT NULL.
CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogenerated.
DEFAULT (0)--Optional Default-Constraint.
WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records.
</code></pre>
<h2>Notes:</h2>
<p><strong>Optional Constraint Name:</strong><br />
If you leave out <code>CONSTRAINT D_SomeTable_SomeCol</code> then SQL Server will autogenerate<br />
a Default-Contraint with a funny Name like: <code>DF__SomeTa__SomeC__4FB7FEF6</code><br /></p>
<p><strong>Optional With-Values Statement:</strong><br />
The <code>WITH VALUES</code> is only needed when your Column is Nullable<br />
and you want the Default Value used for Existing Records.<br />
If your Column is <code>NOT NULL</code>, then it will automatically use the Default Value<br />
for all Existing Records, whether you specify <code>WITH VALUES</code> or not.</p>
<p><strong>How Inserts work with a Default-Constraint:</strong><br />
If you insert a Record into <code>SomeTable</code> and do <strong><em>not</em></strong> Specify <code>SomeCol</code>'s value, then it will Default to <code>0</code>.<br />
If you insert a Record <strong><em>and</em></strong> Specify <code>SomeCol</code>'s value as <code>NULL</code> (and your column allows nulls),<br />
then the Default-Constraint will <strong><em>not</em></strong> be used and <code>NULL</code> will be inserted as the Value.<br /></p>
<p>Notes were based on everyone's great feedback below.<br />
Special Thanks to:<br />
@Yatrix, @WalterStabosz, @YahooSerious, and @StackMan for their Comments.</p> | {
"question_id": 92082,
"question_date": "2008-09-18T12:30:04.630Z",
"question_score": 3123,
"tags": "sql|sql-server|sql-server-2005|sql-server-2000",
"answer_id": 92123,
"answer_date": "2008-09-18T12:34:33.437Z",
"answer_score": 3940
} |
Please answer the following Stack Overflow question:
Title: How to iterate over a dictionary?
<p>I've seen a few different ways to iterate over a dictionary in C#. Is there a standard way?</p> | <pre class="lang-cs prettyprint-override"><code>foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
</code></pre> | {
"question_id": 141088,
"question_date": "2008-09-26T18:20:06.357Z",
"question_score": 3114,
"tags": "c#|dictionary|loops",
"answer_id": 141098,
"answer_date": "2008-09-26T18:22:10.423Z",
"answer_score": 4318
} |
Please answer the following Stack Overflow question:
Title: What is the difference between Python's list methods append and extend?
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p> | <p><a href="https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types" rel="noreferrer"><code>append</code></a> appends a specified object at the end of the list:</p>
<pre><code>>>> x = [1, 2, 3]
>>> x.append([4, 5])
>>> print(x)
[1, 2, 3, [4, 5]]
</code></pre>
<p><a href="https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types" rel="noreferrer"><code>extend</code></a> extends the list by appending elements from the specified iterable:</p>
<pre><code>>>> x = [1, 2, 3]
>>> x.extend([4, 5])
>>> print(x)
[1, 2, 3, 4, 5]
</code></pre> | {
"question_id": 252703,
"question_date": "2008-10-31T05:55:36.407Z",
"question_score": 3113,
"tags": "python|list|data-structures|append|extend",
"answer_id": 252711,
"answer_date": "2008-10-31T06:02:25.647Z",
"answer_score": 5767
} |
Please answer the following Stack Overflow question:
Title: What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
<p>What do <code>*args</code> and <code>**kwargs</code> mean?</p>
<pre><code>def foo(x, y, *args):
def bar(x, y, **kwargs):
</code></pre> | <p>The <code>*args</code> and <code>**kwargs</code> is a common idiom to allow arbitrary number of arguments to functions as described in the section <a href="http://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions" rel="noreferrer">more on defining functions</a> in the Python documentation.</p>
<p>The <code>*args</code> will give you all function parameters <a href="https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists" rel="noreferrer">as a tuple</a>:</p>
<pre><code>def foo(*args):
for a in args:
print(a)
foo(1)
# 1
foo(1,2,3)
# 1
# 2
# 3
</code></pre>
<p>The <code>**kwargs</code> will give you all
<strong>keyword arguments</strong> except for those corresponding to a formal parameter as a dictionary.</p>
<pre><code>def bar(**kwargs):
for a in kwargs:
print(a, kwargs[a])
bar(name='one', age=27)
# name one
# age 27
</code></pre>
<p>Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:</p>
<pre><code>def foo(kind, *args, **kwargs):
pass
</code></pre>
<p>It is also possible to use this the other way around:</p>
<pre><code>def foo(a, b, c):
print(a, b, c)
obj = {'b':10, 'c':'lee'}
foo(100,**obj)
# 100 10 lee
</code></pre>
<p>Another usage of the <code>*l</code> idiom is to <strong>unpack argument lists</strong> when calling a function.</p>
<pre><code>def foo(bar, lee):
print(bar, lee)
l = [1,2]
foo(*l)
# 1 2
</code></pre>
<p>In Python 3 it is possible to use <code>*l</code> on the left side of an assignment (<a href="http://www.python.org/dev/peps/pep-3132/" rel="noreferrer">Extended Iterable Unpacking</a>), though it gives a list instead of a tuple in this context:</p>
<pre><code>first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
</code></pre>
<p>Also Python 3 adds new semantic (refer <a href="https://www.python.org/dev/peps/pep-3102/" rel="noreferrer">PEP 3102</a>):</p>
<pre><code>def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
</code></pre>
<p>For example the following works in python 3 but not python 2:</p>
<pre><code>>>> x = [1, 2]
>>> [*x]
[1, 2]
>>> [*x, 3, 4]
[1, 2, 3, 4]
>>> x = {1:1, 2:2}
>>> x
{1: 1, 2: 2}
>>> {**x, 3:3, 4:4}
{1: 1, 2: 2, 3: 3, 4: 4}
</code></pre>
<p>Such function accepts only 3 positional arguments, and everything after <code>*</code> can only be passed as keyword arguments.</p>
<h3>Note:</h3>
<ul>
<li>A Python <code>dict</code>, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order.</li>
<li>"The order of elements in <code>**kwargs</code> now corresponds to the order in which keyword arguments were passed to the function." - <a href="https://docs.python.org/3/whatsnew/3.6.html" rel="noreferrer">What’s New In Python 3.6</a></li>
<li>In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, this becomes standard in Python 3.7.</li>
</ul> | {
"question_id": 36901,
"question_date": "2008-08-31T15:04:35.350Z",
"question_score": 3111,
"tags": "python|syntax|parameter-passing|variadic-functions|argument-unpacking",
"answer_id": 36908,
"answer_date": "2008-08-31T15:17:31.137Z",
"answer_score": 2984
} |
Please answer the following Stack Overflow question:
Title: How do I make git use the editor of my choice for editing commit messages?
<p>How do I globally configure git to use a particular editor (e.g. <code>vim</code>) for commit messages?</p> | <h4>Setting the default editor for Git</h4>
<p>Pick one:</p>
<ul>
<li><p>Set <a href="http://git-scm.com/book/en/Customizing-Git-Git-Configuration#Basic-Client-Configuration" rel="noreferrer"><code>core.editor</code></a> in your Git config:</p>
<pre><code>git config --global core.editor "vim"
</code></pre>
</li>
<li><p>Set the <a href="http://git-scm.com/docs/git-var#_variables" rel="noreferrer"><code>GIT_EDITOR</code></a> environment variable:</p>
<pre><code>export GIT_EDITOR=vim
</code></pre>
</li>
</ul>
<hr />
<h4>Setting the default editor for all programs</h4>
<p>Set the standardized <code>VISUAL</code> and <code>EDITOR</code> environment variables*:</p>
<pre><code>export VISUAL=vim
export EDITOR="$VISUAL"
</code></pre>
<p><strong>NOTE:</strong> Setting both is not necessarily needed, but some programs may not use the more-correct <code>VISUAL</code>. See <a href="https://unix.stackexchange.com/questions/4859/visual-vs-editor-whats-the-difference"><code>VISUAL</code> vs. <code>EDITOR</code></a>.</p>
<hr />
<h4>Fixing compatibility issues</h4>
<p>Some editors require a <code>--wait</code> flag, or they will open a blank page. For example:</p>
<ul>
<li><p><strong>Sublime Text</strong> (if <a href="https://stackoverflow.com/questions/25152711/subl-command-not-working-command-not-found/25154529">correctly set up</a>; or use the full path to the executable in place of <code>subl</code>):</p>
<pre><code>export VISUAL="subl --wait"
</code></pre>
</li>
<li><p><strong>VS Code</strong> (after adding the <a href="https://stackoverflow.com/questions/29955500/code-not-working-in-command-line-for-visual-studio-code-on-osx-mac">shell command</a>):</p>
<pre><code>export VISUAL="code --wait"
</code></pre>
</li>
</ul> | {
"question_id": 2596805,
"question_date": "2010-04-08T00:28:46.900Z",
"question_score": 3110,
"tags": "git|vim|emacs|editor|commit-message",
"answer_id": 2596835,
"answer_date": "2010-04-08T00:34:28.813Z",
"answer_score": 4225
} |
Please answer the following Stack Overflow question:
Title: How to stop EditText from gaining focus when an activity starts in Android?
<p>I have an <code>Activity</code> in Android, with two elements:</p>
<ol>
<li><code>EditText</code></li>
<li><code>ListView</code></li>
</ol>
<p>When my <code>Activity</code> starts, the <code>EditText</code> immediately has the input focus (flashing cursor). I don't want any control to have input focus at startup. I tried:</p>
<pre><code>EditText.setSelected(false);
EditText.setFocusable(false);
</code></pre>
<p>No luck. How can I convince the <code>EditText</code> to not select itself when the <code>Activity</code> starts?</p> | <p>Adding the tags <code>android:focusableInTouchMode="true"</code> and <code>android:focusable="true"</code> to the parent layout (e.g. <code>LinearLayout</code> or <code>ConstraintLayout</code>) like in the following example, will fix the problem.</p>
<pre><code><!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
<LinearLayout
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="0px"
android:layout_height="0px"/>
<!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component
to prevent the dummy from receiving focus again -->
<AutoCompleteTextView android:id="@+id/autotext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:nextFocusUp="@id/autotext"
android:nextFocusLeft="@id/autotext"/>
</code></pre> | {
"question_id": 1555109,
"question_date": "2009-10-12T15:03:22.700Z",
"question_score": 3108,
"tags": "android|listview|android-activity|android-edittext|focus",
"answer_id": 1662088,
"answer_date": "2009-11-02T15:49:57.020Z",
"answer_score": 2813
} |
Please answer the following Stack Overflow question:
Title: How do I test a class that has private methods, fields or inner classes?
<p>How do I use JUnit to test a class that has internal private methods, fields or nested classes?</p>
<p>It seems bad to change the access modifier for a method just to be able to run a test.</p> | <p>If you have somewhat of a legacy <strong>Java</strong> application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use <a href="http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29" rel="noreferrer">reflection</a>.</p>
<p>Internally we're using helpers to get/set <code>private</code> and <code>private static</code> variables as well as invoke <code>private</code> and <code>private static</code> methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can't change <code>private static final</code> variables through reflection.</p>
<pre><code>Method method = TargetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
</code></pre>
<p>And for fields:</p>
<pre><code>Field field = TargetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);
</code></pre>
<hr />
<blockquote>
<p><strong>Notes:</strong></p>
<ol>
<li><code>TargetClass.getDeclaredMethod(methodName, argClasses)</code> lets you look into <code>private</code> methods. The same thing applies for
<code>getDeclaredField</code>.</li>
<li>The <code>setAccessible(true)</code> is required to play around with privates.</li>
</ol>
</blockquote> | {
"question_id": 34571,
"question_date": "2008-08-29T16:11:09.933Z",
"question_score": 3103,
"tags": "java|unit-testing|junit|tdd",
"answer_id": 34658,
"answer_date": "2008-08-29T16:35:11.560Z",
"answer_score": 1800
} |
Please answer the following Stack Overflow question:
Title: How do I find and restore a deleted file in a Git repository?
<p>Say I'm in a Git repository. I delete a file and commit that change. I continue working and make some more commits. Then, I discover that I need to restore that file after deleting it.</p>
<p>I know I can checkout a file using <code>git checkout <commit> -- filename.txt</code>, but I don't know when that file was deleted.</p>
<ol>
<li>How do I find the commit that deleted a given filename?</li>
<li>How do I restore that file back into my working copy?</li>
</ol> | <p>Find the last commit that affected the given path. As the file isn't in the HEAD commit, that previous commit must have deleted it.</p>
<pre><code>git rev-list -n 1 HEAD -- <file_path>
</code></pre>
<p>Then checkout the version at the commit before, using the caret (<code>^</code>) symbol:</p>
<pre><code>git checkout <deleting_commit>^ -- <file_path>
</code></pre>
<p>Or in one command, if <code>$file</code> is the file in question.</p>
<pre><code>git checkout $(git rev-list -n 1 HEAD -- "$file")^ -- "$file"
</code></pre>
<hr />
<p>If you are using zsh and have the EXTENDED_GLOB option enabled, the caret symbol won't work. You can use <code>~1</code> instead.</p>
<pre><code>git checkout $(git rev-list -n 1 HEAD -- "$file")~1 -- "$file"
</code></pre> | {
"question_id": 953481,
"question_date": "2009-06-04T22:40:34.407Z",
"question_score": 3103,
"tags": "git|file-io|git-checkout",
"answer_id": 1113140,
"answer_date": "2009-07-11T07:12:20.537Z",
"answer_score": 3416
} |
Please answer the following Stack Overflow question:
Title: Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?
<blockquote>
<p><strong>Mod note</strong>: This question is about why <code>XMLHttpRequest</code>/<code>fetch</code>/etc. on the browser are subject to the Same Access Policy restrictions (you get errors mentioning CORB or CORS) while Postman is not. This question is <strong>not</strong> about how to fix a "No 'Access-Control-Allow-Origin'..." error. It's about why they happen.</p>
</blockquote>
<blockquote>
<p><strong>Please stop posting</strong>:</p>
<ul>
<li>CORS configurations for every language/framework under the sun. Instead <a href="https://stackoverflow.com/search?q=how+to+enable+CORS+is%3Aquestion&mixed=1">find your relevant language/framework's question</a>.</li>
<li>3rd party services that allow a request to circumvent CORS</li>
<li>Command line options for turning off CORS for various browsers</li>
</ul>
</blockquote>
<hr />
<p>I am trying to do authorization using <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> by connecting to the <a href="http://en.wikipedia.org/wiki/Representational_state_transfer#RESTful_web_services" rel="noreferrer">RESTful</a> <a href="http://en.wikipedia.org/wiki/Application_programming_interface" rel="noreferrer">API</a> built-in <a href="https://en.wikipedia.org/wiki/Flask_%28web_framework%29" rel="noreferrer">Flask</a>. However, when I make the request, I get the following error:</p>
<pre class="lang-js prettyprint-override"><code>XMLHttpRequest cannot load http://myApiUrl/login.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.
</code></pre>
<p>I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension <a href="https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop" rel="noreferrer">Postman</a>?</p>
<p>This is the request code:</p>
<pre class="lang-js prettyprint-override"><code>$.ajax({
type: 'POST',
dataType: 'text',
url: api,
username: 'user',
password: 'pass',
crossDomain: true,
xhrFields: {
withCredentials: true,
},
})
.done(function (data) {
console.log('done');
})
.fail(function (xhr, textStatus, errorThrown) {
alert(xhr.responseText);
alert(textStatus);
});
</code></pre> | <p>If I understood it right you are doing an <a href="http://en.wikipedia.org/wiki/XMLHttpRequest" rel="noreferrer">XMLHttpRequest</a> to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request.</p>
<p>When you are using Postman they are not restricted by this policy. Quoted from <em><a href="https://developer.chrome.com/docs/extensions/mv2/xhr/" rel="noreferrer">Cross-Origin XMLHttpRequest</a></em>:</p>
<blockquote>
<p>Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.</p>
</blockquote> | {
"question_id": 20035101,
"question_date": "2013-11-17T19:29:06.337Z",
"question_score": 3099,
"tags": "javascript|jquery|cors|postman|same-origin-policy",
"answer_id": 20035319,
"answer_date": "2013-11-17T19:49:53.533Z",
"answer_score": 1590
} |
Please answer the following Stack Overflow question:
Title: How can I merge properties of two JavaScript objects dynamically?
<p>I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to:</p>
<pre><code>var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }
obj1.merge(obj2);
//obj1 now has three properties: food, car, and animal
</code></pre>
<p>Is there a built in way to do this? I do not need recursion, and I do not need to merge functions, just methods on flat objects.</p> | <p><strong>ECMAScript 2018 Standard Method</strong></p>
<p>You would use <a href="https://github.com/tc39/proposal-object-rest-spread" rel="noreferrer">object spread</a>:</p>
<pre><code>let merged = {...obj1, ...obj2};
</code></pre>
<p><code>merged</code> is now the union of <code>obj1</code> and <code>obj2</code>. Properties in <code>obj2</code> will overwrite those in <code>obj1</code>.</p>
<pre><code>/** There's no limit to the number of objects you can merge.
* Later properties overwrite earlier properties with the same name. */
const allRules = {...obj1, ...obj2, ...obj3};
</code></pre>
<p>Here is also the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax" rel="noreferrer">MDN documentation</a> for this syntax. If you're using babel you'll need the <a href="https://babeljs.io/docs/en/babel-plugin-transform-object-rest-spread.html" rel="noreferrer">babel-plugin-transform-object-rest-spread</a> plugin for it to work.</p>
<p><strong>ECMAScript 2015 (ES6) Standard Method</strong></p>
<pre><code>/* For the case in question, you would do: */
Object.assign(obj1, obj2);
/** There's no limit to the number of objects you can merge.
* All objects get merged into the first object.
* Only the object in the first argument is mutated and returned.
* Later properties overwrite earlier properties with the same name. */
const allRules = Object.assign({}, obj1, obj2, obj3, etc);
</code></pre>
<p>(see <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Browser_compatibility" rel="noreferrer">MDN JavaScript Reference</a>)</p>
<hr />
<p><strong>Method for ES5 and Earlier</strong></p>
<pre><code>for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }
</code></pre>
<p>Note that this will simply add all attributes of <code>obj2</code> to <code>obj1</code> which might not be what you want if you still want to use the unmodified <code>obj1</code>.</p>
<p>If you're using a framework that craps all over your prototypes then you have to get fancier with checks like <code>hasOwnProperty</code>, but that code will work for 99% of cases.</p>
<p>Example function:</p>
<pre><code>/**
* Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
* @param obj1
* @param obj2
* @returns obj3 a new object based on obj1 and obj2
*/
function merge_options(obj1,obj2){
var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;
}
</code></pre> | {
"question_id": 171251,
"question_date": "2008-10-05T00:30:54.833Z",
"question_score": 3084,
"tags": "javascript|javascript-objects",
"answer_id": 171256,
"answer_date": "2008-10-05T00:33:25.077Z",
"answer_score": 3731
} |
Please answer the following Stack Overflow question:
Title: Is there an "exists" function for jQuery?
<p>How can I check the existence of an element in jQuery?</p>
<p>The current code that I have is this:</p>
<pre><code>if ($(selector).length > 0) {
// Do something
}
</code></pre>
<p>Is there a more elegant way to approach this? Perhaps a plugin or a function?</p> | <p>In JavaScript, everything is 'truthy' or 'falsy', and for numbers <code>0</code> means <code>false</code>, everything else <code>true</code>. So you could write:</p>
<pre><code>if ($(selector).length)
</code></pre>
<p>You don't need that <code>>0</code> part.</p> | {
"question_id": 31044,
"question_date": "2008-08-27T19:49:41.107Z",
"question_score": 3062,
"tags": "javascript|jquery",
"answer_id": 587408,
"answer_date": "2009-02-25T19:16:21.610Z",
"answer_score": 2713
} |
Please answer the following Stack Overflow question:
Title: Understanding Python super() with __init__() methods
<p>Why is <code>super()</code> used?</p>
<p>Is there a difference between using <code>Base.__init__</code> and <code>super().__init__</code>?</p>
<pre><code>class Base(object):
def __init__(self):
print "Base created"
class ChildA(Base):
def __init__(self):
Base.__init__(self)
class ChildB(Base):
def __init__(self):
super(ChildB, self).__init__()
ChildA()
ChildB()
</code></pre> | <p><code>super()</code> lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=236275" rel="noreferrer">fun stuff</a> can happen. See the <a href="https://docs.python.org/2/library/functions.html#super" rel="noreferrer">standard docs on super</a> if you haven't already.</p>
<p>Note that <a href="https://docs.python.org/3/library/functions.html#super" rel="noreferrer">the syntax changed in Python 3.0</a>: you can just say <code>super().__init__()</code> instead of <code>super(ChildB, self).__init__()</code> which IMO is quite a bit nicer. The standard docs also refer to a <a href="https://rhettinger.wordpress.com/2011/05/26/super-considered-super/" rel="noreferrer">guide to using <code>super()</code></a> which is quite explanatory.</p> | {
"question_id": 576169,
"question_date": "2009-02-23T00:30:08.570Z",
"question_score": 3060,
"tags": "python|class|oop|inheritance|super",
"answer_id": 576183,
"answer_date": "2009-02-23T00:37:31.220Z",
"answer_score": 2212
} |
Please answer the following Stack Overflow question:
Title: How do I make function decorators and chain them together?
<p>How do I make two decorators in Python that would do the following?</p>
<pre><code>@make_bold
@make_italic
def say():
return "Hello"
</code></pre>
<p>Calling <code>say()</code> should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre> | <p>Check out <a href="http://docs.python.org/reference/compound_stmts.html#function" rel="noreferrer">the documentation</a> to see how decorators work. Here is what you asked for:</p>
<pre><code>from functools import wraps
def makebold(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
return "<b>" + fn(*args, **kwargs) + "</b>"
return wrapper
def makeitalic(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
return "<i>" + fn(*args, **kwargs) + "</i>"
return wrapper
@makebold
@makeitalic
def hello():
return "hello world"
@makebold
@makeitalic
def log(s):
return s
print hello() # returns "<b><i>hello world</i></b>"
print hello.__name__ # with functools.wraps() this returns "hello"
print log('hello') # returns "<b><i>hello</i></b>"
</code></pre> | {
"question_id": 739654,
"question_date": "2009-04-11T07:05:31.503Z",
"question_score": 3053,
"tags": "python|decorator|python-decorators",
"answer_id": 739665,
"answer_date": "2009-04-11T07:16:18.420Z",
"answer_score": 3057
} |
Please answer the following Stack Overflow question:
Title: How do I find out which process is listening on a TCP or UDP port on Windows?
<p>How do I find out which process is listening on a TCP or UDP port on Windows?</p> | <h1>New answer, powershell</h1>
<h2>TCP</h2>
<pre><code>Get-Process -Id (Get-NetTCPConnection -LocalPort YourPortNumberHere).OwningProcess
</code></pre>
<h2>UDP</h2>
<pre><code>Get-Process -Id (Get-NetUDPEndpoint -LocalPort YourPortNumberHere).OwningProcess
</code></pre>
<h1>Old answer, cmd</h1>
<pre><code> C:\> netstat -a -b
</code></pre>
<p>(Add <strong>-n</strong> to stop it trying to resolve hostnames, which will make it a lot faster.)</p>
<p>Note Dane's recommendation for <a href="http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx" rel="noreferrer">TCPView</a>. It looks very useful!</p>
<p><strong>-a</strong> Displays all connections and listening ports.</p>
<p><strong>-b</strong> Displays the executable involved in creating each connection or listening port. In some cases well-known executables host multiple independent components, and in these cases the sequence of components involved in creating the connection or listening port is displayed. In this case the executable name is in [] at the bottom, on top is the component it called, and so forth until TCP/IP was reached. Note that this option can be time-consuming and will fail unless you have sufficient permissions.</p>
<p><strong>-n</strong> Displays addresses and port numbers in numerical form.</p>
<p><strong>-o</strong> Displays the owning process ID associated with each connection.</p> | {
"question_id": 48198,
"question_date": "2008-09-07T06:26:12.993Z",
"question_score": 3050,
"tags": "windows|networking|port",
"answer_id": 48199,
"answer_date": "2008-09-07T06:28:33.970Z",
"answer_score": 3503
} |
Please answer the following Stack Overflow question:
Title: What does cherry-picking a commit with Git mean?
<p>What does <a href="https://git-scm.com/docs/git-cherry-pick" rel="noreferrer"><code>git cherry-pick <commit></code></a> do?</p> | <p>Cherry picking in Git means to choose a commit from one branch and apply it onto another.</p>
<p>This is in contrast with other ways such as <code>merge</code> and <code>rebase</code> which normally apply many commits onto another branch.</p>
<ol>
<li><p>Make sure you are on the branch you want to apply the commit to.</p>
<pre><code> git switch master
</code></pre>
</li>
<li><p>Execute the following:</p>
<pre><code> git cherry-pick <commit-hash>
</code></pre>
</li>
</ol>
<p>N.B.:</p>
<ol>
<li><p>If you cherry-pick from a public branch, you should consider using</p>
<pre><code> git cherry-pick -x <commit-hash>
</code></pre>
<p>This will generate a standardized commit message. This way, you (and your co-workers) can still keep track of the origin of the commit and may avoid merge conflicts in the future.</p>
</li>
<li><p>If you have notes attached to the commit they do not follow the cherry-pick. To bring them over as well, You have to use:</p>
<pre><code> git notes copy <from> <to>
</code></pre>
</li>
</ol>
<p>Additional links:</p>
<ul>
<li><a href="http://git-scm.com/docs/git-cherry-pick" rel="noreferrer">git official guide page</a></li>
</ul> | {
"question_id": 9339429,
"question_date": "2012-02-18T07:20:47.677Z",
"question_score": 3049,
"tags": "git|cherry-pick|git-cherry-pick",
"answer_id": 9339460,
"answer_date": "2012-02-18T07:29:42.237Z",
"answer_score": 3682
} |
Please answer the following Stack Overflow question:
Title: How do I delete a file or folder in Python?
<p>How do I delete a file or folder?</p> | <ul>
<li><p><a href="http://docs.python.org/library/os.html#os.remove" rel="noreferrer"><code>os.remove()</code></a> removes a file.</p></li>
<li><p><a href="http://docs.python.org/library/os.html#os.rmdir" rel="noreferrer"><code>os.rmdir()</code></a> removes an empty directory.</p></li>
<li><p><a href="http://docs.python.org/library/shutil.html#shutil.rmtree" rel="noreferrer"><code>shutil.rmtree()</code></a> deletes a directory and all its contents.</p></li>
</ul>
<hr>
<p><a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path" rel="noreferrer"><code>Path</code></a> objects from the Python 3.4+ <a href="https://docs.python.org/3/library/pathlib.html" rel="noreferrer"><code>pathlib</code></a> module also expose these instance methods:</p>
<ul>
<li><p><a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.unlink" rel="noreferrer"><code>pathlib.Path.unlink()</code></a> removes a file or symbolic link.</p></li>
<li><p><a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.rmdir" rel="noreferrer"><code>pathlib.Path.rmdir()</code></a> removes an empty directory.</p></li>
</ul> | {
"question_id": 6996603,
"question_date": "2011-08-09T13:05:42.343Z",
"question_score": 3047,
"tags": "python|file-io|directory|delete-file",
"answer_id": 6996628,
"answer_date": "2011-08-09T13:07:39.090Z",
"answer_score": 4464
} |
Please answer the following Stack Overflow question:
Title: Should I use the datetime or timestamp data type in MySQL?
<p>Would you recommend using a <a href="https://dev.mysql.com/doc/refman/5.0/en/datetime.html" rel="noreferrer">datetime</a> or a <a href="https://dev.mysql.com/doc/refman/5.0/en/datetime.html" rel="noreferrer">timestamp</a> field, and why (using MySQL)? </p>
<p>I'm working with PHP on the server side.</p> | <p>Timestamps in MySQL are generally used to track changes to records, and are often updated every time the record is changed. If you want to store a specific value you should use a datetime field.</p>
<p>If you meant that you want to decide between using a UNIX timestamp or a native MySQL datetime field, go with the native <code>DATETIME</code> format. You can do calculations within MySQL that way
<code>("SELECT DATE_ADD(my_datetime, INTERVAL 1 DAY)")</code> and it is simple to change the format of the value to a UNIX timestamp <code>("SELECT UNIX_TIMESTAMP(my_datetime)")</code> when you query the record if you want to operate on it with PHP.</p> | {
"question_id": 409286,
"question_date": "2009-01-03T16:14:37.090Z",
"question_score": 3035,
"tags": "mysql|datetime|timestamp|sqldatatypes",
"answer_id": 409305,
"answer_date": "2009-01-03T16:26:17.313Z",
"answer_score": 2056
} |
Please answer the following Stack Overflow question:
Title: Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)
<p>I updated to the latest OS, and/or restarted my computer (this happens on every major update, but this time all I did was restart my computer on 2022-09-13)</p>
<p>This morning I navigated to my work's codebase in the Command Line on my MacBook pro, typed in "git status" in the repository and received an error:</p>
<p>(IN 9/2022, this error was much different, but I didn't capture it)</p>
<blockquote>
<p>xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun</p>
</blockquote>
<p>git will not work!</p>
<p>How do I fix git, and command line tools?</p> | <p>The problem is that Xcode Command-line Tools needs to be updated.</p>
<p>** UPDATED FOR Sept. 2022 M1 MacBook Pro **</p>
<p>After opening the terminal after a restart, I tried to go to my code, and do a git status, and I got an error and prompt for command line software agreement.</p>
<p>So press space until you get to the <code>[agree, print, cancel]</code> option, so careful hit space to scroll down to the end, if you blow past It you have to run a command to get it back. Use <code>sudo xcodebuild -license</code> to get to it again.</p>
<p>Just be careful on scrolling down and enter <code>agree</code> and press return and it will launch into an update.</p>
<p><a href="https://i.stack.imgur.com/Jm3iY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Jm3iY.png" alt="Xcode software license" /></a></p>
<p>Then I tried to use git after the install, and it prompted me to install Xcode tools again.</p>
<p>I followed my own advice from previous years (see below), and went to <a href="https://developer.apple.com/download/more/" rel="noreferrer">https://developer.apple.com/download/more/</a> and downloaded
"Command Line Tools for Xcode 14" (You have to log in with your Apple ID, so have that login readily available.</p>
<p><a href="https://i.stack.imgur.com/YS2KU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YS2KU.png" alt="developer download page selection for "Command Line Tools for Xcode 14"" /></a></p>
<p>** I am not sure if this step is needed, but I did it all the same as that's what worked the previous years.</p>
<p>Before you can use git, you need to reboot. This completed the install and git is now working.</p>
<p>Solutions for previous years, these may or may not be valid these days as the downloads page has changed significantly:</p>
<p>PREVIOUS YEARS SOLUTIONS, probably #2 is most helpful.</p>
<p>** Solution #1 **</p>
<p>Go back to your terminal and enter:</p>
<pre><code>xcode-select --install
</code></pre>
<p>You'll then receive the following output:</p>
<pre><code>xcode-select: note: install requested for command line developer tools
</code></pre>
<p>You will then be prompted in a window to update Xcode Command Line tools. (which may take a while)</p>
<p>Open a new terminal window and your development tools should be returned.</p>
<p><strong>Addition:</strong> With any major or semi-major update you'll need to update the command line tools in order to get them functioning properly again. Check Xcode with any update. This goes beyond Mojave...</p>
<p><strong>After that restart your terminal</strong></p>
<p>Alternatively, <strong>IF that fails,</strong> and it very well might.... you'll get a pop-up box saying "Software not found on server", see below!</p>
<p><strong>Solution #2</strong></p>
<p>and you hit <code>xcode-select --install</code> and it doesn't find the software, log into Apple Developer, and install it via webpage.</p>
<p>Log in or sign up here:</p>
<p><a href="https://developer.apple.com/download/more/" rel="noreferrer">https://developer.apple.com/download/more/</a></p>
<p>Look for: <strong>"Command Line Tools for Xcode 14.x"</strong> in the list of downloads
Then click the dmg and download.</p>
<p><a href="https://i.stack.imgur.com/WwAlF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WwAlF.png" alt="image of apple developer page and dmg for DL" /></a></p> | {
"question_id": 52522565,
"question_date": "2018-09-26T16:43:18.797Z",
"question_score": 3024,
"tags": "xcode|git|macos|command-line|terminal",
"answer_id": 52522566,
"answer_date": "2018-09-26T16:43:18.797Z",
"answer_score": 4650
} |
Please answer the following Stack Overflow question:
Title: Is there a unique Android device ID?
<p>Do Android devices have a unique ID, and if so, what is a simple way to access it using Java?</p> | <p><a href="http://developer.android.com/reference/android/provider/Settings.Secure.html#ANDROID_ID" rel="noreferrer"><code>Settings.Secure#ANDROID_ID</code></a> returns the Android ID as an <em><a href="https://developer.android.com/reference/android/provider/Settings.Secure.html#ANDROID_ID" rel="noreferrer">unique for each user</a></em> 64-bit hex string.</p>
<pre><code>import android.provider.Settings.Secure;
private String android_id = Secure.getString(getContext().getContentResolver(),
Secure.ANDROID_ID);
</code></pre>
<p>Also read <strong>Best practices for unique identifiers</strong>: <a href="https://developer.android.com/training/articles/user-data-ids" rel="noreferrer">https://developer.android.com/training/articles/user-data-ids</a></p> | {
"question_id": 2785485,
"question_date": "2010-05-07T00:47:28.433Z",
"question_score": 3008,
"tags": "android|uniqueidentifier",
"answer_id": 2785493,
"answer_date": "2010-05-07T00:49:47.110Z",
"answer_score": 2187
} |
Please answer the following Stack Overflow question:
Title: How do I set, clear, and toggle a single bit?
<p>How do I set, clear, and toggle a bit?</p> | <h1>Setting a bit</h1>
<p>Use the bitwise OR operator (<code>|</code>) to set a bit.</p>
<pre><code>number |= 1UL << n;
</code></pre>
<p>That will set the <code>n</code>th bit of <code>number</code>. <code>n</code> should be zero, if you want to set the <code>1</code>st bit and so on upto <code>n-1</code>, if you want to set the <code>n</code>th bit.</p>
<p>Use <code>1ULL</code> if <code>number</code> is wider than <code>unsigned long</code>; promotion of <code>1UL << n</code> doesn't happen until after evaluating <code>1UL << n</code> where it's undefined behaviour to shift by more than the width of a <code>long</code>. The same applies to all the rest of the examples.</p>
<h1>Clearing a bit</h1>
<p>Use the bitwise AND operator (<code>&</code>) to clear a bit.</p>
<pre><code>number &= ~(1UL << n);
</code></pre>
<p>That will clear the <code>n</code>th bit of <code>number</code>. You must invert the bit string with the bitwise NOT operator (<code>~</code>), then AND it.</p>
<h1>Toggling a bit</h1>
<p>The XOR operator (<code>^</code>) can be used to toggle a bit.</p>
<pre><code>number ^= 1UL << n;
</code></pre>
<p>That will toggle the <code>n</code>th bit of <code>number</code>.</p>
<h1>Checking a bit</h1>
<p>You didn't ask for this, but I might as well add it.</p>
<p>To check a bit, shift the number n to the right, then bitwise AND it:</p>
<pre><code>bit = (number >> n) & 1U;
</code></pre>
<p>That will put the value of the <code>n</code>th bit of <code>number</code> into the variable <code>bit</code>.</p>
<h1>Changing the <em>n</em>th bit to <em>x</em></h1>
<p>Setting the <code>n</code>th bit to either <code>1</code> or <code>0</code> can be achieved with the following on a 2's complement C++ implementation:</p>
<pre><code>number ^= (-x ^ number) & (1UL << n);
</code></pre>
<p>Bit <code>n</code> will be set if <code>x</code> is <code>1</code>, and cleared if <code>x</code> is <code>0</code>. If <code>x</code> has some other value, you get garbage. <code>x = !!x</code> will booleanize it to 0 or 1.</p>
<p>To make this independent of 2's complement negation behaviour (where <code>-1</code> has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation.</p>
<pre><code>number ^= (-(unsigned long)x ^ number) & (1UL << n);
</code></pre>
<p>or</p>
<pre><code>unsigned long newbit = !!x; // Also booleanize to force 0 or 1
number ^= (-newbit ^ number) & (1UL << n);
</code></pre>
<p>It's generally a good idea to use unsigned types for portable bit manipulation.</p>
<p>or</p>
<pre><code>number = (number & ~(1UL << n)) | (x << n);
</code></pre>
<p><code>(number & ~(1UL << n))</code> will clear the <code>n</code>th bit and <code>(x << n)</code> will set the <code>n</code>th bit to <code>x</code>.</p>
<p>It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like <a href="https://stackoverflow.com/a/263738/52074">the community wiki answer further down</a>) or some sort of encapsulation.</p> | {
"question_id": 47981,
"question_date": "2008-09-07T00:42:17.500Z",
"question_score": 3004,
"tags": "c++|c|bit-manipulation|bitwise-operators",
"answer_id": 47990,
"answer_date": "2008-09-07T00:50:45.403Z",
"answer_score": 4179
} |
Please answer the following Stack Overflow question:
Title: How do you push a tag to a remote repository using Git?
<p>I added a tag to the master branch on my machine:</p>
<pre><code>git tag mytag master
</code></pre>
<p>How do I push this to the remote repository? Running <code>git push</code> gives the message:</p>
<blockquote>
<p>Everything up-to-date</p>
</blockquote>
<p>However, the remote repository does not contain my tag.</p> | <p>To push specific, one tag do following
<code>git push origin tag_name</code></p> | {
"question_id": 5195859,
"question_date": "2011-03-04T15:37:24.330Z",
"question_score": 3001,
"tags": "git|git-push|git-tag",
"answer_id": 13051597,
"answer_date": "2012-10-24T14:43:31.493Z",
"answer_score": 304
} |
Please answer the following Stack Overflow question:
Title: How can I know which radio button is selected via jQuery?
<p>I have two radio buttons and want to post the value of the selected one.
How can I get the value with jQuery?</p>
<p>I can get all of them like this:</p>
<pre><code>$("form :radio")
</code></pre>
<p>How do I know which one is selected?</p> | <p>To get the value of the <strong>selected</strong> <code>radioName</code> item of a form with id <code>myForm</code>:</p>
<pre><code>$('input[name=radioName]:checked', '#myForm').val()
</code></pre>
<p>Here's an example:</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-js lang-js prettyprint-override"><code>$('#myForm input').on('change', function() {
alert($('input[name=radioName]:checked', '#myForm').val());
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<fieldset>
<legend>Choose radioName</legend>
<label><input type="radio" name="radioName" value="1" /> 1</label> <br />
<label><input type="radio" name="radioName" value="2" /> 2</label> <br />
<label><input type="radio" name="radioName" value="3" /> 3</label> <br />
</fieldset>
</form></code></pre>
</div>
</div>
</p> | {
"question_id": 596351,
"question_date": "2009-02-27T19:53:27.180Z",
"question_score": 2987,
"tags": "javascript|jquery|html|jquery-selectors|radio-button",
"answer_id": 596369,
"answer_date": "2009-02-27T19:58:39.320Z",
"answer_score": 4218
} |
Please answer the following Stack Overflow question:
Title: Manually raising (throwing) an exception in Python
<p>How do I raise an exception in Python so that it can later be caught via an <code>except</code> block?</p> | <blockquote>
<h2>How do I manually throw/raise an exception in Python?</h2>
</blockquote>
<p><a href="https://docs.python.org/3/library/exceptions.html#exception-hierarchy" rel="noreferrer">Use the most specific Exception constructor that semantically fits your issue</a>.</p>
<p>Be specific in your message, e.g.:</p>
<pre><code>raise ValueError('A very specific bad thing happened.')
</code></pre>
<h2>Don't raise generic exceptions</h2>
<p>Avoid raising a generic <code>Exception</code>. To catch it, you'll have to catch all other more specific exceptions that subclass it.</p>
<h3>Problem 1: Hiding bugs</h3>
<pre><code>raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
</code></pre>
<p>For example:</p>
<pre><code>def demo_bad_catch():
try:
raise ValueError('Represents a hidden bug, do not catch this')
raise Exception('This is the exception you expect to handle')
except Exception as error:
print('Caught this error: ' + repr(error))
>>> demo_bad_catch()
Caught this error: ValueError('Represents a hidden bug, do not catch this',)
</code></pre>
<h3>Problem 2: Won't catch</h3>
<p>And more specific catches won't catch the general exception:</p>
<pre><code>def demo_no_catch():
try:
raise Exception('general exceptions not caught by specific handling')
except ValueError as e:
print('we will not catch exception: Exception')
>>> demo_no_catch()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling
</code></pre>
<h2>Best Practices: <code>raise</code> statement</h2>
<p><a href="https://docs.python.org/3/library/exceptions.html#exception-hierarchy" rel="noreferrer">Instead, use the most specific Exception constructor that semantically fits your issue</a>.</p>
<pre><code>raise ValueError('A very specific bad thing happened')
</code></pre>
<p>which also handily allows an arbitrary number of arguments to be passed to the constructor:</p>
<pre><code>raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz')
</code></pre>
<p>These arguments are accessed by the <code>args</code> attribute on the <code>Exception</code> object. For example:</p>
<pre><code>try:
some_code_that_may_raise_our_value_error()
except ValueError as err:
print(err.args)
</code></pre>
<p>prints</p>
<pre><code>('message', 'foo', 'bar', 'baz')
</code></pre>
<p>In Python 2.5, an actual <code>message</code> attribute was added to <code>BaseException</code> in favor of encouraging users to subclass Exceptions and stop using <code>args</code>, but <a href="http://www.python.org/dev/peps/pep-0352/#retracted-ideas" rel="noreferrer">the introduction of <code>message</code> and the original deprecation of args has been retracted</a>.</p>
<h2>Best Practices: <code>except</code> clause</h2>
<p>When inside an except clause, you might want to, for example, log that a specific type of error happened, and then re-raise. The best way to do this while preserving the stack trace is to use a bare raise statement. For example:</p>
<pre><code>logger = logging.getLogger(__name__)
try:
do_something_in_app_that_breaks_easily()
except AppError as error:
logger.error(error)
raise # just this!
# raise AppError # Don't do this, you'll lose the stack trace!
</code></pre>
<h3>Don't modify your errors... but if you insist.</h3>
<p>You can preserve the stacktrace (and error value) with <code>sys.exc_info()</code>, but <strong>this is way more error prone</strong> and <strong>has compatibility problems between Python 2 and 3</strong>, prefer to use a bare <code>raise</code> to re-raise.</p>
<p>To explain - the <code>sys.exc_info()</code> returns the type, value, and traceback.</p>
<pre><code>type, value, traceback = sys.exc_info()
</code></pre>
<p>This is the syntax in Python 2 - note this is not compatible with Python 3:</p>
<pre><code>raise AppError, error, sys.exc_info()[2] # avoid this.
# Equivalently, as error *is* the second object:
raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
</code></pre>
<p>If you want to, you can modify what happens with your new raise - e.g. setting new <code>args</code> for the instance:</p>
<pre><code>def error():
raise ValueError('oops!')
def catch_error_modify_message():
try:
error()
except ValueError:
error_type, error_instance, traceback = sys.exc_info()
error_instance.args = (error_instance.args[0] + ' <modification>',)
raise error_type, error_instance, traceback
</code></pre>
<p>And we have preserved the whole traceback while modifying the args. Note that this is <strong>not a best practice</strong> and it is <strong>invalid syntax</strong> in Python 3 (making keeping compatibility much harder to work around).</p>
<pre><code>>>> catch_error_modify_message()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in catch_error_modify_message
File "<stdin>", line 2, in error
ValueError: oops! <modification>
</code></pre>
<p>In <a href="https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement" rel="noreferrer">Python 3</a>:</p>
<pre><code>raise error.with_traceback(sys.exc_info()[2])
</code></pre>
<p>Again: avoid manually manipulating tracebacks. It's <a href="https://docs.python.org/2/reference/simple_stmts.html#the-raise-statement" rel="noreferrer">less efficient</a> and more error prone. And if you're using threading and <code>sys.exc_info</code> you may even get the wrong traceback (especially if you're using exception handling for control flow - which I'd personally tend to avoid.)</p>
<h3>Python 3, Exception chaining</h3>
<p>In Python 3, you can chain Exceptions, which preserve tracebacks:</p>
<pre><code>raise RuntimeError('specific message') from error
</code></pre>
<p>Be aware:</p>
<ul>
<li>this <em>does</em> allow changing the error type raised, and</li>
<li>this is <em>not</em> compatible with Python 2.</li>
</ul>
<h3>Deprecated Methods:</h3>
<p>These can easily hide and even get into production code. You want to raise an exception, and doing them will raise an exception, <strong>but not the one intended!</strong></p>
<p><a href="http://www.python.org/dev/peps/pep-3109/" rel="noreferrer">Valid in Python 2, but not in Python 3</a> is the following:</p>
<pre><code>raise ValueError, 'message' # Don't do this, it's deprecated!
</code></pre>
<p>Only <a href="https://docs.python.org/2/whatsnew/2.5.html#pep-352-exceptions-as-new-style-classes" rel="noreferrer">valid in much older versions of Python</a> (2.4 and lower), you may still see people raising strings:</p>
<pre><code>raise 'message' # really really wrong. don't do this.
</code></pre>
<p>In all modern versions, this will actually raise a <code>TypeError</code>, because you're not raising a <code>BaseException</code> type. If you're not checking for the right exception and don't have a reviewer that's aware of the issue, it could get into production.</p>
<h2>Example Usage</h2>
<p>I raise Exceptions to warn consumers of my API if they're using it incorrectly:</p>
<pre><code>def api_func(foo):
'''foo should be either 'baz' or 'bar'. returns something very useful.'''
if foo not in _ALLOWED_ARGS:
raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))
</code></pre>
<h2>Create your own error types when apropos</h2>
<blockquote>
<p><strong>"I want to make an error on purpose, so that it would go into the except"</strong></p>
</blockquote>
<p>You can create your own error types, if you want to indicate something specific is wrong with your application, just subclass the appropriate point in the exception hierarchy:</p>
<pre><code>class MyAppLookupError(LookupError):
'''raise this when there's a lookup error for my app'''
</code></pre>
<p>and usage:</p>
<pre><code>if important_key not in resource_dict and not ok_to_be_missing:
raise MyAppLookupError('resource is missing, and that is not ok.')
</code></pre> | {
"question_id": 2052390,
"question_date": "2010-01-12T21:07:40.613Z",
"question_score": 2964,
"tags": "python|exception",
"answer_id": 24065533,
"answer_date": "2014-06-05T16:30:58.477Z",
"answer_score": 3882
} |
Please answer the following Stack Overflow question:
Title: How to store objects in HTML5 localStorage/sessionStorage
<p>I'd like to store a JavaScript object in HTML5 <code>localStorage</code>, but my object is apparently being converted to a string.</p>
<p>I can store and retrieve primitive JavaScript types and arrays using <code>localStorage</code>, but objects don't seem to work. Should they?</p>
<p>Here's my code:</p>
<pre><code>var testObject = { 'one': 1, 'two': 2, 'three': 3 };
console.log('typeof testObject: ' + typeof testObject);
console.log('testObject properties:');
for (var prop in testObject) {
console.log(' ' + prop + ': ' + testObject[prop]);
}
// Put the object into storage
localStorage.setItem('testObject', testObject);
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('typeof retrievedObject: ' + typeof retrievedObject);
console.log('Value of retrievedObject: ' + retrievedObject);
</code></pre>
<p>The console output is</p>
<pre class="lang-none prettyprint-override"><code>typeof testObject: object
testObject properties:
one: 1
two: 2
three: 3
typeof retrievedObject: string
Value of retrievedObject: [object Object]
</code></pre>
<p>It looks to me like the <code>setItem</code> method is converting the input to a string before storing it.</p>
<p>I see this behavior in Safari, Chrome, and Firefox, so I assume it's my misunderstanding of the <a href="http://www.w3.org/TR/webstorage/" rel="noreferrer">HTML5 Web Storage</a> specification, not a browser-specific bug or limitation.</p>
<p>I've tried to make sense of the <em>structured clone</em> algorithm described in <em><a href="https://html.spec.whatwg.org/multipage/infrastructure.html#infrastructure" rel="noreferrer">2 Common infrastructure</a></em>. I don't fully understand what it's saying, but maybe my problem has to do with my object's properties not being enumerable (???).</p>
<p>Is there an easy workaround?</p>
<hr />
<p>Update: The W3C eventually changed their minds about the structured-clone specification, and decided to change the spec to match the implementations. See <em><a href="https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111" rel="noreferrer">12111 – spec for Storage object getItem(key) method does not match implementation behavior</a></em>. So this question is no longer 100% valid, but the answers still may be of interest.</p> | <p>Looking at the <a href="https://developer.apple.com/library/archive/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/Name-ValueStorage/Name-ValueStorage.html" rel="noreferrer">Apple</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API" rel="noreferrer">Mozilla</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem" rel="noreferrer">Mozilla again</a> documentation, the functionality seems to be limited to handle only string key/value pairs.</p>
<p>A workaround can be to <a href="https://www.w3schools.com/js/js_json_stringify.asp" rel="noreferrer"><em>stringify</em></a> your object before storing it, and later parse it when you retrieve it:</p>
<pre><code>var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
</code></pre> | {
"question_id": 2010892,
"question_date": "2010-01-06T04:05:51.397Z",
"question_score": 2958,
"tags": "javascript|html|local-storage",
"answer_id": 2010948,
"answer_date": "2010-01-06T04:25:58.127Z",
"answer_score": 3702
} |
Please answer the following Stack Overflow question:
Title: When should static_cast, dynamic_cast, const_cast, and reinterpret_cast be used?
<p>What are the proper uses of:</p>
<ul>
<li><a href="https://en.cppreference.com/w/cpp/language/static_cast" rel="noreferrer"><code>static_cast</code></a></li>
<li><a href="https://en.cppreference.com/w/cpp/language/dynamic_cast" rel="noreferrer"><code>dynamic_cast</code></a></li>
<li><a href="https://en.cppreference.com/w/cpp/language/const_cast" rel="noreferrer"><code>const_cast</code></a></li>
<li><a href="https://en.cppreference.com/w/cpp/language/reinterpret_cast" rel="noreferrer"><code>reinterpret_cast</code></a></li>
<li><a href="https://en.cppreference.com/w/cpp/language/explicit_cast" rel="noreferrer"><code>(type)value</code></a> (C-style cast)</li>
<li><a href="https://en.cppreference.com/w/cpp/language/explicit_cast" rel="noreferrer"><code>type(value)</code></a> (function-style cast)</li>
</ul>
<p>How does one decide which to use in which specific cases?</p> | <p><strong><code>static_cast</code></strong> is the first cast you should attempt to use. It does things like implicit conversions between types (such as <code>int</code> to <code>float</code>, or pointer to <code>void*</code>), and it can also call explicit conversion functions (or implicit ones). In many cases, explicitly stating <code>static_cast</code> isn't necessary, but it's important to note that the <code>T(something)</code> syntax is equivalent to <code>(T)something</code> and should be avoided (more on that later). A <code>T(something, something_else)</code> is safe, however, and guaranteed to call the constructor.</p>
<p><code>static_cast</code> can also cast through inheritance hierarchies. It is unnecessary when casting upwards (towards a base class), but when casting downwards it can be used as long as it doesn't cast through <code>virtual</code> inheritance. It does not do checking, however, and it is undefined behavior to <code>static_cast</code> down a hierarchy to a type that isn't actually the type of the object.</p>
<hr>
<p><strong><code>const_cast</code></strong> can be used to remove or add <code>const</code> to a variable; no other C++ cast is capable of removing it (not even <code>reinterpret_cast</code>). It is important to note that modifying a formerly <code>const</code> value is only undefined if the original variable is <code>const</code>; if you use it to take the <code>const</code> off a reference to something that wasn't declared with <code>const</code>, it is safe. This can be useful when overloading member functions based on <code>const</code>, for instance. It can also be used to add <code>const</code> to an object, such as to call a member function overload.</p>
<p><code>const_cast</code> also works similarly on <code>volatile</code>, though that's less common.</p>
<hr>
<p><strong><code>dynamic_cast</code></strong> is exclusively used for handling polymorphism. You can cast a pointer or reference to any polymorphic type to any other class type (a polymorphic type has at least one virtual function, declared or inherited). You can use it for more than just casting downwards – you can cast sideways or even up another chain. The <code>dynamic_cast</code> will seek out the desired object and return it if possible. If it can't, it will return <code>nullptr</code> in the case of a pointer, or throw <code>std::bad_cast</code> in the case of a reference.</p>
<p><code>dynamic_cast</code> has some limitations, though. It doesn't work if there are multiple objects of the same type in the inheritance hierarchy (the so-called 'dreaded diamond') and you aren't using <code>virtual</code> inheritance. It also can only go through public inheritance - it will always fail to travel through <code>protected</code> or <code>private</code> inheritance. This is rarely an issue, however, as such forms of inheritance are rare.</p>
<hr>
<p><strong><code>reinterpret_cast</code></strong> is the most dangerous cast, and should be used very sparingly. It turns one type directly into another — such as casting the value from one pointer to another, or storing a pointer in an <code>int</code>, or all sorts of other nasty things. Largely, the only guarantee you get with <code>reinterpret_cast</code> is that normally if you cast the result back to the original type, you will get the exact same value (but <strong><em>not</em></strong> if the intermediate type is smaller than the original type). There are a number of conversions that <strong><code>reinterpret_cast</code></strong> cannot do, too. It's used primarily for particularly weird conversions and bit manipulations, like turning a raw data stream into actual data, or storing data in the low bits of a pointer to aligned data.</p>
<hr>
<p><strong>C-style cast</strong> and <strong>function-style cast</strong> are casts using <code>(type)object</code> or <code>type(object)</code>, respectively, and are functionally equivalent. They are defined as the first of the following which succeeds:</p>
<ul>
<li><code>const_cast</code></li>
<li><code>static_cast</code> (though ignoring access restrictions)</li>
<li><code>static_cast</code> (see above), then <code>const_cast</code></li>
<li><code>reinterpret_cast</code></li>
<li><code>reinterpret_cast</code>, then <code>const_cast</code></li>
</ul>
<p>It can therefore be used as a replacement for other casts in some instances, but can be extremely dangerous because of the ability to devolve into a <code>reinterpret_cast</code>, and the latter should be preferred when explicit casting is needed, unless you are sure <code>static_cast</code> will succeed or <code>reinterpret_cast</code> will fail. Even then, consider the longer, more explicit option.</p>
<p>C-style casts also ignore access control when performing a <code>static_cast</code>, which means that they have the ability to perform an operation that no other cast can. This is mostly a kludge, though, and in my mind is just another reason to avoid C-style casts.</p> | {
"question_id": 332030,
"question_date": "2008-12-01T20:11:07.237Z",
"question_score": 2948,
"tags": "c++|pointers|casting|c++-faq",
"answer_id": 332086,
"answer_date": "2008-12-01T20:26:41.810Z",
"answer_score": 2924
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.