input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Why is processing a sorted array faster than processing an unsorted array? <p>Here is a piece of C++ code that shows some very peculiar behavior. For some strange reason, sorting the data (<em>before</em> the timed region) miraculously makes the loop almost six times faster.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;algorithm&gt; #include &lt;ctime&gt; #include &lt;iostream&gt; int main() { // Generate data const unsigned arraySize = 32768; int data[arraySize]; for (unsigned c = 0; c &lt; arraySize; ++c) data[c] = std::rand() % 256; // !!! With this, the next loop runs faster. std::sort(data, data + arraySize); // Test clock_t start = clock(); long long sum = 0; for (unsigned i = 0; i &lt; 100000; ++i) { for (unsigned c = 0; c &lt; arraySize; ++c) { // Primary loop if (data[c] &gt;= 128) sum += data[c]; } } double elapsedTime = static_cast&lt;double&gt;(clock()-start) / CLOCKS_PER_SEC; std::cout &lt;&lt; elapsedTime &lt;&lt; '\n'; std::cout &lt;&lt; &quot;sum = &quot; &lt;&lt; sum &lt;&lt; '\n'; } </code></pre> <ul> <li>Without <code>std::sort(data, data + arraySize);</code>, the code runs in 11.54 seconds.</li> <li>With the sorted data, the code runs in 1.93 seconds.</li> </ul> <p>(Sorting itself takes more time than this one pass over the array, so it's not actually worth doing if we needed to calculate this for an unknown array.)</p> <hr /> <p>Initially, I thought this might be just a language or compiler anomaly, so I tried Java:</p> <pre class="lang-java prettyprint-override"><code>import java.util.Arrays; import java.util.Random; public class Main { public static void main(String[] args) { // Generate data int arraySize = 32768; int data[] = new int[arraySize]; Random rnd = new Random(0); for (int c = 0; c &lt; arraySize; ++c) data[c] = rnd.nextInt() % 256; // !!! With this, the next loop runs faster Arrays.sort(data); // Test long start = System.nanoTime(); long sum = 0; for (int i = 0; i &lt; 100000; ++i) { for (int c = 0; c &lt; arraySize; ++c) { // Primary loop if (data[c] &gt;= 128) sum += data[c]; } } System.out.println((System.nanoTime() - start) / 1000000000.0); System.out.println(&quot;sum = &quot; + sum); } } </code></pre> <p>With a similar but less extreme result.</p> <hr /> <p>My first thought was that sorting brings the data into the <a href="https://en.wikipedia.org/wiki/CPU_cache" rel="noreferrer">cache</a>, but then I thought how silly that was because the array was just generated.</p> <ul> <li>What is going on?</li> <li>Why is processing a sorted array faster than processing an unsorted array?</li> </ul> <p>The code is summing up some independent terms, so the order should not matter.</p> <hr /> <p><strong>Related / followup Q&amp;As</strong> about the same effect with different / later compilers and options:</p> <ul> <li><a href="https://stackoverflow.com/q/66521344">Why is processing an unsorted array the same speed as processing a sorted array with modern x86-64 clang?</a></li> <li><a href="https://stackoverflow.com/q/28875325">gcc optimization flag -O3 makes code slower than -O2</a></li> </ul>
<p><strong>You are a victim of <a href="https://en.wikipedia.org/wiki/Branch_predictor" rel="noreferrer">branch prediction</a> fail.</strong></p> <hr /> <h2>What is Branch Prediction?</h2> <p>Consider a railroad junction:</p> <p><a href="https://commons.wikimedia.org/wiki/File:Entroncamento_do_Transpraia.JPG" rel="noreferrer"><img src="https://i.stack.imgur.com/muxnt.jpg" alt="Image showing a railroad junction" /></a> <sub><a href="https://commons.wikimedia.org/wiki/File:Entroncamento_do_Transpraia.JPG" rel="noreferrer">Image</a> by Mecanismo, via Wikimedia Commons. Used under the <a href="https://creativecommons.org/licenses/by-sa/3.0/deed.en" rel="noreferrer">CC-By-SA 3.0</a> license.</sub></p> <p>Now for the sake of argument, suppose this is back in the 1800s - before long-distance or radio communication.</p> <p>You are a blind operator of a junction and you hear a train coming. You have no idea which way it is supposed to go. You stop the train to ask the driver which direction they want. And then you set the switch appropriately.</p> <p><em>Trains are heavy and have a lot of inertia, so they take forever to start up and slow down.</em></p> <p>Is there a better way? You guess which direction the train will go!</p> <ul> <li>If you guessed right, it continues on.</li> <li>If you guessed wrong, the captain will stop, back up, and yell at you to flip the switch. Then it can restart down the other path.</li> </ul> <p><strong>If you guess right every time</strong>, the train will never have to stop.<br /> <strong>If you guess wrong too often</strong>, the train will spend a lot of time stopping, backing up, and restarting.</p> <hr /> <p><strong>Consider an if-statement:</strong> At the processor level, it is a branch instruction:</p> <p><img src="https://i.stack.imgur.com/pyfwC.png" alt="Screenshot of compiled code containing an if statement" /></p> <p>You are a processor and you see a branch. You have no idea which way it will go. What do you do? You halt execution and wait until the previous instructions are complete. Then you continue down the correct path.</p> <p><em>Modern processors are complicated and have long pipelines. This means they take forever to &quot;warm up&quot; and &quot;slow down&quot;.</em></p> <p>Is there a better way? You guess which direction the branch will go!</p> <ul> <li>If you guessed right, you continue executing.</li> <li>If you guessed wrong, you need to flush the pipeline and roll back to the branch. Then you can restart down the other path.</li> </ul> <p><strong>If you guess right every time</strong>, the execution will never have to stop.<br /> <strong>If you guess wrong too often</strong>, you spend a lot of time stalling, rolling back, and restarting.</p> <hr /> <p>This is branch prediction. I admit it's not the best analogy since the train could just signal the direction with a flag. But in computers, the processor doesn't know which direction a branch will go until the last moment.</p> <p>How would you strategically guess to minimize the number of times that the train must back up and go down the other path? You look at the past history! If the train goes left 99% of the time, then you guess left. If it alternates, then you alternate your guesses. If it goes one way every three times, you guess the same...</p> <p><em><strong>In other words, you try to identify a pattern and follow it.</strong></em> This is more or less how branch predictors work.</p> <p>Most applications have well-behaved branches. Therefore, modern branch predictors will typically achieve &gt;90% hit rates. But when faced with unpredictable branches with no recognizable patterns, branch predictors are virtually useless.</p> <p>Further reading: <a href="https://en.wikipedia.org/wiki/Branch_predictor" rel="noreferrer">&quot;Branch predictor&quot; article on Wikipedia</a>.</p> <hr /> <h2>As hinted from above, the culprit is this if-statement:</h2> <pre><code>if (data[c] &gt;= 128) sum += data[c]; </code></pre> <p>Notice that the data is evenly distributed between 0 and 255. When the data is sorted, roughly the first half of the iterations will not enter the if-statement. After that, they will all enter the if-statement.</p> <p>This is very friendly to the branch predictor since the branch consecutively goes the same direction many times. Even a simple saturating counter will correctly predict the branch except for the few iterations after it switches direction.</p> <p><strong>Quick visualization:</strong></p> <pre class="lang-none prettyprint-override"><code>T = branch taken N = branch not taken data[] = 0, 1, 2, 3, 4, ... 126, 127, 128, 129, 130, ... 250, 251, 252, ... branch = N N N N N ... N N T T T ... T T T ... = NNNNNNNNNNNN ... NNNNNNNTTTTTTTTT ... TTTTTTTTTT (easy to predict) </code></pre> <p>However, when the data is completely random, the branch predictor is rendered useless, because it can't predict random data. Thus there will probably be around 50% misprediction (no better than random guessing).</p> <pre class="lang-none prettyprint-override"><code>data[] = 226, 185, 125, 158, 198, 144, 217, 79, 202, 118, 14, 150, 177, 182, ... branch = T, T, N, T, T, T, T, N, T, N, N, T, T, T ... = TTNTTTTNTNNTTT ... (completely random - impossible to predict) </code></pre> <hr /> <p><strong>What can be done?</strong></p> <p>If the compiler isn't able to optimize the branch into a conditional move, you can try some hacks if you are willing to sacrifice readability for performance.</p> <p>Replace:</p> <pre><code>if (data[c] &gt;= 128) sum += data[c]; </code></pre> <p>with:</p> <pre><code>int t = (data[c] - 128) &gt;&gt; 31; sum += ~t &amp; data[c]; </code></pre> <p>This eliminates the branch and replaces it with some bitwise operations.</p> <p><sub>(Note that this hack is not strictly equivalent to the original if-statement. But in this case, it's valid for all the input values of <code>data[]</code>.)</sub></p> <p><strong>Benchmarks: Core i7 920 @ 3.5 GHz</strong></p> <p>C++ - Visual Studio 2010 - x64 Release</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Scenario</th> <th>Time (seconds)</th> </tr> </thead> <tbody> <tr> <td>Branching - Random data</td> <td>11.777</td> </tr> <tr> <td>Branching - Sorted data</td> <td>2.352</td> </tr> <tr> <td>Branchless - Random data</td> <td>2.564</td> </tr> <tr> <td>Branchless - Sorted data</td> <td>2.587</td> </tr> </tbody> </table> </div> <p>Java - NetBeans 7.1.1 JDK 7 - x64</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Scenario</th> <th>Time (seconds)</th> </tr> </thead> <tbody> <tr> <td>Branching - Random data</td> <td>10.93293813</td> </tr> <tr> <td>Branching - Sorted data</td> <td>5.643797077</td> </tr> <tr> <td>Branchless - Random data</td> <td>3.113581453</td> </tr> <tr> <td>Branchless - Sorted data</td> <td>3.186068823</td> </tr> </tbody> </table> </div> <p>Observations:</p> <ul> <li><strong>With the Branch:</strong> There is a huge difference between the sorted and unsorted data.</li> <li><strong>With the Hack:</strong> There is no difference between sorted and unsorted data.</li> <li>In the C++ case, the hack is actually a tad slower than with the branch when the data is sorted.</li> </ul> <p>A general rule of thumb is to avoid data-dependent branching in critical loops (such as in this example).</p> <hr /> <p><strong>Update:</strong></p> <ul> <li><p>GCC 4.6.1 with <code>-O3</code> or <code>-ftree-vectorize</code> on x64 is able to generate a conditional move, so there is no difference between the sorted and unsorted data - both are fast.</p> <p>(Or somewhat fast: for the already-sorted case, <code>cmov</code> can be slower especially if GCC puts it on the critical path instead of just <code>add</code>, especially on Intel before Broadwell where <code>cmov</code> has 2 cycle latency: <a href="https://stackoverflow.com/questions/28875325/gcc-optimization-flag-o3-makes-code-slower-than-o2">gcc optimization flag -O3 makes code slower than -O2</a>)</p> </li> <li><p>VC++ 2010 is unable to generate conditional moves for this branch even under <code>/Ox</code>.</p> </li> <li><p><a href="https://en.wikipedia.org/wiki/Intel_C++_Compiler" rel="noreferrer">Intel C++ Compiler</a> (ICC) 11 does something miraculous. It <a href="https://en.wikipedia.org/wiki/Loop_interchange" rel="noreferrer">interchanges the two loops</a>, thereby hoisting the unpredictable branch to the outer loop. Not only is it immune to the mispredictions, it's also twice as fast as whatever VC++ and GCC can generate! In other words, ICC took advantage of the test-loop to defeat the benchmark...</p> </li> <li><p>If you give the Intel compiler the branchless code, it just outright vectorizes it... and is just as fast as with the branch (with the loop interchange).</p> </li> </ul> <p>This goes to show that even mature modern compilers can vary wildly in their ability to optimize code...</p>
{ "question_id": 11227809, "question_date": "2012-06-27T13:51:36.160Z", "question_score": 26621, "tags": "java|c++|performance|cpu-architecture|branch-prediction", "answer_id": 11227902, "answer_date": "2012-06-27T13:56:42.820Z", "answer_score": 34269 }
Please answer the following Stack Overflow question: Title: How do I undo the most recent local commits in Git? <p>I accidentally committed the wrong files to <a href="https://en.wikipedia.org/wiki/Git" rel="noreferrer">Git</a>, but didn't push the commit to the server yet. How do I undo those commits from the <em>local</em> repository?</p>
<h1>Undo a commit &amp; redo</h1> <pre class="lang-sh prettyprint-override"><code>$ git commit -m &quot;Something terribly misguided&quot; # (0: Your Accident) $ git reset HEAD~ # (1) [ edit files as necessary ] # (2) $ git add . # (3) $ git commit -c ORIG_HEAD # (4) </code></pre> <ol> <li><a href="https://git-scm.com/docs/git-reset" rel="noreferrer"><code>git reset</code></a> is the command responsible for the <strong>undo</strong>. It will undo your last commit while <strong>leaving your working tree (the state of your files on disk) untouched.</strong> You'll need to add them again before you can commit them again).</li> <li>Make corrections to <a href="https://git-scm.com/book/en/v2/Git-Tools-Reset-Demystified#_the_working_directory" rel="noreferrer">working tree</a> files.</li> <li><a href="https://git-scm.com/docs/git-add" rel="noreferrer"><code>git add</code></a> anything that you want to include in your new commit.</li> <li>Commit the changes, reusing the old commit message. <code>reset</code> copied the old head to <code>.git/ORIG_HEAD</code>; <a href="https://git-scm.com/docs/git-commit#Documentation/git-commit.txt--cltcommitgt" rel="noreferrer"><code>commit</code> with <code>-c ORIG_HEAD</code></a> will open an editor, which initially contains the log message from the old commit and allows you to edit it. If you do not need to edit the message, you could use the <a href="https://git-scm.com/docs/git-commit#Documentation/git-commit.txt--Cltcommitgt" rel="noreferrer"><code>-C</code></a> option.</li> </ol> <p><strong>Alternatively, to edit the previous commit (or just its commit message)</strong>, <a href="https://stackoverflow.com/q/179123/1146608"><code>commit --amend</code></a> will add changes within the current index to the previous commit.</p> <p><strong>To remove (not revert) a commit that has been pushed to the server</strong>, rewriting history with <code>git push origin main --force[-with-lease]</code> is necessary. <a href="https://stackoverflow.com/q/52823692/4096791">It's <em>almost always</em> a bad idea to use <code>--force</code>; prefer <code>--force-with-lease</code></a> instead, and as noted in <a href="https://git-scm.com/docs" rel="noreferrer">the git manual</a>:</p> <blockquote> <p>You should understand the implications of rewriting history if you [rewrite history] has already been published.</p> </blockquote> <hr /> <h2>Further Reading</h2> <p><a href="https://stackoverflow.com/questions/34519665/how-to-move-head-back-to-a-previous-location-detached-head/34519716#34519716">You can use <code>git reflog</code> to determine the SHA-1</a> for the commit to which you wish to revert. Once you have this value, use the sequence of commands as explained above.</p> <hr /> <p><code>HEAD~</code> is the same as <code>HEAD~1</code>. The article <a href="https://stackoverflow.com/a/46350644/5175709">What is the HEAD in git?</a> is helpful if you want to uncommit multiple commits.</p>
{ "question_id": 927358, "question_date": "2009-05-29T18:09:14.627Z", "question_score": 24809, "tags": "git|version-control|git-commit|undo", "answer_id": 927386, "answer_date": "2009-05-29T18:13:42.373Z", "answer_score": 27023 }
Please answer the following Stack Overflow question: Title: How do I delete a Git branch locally and remotely? <h4>Failed Attempts to Delete a Remote Branch:</h4> <pre class="lang-bash prettyprint-override"><code>$ git branch -d remotes/origin/bugfix error: branch 'remotes/origin/bugfix' not found. $ git branch -d origin/bugfix error: branch 'origin/bugfix' not found. $ git branch -rd origin/bugfix Deleted remote branch origin/bugfix (was 2a14ef7). $ git push Everything up-to-date $ git pull From github.com:gituser/gitproject * [new branch] bugfix -&gt; origin/bugfix Already up-to-date. </code></pre> <p>How do I properly delete the <code>remotes/origin/bugfix</code> branch both locally and remotely?</p>
<h1>Executive Summary</h1> <pre><code>git push -d &lt;remote_name&gt; &lt;branchname&gt; git branch -d &lt;branchname&gt; </code></pre> <p><strong>Note:</strong> In most cases, <code>&lt;remote_name&gt;</code> will be <code>origin</code>.</p> <h1>Delete Local Branch</h1> <p>To delete the <em><strong>local</strong></em> branch use one of the following:</p> <pre><code>git branch -d &lt;branch_name&gt; git branch -D &lt;branch_name&gt; </code></pre> <ul> <li>The <code>-d</code> option is an alias for <code>--delete</code>, which only deletes the branch if it has already been fully merged in its upstream branch.</li> <li>The <code>-D</code> option is an alias for <code>--delete --force</code>, which deletes the branch &quot;irrespective of its merged status.&quot; [Source: <code>man git-branch</code>]</li> <li>As of <a href="https://github.com/git/git/blob/master/Documentation/RelNotes/2.3.0.txt" rel="noreferrer">Git v2.3</a>, <code>git branch -d</code> (delete) learned to honor the <code>-f</code> (force) flag.</li> <li>You will receive an error if you try to delete the currently selected branch.</li> </ul> <h1>Delete Remote Branch</h1> <p>As of <a href="https://github.com/gitster/git/blob/master/Documentation/RelNotes/1.7.0.txt" rel="noreferrer">Git v1.7.0</a>, you can delete a <em><strong>remote</strong></em> branch using</p> <pre><code>$ git push &lt;remote_name&gt; --delete &lt;branch_name&gt; </code></pre> <p>which might be easier to remember than</p> <pre><code>$ git push &lt;remote_name&gt; :&lt;branch_name&gt; </code></pre> <p>which was added in <a href="https://github.com/gitster/git/blob/master/Documentation/RelNotes/1.5.0.txt" rel="noreferrer">Git v1.5.0</a> &quot;to delete a remote branch or a tag.&quot;</p> <p>Starting with <a href="https://github.com/git/git/blob/master/Documentation/RelNotes/2.8.0.txt" rel="noreferrer">Git v2.8.0</a>, you can also use <code>git push</code> with the <code>-d</code> option as an alias for <code>--delete</code>. Therefore, the version of Git you have installed will dictate whether you need to use the easier or harder syntax.</p> <h2>Delete Remote Branch [Original Answer from 5-Jan-2010]</h2> <p>From Chapter 3 of <a href="http://git-scm.com/book/en/Git-Branching-Remote-Branches" rel="noreferrer"><em>Pro Git</em></a> by Scott Chacon:</p> <blockquote> <h3>Deleting Remote Branches</h3> <p>Suppose you’re done with a remote branch — say, you and your collaborators are finished with a feature and have merged it into your remote’s main branch (or whatever branch your stable code-line is in). You can delete a remote branch using the rather obtuse syntax <code>git push [remotename] :[branch]</code>. If you want to delete your server-fix branch from the server, you run the following:</p> </blockquote> <pre><code>$ git push origin :serverfix To git@github.com:schacon/simplegit.git - [deleted] serverfix </code></pre> <blockquote> <p>Boom. No more branches on your server. You may want to dog-ear this page, because you’ll need that command, and you’ll likely forget the syntax. A way to remember this command is by recalling the <code>git push [remotename] [localbranch]:[remotebranch]</code> syntax that we went over a bit earlier. If you leave off the <code>[localbranch]</code> portion, then you’re basically saying, “Take nothing on my side and make it be <code>[remotebranch]</code>.”</p> </blockquote> <p>I issued <code>git push origin: bugfix</code> and it worked beautifully. Scott Chacon was right—I will want to <a href="http://en.wiktionary.org/wiki/dogear#Verb" rel="noreferrer">dog ear</a> that page (or virtually dog ear by answering this on Stack Overflow).</p> <p>Then you should execute this on other machines</p> <pre><code># Fetch changes from all remotes and locally delete # remote deleted branches/tags etc # --prune will do the job :-; git fetch --all --prune </code></pre> <p>to propagate changes.</p>
{ "question_id": 2003505, "question_date": "2010-01-05T01:12:15.867Z", "question_score": 19556, "tags": "git|version-control|git-branch|git-push|git-remote", "answer_id": 2003515, "answer_date": "2010-01-05T01:13:55.193Z", "answer_score": 24567 }
Please answer the following Stack Overflow question: Title: What is the difference between 'git pull' and 'git fetch'? <p>What are the differences between <a href="https://git-scm.com/docs/git-pull" rel="noreferrer"><code>git pull</code></a> and <a href="https://git-scm.com/docs/git-fetch" rel="noreferrer"><code>git fetch</code></a>?</p>
<p>In the simplest terms, <a href="http://git-scm.com/docs/git-pull" rel="noreferrer"><code>git pull</code></a> does a <a href="http://git-scm.com/docs/git-fetch" rel="noreferrer"><code>git fetch</code></a> followed by a <a href="http://git-scm.com/docs/git-merge" rel="noreferrer"><code>git merge</code></a>.</p> <hr /> <p><em><code>git fetch</code></em> updates your remote-tracking branches under <code>refs/remotes/&lt;remote&gt;/</code>. This operation is safe to run at any time since it never changes any of your local branches under <code>refs/heads</code>.</p> <p><em><code>git pull</code></em> brings a local branch up-to-date with its remote version, while also updating your other remote-tracking branches.</p> <p>From the Git documentation for <a href="http://git-scm.com/docs/git-pull" rel="noreferrer"><code>git pull</code></a>:</p> <blockquote> <p>In its default mode, <code>git pull</code> is shorthand for <code>git fetch</code> followed by <code>git merge FETCH_HEAD</code>.</p> </blockquote>
{ "question_id": 292357, "question_date": "2008-11-15T09:51:09.660Z", "question_score": 13368, "tags": "git|version-control|git-pull|git-fetch", "answer_id": 292359, "answer_date": "2008-11-15T09:52:40.267Z", "answer_score": 11135 }
Please answer the following Stack Overflow question: Title: What does the "yield" keyword do? <p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: yield self._leftchild if self._rightchild and distance + max_dist &gt;= self._median: yield self._rightchild </code></pre> <p>And this is the caller:</p> <pre><code>result, candidates = [], [self] while candidates: node = candidates.pop() distance = node._get_dist(obj) if distance &lt;= max_dist and distance &gt;= min_dist: result.extend(node._values) candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) return result </code></pre> <p>What happens when the method <code>_get_child_candidates</code> is called? Is a list returned? A single element? Is it called again? When will subsequent calls stop?</p> <hr /> <sub> 1. This piece of code was written by Jochen Schulz (jrschulz), who made a great Python library for metric spaces. This is the link to the complete source: <a href="https://well-adjusted.de/~jrspieker/mspace/" rel="noreferrer">Module mspace</a>.</sub>
<p>To understand what <code>yield</code> does, you must understand what <em>generators</em> are. And before you can understand generators, you must understand <em>iterables</em>.</p> <h2>Iterables</h2> <p>When you create a list, you can read its items one by one. Reading its items one by one is called iteration:</p> <pre><code>&gt;&gt;&gt; mylist = [1, 2, 3] &gt;&gt;&gt; for i in mylist: ... print(i) 1 2 3 </code></pre> <p><code>mylist</code> is an <em>iterable</em>. When you use a list comprehension, you create a list, and so an iterable:</p> <pre><code>&gt;&gt;&gt; mylist = [x*x for x in range(3)] &gt;&gt;&gt; for i in mylist: ... print(i) 0 1 4 </code></pre> <p>Everything you can use &quot;<code>for... in...</code>&quot; on is an iterable; <code>lists</code>, <code>strings</code>, files...</p> <p>These iterables are handy because you can read them as much as you wish, but you store all the values in memory and this is not always what you want when you have a lot of values.</p> <h2>Generators</h2> <p>Generators are iterators, a kind of iterable <strong>you can only iterate over once</strong>. Generators do not store all the values in memory, <strong>they generate the values on the fly</strong>:</p> <pre><code>&gt;&gt;&gt; mygenerator = (x*x for x in range(3)) &gt;&gt;&gt; for i in mygenerator: ... print(i) 0 1 4 </code></pre> <p>It is just the same except you used <code>()</code> instead of <code>[]</code>. BUT, you <strong>cannot</strong> perform <code>for i in mygenerator</code> a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end calculating 4, one by one.</p> <h2>Yield</h2> <p><code>yield</code> is a keyword that is used like <code>return</code>, except the function will return a generator.</p> <pre><code>&gt;&gt;&gt; def create_generator(): ... mylist = range(3) ... for i in mylist: ... yield i*i ... &gt;&gt;&gt; mygenerator = create_generator() # create a generator &gt;&gt;&gt; print(mygenerator) # mygenerator is an object! &lt;generator object create_generator at 0xb7555c34&gt; &gt;&gt;&gt; for i in mygenerator: ... print(i) 0 1 4 </code></pre> <p>Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.</p> <p>To master <code>yield</code>, you must understand that <strong>when you call the function, the code you have written in the function body does not run.</strong> The function only returns the generator object, this is a bit tricky.</p> <p>Then, your code will continue from where it left off each time <code>for</code> uses the generator.</p> <p>Now the hard part:</p> <p>The first time the <code>for</code> calls the generator object created from your function, it will run the code in your function from the beginning until it hits <code>yield</code>, then it'll return the first value of the loop. Then, each subsequent call will run another iteration of the loop you have written in the function and return the next value. This will continue until the generator is considered empty, which happens when the function runs without hitting <code>yield</code>. That can be because the loop has come to an end, or because you no longer satisfy an <code>&quot;if/else&quot;</code>.</p> <hr /> <h2>Your code explained</h2> <p><em>Generator:</em></p> <pre><code># Here you create the method of the node object that will return the generator def _get_child_candidates(self, distance, min_dist, max_dist): # Here is the code that will be called each time you use the generator object: # If there is still a child of the node object on its left # AND if the distance is ok, return the next child if self._leftchild and distance - max_dist &lt; self._median: yield self._leftchild # If there is still a child of the node object on its right # AND if the distance is ok, return the next child if self._rightchild and distance + max_dist &gt;= self._median: yield self._rightchild # If the function arrives here, the generator will be considered empty # there is no more than two values: the left and the right children </code></pre> <p><em>Caller:</em></p> <pre><code># Create an empty list and a list with the current object reference result, candidates = list(), [self] # Loop on candidates (they contain only one element at the beginning) while candidates: # Get the last candidate and remove it from the list node = candidates.pop() # Get the distance between obj and the candidate distance = node._get_dist(obj) # If distance is ok, then you can fill the result if distance &lt;= max_dist and distance &gt;= min_dist: result.extend(node._values) # Add the children of the candidate in the candidate's list # so the loop will keep running until it will have looked # at all the children of the children of the children, etc. of the candidate candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) return result </code></pre> <p>This code contains several smart parts:</p> <ul> <li><p>The loop iterates on a list, but the list expands while the loop is being iterated. It's a concise way to go through all these nested data even if it's a bit dangerous since you can end up with an infinite loop. In this case, <code>candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))</code> exhaust all the values of the generator, but <code>while</code> keeps creating new generator objects which will produce different values from the previous ones since it's not applied on the same node.</p> </li> <li><p>The <code>extend()</code> method is a list object method that expects an iterable and adds its values to the list.</p> </li> </ul> <p>Usually we pass a list to it:</p> <pre><code>&gt;&gt;&gt; a = [1, 2] &gt;&gt;&gt; b = [3, 4] &gt;&gt;&gt; a.extend(b) &gt;&gt;&gt; print(a) [1, 2, 3, 4] </code></pre> <p>But in your code, it gets a generator, which is good because:</p> <ol> <li>You don't need to read the values twice.</li> <li>You may have a lot of children and you don't want them all stored in memory.</li> </ol> <p>And it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples, and generators! This is called duck typing and is one of the reasons why Python is so cool. But this is another story, for another question...</p> <p>You can stop here, or read a little bit to see an advanced use of a generator:</p> <h2>Controlling a generator exhaustion</h2> <pre><code>&gt;&gt;&gt; class Bank(): # Let's create a bank, building ATMs ... crisis = False ... def create_atm(self): ... while not self.crisis: ... yield &quot;$100&quot; &gt;&gt;&gt; hsbc = Bank() # When everything's ok the ATM gives you as much as you want &gt;&gt;&gt; corner_street_atm = hsbc.create_atm() &gt;&gt;&gt; print(corner_street_atm.next()) $100 &gt;&gt;&gt; print(corner_street_atm.next()) $100 &gt;&gt;&gt; print([corner_street_atm.next() for cash in range(5)]) ['$100', '$100', '$100', '$100', '$100'] &gt;&gt;&gt; hsbc.crisis = True # Crisis is coming, no more money! &gt;&gt;&gt; print(corner_street_atm.next()) &lt;type 'exceptions.StopIteration'&gt; &gt;&gt;&gt; wall_street_atm = hsbc.create_atm() # It's even true for new ATMs &gt;&gt;&gt; print(wall_street_atm.next()) &lt;type 'exceptions.StopIteration'&gt; &gt;&gt;&gt; hsbc.crisis = False # The trouble is, even post-crisis the ATM remains empty &gt;&gt;&gt; print(corner_street_atm.next()) &lt;type 'exceptions.StopIteration'&gt; &gt;&gt;&gt; brand_new_atm = hsbc.create_atm() # Build a new one to get back in business &gt;&gt;&gt; for cash in brand_new_atm: ... print cash $100 $100 $100 $100 $100 $100 $100 $100 $100 ... </code></pre> <p><strong>Note:</strong> For Python 3, use<code>print(corner_street_atm.__next__())</code> or <code>print(next(corner_street_atm))</code></p> <p>It can be useful for various things like controlling access to a resource.</p> <h2>Itertools, your best friend</h2> <p>The itertools module contains special functions to manipulate iterables. Ever wish to duplicate a generator? Chain two generators? Group values in a nested list with a one-liner? <code>Map / Zip</code> without creating another list?</p> <p>Then just <code>import itertools</code>.</p> <p>An example? Let's see the possible orders of arrival for a four-horse race:</p> <pre><code>&gt;&gt;&gt; horses = [1, 2, 3, 4] &gt;&gt;&gt; races = itertools.permutations(horses) &gt;&gt;&gt; print(races) &lt;itertools.permutations object at 0xb754f1dc&gt; &gt;&gt;&gt; print(list(itertools.permutations(horses))) [(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)] </code></pre> <h2>Understanding the inner mechanisms of iteration</h2> <p>Iteration is a process implying iterables (implementing the <code>__iter__()</code> method) and iterators (implementing the <code>__next__()</code> method). Iterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.</p> <p>There is more about it in this article about <a href="https://web.archive.org/web/20201109034340/http://effbot.org/zone/python-for-statement.htm" rel="noreferrer">how <code>for</code> loops work</a>.</p>
{ "question_id": 231767, "question_date": "2008-10-23T22:21:11.623Z", "question_score": 12259, "tags": "python|iterator|generator", "answer_id": 231855, "answer_date": "2008-10-23T22:48:44.797Z", "answer_score": 17250 }
Please answer the following Stack Overflow question: Title: Which JSON content type do I use? <p>There are many &quot;standards&quot; for the <a href="http://en.wikipedia.org/wiki/JSON" rel="noreferrer">JSON</a> content type:</p> <pre class="lang-none prettyprint-override"><code>application/json application/x-javascript text/javascript text/x-javascript text/x-json </code></pre> <p>Which one do I use, and where? I assume security and browser support issues are a factor.</p> <p>Related: <a href="https://stackoverflow.com/questions/404470/what-mime-type-if-json-is-being-returned-by-a-rest-api">What MIME type if JSON is being returned by a REST API?</a></p>
<p>For JSON text:</p> <pre><code>application/json </code></pre> <blockquote> <p>The MIME media type for JSON text is <code>application/json</code>. The default encoding is UTF-8. <sup>(Source: <a href="http://www.ietf.org/rfc/rfc4627.txt" rel="noreferrer">RFC 4627</a>)</sup></p> </blockquote> <p>For <a href="http://en.wikipedia.org/wiki/JSONP" rel="noreferrer">JSONP</a> (runnable JavaScript) with callback:</p> <pre><code>application/javascript </code></pre> <p>Here are some blog posts that were mentioned in the relevant comments:</p> <ul> <li><a href="http://jibbering.com/blog/?p=514" rel="noreferrer">Why you shouldn't use <code>text/html</code> for JSON</a></li> <li><a href="https://web.archive.org/web/20180102070201/www.entwicklungsgedanken.de/2008/06/06/problems-with-internet-explorer-and-applicationjson/" rel="noreferrer">Internet Explorer sometimes has issues with <code>application/json</code></a></li> <li><a href="https://github.com/h5bp/server-configs-nginx/blob/master/mime.types" rel="noreferrer">A rather complete list of Mimetypes and what to use them for</a></li> <li><a href="http://www.iana.org/assignments/media-types/application/" rel="noreferrer">The official mime type list at IANA</a> from @gnrfan's answer below</li> </ul>
{ "question_id": 477816, "question_date": "2009-01-25T15:25:19.067Z", "question_score": 11267, "tags": "json|mime-types|content-type", "answer_id": 477819, "answer_date": "2009-01-25T15:27:29.720Z", "answer_score": 11322 }
Please answer the following Stack Overflow question: Title: How can I remove a specific item from an array? <p>How do I remove a specific value from an array? Something like:</p> <pre class="lang-js prettyprint-override"><code>array.remove(value); // removes all elements with value </code></pre> <p>I have to use <em>core</em> JavaScript. Frameworks are not allowed.</p>
<p>Find the <code>index</code> of the array element you want to remove using <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf" rel="noreferrer"><code>indexOf</code></a>, and then remove that index with <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/splice" rel="noreferrer"><code>splice</code></a>.</p> <blockquote> <p>The splice() method changes the contents of an array by removing existing elements and/or adding new elements.</p> </blockquote> <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 array = [2, 5, 9]; console.log(array); const index = array.indexOf(5); if (index &gt; -1) { // only splice array when item is found array.splice(index, 1); // 2nd parameter means remove one item only } // array = [2, 9] console.log(array); </code></pre> </div> </div> </p> <p>The second parameter of <code>splice</code> is the number of elements to remove. Note that <code>splice</code> modifies the array in place and returns a new array containing the elements that have been removed.</p> <hr /> <p>For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of <code>5</code> from <code>[2,5,9,1,5,8,5]</code>), while the second function removes all occurrences:</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 removeItemOnce(arr, value) { var index = arr.indexOf(value); if (index &gt; -1) { arr.splice(index, 1); } return arr; } function removeItemAll(arr, value) { var i = 0; while (i &lt; arr.length) { if (arr[i] === value) { arr.splice(i, 1); } else { ++i; } } return arr; } // Usage console.log(removeItemOnce([2,5,9,1,5,8,5], 5)) console.log(removeItemAll([2,5,9,1,5,8,5], 5))</code></pre> </div> </div> </p> <p>In TypeScript, these functions can stay type-safe with a type parameter:</p> <pre class="lang-js prettyprint-override"><code>function removeItem&lt;T&gt;(arr: Array&lt;T&gt;, value: T): Array&lt;T&gt; { const index = arr.indexOf(value); if (index &gt; -1) { arr.splice(index, 1); } return arr; } </code></pre>
{ "question_id": 5767325, "question_date": "2011-04-23T22:17:18.487Z", "question_score": 10953, "tags": "javascript|arrays", "answer_id": 5767357, "answer_date": "2011-04-23T22:23:50.933Z", "answer_score": 15553 }
Please answer the following Stack Overflow question: Title: How do I rename a local Git branch? <p>How do I rename a local branch which has not yet been pushed to a remote repository?</p> <p>Related:</p> <ul> <li><a href="https://stackoverflow.com/questions/1526794/rename-master-branch-for-both-local-and-remote-git-repositories?answertab=votes#tab-top">Rename master branch for both local and remote Git repositories</a></li> <li><a href="https://stackoverflow.com/questions/30590083/how-to-rename-a-remote-git-branch-name/30590238#30590238">How do I rename both a Git local and remote branch name?</a></li> </ul>
<p>To rename the current branch:</p> <pre><code>git branch -m &lt;newname&gt; </code></pre> <p>To rename a branch while pointed to any branch:</p> <pre><code>git branch -m &lt;oldname&gt; &lt;newname&gt; </code></pre> <p><code>-m</code> is short for <code>--move</code>.</p> <hr /> <p>To push the local branch and reset the upstream branch:</p> <pre><code>git push origin -u &lt;newname&gt; </code></pre> <p>To delete the remote branch:</p> <pre><code>git push origin --delete &lt;oldname&gt; </code></pre> <hr /> <p>To create a <code>git rename</code> alias:</p> <pre><code>git config --global alias.rename 'branch -m' </code></pre> <hr /> <p>On Windows or another case-insensitive filesystem, use <code>-M</code> if there are only capitalization changes in the name. Otherwise, Git will throw a <em>&quot;branch already exists&quot;</em> error.</p> <pre><code>git branch -M &lt;newname&gt; </code></pre>
{ "question_id": 6591213, "question_date": "2011-07-06T03:20:36.830Z", "question_score": 10738, "tags": "git|version-control|git-branch", "answer_id": 6591218, "answer_date": "2011-07-06T03:21:42.917Z", "answer_score": 17541 }
Please answer the following Stack Overflow question: Title: How do I undo 'git add' before commit? <p>I mistakenly added files to Git using the command:</p> <pre><code>git add myfile.txt </code></pre> <p>I have not yet run <code>git commit</code>. How do I undo this so that these changes will not be included in the commit?</p>
<p>Undo <code>git add</code> for uncommitted changes with:</p> <pre><code>git reset &lt;file&gt; </code></pre> <p>That will remove the file from the current index (the &quot;about to be committed&quot; list) without changing anything else.</p> <hr /> <p>To unstage all changes for all files:</p> <pre><code>git reset </code></pre> <hr /> <p>In old versions of Git, the above commands are equivalent to <code>git reset HEAD &lt;file&gt;</code> and <code>git reset HEAD</code> respectively, and will fail if <code>HEAD</code> is undefined (because you haven't yet made any commits in your repository) or ambiguous (because you created a branch called <code>HEAD</code>, which is a stupid thing that you shouldn't do). This <a href="https://git.kernel.org/cgit/git/git.git/tree/Documentation/RelNotes/1.8.2.txt#n179" rel="noreferrer">was changed in Git 1.8.2</a>, though, so in modern versions of Git you can use the commands above even prior to making your first commit:</p> <blockquote> <p>&quot;git reset&quot; (without options or parameters) used to error out when you do not have any commits in your history, but it now gives you an empty index (to match non-existent commit you are not even on).</p> </blockquote> <p>Documentation: <a href="https://git-scm.com/docs/git-reset" rel="noreferrer"><strong>git reset</strong></a></p>
{ "question_id": 348170, "question_date": "2008-12-07T21:57:46.503Z", "question_score": 10682, "tags": "git|undo|git-add", "answer_id": 348234, "answer_date": "2008-12-07T22:30:48.340Z", "answer_score": 12688 }
Please answer the following Stack Overflow question: Title: What is the "-->" operator in C++? <p>After reading <a href="http://groups.google.com/group/comp.lang.c++.moderated/msg/33f173780d58dd20" rel="noreferrer">Hidden Features and Dark Corners of C++/STL</a> on <code>comp.lang.c++.moderated</code>, I was completely surprised that the following snippet compiled and worked in both Visual Studio 2008 and G++ 4.4.</p> <p>Here's the code:</p> <pre><code>#include &lt;stdio.h&gt; int main() { int x = 10; while (x --&gt; 0) // x goes to 0 { printf(&quot;%d &quot;, x); } } </code></pre> <p>Output:</p> <pre><code>9 8 7 6 5 4 3 2 1 0 </code></pre> <p>I'd assume this is C, since it works in GCC as well. Where is this defined in the standard, and where has it come from?</p>
<p><code>--&gt;</code> is not an operator. It is in fact two separate operators, <code>--</code> and <code>&gt;</code>.</p> <p>The conditional's code decrements <code>x</code>, while returning <code>x</code>'s original (not decremented) value, and then compares the original value with <code>0</code> using the <code>&gt;</code> operator.</p> <p><strong>To better understand, the statement could be written as follows:</strong></p> <pre class="lang-c prettyprint-override"><code>while( (x--) &gt; 0 ) </code></pre>
{ "question_id": 1642028, "question_date": "2009-10-29T06:57:45.903Z", "question_score": 9843, "tags": "c++|c|operators|code-formatting|standards-compliance", "answer_id": 1642035, "answer_date": "2009-10-29T07:00:09.617Z", "answer_score": 9538 }
Please answer the following Stack Overflow question: Title: What and where are the stack and heap? <ul> <li>What are the stack and heap?</li> <li>Where are they located physically in a computer's memory?</li> <li>To what extent are they controlled by the OS or language run-time?</li> <li>What is their scope?</li> <li>What determines their sizes?</li> <li>What makes one faster?</li> </ul>
<p>The stack is the memory set aside as scratch space for a thread of execution. When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns, the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO (last in first out) order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.</p> <p>The heap is memory set aside for dynamic allocation. Unlike the stack, there's no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns.</p> <p>Each thread gets a stack, while there's typically only one heap for the application (although it isn't uncommon to have multiple heaps for different types of allocation).</p> <p>To answer your questions directly:</p> <blockquote> <p><em>To what extent are they controlled by the OS or language runtime?</em></p> </blockquote> <p>The OS allocates the stack for each system-level thread when the thread is created. Typically the OS is called by the language runtime to allocate the heap for the application.</p> <blockquote> <p><em>What is their scope?</em></p> </blockquote> <p>The stack is attached to a thread, so when the thread exits the stack is reclaimed. The heap is typically allocated at application startup by the runtime, and is reclaimed when the application (technically process) exits.</p> <blockquote> <p><em>What determines the size of each of them?</em></p> </blockquote> <p>The size of the stack is set when a thread is created. The size of the heap is set on application startup, but can grow as space is needed (the allocator requests more memory from the operating system).</p> <blockquote> <p><em>What makes one faster?</em></p> </blockquote> <p>The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it (a pointer/integer is simply incremented or decremented), while the heap has much more complex bookkeeping involved in an allocation or deallocation. Also, each byte in the stack tends to be reused very frequently which means it tends to be mapped to the processor's cache, making it very fast. Another performance hit for the heap is that the heap, being mostly a global resource, typically has to be multi-threading safe, i.e. each allocation and deallocation needs to be - typically - synchronized with &quot;all&quot; other heap accesses in the program.</p> <p>A clear demonstration: <img src="https://i.stack.imgur.com/i6k0Z.png" alt="" /> <br/><sub>Image source: <a href="http://vikashazrati.wordpress.com/2007/10/01/quicktip-java-basics-stack-and-heap/" rel="noreferrer">vikashazrati.wordpress.com</a></sub></p>
{ "question_id": 79923, "question_date": "2008-09-17T04:18:06.337Z", "question_score": 9106, "tags": "memory-management|stack|language-agnostic|dynamic-memory-allocation|heap-memory", "answer_id": 80113, "answer_date": "2008-09-17T04:52:19.437Z", "answer_score": 6633 }
Please answer the following Stack Overflow question: Title: Can comments be used in JSON? <p>Can I use comments inside a <a href="https://en.wikipedia.org/wiki/JSON" rel="noreferrer">JSON</a> file? If so, how?</p>
<p>No.</p> <p>JSON is data-only. If you include a comment, then it must be data too.</p> <p>You could have a designated data element called <code>&quot;_comment&quot;</code> (or something) that should be ignored by apps that use the JSON data.</p> <p>You would probably be better having the comment in the processes that generates/receives the JSON, as they are supposed to know what the JSON data will be in advance, or at least the structure of it.</p> <p>But if you decided to:</p> <pre><code>{ &quot;_comment&quot;: &quot;comment text goes here...&quot;, &quot;glossary&quot;: { &quot;title&quot;: &quot;example glossary&quot;, &quot;GlossDiv&quot;: { &quot;title&quot;: &quot;S&quot;, &quot;GlossList&quot;: { &quot;GlossEntry&quot;: { &quot;ID&quot;: &quot;SGML&quot;, &quot;SortAs&quot;: &quot;SGML&quot;, &quot;GlossTerm&quot;: &quot;Standard Generalized Markup Language&quot;, &quot;Acronym&quot;: &quot;SGML&quot;, &quot;Abbrev&quot;: &quot;ISO 8879:1986&quot;, &quot;GlossDef&quot;: { &quot;para&quot;: &quot;A meta-markup language, used to create markup languages such as DocBook.&quot;, &quot;GlossSeeAlso&quot;: [&quot;GML&quot;, &quot;XML&quot;] }, &quot;GlossSee&quot;: &quot;markup&quot; } } } } } </code></pre>
{ "question_id": 244777, "question_date": "2008-10-28T20:39:03.333Z", "question_score": 9088, "tags": "json|comments", "answer_id": 244858, "answer_date": "2008-10-28T21:01:42.307Z", "answer_score": 6741 }
Please answer the following Stack Overflow question: Title: How do I force "git pull" to overwrite local files? <p>How do I force an overwrite of local files on a <code>git pull</code>? My local repository contains a file of the same filename as on the server.</p> <blockquote> <p>error: Untracked working tree file 'example.txt' would be overwritten by merge</p> </blockquote>
<blockquote> <h2>⚠ Warning:</h2> <p>Any uncommitted local changes to tracked files will be lost.</p> <p>Any local files that are <em>not</em> tracked by Git will not be affected.</p> </blockquote> <hr /> <p>First, update all <code>origin/&lt;branch&gt;</code> refs to latest:</p> <pre><code>git fetch --all </code></pre> <p>Backup your current branch (e.g. <code>master</code>):</p> <pre><code>git branch backup-master </code></pre> <p>Jump to the latest commit on <code>origin/master</code> and checkout those files:</p> <pre><code>git reset --hard origin/master </code></pre> <h3>Explanation:</h3> <p><code>git fetch</code> downloads the latest from remote without trying to merge or rebase anything.</p> <p><code>git reset</code> resets the master branch to what you just fetched. The <code>--hard</code> option changes all the files in your working tree to match the files in <code>origin/master</code>.</p> <hr /> <h3>Maintain current local commits</h3> <p><sup>[*]</sup>: It's worth noting that it is possible to maintain current local commits by creating a branch from <code>master</code> before resetting:</p> <pre><code>git checkout master git branch new-branch-to-save-current-commits git fetch --all git reset --hard origin/master </code></pre> <p>After this, all of the old commits will be kept in <code>new-branch-to-save-current-commits</code>.</p> <h3>Uncommitted changes</h3> <p>Uncommitted changes, however (even staged), will be lost. Make sure to stash and commit anything you need. For that you can run the following:</p> <pre><code>git stash </code></pre> <p>And then to reapply these uncommitted changes:</p> <pre><code>git stash pop </code></pre>
{ "question_id": 1125968, "question_date": "2009-07-14T14:58:15.550Z", "question_score": 8913, "tags": "git|version-control|overwrite|git-pull|git-fetch", "answer_id": 8888015, "answer_date": "2012-01-17T00:02:58.813Z", "answer_score": 12364 }
Please answer the following Stack Overflow question: Title: Why does HTML think “chucknorris” is a color? <p>Why do certain random strings produce colors when entered as background colors in HTML?</p> <p>For example, <code>bgcolor=&quot;chucknorris&quot;</code> produces a <strong>red background</strong>:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body bgcolor="chucknorris"&gt; test &lt;/body&gt;</code></pre> </div> </div> </p> <p>Conversely, <code>bgcolor=&quot;chucknorr&quot;</code> produces a <strong>yellow background</strong>:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body bgcolor="chucknorr"&gt; test &lt;/body&gt;</code></pre> </div> </div> </p> <p>This holds true across various browsers and platforms. What’s going on here?</p>
<p>It’s a holdover from the Netscape days:</p> <blockquote> <p>Missing digits are treated as 0[...]. An incorrect digit is simply interpreted as 0. For example the values #F0F0F0, F0F0F0, F0F0F, #FxFxFx and FxFxFx are all the same.</p> </blockquote> <p>It is from the blog post <em><a href="http://scrappy-do.blogspot.com/2004/08/little-rant-about-microsoft-internet.html" rel="noreferrer">A little rant about Microsoft Internet Explorer's color parsing</a></em> which covers it in great detail, including varying lengths of color values, etc.</p> <p>If we apply the rules in turn from the blog post, we get the following:</p> <ol> <li><p>Replace all nonvalid hexadecimal characters with 0’s:</p> <pre><code>chucknorris becomes c00c0000000 </code></pre> </li> <li><p>Pad out to the next total number of characters divisible by 3 (11 → 12):</p> <pre><code>c00c 0000 0000 </code></pre> </li> <li><p>Split into three equal groups, with each component representing the corresponding colour component of an RGB colour:</p> <pre><code>RGB (c00c, 0000, 0000) </code></pre> </li> <li><p>Truncate each of the arguments from the right down to two characters.</p> </li> </ol> <p>Which, finally, gives the following result:</p> <pre><code>RGB (c0, 00, 00) = #C00000 or RGB(192, 0, 0) </code></pre> <p>Here’s an example demonstrating the <code>bgcolor</code> attribute in action, to produce this “amazing” colour swatch:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table&gt; &lt;tr&gt; &lt;td bgcolor="chucknorris" cellpadding="8" width="100" align="center"&gt;chuck norris&lt;/td&gt; &lt;td bgcolor="mrt" cellpadding="8" width="100" align="center" style="color:#ffffff"&gt;Mr T&lt;/td&gt; &lt;td bgcolor="ninjaturtle" cellpadding="8" width="100" align="center" style="color:#ffffff"&gt;ninjaturtle&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td bgcolor="sick" cellpadding="8" width="100" align="center"&gt;sick&lt;/td&gt; &lt;td bgcolor="crap" cellpadding="8" width="100" align="center"&gt;crap&lt;/td&gt; &lt;td bgcolor="grass" cellpadding="8" width="100" align="center"&gt;grass&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <p>This also answers the other part of the question: Why does <code>bgcolor=&quot;chucknorr&quot;</code> produce a yellow colour? Well, if we apply the rules, the string is:</p> <pre><code>c00c00000 =&gt; c00 c00 000 =&gt; c0 c0 00 [RGB(192, 192, 0)] </code></pre> <p>Which gives a light yellow gold colour. As the string starts off as 9 characters, we keep the second ‘C’ this time around, hence it ends up in the final colour value.</p> <p>I originally encountered this when someone pointed out that you could do <code>color=&quot;crap&quot;</code> and, well, it comes out brown.</p>
{ "question_id": 8318911, "question_date": "2011-11-29T22:54:22.833Z", "question_score": 8506, "tags": "html|browser|background-color", "answer_id": 8333464, "answer_date": "2011-11-30T21:53:38.350Z", "answer_score": 7907 }
Please answer the following Stack Overflow question: Title: How do I check if an element is hidden in jQuery? <p>How do I toggle the visibility of an element using <code>.hide()</code>, <code>.show()</code>, or <code>.toggle()</code>?</p> <p>How do I test if an element is <code>visible</code> or <code>hidden</code>?</p>
<p>Since the question refers to a single element, this code might be more suitable:</p> <pre><code>// Checks CSS content for display:[none|block], ignores visibility:[true|false] $(element).is(&quot;:visible&quot;); // The same works with hidden $(element).is(&quot;:hidden&quot;); </code></pre> <p>It is the same as <a href="https://stackoverflow.com/questions/178325/how-do-you-test-if-something-is-hidden-in-jquery/178386#178386">twernt's suggestion</a>, but applied to a single element; and it <a href="https://stackoverflow.com/questions/178325/how-do-i-check-if-an-element-is-hidden-in-jquery/4685330#4685330">matches the algorithm recommended in the jQuery FAQ</a>.</p> <p>We use jQuery's <a href="https://api.jquery.com/is/" rel="noreferrer">is()</a> to check the selected element with another element, selector or any jQuery object. This method traverses along the DOM elements to find a match, which satisfies the passed parameter. It will return true if there is a match, otherwise return false.</p>
{ "question_id": 178325, "question_date": "2008-10-07T13:03:18.057Z", "question_score": 8447, "tags": "javascript|jquery|dom|visibility", "answer_id": 178450, "answer_date": "2008-10-07T13:30:22.217Z", "answer_score": 10070 }
Please answer the following Stack Overflow question: Title: What does "use strict" do in JavaScript, and what is the reasoning behind it? <p>Recently, I ran some of my JavaScript code through Crockford's <a href="http://www.jslint.com/" rel="noreferrer">JSLint</a>, and it gave the following error:</p> <blockquote> <p>Problem at line 1 character 1: Missing &quot;use strict&quot; statement.</p> </blockquote> <p>Doing some searching, I realized that some people add <code>&quot;use strict&quot;;</code> into their JavaScript code. Once I added the statement, the error stopped appearing. Unfortunately, Google did not reveal much of the history behind this string statement. Certainly it must have something to do with how the JavaScript is interpreted by the browser, but I have no idea what the effect would be.</p> <p>So what is <code>&quot;use strict&quot;;</code> all about, what does it imply, and is it still relevant?</p> <p>Do any of the current browsers respond to the <code>&quot;use strict&quot;;</code> string or is it for future use?</p>
<h2>Update for ES6 modules</h2> <p>Inside <a href="https://caniuse.com/#feat=es6-module" rel="noreferrer">native ECMAScript modules</a> (with <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import" rel="noreferrer"><code>import</code></a> and <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export" rel="noreferrer"><code>export</code></a> statements) and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes" rel="noreferrer">ES6 classes</a>, strict mode is always enabled and cannot be disabled.</p> <h2>Original answer</h2> <p>This article about Javascript Strict Mode might interest you: <a href="http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/" rel="noreferrer">John Resig - ECMAScript 5 Strict Mode, JSON, and More</a></p> <p>To quote some interesting parts:</p> <blockquote> <p>Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a &quot;strict&quot; operating context. This strict context prevents certain actions from being taken and throws more exceptions.</p> </blockquote> <p>And:</p> <blockquote> <p>Strict mode helps out in a couple ways:</p> <ul> <li>It catches some common coding bloopers, throwing exceptions.</li> <li>It prevents, or throws errors, when relatively &quot;unsafe&quot; actions are taken (such as gaining access to the global object).</li> <li>It disables features that are confusing or poorly thought out.</li> </ul> </blockquote> <p>Also note you can apply &quot;strict mode&quot; to the whole file... Or you can use it only for a specific function <em>(still quoting from John Resig's article)</em>:</p> <pre class="lang-js prettyprint-override"><code>// Non-strict code... (function(){ &quot;use strict&quot;; // Define your library strictly... })(); // Non-strict code... </code></pre> <p>Which might be helpful if you have to mix old and new code ;-)</p> <p>So, I suppose it's a bit like the <a href="https://perldoc.perl.org/strict" rel="noreferrer"><code>&quot;use strict&quot;</code></a> you can use in Perl <em>(hence the name?)</em>: it helps you make fewer errors, by detecting more things that could lead to breakages.</p> <p>Strict mode is now <a href="http://caniuse.com/use-strict" rel="noreferrer">supported by all major browsers</a>.</p>
{ "question_id": 1335851, "question_date": "2009-08-26T16:10:13.827Z", "question_score": 8264, "tags": "javascript|syntax|jslint|use-strict", "answer_id": 1335881, "answer_date": "2009-08-26T16:15:39.370Z", "answer_score": 5369 }
Please answer the following Stack Overflow question: Title: How do I check out a remote Git branch? <p>Somebody pushed a branch called <code>test</code> with <code>git push origin test</code> to a shared repository. I can see the branch with <code>git branch -r</code>. How do I check out the remote <code>test</code> branch? I've tried:</p> <ul> <li><code>git checkout test</code>, which does nothing</li> <li><code>git checkout origin/test</code> gives <code>* (no branch)</code></li> </ul>
<p>The answer has been split depending on whether there is one remote repository configured or multiple. The reason for this is that for the single remote case, some of the commands can be simplified as there is less ambiguity.</p> <p><strong>Updated for Git 2.23:</strong> For older versions, see the section at the end.</p> <h2>With One Remote</h2> <p>In both cases, start by fetching from the remote repository to make sure you have all the latest changes downloaded.</p> <pre><code>$ git fetch </code></pre> <p>This will fetch all of the remote branches for you. You can see the branches available for checkout with:</p> <pre><code>$ git branch -v -a ... remotes/origin/test </code></pre> <p>The branches that start with <code>remotes/*</code> can be thought of as read only copies of the remote branches. To work on a branch you need to create a local branch from it. This is done with the Git command <code>switch</code> (since Git 2.23) by giving it the name of the remote branch (minus the remote name):</p> <pre><code>$ git switch test </code></pre> <p>In this case Git is guessing (can be disabled with <code>--no-guess</code>) that you are trying to checkout and track the remote branch with the same name.</p> <h2>With Multiple Remotes</h2> <p>In the case where multiple remote repositories exist, the remote repository needs to be explicitly named.</p> <p>As before, start by fetching the latest remote changes:</p> <pre><code>$ git fetch origin </code></pre> <p>This will fetch all of the remote branches for you. You can see the branches available for checkout with:</p> <pre><code>$ git branch -v -a </code></pre> <p>With the remote branches in hand, you now need to check out the branch you are interested in with <code>-c</code> to create a new local branch:</p> <pre><code>$ git switch -c test origin/test </code></pre> <p>For more information about using <code>git switch</code>:</p> <pre><code>$ man git-switch </code></pre> <p>I also created the image below for you to share the differences, look at how to fetch works, and also how it's different to pull:</p> <p><a href="https://i.stack.imgur.com/zBb51.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zBb51.png" alt="enter image description here" /></a></p> <h2>Prior to Git 2.23</h2> <p><code>git switch</code> was added in Git 2.23, prior to this <code>git checkout</code> was used to switch branches.</p> <p>To checkout out with only a single remote repository:</p> <pre><code>git checkout test </code></pre> <p>if there there are multiple remote repositories configured it becomes a bit longer</p> <pre><code>git checkout -b test &lt;name of remote&gt;/test </code></pre>
{ "question_id": 1783405, "question_date": "2009-11-23T14:23:46.150Z", "question_score": 8058, "tags": "git|git-checkout|remote-branch", "answer_id": 1783426, "answer_date": "2009-11-23T14:26:08.970Z", "answer_score": 10952 }
Please answer the following Stack Overflow question: Title: How do I remove local (untracked) files from the current Git working tree? <p>How do I delete untracked local files from the current working tree?</p>
<blockquote> <h2><a href="https://git-scm.com/docs/git-clean" rel="noreferrer">git-clean</a> - Remove untracked files from the working tree</h2> <h3>Synopsis</h3> <pre><code>git clean [-d] [-f] [-i] [-n] [-q] [-e &lt;pattern&gt;] [-x | -X] [--] &lt;path&gt;…​ </code></pre> <h3>Description</h3> <p>Cleans the working tree by recursively removing files that are not under version control, <strong>starting from the current directory</strong>.</p> <p>Normally, only files unknown to Git are removed, but if the <code>-x</code> option is specified, ignored files are also removed. This can, for example, be useful to remove all build products.</p> <p>If any optional <code>&lt;path&gt;...</code> arguments are given, only those paths are affected.</p> </blockquote> <hr /> <p>Step 1 is to show what will be deleted by using the <code>-n</code> option:</p> <pre><code># Print out the list of files and directories which will be removed (dry run) git clean -n -d </code></pre> <p>Clean Step - <strong>beware: this will delete files</strong>:</p> <pre><code># Delete the files from the repository git clean -f </code></pre> <ul> <li>To remove directories, run <code>git clean -f -d</code> or <code>git clean -fd</code></li> <li>To remove ignored files, run <code>git clean -f -X</code> or <code>git clean -fX</code></li> <li>To remove ignored and non-ignored files, run <code>git clean -f -x</code> or <code>git clean -fx</code></li> </ul> <p><strong>Note</strong> the case difference on the <code>X</code> for the two latter commands.</p> <p>If <code>clean.requireForce</code> is set to &quot;true&quot; (the default) in your configuration, one needs to specify <code>-f</code> otherwise nothing will actually happen.</p> <p>Again see the <a href="http://git-scm.com/docs/git-clean" rel="noreferrer"><code>git-clean</code></a> docs for more information.</p> <hr /> <blockquote> <h3>Options</h3> <p><strong><code>-f</code>, <code>--force</code></strong></p> <p>If the Git configuration variable clean.requireForce is not set to false, git clean will refuse to run unless given <code>-f</code>, <code>-n</code> or <code>-i</code>.</p> <p><strong><code>-x</code></strong></p> <p>Don’t use the standard ignore rules read from .gitignore (per directory) and <code>$GIT_DIR/info/exclude</code>, but do still use the ignore rules given with <code>-e</code> options. This allows removing all untracked files, including build products. This can be used (possibly in conjunction with git reset) to create a pristine working directory to test a clean build.</p> <p><strong><code>-X</code></strong></p> <p>Remove only files ignored by Git. This may be useful to rebuild everything from scratch, but keep manually created files.</p> <p><strong><code>-n</code>, <code>--dry-run</code></strong></p> <p>Don’t actually remove anything, just show what would be done.</p> <p><strong><code>-d</code></strong></p> <p>Remove untracked directories in addition to untracked files. If an untracked directory is managed by a different Git repository, it is not removed by default. Use <code>-f</code> option twice if you really want to remove such a directory.</p> </blockquote>
{ "question_id": 61212, "question_date": "2008-09-14T09:06:10.647Z", "question_score": 7766, "tags": "git|branch|git-branch", "answer_id": 64966, "answer_date": "2008-09-15T17:32:55.957Z", "answer_score": 9518 }
Please answer the following Stack Overflow question: Title: What does if __name__ == "__main__": do? <p>What does this do, and why should one include the <code>if</code> statement?</p> <pre><code>if __name__ == &quot;__main__&quot;: print(&quot;Hello, World!&quot;) </code></pre> <hr /> <p><sub>This question explains what the code does and how it works. If you are trying to close a question where someone should be using this idiom and isn't, consider closing as a duplicate of <a href="https://stackoverflow.com/questions/6523791">Why is Python running my module when I import it, and how do I stop it?</a> instead.</sub></p>
<h1>Short Answer</h1> <p>It's boilerplate code that protects users from accidentally invoking the script when they didn't intend to. Here are some common problems when the guard is omitted from a script:</p> <ul> <li><p>If you import the guardless script in another script (e.g. <code>import my_script_without_a_name_eq_main_guard</code>), then the latter script will trigger the former to run <em>at import time</em> and <em>using the second script's command line arguments</em>. This is almost always a mistake.</p> </li> <li><p>If you have a custom class in the guardless script and save it to a pickle file, then unpickling it in another script will trigger an import of the guardless script, with the same problems outlined in the previous bullet.</p> </li> </ul> <h1>Long Answer</h1> <p>To better understand why and how this matters, we need to take a step back to understand how Python initializes scripts and how this interacts with its module import mechanism.</p> <p>Whenever the Python interpreter reads a source file, it does two things:</p> <ul> <li><p>it sets a few special variables like <code>__name__</code>, and then</p> </li> <li><p>it executes all of the code found in the file.</p> </li> </ul> <p>Let's see how this works and how it relates to your question about the <code>__name__</code> checks we always see in Python scripts.</p> <h2>Code Sample</h2> <p>Let's use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called <code>foo.py</code>.</p> <pre><code># Suppose this is foo.py. print(&quot;before import&quot;) import math print(&quot;before function_a&quot;) def function_a(): print(&quot;Function A&quot;) print(&quot;before function_b&quot;) def function_b(): print(&quot;Function B {}&quot;.format(math.sqrt(100))) print(&quot;before __name__ guard&quot;) if __name__ == '__main__': function_a() function_b() print(&quot;after __name__ guard&quot;) </code></pre> <h2>Special Variables</h2> <p>When the Python interpreter reads a source file, it first defines a few special variables. In this case, we care about the <code>__name__</code> variable.</p> <p><strong>When Your Module Is the Main Program</strong></p> <p>If you are running your module (the source file) as the main program, e.g.</p> <pre><code>python foo.py </code></pre> <p>the interpreter will assign the hard-coded string <code>&quot;__main__&quot;</code> to the <code>__name__</code> variable, i.e.</p> <pre><code># It's as if the interpreter inserts this at the top # of your module when run as the main program. __name__ = &quot;__main__&quot; </code></pre> <p><strong>When Your Module Is Imported By Another</strong></p> <p>On the other hand, suppose some other module is the main program and it imports your module. This means there's a statement like this in the main program, or in some other module the main program imports:</p> <pre><code># Suppose this is in some other main program. import foo </code></pre> <p>The interpreter will search for your <code>foo.py</code> file (along with searching for a few other variants), and prior to executing that module, it will assign the name <code>&quot;foo&quot;</code> from the import statement to the <code>__name__</code> variable, i.e.</p> <pre><code># It's as if the interpreter inserts this at the top # of your module when it's imported from another module. __name__ = &quot;foo&quot; </code></pre> <h2>Executing the Module's Code</h2> <p>After the special variables are set up, the interpreter executes all the code in the module, one statement at a time. You may want to open another window on the side with the code sample so you can follow along with this explanation.</p> <p><strong>Always</strong></p> <ol> <li><p>It prints the string <code>&quot;before import&quot;</code> (without quotes).</p> </li> <li><p>It loads the <code>math</code> module and assigns it to a variable called <code>math</code>. This is equivalent to replacing <code>import math</code> with the following (note that <code>__import__</code> is a low-level function in Python that takes a string and triggers the actual import):</p> </li> </ol> <pre><code># Find and load a module given its string name, &quot;math&quot;, # then assign it to a local variable called math. math = __import__(&quot;math&quot;) </code></pre> <ol start="3"> <li><p>It prints the string <code>&quot;before function_a&quot;</code>.</p> </li> <li><p>It executes the <code>def</code> block, creating a function object, then assigning that function object to a variable called <code>function_a</code>.</p> </li> <li><p>It prints the string <code>&quot;before function_b&quot;</code>.</p> </li> <li><p>It executes the second <code>def</code> block, creating another function object, then assigning it to a variable called <code>function_b</code>.</p> </li> <li><p>It prints the string <code>&quot;before __name__ guard&quot;</code>.</p> </li> </ol> <p><strong>Only When Your Module Is the Main Program</strong></p> <ol start="8"> <li>If your module is the main program, then it will see that <code>__name__</code> was indeed set to <code>&quot;__main__&quot;</code> and it calls the two functions, printing the strings <code>&quot;Function A&quot;</code> and <code>&quot;Function B 10.0&quot;</code>.</li> </ol> <p><strong>Only When Your Module Is Imported by Another</strong></p> <ol start="8"> <li>(<strong>instead</strong>) If your module is not the main program but was imported by another one, then <code>__name__</code> will be <code>&quot;foo&quot;</code>, not <code>&quot;__main__&quot;</code>, and it'll skip the body of the <code>if</code> statement.</li> </ol> <p><strong>Always</strong></p> <ol start="9"> <li>It will print the string <code>&quot;after __name__ guard&quot;</code> in both situations.</li> </ol> <p><em><strong>Summary</strong></em></p> <p>In summary, here's what'd be printed in the two cases:</p> <pre class="lang-none prettyprint-override"><code># What gets printed if foo is the main program before import before function_a before function_b before __name__ guard Function A Function B 10.0 after __name__ guard </code></pre> <pre class="lang-none prettyprint-override"><code># What gets printed if foo is imported as a regular module before import before function_a before function_b before __name__ guard after __name__ guard </code></pre> <h2>Why Does It Work This Way?</h2> <p>You might naturally wonder why anybody would want this. Well, sometimes you want to write a <code>.py</code> file that can be both used by other programs and/or modules as a module, and can also be run as the main program itself. Examples:</p> <ul> <li><p>Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.</p> </li> <li><p>Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing <code>.py</code> files like your script and running special test functions. You don't want it to try running the script just because it's importing the module.</p> </li> <li><p>Your module is mostly used as a main program, but it also provides a programmer-friendly API for advanced users.</p> </li> </ul> <p>Beyond those examples, it's elegant that running a script in Python is just setting up a few magic variables and importing the script. &quot;Running&quot; the script is a side effect of importing the script's module.</p> <h2>Food for Thought</h2> <ul> <li><p>Question: Can I have multiple <code>__name__</code> checking blocks? Answer: it's strange to do so, but the language won't stop you.</p> </li> <li><p>Suppose the following is in <code>foo2.py</code>. What happens if you say <code>python foo2.py</code> on the command-line? Why?</p> </li> </ul> <pre class="lang-py prettyprint-override"><code># Suppose this is foo2.py. import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters def function_a(): print(&quot;a1&quot;) from foo2 import function_b print(&quot;a2&quot;) function_b() print(&quot;a3&quot;) def function_b(): print(&quot;b&quot;) print(&quot;t1&quot;) if __name__ == &quot;__main__&quot;: print(&quot;m1&quot;) function_a() print(&quot;m2&quot;) print(&quot;t2&quot;) </code></pre> <ul> <li>Now, figure out what will happen if you remove the <code>__name__</code> check in <code>foo3.py</code>:</li> </ul> <pre class="lang-py prettyprint-override"><code># Suppose this is foo3.py. import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters def function_a(): print(&quot;a1&quot;) from foo3 import function_b print(&quot;a2&quot;) function_b() print(&quot;a3&quot;) def function_b(): print(&quot;b&quot;) print(&quot;t1&quot;) print(&quot;m1&quot;) function_a() print(&quot;m2&quot;) print(&quot;t2&quot;) </code></pre> <ul> <li>What will this do when used as a script? When imported as a module?</li> </ul> <pre class="lang-py prettyprint-override"><code># Suppose this is in foo4.py __name__ = &quot;__main__&quot; def bar(): print(&quot;bar&quot;) print(&quot;before __name__ guard&quot;) if __name__ == &quot;__main__&quot;: bar() print(&quot;after __name__ guard&quot;) </code></pre>
{ "question_id": 419163, "question_date": "2009-01-07T04:11:00.010Z", "question_score": 7713, "tags": "python|namespaces|program-entry-point|python-module|idioms", "answer_id": 419185, "answer_date": "2009-01-07T04:26:43.380Z", "answer_score": 8420 }
Please answer the following Stack Overflow question: Title: How do I redirect to another webpage? <p>How can I redirect the user from one page to another using jQuery or pure JavaScript?</p>
<h2>One does not simply redirect using jQuery</h2> <p>jQuery is not necessary, and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/replace" rel="noreferrer"><strong><code>window.location.replace(...)</code></strong></a> will best simulate an HTTP redirect. </p> <p><code>window.location.replace(...)</code> is better than using <code>window.location.href</code>, because <code>replace()</code> does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.</p> <p>If you want to simulate someone clicking on a link, use <strong><code>location.href</code></strong></p> <p>If you want to simulate an HTTP redirect, use <strong><code>location.replace</code></strong></p> <p><strong>For example:</strong></p> <pre><code>// similar behavior as an HTTP redirect window.location.replace("http://stackoverflow.com"); // similar behavior as clicking on a link window.location.href = "http://stackoverflow.com"; </code></pre>
{ "question_id": 503093, "question_date": "2009-02-02T12:54:16.867Z", "question_score": 7707, "tags": "javascript|jquery|redirect", "answer_id": 506004, "answer_date": "2009-02-03T04:24:09.767Z", "answer_score": 16001 }
Please answer the following Stack Overflow question: Title: How to modify existing, unpushed commit messages? <p>I wrote the wrong thing in a commit message.</p> <p>How can I change the message? The commit has not been pushed yet.</p>
<h1>Amending the most recent commit message</h1> <pre class="lang-sh prettyprint-override"><code>git commit --amend </code></pre> <p>will open your editor, allowing you to change the commit message of the most recent commit. Additionally, you can set the commit message directly in the command line with:</p> <pre class="lang-sh prettyprint-override"><code>git commit --amend -m &quot;New commit message&quot; </code></pre> <p>…however, this can make multi-line commit messages or small corrections more cumbersome to enter.</p> <p>Make sure you don't have any working copy changes <em>staged</em> before doing this or they will get committed too. (<em>Unstaged</em> changes will not get committed.)</p> <h2>Changing the message of a commit that you've already pushed to your remote branch</h2> <p>If you've already pushed your commit up to your remote branch, then - after amending your commit locally (as described above) - you'll also <a href="https://stackoverflow.com/questions/41003071/why-must-i-force-push-after-changing-a-commit-message">need to force push the commit</a> with:</p> <pre class="lang-bash prettyprint-override"><code>git push &lt;remote&gt; &lt;branch&gt; --force # Or git push &lt;remote&gt; &lt;branch&gt; -f </code></pre> <p><strong>Warning: force-pushing will overwrite the remote branch with the state of your local one</strong>. If there are commits on the remote branch that you don't have in your local branch, you <em>will</em> lose those commits.</p> <p><strong>Warning: be cautious about amending commits that you have already shared with other people.</strong> Amending commits essentially <em>rewrites</em> them to have different <a href="https://en.wikipedia.org/wiki/SHA-1" rel="noreferrer">SHA</a> IDs, which poses a problem if other people have copies of the old commit that you've rewritten. Anyone who has a copy of the old commit will need to synchronize their work with your newly re-written commit, which can sometimes be difficult, so make sure you coordinate with others when attempting to rewrite shared commit history, or just avoid rewriting shared commits altogether.</p> <hr /> <h3>Perform an interactive rebase</h3> <p>Another option is to use interactive rebase. This allows you to edit any message you want to update even if it's not the latest message.</p> <p>In order to do a Git squash, follow these steps:</p> <pre><code>// n is the number of commits up to the last commit you want to be able to edit git rebase -i HEAD~n </code></pre> <p>Once you squash your commits - choose the <code>e/r</code> for editing the message:</p> <p><a href="https://i.stack.imgur.com/LVcm9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LVcm9.png" alt="Screenshot of terminal while editing commit" /></a></p> <h3>Important note about interactive rebase</h3> <p>When you use <code>git rebase -i HEAD~n</code> there can be <strong>more</strong> than n commits. Git will &quot;collect&quot; all the commits in the last n commits, and if there was a merge somewhere in between that range you will see all the commits as well, so the outcome will be n + .</p> <h3>Good tip:</h3> <p>If you have to do it for more than a single branch and you might face conflicts when amending the content, set up <a href="https://stackoverflow.com/questions/35415925/is-it-possible-to-setup-git-merge-for-automatic-resolving-git-rerere/35417944#35417944"><code>git rerere</code></a> and let Git resolve those conflicts automatically for you.</p> <hr /> <h2>Documentation</h2> <ul> <li><p><a href="https://www.kernel.org/pub/software/scm/git/docs/git-commit.html" rel="noreferrer">git-commit(1) Manual Page</a></p> </li> <li><p><a href="https://www.kernel.org/pub/software/scm/git/docs/git-rebase.html" rel="noreferrer">git-rebase(1) Manual Page</a></p> </li> <li><p><a href="https://www.kernel.org/pub/software/scm/git/docs/git-push.html" rel="noreferrer">git-push(1) Manual Page</a></p> </li> </ul>
{ "question_id": 179123, "question_date": "2008-10-07T15:44:47.920Z", "question_score": 7653, "tags": "git|git-commit|git-rewrite-history|git-amend", "answer_id": 179147, "answer_date": "2008-10-07T15:50:34.630Z", "answer_score": 17827 }
Please answer the following Stack Overflow question: Title: How do JavaScript closures work? <p>How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?</p> <p>I have seen <a href="http://en.wikipedia.org/wiki/Scheme_%28programming_language%29" rel="noreferrer">the Scheme example</a> given on Wikipedia, but unfortunately it did not help.</p>
<p>A closure is a pairing of:</p> <ol> <li>A function and</li> <li>A reference to that function's outer scope (lexical environment)</li> </ol> <p>A lexical environment is part of every execution context (stack frame) and is a map between identifiers (i.e. local variable names) and values.</p> <p>Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to &quot;see&quot; variables declared outside the function, regardless of when and where the function is called.</p> <p>If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain.</p> <p>In the following code, <code>inner</code> forms a closure with the lexical environment of the execution context created when <code>foo</code> is invoked, <em>closing over</em> variable <code>secret</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 foo() { const secret = Math.trunc(Math.random() * 100) return function inner() { console.log(`The secret number is ${secret}.`) } } const f = foo() // `secret` is not directly accessible from outside `foo` f() // The only way to retrieve `secret`, is to invoke `f`</code></pre> </div> </div> </p> <p>In other words: in JavaScript, functions carry a reference to a private &quot;box of state&quot;, to which only they (and any other functions declared within the same lexical environment) have access. This box of the state is invisible to the caller of the function, delivering an excellent mechanism for data-hiding and encapsulation.</p> <p>And remember: functions in JavaScript can be passed around like variables (first-class functions), meaning these pairings of functionality and state can be passed around your program: similar to how you might pass an instance of a class around in C++.</p> <p>If JavaScript did not have closures, then more states would have to be passed between functions <em>explicitly</em>, making parameter lists longer and code noisier.</p> <p>So, if you want a function to always have access to a private piece of state, you can use a closure.</p> <p>...and frequently we <em>do</em> want to associate the state with a function. For example, in Java or C++, when you add a private instance variable and a method to a class, you are associating the state with functionality.</p> <p>In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables of the outer function can remain accessible after returning from it. In this way, in the code above, <code>secret</code> remains available to the function object <code>inner</code>, <em>after</em> it has been returned from <code>foo</code>.</p> <h2>Uses of Closures</h2> <p>Closures are useful whenever you need a private state associated with a function. This is a very common scenario - and remember: JavaScript did not have a class syntax until 2015, and it still does not have a private field syntax. Closures meet this need.</p> <h3>Private Instance Variables</h3> <p>In the following code, the function <code>toString</code> closes over the details of the car.</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 Car(manufacturer, model, year, color) { return { toString() { return `${manufacturer} ${model} (${year}, ${color})` } } } const car = new Car('Aston Martin', 'V8 Vantage', '2012', 'Quantum Silver') console.log(car.toString())</code></pre> </div> </div> </p> <h3>Functional Programming</h3> <p>In the following code, the function <code>inner</code> closes over both <code>fn</code> and <code>args</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 curry(fn) { const args = [] return function inner(arg) { if(args.length === fn.length) return fn(...args) args.push(arg) return inner } } function add(a, b) { return a + b } const curriedAdd = curry(add) console.log(curriedAdd(2)(3)()) // 5</code></pre> </div> </div> </p> <h3>Event-Oriented Programming</h3> <p>In the following code, function <code>onClick</code> closes over variable <code>BACKGROUND_COLOR</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>const $ = document.querySelector.bind(document) const BACKGROUND_COLOR = 'rgba(200, 200, 242, 1)' function onClick() { $('body').style.background = BACKGROUND_COLOR } $('button').addEventListener('click', onClick)</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button&gt;Set background color&lt;/button&gt;</code></pre> </div> </div> </p> <h3>Modularization</h3> <p>In the following example, all the implementation details are hidden inside an immediately executed function expression. The functions <code>tick</code> and <code>toString</code> close over the private state and functions they need to complete their work. Closures have enabled us to modularize and encapsulate our 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>let namespace = {}; (function foo(n) { let numbers = [] function format(n) { return Math.trunc(n) } function tick() { numbers.push(Math.random() * 100) } function toString() { return numbers.map(format) } n.counter = { tick, toString } }(namespace)) const counter = namespace.counter counter.tick() counter.tick() console.log(counter.toString())</code></pre> </div> </div> </p> <h2>Examples</h2> <h3>Example 1</h3> <p>This example shows that the local variables are not copied in the closure: the closure maintains a reference to the original variables <em>themselves</em>. It is as though the stack-frame stays alive in memory even after the outer function exits.</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 foo() { let x = 42 let inner = () =&gt; console.log(x) x = x + 1 return inner } foo()() // logs 43</code></pre> </div> </div> </p> <h3>Example 2</h3> <p>In the following code, three methods <code>log</code>, <code>increment</code>, and <code>update</code> all close over the same lexical environment.</p> <p>And every time <code>createObject</code> is called, a new execution context (stack frame) is created and a completely new variable <code>x</code>, and a new set of functions (<code>log</code> etc.) are created, that close over this new variable.</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 createObject() { let x = 42; return { log() { console.log(x) }, increment() { x++ }, update(value) { x = value } } } const o = createObject() o.increment() o.log() // 43 o.update(5) o.log() // 5 const p = createObject() p.log() // 42</code></pre> </div> </div> </p> <h3>Example 3</h3> <p>If you are using variables declared using <code>var</code>, be careful you understand which variable you are closing over. Variables declared using <code>var</code> are hoisted. This is much less of a problem in modern JavaScript due to the introduction of <code>let</code> and <code>const</code>.</p> <p>In the following code, each time around the loop, a new function <code>inner</code> is created, which closes over <code>i</code>. But because <code>var i</code> is hoisted outside the loop, all of these inner functions close over the same variable, meaning that the final value of <code>i</code> (3) is printed, three times.</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 foo() { var result = [] for (var i = 0; i &lt; 3; i++) { result.push(function inner() { console.log(i) } ) } return result } const result = foo() // The following will print `3`, three times... for (var i = 0; i &lt; 3; i++) { result[i]() }</code></pre> </div> </div> </p> <h2>Final points:</h2> <ul> <li>Whenever a function is declared in JavaScript closure is created.</li> <li>Returning a <code>function</code> from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution.</li> <li>Whenever you use <code>eval()</code> inside a function, a closure is used. The text you <code>eval</code> can reference local variables of the function, and in the non-strict mode, you can even create new local variables by using <code>eval('var foo = …')</code>.</li> <li>When you use <code>new Function(…)</code> (the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" rel="noreferrer">Function constructor</a>) inside a function, it does not close over its lexical environment: it closes over the global context instead. The new function cannot reference the local variables of the outer function.</li> <li>A closure in JavaScript is like keeping a reference (<strong>NOT</strong> a copy) to the scope at the point of function declaration, which in turn keeps a reference to its outer scope, and so on, all the way to the global object at the top of the scope chain.</li> <li>A closure is created when a function is declared; this closure is used to configure the execution context when the function is invoked.</li> <li>A new set of local variables is created every time a function is called.</li> </ul> <h2>Links</h2> <ul> <li>Douglas Crockford's simulated <a href="http://www.crockford.com/javascript/private.html" rel="noreferrer">private attributes and private methods</a> for an object, using closures.</li> <li>A great explanation of how closures can <a href="https://www.codeproject.com/Articles/12231/Memory-Leakage-in-Internet-Explorer-revisited" rel="noreferrer">cause memory leaks in IE</a> if you are not careful.</li> <li>MDN documentation on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures" rel="noreferrer">JavaScript Closures</a>.</li> </ul>
{ "question_id": 111102, "question_date": "2008-09-21T14:12:07.003Z", "question_score": 7623, "tags": "javascript|function|variables|scope|closures", "answer_id": 111111, "answer_date": "2008-09-21T14:18:18.347Z", "answer_score": 8191 }
Please answer the following Stack Overflow question: Title: How do I revert a Git repository to a previous commit? <p>How do I revert from my current state to a snapshot made on a certain commit?</p> <p>If I do <code>git log</code>, then I get the following output:</p> <pre><code>$ git log commit a867b4af366350be2e7c21b8de9cc6504678a61b` Author: Me &lt;me@me.com&gt; Date: Thu Nov 4 18:59:41 2010 -0400 blah blah blah... commit 25eee4caef46ae64aa08e8ab3f988bc917ee1ce4 Author: Me &lt;me@me.com&gt; Date: Thu Nov 4 05:13:39 2010 -0400 more blah blah blah... commit 0766c053c0ea2035e90f504928f8df3c9363b8bd Author: Me &lt;me@me.com&gt; Date: Thu Nov 4 00:55:06 2010 -0400 And yet more blah blah... commit 0d1d7fc32e5a947fbd92ee598033d85bfc445a50 Author: Me &lt;me@me.com&gt; Date: Wed Nov 3 23:56:08 2010 -0400 Yep, more blah blah. </code></pre> <p>How do I revert to the commit from November 3, i.e. commit <code>0d1d7fc</code>?</p>
<p>This depends a lot on what you mean by &quot;revert&quot;.</p> <h2>Temporarily switch to a different commit</h2> <p>If you want to temporarily go back to it, fool around, then come back to where you are, all you have to do is check out the desired commit:</p> <pre class="lang-sh prettyprint-override"><code># This will detach your HEAD, that is, leave you with no branch checked out: git checkout 0d1d7fc32 </code></pre> <p>Or if you want to make commits while you're there, go ahead and make a new branch while you're at it:</p> <pre><code>git checkout -b old-state 0d1d7fc32 </code></pre> <p>To go back to where you were, just check out the branch you were on again. (If you've made changes, as always when switching branches, you'll have to deal with them as appropriate. You could reset to throw them away; you could stash, checkout, stash pop to take them with you; you could commit them to a branch there if you want a branch there.)</p> <h2>Hard delete unpublished commits</h2> <p>If, on the other hand, you want to really get rid of everything you've done since then, there are two possibilities. One, if you haven't published any of these commits, simply reset:</p> <pre class="lang-sh prettyprint-override"><code># This will destroy any local modifications. # Don't do it if you have uncommitted work you want to keep. git reset --hard 0d1d7fc32 # Alternatively, if there's work to keep: git stash git reset --hard 0d1d7fc32 git stash pop # This saves the modifications, then reapplies that patch after resetting. # You could get merge conflicts, if you've modified things which were # changed since the commit you reset to. </code></pre> <p>If you mess up, you've already thrown away your local changes, but you can at least get back to where you were before by resetting again.</p> <h2>Undo published commits with new commits</h2> <p>On the other hand, if you've published the work, you probably don't want to reset the branch, since that's effectively rewriting history. In that case, you could indeed revert the commits. With Git, revert has a very specific meaning: create a commit with the reverse patch to cancel it out. This way you don't rewrite any history.</p> <pre class="lang-sh prettyprint-override"><code># This will create three separate revert commits: git revert a867b4af 25eee4ca 0766c053 # It also takes ranges. This will revert the last two commits: git revert HEAD~2..HEAD #Similarly, you can revert a range of commits using commit hashes (non inclusive of first hash): git revert 0d1d7fc..a867b4a # Reverting a merge commit git revert -m 1 &lt;merge_commit_sha&gt; # To get just one, you could use `rebase -i` to squash them afterwards # Or, you could do it manually (be sure to do this at top level of the repo) # get your index and work tree into the desired state, without changing HEAD: git checkout 0d1d7fc32 . # Then commit. Be sure and write a good message describing what you just did git commit </code></pre> <p>The <a href="https://git-scm.com/docs/git-revert" rel="noreferrer"><code>git-revert</code> manpage</a> actually covers a lot of this in its description. Another useful link is <a href="https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging#_undoing_merges" rel="noreferrer">this git-scm.com section discussing git-revert</a>.</p> <p>If you decide you didn't want to revert after all, you can revert the revert (as described here) or reset back to before the revert (see the previous section).</p> <p>You may also find this answer helpful in this case:<br /> <a href="https://stackoverflow.com/questions/34519665/how-to-move-head-forward-checkout-revet-reflog-reset/34519716#34519716">How can I move HEAD back to a previous location? (Detached head) &amp; Undo commits</a></p>
{ "question_id": 4114095, "question_date": "2010-11-06T16:58:14.550Z", "question_score": 7617, "tags": "git|git-checkout|git-reset|git-revert", "answer_id": 4114122, "answer_date": "2010-11-06T17:04:54.543Z", "answer_score": 11626 }
Please answer the following Stack Overflow question: Title: Does Python have a ternary conditional operator? <p>Is there a <a href="https://en.wikipedia.org/wiki/%3F:#Python" rel="noreferrer">ternary conditional operator</a> in Python?</p>
<p>Yes, it was <a href="https://mail.python.org/pipermail/python-dev/2005-September/056846.html" rel="noreferrer" title="[Python-Dev] Conditional Expression Resolution">added</a> in version 2.5. The expression syntax is:</p> <pre class="lang-py prettyprint-override"><code>a if condition else b </code></pre> <p>First <code>condition</code> is evaluated, then exactly one of either <code>a</code> or <code>b</code> is evaluated and returned based on the <a href="https://en.wikipedia.org/wiki/Boolean_data_type" rel="noreferrer" title="Boolean data type">Boolean</a> value of <code>condition</code>. If <code>condition</code> evaluates to <code>True</code>, then <code>a</code> is evaluated and returned but <code>b</code> is ignored, or else when <code>b</code> is evaluated and returned but <code>a</code> is ignored.</p> <p>This allows short-circuiting because when <code>condition</code> is true only <code>a</code> is evaluated and <code>b</code> is not evaluated at all, but when <code>condition</code> is false only <code>b</code> is evaluated and <code>a</code> is not evaluated at all.</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; 'true' if True else 'false' 'true' &gt;&gt;&gt; 'true' if False else 'false' 'false' </code></pre> <p>Note that conditionals are an <em>expression</em>, not a <em>statement</em>. This means you can't use <strong>statements</strong> such as <code>pass</code>, or assignments with <code>=</code> (or &quot;augmented&quot; assignments like <code>+=</code>), within a conditional <strong>expression</strong>:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; pass if False else pass File &quot;&lt;stdin&gt;&quot;, line 1 pass if False else pass ^ SyntaxError: invalid syntax &gt;&gt;&gt; # Python parses this as `x = (1 if False else y) = 2` &gt;&gt;&gt; # The `(1 if False else x)` part is actually valid, but &gt;&gt;&gt; # it can't be on the left-hand side of `=`. &gt;&gt;&gt; x = 1 if False else y = 2 File &quot;&lt;stdin&gt;&quot;, line 1 SyntaxError: cannot assign to conditional expression &gt;&gt;&gt; # If we parenthesize it instead... &gt;&gt;&gt; (x = 1) if False else (y = 2) File &quot;&lt;stdin&gt;&quot;, line 1 (x = 1) if False else (y = 2) ^ SyntaxError: invalid syntax </code></pre> <p>(In 3.8 and above, the <code>:=</code> &quot;walrus&quot; operator allows simple assignment of values <em>as an expression</em>, which is then compatible with this syntax. But please don't write code like that; it will quickly become very difficult to understand.)</p> <p>Similarly, because it is an expression, the <code>else</code> part is <em>mandatory</em>:</p> <pre><code># Invalid syntax: we didn't specify what the value should be if the # condition isn't met. It doesn't matter if we can verify that # ahead of time. a if True </code></pre> <p>You can, however, use conditional expressions to assign a variable like so:</p> <pre class="lang-py prettyprint-override"><code>x = a if True else b </code></pre> <p>Or for example to return a value:</p> <pre><code># Of course we should just use the standard library `max`; # this is just for demonstration purposes. def my_max(a, b): return a if a &gt; b else b </code></pre> <p>Think of the conditional expression as switching between two values. We can use it when we are in a 'one value or another' situation, where we will <em>do the same thing</em> with the result, regardless of whether the condition is met. We use the expression to compute the value, and then do something with it. If you need to <em>do something different</em> depending on the condition, then use a normal <code>if</code> <strong>statement</strong> instead.</p> <hr /> <p>Keep in mind that it's frowned upon by some Pythonistas for several reasons:</p> <ul> <li>The order of the arguments is different from those of the classic <code>condition ? a : b</code> ternary operator from many other languages (such as <a href="https://en.wikipedia.org/wiki/C_%28programming_language%29" rel="noreferrer">C</a>, <a href="https://en.wikipedia.org/wiki/C%2B%2B" rel="noreferrer">C++</a>, <a href="https://en.wikipedia.org/wiki/Go_%28programming_language%29" rel="noreferrer">Go</a>, <a href="https://en.wikipedia.org/wiki/Perl" rel="noreferrer">Perl</a>, <a href="https://en.wikipedia.org/wiki/Ruby_%28programming_language%29" rel="noreferrer">Ruby</a>, <a href="https://en.wikipedia.org/wiki/Java_%28programming_language%29" rel="noreferrer">Java</a>, <a href="https://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a>, etc.), which may lead to bugs when people unfamiliar with Python's &quot;surprising&quot; behaviour use it (they may reverse the argument order).</li> <li>Some find it &quot;unwieldy&quot;, since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).</li> <li>Stylistic reasons. (Although the 'inline <code>if</code>' can be <em>really</em> useful, and make your script more concise, it really does complicate your code)</li> </ul> <p>If you're having trouble remembering the order, then remember that when read aloud, you (almost) say what you mean. For example, <code>x = 4 if b &gt; 8 else 9</code> is read aloud as <code>x will be 4 if b is greater than 8 otherwise 9</code>.</p> <p>Official documentation:</p> <ul> <li><a href="https://docs.python.org/3/reference/expressions.html#conditional-expressions" rel="noreferrer" title="Conditional expressions">Conditional expressions</a></li> <li><a href="https://docs.python.org/3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator" rel="noreferrer" title="Is there an equivalent of C’s ”?:” ternary operator?">Is there an equivalent of C’s ”?:” ternary operator?</a></li> </ul>
{ "question_id": 394809, "question_date": "2008-12-27T08:32:18.533Z", "question_score": 7477, "tags": "python|operators|conditional-operator", "answer_id": 394814, "answer_date": "2008-12-27T08:44:19.883Z", "answer_score": 8627 }
Please answer the following Stack Overflow question: Title: var functionName = function() {} vs function functionName() {} <p>I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent.</p> <p>The previous developer used two ways of declaring functions and I can't work out if there is a reason behind it or not.</p> <p>The two ways are:</p> <pre><code>var functionOne = function() { // Some code }; </code></pre> <pre><code>function functionTwo() { // Some code } </code></pre> <p>What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?</p>
<p>The difference is that <code>functionOne</code> is a function expression and so only defined when that line is reached, whereas <code>functionTwo</code> is a function declaration and is defined as soon as its surrounding function or script is executed (due to <a href="http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html" rel="noreferrer">hoisting</a>). </p> <p>For example, a function expression:</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>// TypeError: functionOne is not a function functionOne(); var functionOne = function() { console.log("Hello!"); };</code></pre> </div> </div> </p> <p>And, a function declaration: </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>// Outputs: "Hello!" functionTwo(); function functionTwo() { console.log("Hello!"); }</code></pre> </div> </div> </p> <p>Historically, function declarations defined within blocks were handled inconsistently between browsers. Strict mode (introduced in ES5) resolved this by scoping function declarations to their enclosing block.</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>'use strict'; { // note this block! function functionThree() { console.log("Hello!"); } } functionThree(); // ReferenceError</code></pre> </div> </div> </p>
{ "question_id": 336859, "question_date": "2008-12-03T11:31:07.473Z", "question_score": 7477, "tags": "javascript|function|syntax|idioms", "answer_id": 336868, "answer_date": "2008-12-03T11:37:42.267Z", "answer_score": 5484 }
Please answer the following Stack Overflow question: Title: How to check whether a string contains a substring in JavaScript? <p>Usually I would expect a <code>String.contains()</code> method, but there doesn't seem to be one. </p> <p>What is a reasonable way to check for this?</p>
<p>ECMAScript 6 introduced <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes" rel="noreferrer"><code>String.prototype.includes</code></a>:</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 string = "foo"; const substring = "oo"; console.log(string.includes(substring)); // true</code></pre> </div> </div> </p> <p><code>String.prototype.includes</code> is <strong>case-sensitive</strong> and <a href="https://caniuse.com/#feat=es6-string-includes" rel="noreferrer">is <strong>not</strong> supported by Internet Explorer</a> without a <a href="https://github.com/zloirock/core-js/blob/master/packages/core-js/modules/es.string.includes.js" rel="noreferrer">polyfill</a>.</p> <p>In ECMAScript 5 or older environments, use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf" rel="noreferrer"><code>String.prototype.indexOf</code></a>, which returns -1 when a substring cannot be found:</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 string = "foo"; var substring = "oo"; console.log(string.indexOf(substring) !== -1); // true</code></pre> </div> </div> </p>
{ "question_id": 1789945, "question_date": "2009-11-24T13:04:29.157Z", "question_score": 7413, "tags": "javascript|string|substring|string-matching", "answer_id": 1789952, "answer_date": "2009-11-24T13:05:36.550Z", "answer_score": 15389 }
Please answer the following Stack Overflow question: Title: How do I make Git forget about a file that was tracked, but is now in .gitignore? <p>I put a file that was previously being tracked by Git onto the <code>.gitignore</code> list. However, the file still shows up in <code>git status</code> after it is edited. How do I force Git to completely forget the file?</p>
<p><code>.gitignore</code> will prevent untracked files from being added (without an <code>add -f</code>) to the set of files tracked by Git. However, Git will continue to track any files that are already being tracked.</p> <p>To stop tracking a file, we must remove it from the index:</p> <pre><code>git rm --cached &lt;file&gt; </code></pre> <p>To remove a folder and all files in the folder recursively:</p> <pre><code>git rm -r --cached &lt;folder&gt; </code></pre> <p>The removal of the file from the head revision will happen on the next commit.</p> <p><strong>WARNING: While this will not remove the physical file from your local machine, it will remove the files from other developers' machines on their next <code>git pull</code>.</strong></p>
{ "question_id": 1274057, "question_date": "2009-08-13T19:23:22.140Z", "question_score": 7405, "tags": "git|gitignore|git-rm", "answer_id": 1274447, "answer_date": "2009-08-13T20:40:59.257Z", "answer_score": 7877 }
Please answer the following Stack Overflow question: Title: Why is subtracting these two times (in 1927) giving a strange result? <p>If I run the following program, which parses two date strings referencing times 1 second apart and compares them:</p> <pre><code>public static void main(String[] args) throws ParseException { SimpleDateFormat sf = new SimpleDateFormat(&quot;yyyy-MM-dd HH:mm:ss&quot;); String str3 = &quot;1927-12-31 23:54:07&quot;; String str4 = &quot;1927-12-31 23:54:08&quot;; Date sDt3 = sf.parse(str3); Date sDt4 = sf.parse(str4); long ld3 = sDt3.getTime() /1000; long ld4 = sDt4.getTime() /1000; System.out.println(ld4-ld3); } </code></pre> <p><strong>The output is:</strong></p> <pre><code>353 </code></pre> <p>Why is <code>ld4-ld3</code>, not <code>1</code> (as I would expect from the one-second difference in the times), but <code>353</code>?</p> <p>If I change the dates to times 1 second later:</p> <pre><code>String str3 = &quot;1927-12-31 23:54:08&quot;; String str4 = &quot;1927-12-31 23:54:09&quot;; </code></pre> <p>Then <code>ld4-ld3</code> will be <code>1</code>.</p> <hr /> <p><strong>Java version:</strong></p> <pre class="lang-none prettyprint-override"><code>java version &quot;1.6.0_22&quot; Java(TM) SE Runtime Environment (build 1.6.0_22-b04) Dynamic Code Evolution Client VM (build 0.2-b02-internal, 19.0-b04-internal, mixed mode) </code></pre> <pre class="lang-java prettyprint-override"><code>Timezone(`TimeZone.getDefault()`): sun.util.calendar.ZoneInfo[id=&quot;Asia/Shanghai&quot;, offset=28800000,dstSavings=0, useDaylight=false, transitions=19, lastRule=null] Locale(Locale.getDefault()): zh_CN </code></pre>
<p>It's a time zone change on December 31st in Shanghai.</p> <p>See <a href="http://www.timeanddate.com/worldclock/clockchange.html?n=237&amp;year=1927" rel="noreferrer">this page</a> for details of 1927 in Shanghai. Basically at midnight at the end of 1927, the clocks went back 5 minutes and 52 seconds. So "1927-12-31 23:54:08" actually happened twice, and it looks like Java is parsing it as the <em>later</em> possible instant for that local date/time - hence the difference.</p> <p>Just another episode in the often weird and wonderful world of time zones.</p> <p><strong>EDIT:</strong> Stop press! History changes...</p> <p>The original question would no longer demonstrate quite the same behaviour, if rebuilt with version 2013a of <a href="https://github.com/nodatime/nodatime/blob/master/src/NodaTime.Demo/StackOverflowExamples.cs#L68" rel="noreferrer">TZDB</a>. In 2013a, the result would be 358 seconds, with a transition time of 23:54:03 instead of 23:54:08.</p> <p>I only noticed this because I'm collecting questions like this in Noda Time, in the form of <a href="https://github.com/nodatime/nodatime/blob/master/src/NodaTime.Demo/StackOverflowExamples.cs#L68" rel="noreferrer">unit tests</a>... The test has now been changed, but it just goes to show - not even historical data is safe.</p> <p><strong>EDIT:</strong> History has changed again...</p> <p>In TZDB 2014f, the time of the change has moved to 1900-12-31, and it's now a mere 343 second change (so the time between <code>t</code> and <code>t+1</code> is 344 seconds, if you see what I mean).</p> <p><strong>EDIT:</strong> To answer a question around a transition at 1900... it looks like the Java timezone implementation treats <em>all</em> time zones as simply being in their standard time for any instant before the start of 1900 UTC:</p> <pre><code>import java.util.TimeZone; public class Test { public static void main(String[] args) throws Exception { long startOf1900Utc = -2208988800000L; for (String id : TimeZone.getAvailableIDs()) { TimeZone zone = TimeZone.getTimeZone(id); if (zone.getRawOffset() != zone.getOffset(startOf1900Utc - 1)) { System.out.println(id); } } } } </code></pre> <p>The code above produces no output on my Windows machine. So any time zone which has any offset other than its standard one at the start of 1900 will count that as a transition. TZDB itself has some data going back earlier than that, and doesn't rely on any idea of a "fixed" standard time (which is what <code>getRawOffset</code> assumes to be a valid concept) so other libraries needn't introduce this artificial transition.</p>
{ "question_id": 6841333, "question_date": "2011-07-27T08:15:58.380Z", "question_score": 7398, "tags": "java|date|timezone", "answer_id": 6841479, "answer_date": "2011-07-27T08:31:10.090Z", "answer_score": 11679 }
Please answer the following Stack Overflow question: Title: What is the difference between String and string in C#? <p>What are the differences between these two and which one should I use?</p> <pre><code>string s = &quot;Hello world!&quot;; String s = &quot;Hello world!&quot;; </code></pre>
<p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/string" rel="noreferrer"><code>string</code></a> is an alias in C# for <a href="https://docs.microsoft.com/en-us/dotnet/api/system.string" rel="noreferrer"><code>System.String</code></a>.<br /> So technically, there is no difference. It's like <a href="https://stackoverflow.com/questions/62503/c-int-or-int32-should-i-care"><code>int</code> <em>vs.</em> <code>System.Int32</code></a>.</p> <p>As far as guidelines, it's generally recommended to use <code>string</code> any time you're referring to an object.</p> <p>e.g.</p> <pre><code>string place = &quot;world&quot;; </code></pre> <p>Likewise, I think it's generally recommended to use <code>String</code> if you need to refer specifically to the class.</p> <p>e.g.</p> <pre><code>string greet = String.Format(&quot;Hello {0}!&quot;, place); </code></pre> <h3>This is the style that Microsoft tends to use in <a href="https://docs.microsoft.com/en-us/dotnet/api/system.string.format#examples" rel="noreferrer">their examples</a>.</h3> <p>It appears that the guidance in this area may have changed, as <a href="https://github.com/StyleCop" rel="noreferrer">StyleCop</a> now enforces the use of the C# specific aliases.</p>
{ "question_id": 7074, "question_date": "2008-08-10T07:18:02.320Z", "question_score": 7301, "tags": "c#|.net|string|types|alias", "answer_id": 7077, "answer_date": "2008-08-10T07:22:02.030Z", "answer_score": 6861 }
Please answer the following Stack Overflow question: Title: How do I remove a property from a JavaScript object? <p>Given an object:</p> <pre><code>let myObject = { &quot;ircEvent&quot;: &quot;PRIVMSG&quot;, &quot;method&quot;: &quot;newURI&quot;, &quot;regex&quot;: &quot;^http://.*&quot; }; </code></pre> <p>How do I remove the property <code>regex</code> to end up with the following <code>myObject</code>?</p> <pre><code>let myObject = { &quot;ircEvent&quot;: &quot;PRIVMSG&quot;, &quot;method&quot;: &quot;newURI&quot; }; </code></pre>
<p>To remove a property from an object (mutating the object), you can do it like this:</p> <pre><code>delete myObject.regex; // or, delete myObject['regex']; // or, var prop = &quot;regex&quot;; delete myObject[prop]; </code></pre> <p>Demo <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 myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; delete myObject.regex; console.log(myObject);</code></pre> </div> </div> </p> <p>For anyone interested in reading more about it, Stack Overflow user <a href="https://stackoverflow.com/users/130652/kangax">kangax</a> has written an incredibly in-depth blog post about the <code>delete</code> statement on their blog, <em><a href="http://perfectionkills.com/understanding-delete" rel="noreferrer">Understanding delete</a></em>. It is highly recommended.</p> <p>If you'd like a <em>new</em> object with all the keys of the original except some, you could use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring" rel="noreferrer">destructuring</a>.</p> <p>Demo <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 myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; // assign the key regex to the variable _ indicating it will be unused const {regex: _, ...newObj} = myObject; console.log(newObj); // has no 'regex' key console.log(myObject); // remains unchanged</code></pre> </div> </div> </p>
{ "question_id": 208105, "question_date": "2008-10-16T10:57:45.830Z", "question_score": 7138, "tags": "javascript|object|properties", "answer_id": 208106, "answer_date": "2008-10-16T10:58:53.207Z", "answer_score": 9479 }
Please answer the following Stack Overflow question: Title: What are metaclasses in Python? <p>What are metaclasses? What are they used for?</p>
<p>A metaclass is the class of a class. A class defines how an instance of the class (i.e. an object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass.</p> <p>While in Python you can use arbitrary callables for metaclasses (like <a href="https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python/100037#100037">Jerub</a> shows), the better approach is to make it an actual class itself. <code>type</code> is the usual metaclass in Python. <code>type</code> is itself a class, and it is its own type. You won't be able to recreate something like <code>type</code> purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass <code>type</code>.</p> <p>A metaclass is most commonly used as a class-factory. When you create an object by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass. Combined with the normal <code>__init__</code> and <code>__new__</code> methods, metaclasses therefore allow you to do 'extra things' when creating a class, like registering the new class with some registry or replace the class with something else entirely.</p> <p>When the <code>class</code> statement is executed, Python first executes the body of the <code>class</code> statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be. The metaclass is determined by looking at the baseclasses of the class-to-be (metaclasses are inherited), at the <code>__metaclass__</code> attribute of the class-to-be (if any) or the <code>__metaclass__</code> global variable. The metaclass is then called with the name, bases and attributes of the class to instantiate it.</p> <p>However, metaclasses actually define the <em>type</em> of a class, not just a factory for it, so you can do much more with them. You can, for instance, define normal methods on the metaclass. These metaclass-methods are like classmethods in that they can be called on the class without an instance, but they are also not like classmethods in that they cannot be called on an instance of the class. <code>type.__subclasses__()</code> is an example of a method on the <code>type</code> metaclass. You can also define the normal 'magic' methods, like <code>__add__</code>, <code>__iter__</code> and <code>__getattr__</code>, to implement or change how the class behaves.</p> <p>Here's an aggregated example of the bits and pieces:</p> <pre><code>def make_hook(f): """Decorator to turn 'foo' method into '__foo__'""" f.is_hook = 1 return f class MyType(type): def __new__(mcls, name, bases, attrs): if name.startswith('None'): return None # Go over attributes and see if they should be renamed. newattrs = {} for attrname, attrvalue in attrs.iteritems(): if getattr(attrvalue, 'is_hook', 0): newattrs['__%s__' % attrname] = attrvalue else: newattrs[attrname] = attrvalue return super(MyType, mcls).__new__(mcls, name, bases, newattrs) def __init__(self, name, bases, attrs): super(MyType, self).__init__(name, bases, attrs) # classregistry.register(self, self.interfaces) print "Would register class %s now." % self def __add__(self, other): class AutoClass(self, other): pass return AutoClass # Alternatively, to autogenerate the classname as well as the class: # return type(self.__name__ + other.__name__, (self, other), {}) def unregister(self): # classregistry.unregister(self) print "Would unregister class %s now." % self class MyObject: __metaclass__ = MyType class NoneSample(MyObject): pass # Will print "NoneType None" print type(NoneSample), repr(NoneSample) class Example(MyObject): def __init__(self, value): self.value = value @make_hook def add(self, other): return self.__class__(self.value + other.value) # Will unregister the class Example.unregister() inst = Example(10) # Will fail with an AttributeError #inst.unregister() print inst + inst class Sibling(MyObject): pass ExampleSibling = Example + Sibling # ExampleSibling is now a subclass of both Example and Sibling (with no # content of its own) although it will believe it's called 'AutoClass' print ExampleSibling print ExampleSibling.__mro__ </code></pre>
{ "question_id": 100003, "question_date": "2008-09-19T06:10:46.830Z", "question_score": 6956, "tags": "python|oop|metaclass|python-class|python-datamodel", "answer_id": 100146, "answer_date": "2008-09-19T07:01:58.623Z", "answer_score": 3383 }
Please answer the following Stack Overflow question: Title: How to find all files containing specific text (string) on Linux <p>How do I find all files containing a specific string of text within their file contents?</p> <p>The following doesn't work. It seems to display every single file in the system.</p> <pre class="lang-bash prettyprint-override"><code>find / -type f -exec grep -H 'text-to-find-here' {} \; </code></pre>
<p>Do the following:</p> <pre class="lang-sh prettyprint-override"><code>grep -rnw '/path/to/somewhere/' -e 'pattern' </code></pre> <ul> <li><code>-r</code> or <code>-R</code> is recursive,</li> <li><code>-n</code> is line number, and</li> <li><code>-w</code> stands for match the whole word.</li> <li><code>-l</code> (lower-case L) can be added to just give the file name of matching files.</li> <li><code>-e</code> is the pattern used during the search</li> </ul> <p>Along with these, <code>--exclude</code>, <code>--include</code>, <code>--exclude-dir</code> flags could be used for efficient searching:</p> <ul> <li>This will only search through those files which have .c or .h extensions:</li> </ul> <pre class="lang-sh prettyprint-override"><code>grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e &quot;pattern&quot; </code></pre> <ul> <li>This will exclude searching all the files ending with .o extension:</li> </ul> <pre class="lang-sh prettyprint-override"><code>grep --exclude=\*.o -rnw '/path/to/somewhere/' -e &quot;pattern&quot; </code></pre> <ul> <li>For directories it's possible to exclude one or more directories using the <code>--exclude-dir</code> parameter. For example, this will exclude the dirs dir1/, dir2/ and all of them matching *.dst/:</li> </ul> <pre class="lang-sh prettyprint-override"><code>grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e &quot;pattern&quot; </code></pre> <p>This works very well for me, to achieve almost the same purpose like yours.</p> <p>For more options, see <a href="https://ss64.com/bash/grep.html" rel="noreferrer"><code>man grep</code></a>.</p>
{ "question_id": 16956810, "question_date": "2013-06-06T08:06:45.533Z", "question_score": 6894, "tags": "linux|text|grep|directory|find", "answer_id": 16957078, "answer_date": "2013-06-06T08:21:35.803Z", "answer_score": 12548 }
Please answer the following Stack Overflow question: Title: What is the difference between px, dip, dp, and sp? <p>What is the difference between the units of measure px, dip, dp, and sp?</p>
<p>From the <a href="http://developer.android.com/guide/topics/resources/more-resources.html#Dimension" rel="noreferrer">Android Developer Documentation</a>:</p> <ol> <li> <blockquote> <p><strong>px</strong><br /> <strong>Pixels</strong> - corresponds to actual pixels on the screen.</p> </blockquote> </li> <li> <blockquote> <p><strong>in</strong><br /> <strong>Inches</strong> - based on the physical size of the screen.<br /> 1 Inch OR 2.54 centimeters</p> </blockquote> </li> <li> <blockquote> <p><strong>mm</strong><br /> &gt; <strong>Millimeters</strong> - based on the physical size of the screen.</p> </blockquote> </li> <li> <blockquote> <p><strong>pt</strong><br /> &gt; <strong>Points</strong> - 1/72 of an inch based on the physical size of the screen.</p> </blockquote> </li> <li> <blockquote> <p><strong>dp</strong> or <strong>dip</strong><br /> &gt; <strong>Density</strong>-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both &quot;dip&quot; and &quot;dp&quot;, though &quot;dp&quot; is more consistent with &quot;sp&quot;.</p> </blockquote> </li> <li> <blockquote> <p><strong>sp</strong><br /> &gt; <a href="https://developer.android.com/training/multiscreen/screendensities#TaskUseDP" rel="noreferrer">Scaleable Pixels</a> <strong>OR</strong> <a href="https://developer.android.com/guide/topics/resources/more-resources.html#Dimension" rel="noreferrer">scale-independent pixels</a> - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommended you use this unit when specifying font sizes, so they will be adjusted for both the screen density and the user's preference. Note, the Android documentation is inconsistent on what <code>sp</code> actually stands for, one <a href="https://developer.android.com/guide/topics/resources/more-resources.html#Dimension" rel="noreferrer">doc</a> says &quot;scale-independent pixels&quot;, the <a href="https://developer.android.com/training/multiscreen/screendensities#TaskUseDP" rel="noreferrer">other</a> says &quot;scaleable pixels&quot;.</p> </blockquote> </li> </ol> <p>From <a href="https://blog.mindorks.com/understanding-density-independent-pixel-sp-dp-dip-in-android" rel="noreferrer">Understanding Density Independence In Android</a>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Density Bucket</th> <th>Screen Density</th> <th>Physical Size</th> <th>Pixel Size</th> </tr> </thead> <tbody> <tr> <td>ldpi</td> <td>120 dpi</td> <td>0.5 x 0.5 in</td> <td>0.5 in * 120 dpi = 60x60 px</td> </tr> <tr> <td>mdpi</td> <td>160 dpi</td> <td>0.5 x 0.5 in</td> <td>0.5 in * 160 dpi = 80x80 px</td> </tr> <tr> <td>hdpi</td> <td>240 dpi</td> <td>0.5 x 0.5 in</td> <td>0.5 in * 240 dpi = 120x120 px</td> </tr> <tr> <td>xhdpi</td> <td>320 dpi</td> <td>0.5 x 0.5 in</td> <td>0.5 in * 320 dpi = 160x160 px</td> </tr> <tr> <td>xxhdpi</td> <td>480 dpi</td> <td>0.5 x 0.5 in</td> <td>0.5 in * 480 dpi = 240x240 px</td> </tr> <tr> <td>xxxhdpi</td> <td>640 dpi</td> <td>0.5 x 0.5 in</td> <td>0.5 in * 640 dpi = 320x320 px</td> </tr> </tbody> </table> </div><div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Unit</th> <th>Description</th> <th>Units Per Physical Inch</th> <th>Density Independent?</th> <th>Same Physical Size On Every Screen?</th> </tr> </thead> <tbody> <tr> <td>px</td> <td>Pixels</td> <td>Varies</td> <td>No</td> <td>No</td> </tr> <tr> <td>in</td> <td>Inches</td> <td>1</td> <td>Yes</td> <td>Yes</td> </tr> <tr> <td>mm</td> <td>Millimeters</td> <td>25.4</td> <td>Yes</td> <td>Yes</td> </tr> <tr> <td>pt</td> <td>Points</td> <td>72</td> <td>Yes</td> <td>Yes</td> </tr> <tr> <td>dp</td> <td>Density Independent Pixels</td> <td>~160</td> <td>Yes</td> <td>No</td> </tr> <tr> <td>sp</td> <td>Scale Independent Pixels</td> <td>~160</td> <td>Yes</td> <td>No</td> </tr> </tbody> </table> </div> <p>More info can be also be found in the <a href="https://material.io/design/layout/pixel-density.html" rel="noreferrer">Google Design Documentation</a>.</p>
{ "question_id": 2025282, "question_date": "2010-01-08T03:23:46.680Z", "question_score": 6251, "tags": "android|android-layout|user-interface|dimension|units-of-measurement", "answer_id": 2025541, "answer_date": "2010-01-08T04:41:53.070Z", "answer_score": 6114 }
Please answer the following Stack Overflow question: Title: Move the most recent commit(s) to a new branch with Git <p>How do I move my recent commits on master to a new branch, and reset master to before those commits were made? e.g. From this:</p> <pre><code>master A - B - C - D - E </code></pre> <p>To this:</p> <pre><code>newbranch C - D - E / master A - B </code></pre>
<h2>Moving to an existing branch</h2> <p>If you want to move your commits to an <strong>existing branch</strong>, it will look like this:</p> <pre><code>git checkout existingbranch git merge master git checkout master git reset --hard HEAD~3 # Go back 3 commits. You *will* lose uncommitted work. git checkout existingbranch </code></pre> <p>You can store uncommitted edits to your stash before doing this, using <code>git stash</code>. Once complete, you can retrieve the stashed uncommitted edits with <code>git stash pop</code></p> <h2>Moving to a new branch</h2> <p><strong>WARNING:</strong> This method works because you are creating a new branch with the first command: <code>git branch newbranch</code>. If you want to move commits to an <strong>existing branch</strong> you need to merge your changes into the existing branch before executing <code>git reset --hard HEAD~3</code> (see <em><strong>Moving to an existing branch</strong></em> above). <strong>If you don't merge your changes first, they will be lost.</strong></p> <p>Unless there are other circumstances involved, this can be easily done by branching and rolling back.</p> <pre class="lang-sh prettyprint-override"><code># Note: Any changes not committed will be lost. git branch newbranch # Create a new branch, saving the desired commits git checkout master # checkout master, this is the place you want to go back git reset --hard HEAD~3 # Move master back by 3 commits (Make sure you know how many commits you need to go back) git checkout newbranch # Go to the new branch that still has the desired commits </code></pre> <p>But do make sure how many commits to go back. Alternatively, you can instead of <code>HEAD~3</code>, simply provide the hash of the commit (or the reference like <em>origin/master</em>) you want to &quot;revert back to&quot; on the <em>master</em> (/current) branch, e.g:</p> <pre class="lang-sh prettyprint-override"><code>git reset --hard a1b2c3d4 </code></pre> <p>*1 You will <strong>only</strong> be &quot;losing&quot; commits from the master branch, but don't worry, you'll have those commits in newbranch!</p> <p>Lastly, <a href="https://stackoverflow.com/questions/1628563/move-the-most-recent-commits-to-a-new-branch-with-git#comment42808558_6796816">you may need</a> to force push your latest changes to main repo:</p> <pre class="lang-sh prettyprint-override"><code>git push origin master --force </code></pre> <p><strong>WARNING:</strong> With Git version 2.0 and later, if you later <code>git rebase</code> the new branch upon the original (<code>master</code>) branch, you may need an explicit <code>--no-fork-point</code> option during the rebase to avoid losing the carried-over commits. Having <code>branch.autosetuprebase always</code> set makes this more likely. See <a href="https://stackoverflow.com/a/36463546/1256452">John Mellor's answer</a> for details.</p>
{ "question_id": 1628563, "question_date": "2009-10-27T03:07:34.733Z", "question_score": 6101, "tags": "git|git-branch|branching-and-merging", "answer_id": 1628584, "answer_date": "2009-10-27T03:15:15.320Z", "answer_score": 7862 }
Please answer the following Stack Overflow question: Title: What is the difference between POST and PUT in HTTP? <p>According to <a href="https://www.rfc-editor.org/rfc/rfc2616#section-9.5" rel="noreferrer">RFC 2616, § 9.5</a>, <code>POST</code> is used to <em>create</em> a resource:</p> <blockquote> <p>The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.</p> </blockquote> <p>According to <a href="https://www.rfc-editor.org/rfc/rfc2616#section-9.6" rel="noreferrer">RFC 2616, § 9.6</a>, <code>PUT</code> is used to <em>create or replace</em> a resource:</p> <blockquote> <p>The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI.</p> </blockquote> <p>So which HTTP method should be used to create a resource? Or should both be supported?</p>
<p><strong>Overall:</strong></p> <p>Both PUT and POST can be used for creating.</p> <p>You have to ask, &quot;what are you performing the action upon?&quot;, to distinguish what you should be using. Let's assume you're designing an API for asking questions. If you want to use POST, then you would do that to a list of questions. If you want to use PUT, then you would do that to a particular question.</p> <p><strong>Great, both can be used, so which one should I use in my RESTful design:</strong></p> <p>You do not need to support both PUT and POST.</p> <p>Which you use is up to you. But just remember to use the right one depending on what object you are referencing in the request.</p> <p>Some considerations:</p> <ul> <li>Do you name the URL objects you create explicitly, or let the server decide? If you name them then use PUT. If you let the server decide then use POST.</li> <li>PUT is defined to assume idempotency, so if you PUT an object twice, it should have no additional effect. This is a nice property, so I would use PUT when possible. Just make sure that the PUT-idempotency actually is implemented correctly in the server.</li> <li>You can update or create a resource with PUT with the same object URL</li> <li>With POST you can have 2 requests coming in at the same time making modifications to a URL, and they may update different parts of the object.</li> </ul> <p><strong>An example:</strong></p> <p>I wrote the following as part of <a href="https://stackoverflow.com/questions/256349/what-are-the-best-common-restful-url-verbs-and-actions/256359#256359">another answer on SO regarding this</a>:</p> <blockquote> <p><strong>POST:</strong></p> <p>Used to modify and update a resource</p> <pre><code>POST /questions/&lt;existing_question&gt; HTTP/1.1 Host: www.example.com/ </code></pre> <p>Note that the following is an error:</p> <pre><code>POST /questions/&lt;new_question&gt; HTTP/1.1 Host: www.example.com/ </code></pre> <p>If the URL is not yet created, you should not be using POST to create it while specifying the name. This should result in a 'resource not found' error because <code>&lt;new_question&gt;</code> does not exist yet. You should PUT the <code>&lt;new_question&gt;</code> resource on the server first.</p> <p>You could though do something like this to create a resources using POST:</p> <pre><code>POST /questions HTTP/1.1 Host: www.example.com/ </code></pre> <p>Note that in this case the resource name is not specified, the new objects URL path would be returned to you.</p> <p><strong>PUT:</strong></p> <p>Used to create a resource, or overwrite it. While you specify the resources new URL.</p> <p>For a new resource:</p> <pre><code>PUT /questions/&lt;new_question&gt; HTTP/1.1 Host: www.example.com/ </code></pre> <p>To overwrite an existing resource:</p> <pre><code>PUT /questions/&lt;existing_question&gt; HTTP/1.1 Host: www.example.com/ </code></pre> </blockquote> <p>Additionally, and a bit more concisely, <a href="https://www.rfc-editor.org/rfc/rfc7231#section-4.3.4" rel="noreferrer">RFC 7231 Section 4.3.4 PUT</a> states (emphasis added),</p> <blockquote> <p><strong>4.3.4. PUT</strong></p> <p>The PUT method requests that the state of the target resource be <code>created</code> or <code>replaced</code> with the state defined by the representation enclosed in the request message payload.</p> </blockquote>
{ "question_id": 630453, "question_date": "2009-03-10T14:25:20.390Z", "question_score": 6081, "tags": "http|rest|post|put", "answer_id": 630475, "answer_date": "2009-03-10T14:29:46.930Z", "answer_score": 4718 }
Please answer the following Stack Overflow question: Title: How do I include a JavaScript file in another JavaScript file? <p>How do I include a JavaScript file inside another JavaScript file, similar to <code>@import</code> in CSS?</p>
<p>The old versions of JavaScript had no import, include, or require, so many different approaches to this problem have been developed.</p> <p>But since 2015 (ES6), JavaScript has had the <a href="http://exploringjs.com/es6/ch_modules.html" rel="noreferrer">ES6 modules</a> standard to import modules in Node.js, which is also supported by <a href="https://caniuse.com/#feat=es6-module" rel="noreferrer">most modern browsers</a>.</p> <p>For compatibility with older browsers, build tools like <a href="https://webpack.github.io/" rel="noreferrer">Webpack</a> and <a href="https://rollupjs.org/" rel="noreferrer">Rollup</a> and/or transpilation tools like <a href="https://babeljs.io/" rel="noreferrer">Babel</a> can be used.</p> <h1>ES6 Modules</h1> <p>ECMAScript (ES6) modules have been <a href="https://nodejs.org/api/esm.html" rel="noreferrer">supported in Node.js</a> since v8.5, with the <code>--experimental-modules</code> flag, and since at least Node.js v13.8.0 without the flag. To enable &quot;ESM&quot; (vs. Node.js's previous CommonJS-style module system [&quot;CJS&quot;]) you either use <code>&quot;type&quot;: &quot;module&quot;</code> in <code>package.json</code> or give the files the extension <code>.mjs</code>. (Similarly, modules written with Node.js's previous CJS module can be named <code>.cjs</code> if your default is ESM.)</p> <p>Using <code>package.json</code>:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;type&quot;: &quot;module&quot; } </code></pre> <p>Then <code>module.js</code>:</p> <pre class="lang-javascript prettyprint-override"><code>export function hello() { return &quot;Hello&quot;; } </code></pre> <p>Then <code>main.js</code>:</p> <pre><code>import { hello } from './module.js'; let val = hello(); // val is &quot;Hello&quot;; </code></pre> <p>Using <code>.mjs</code>, you'd have <code>module.mjs</code>:</p> <pre><code>export function hello() { return &quot;Hello&quot;; } </code></pre> <p>Then <code>main.mjs</code>:</p> <pre><code>import { hello } from './module.mjs'; let val = hello(); // val is &quot;Hello&quot;; </code></pre> <h2>ECMAScript modules in browsers</h2> <p>Browsers have had support for loading ECMAScript modules directly (no tools like Webpack required) <a href="https://jakearchibald.com/2017/es-modules-in-browsers/" rel="noreferrer">since</a> Safari 10.1, Chrome 61, Firefox 60, and Edge 16. Check the current support at <a href="https://caniuse.com/#feat=es6-module" rel="noreferrer">caniuse</a>. There is no need to use Node.js' <code>.mjs</code> extension; browsers completely ignore file extensions on modules/scripts.</p> <pre class="lang-javascript prettyprint-override"><code>&lt;script type=&quot;module&quot;&gt; import { hello } from './hello.mjs'; // Or the extension could be just `.js` hello('world'); &lt;/script&gt; </code></pre> <pre class="lang-javascript prettyprint-override"><code>// hello.mjs -- or the extension could be just `.js` export function hello(text) { const div = document.createElement('div'); div.textContent = `Hello ${text}`; document.body.appendChild(div); } </code></pre> <p>Read more at <a href="https://jakearchibald.com/2017/es-modules-in-browsers/" rel="noreferrer">https://jakearchibald.com/2017/es-modules-in-browsers/</a></p> <h3>Dynamic imports in browsers</h3> <p>Dynamic imports let the script load other scripts as needed:</p> <pre class="lang-javascript prettyprint-override"><code>&lt;script type=&quot;module&quot;&gt; import('hello.mjs').then(module =&gt; { module.hello('world'); }); &lt;/script&gt; </code></pre> <p>Read more at <a href="https://developers.google.com/web/updates/2017/11/dynamic-import" rel="noreferrer">https://developers.google.com/web/updates/2017/11/dynamic-import</a></p> <h1>Node.js require</h1> <p>The older CJS module style, still widely used in Node.js, is the <a href="https://nodejs.org/api/modules.html" rel="noreferrer"><code>module.exports</code>/<code>require</code></a> system.</p> <pre class="lang-javascript prettyprint-override"><code>// mymodule.js module.exports = { hello: function() { return &quot;Hello&quot;; } } </code></pre> <pre class="lang-javascript prettyprint-override"><code>// server.js const myModule = require('./mymodule'); let val = myModule.hello(); // val is &quot;Hello&quot; </code></pre> <p>There are other ways for JavaScript to include external JavaScript contents in browsers that do not require preprocessing.</p> <h1>AJAX Loading</h1> <p>You could load an additional script with an AJAX call and then use <code>eval</code> to run it. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using <code>eval</code> also opens the door to bugs, hacks and security issues.</p> <h1>Fetch Loading</h1> <p>Like Dynamic Imports you can load one or many scripts with a <code>fetch</code> call using promises to control order of execution for script dependencies using the <a href="https://www.npmjs.com/package/fetch-inject" rel="noreferrer">Fetch Inject</a> library:</p> <pre><code>fetchInject([ 'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js' ]).then(() =&gt; { console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`) }) </code></pre> <h1>jQuery Loading</h1> <p>The <a href="http://jquery.com/" rel="noreferrer">jQuery</a> library provides loading functionality <a href="http://api.jquery.com/jQuery.getScript/" rel="noreferrer">in one line</a>:</p> <pre class="lang-javascript prettyprint-override"><code>$.getScript(&quot;my_lovely_script.js&quot;, function() { alert(&quot;Script loaded but not necessarily executed.&quot;); }); </code></pre> <h1>Dynamic Script Loading</h1> <p>You could add a script tag with the script URL into the HTML. To avoid the overhead of jQuery, this is an ideal solution.</p> <p>The script can even reside on a different server. Furthermore, the browser evaluates the code. The <code>&lt;script&gt;</code> tag can be injected into either the web page <code>&lt;head&gt;</code>, or inserted just before the closing <code>&lt;/body&gt;</code> tag.</p> <p>Here is an example of how this could work:</p> <pre class="lang-javascript prettyprint-override"><code>function dynamicallyLoadScript(url) { var script = document.createElement(&quot;script&quot;); // create a script DOM node script.src = url; // set its src to the provided URL document.head.appendChild(script); // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead) } </code></pre> <p>This function will add a new <code>&lt;script&gt;</code> tag to the end of the head section of the page, where the <code>src</code> attribute is set to the URL which is given to the function as the first parameter.</p> <p>Both of these solutions are discussed and illustrated in <a href="http://unixpapa.com/js/dyna.html" rel="noreferrer">JavaScript Madness: Dynamic Script Loading</a>.</p> <h1>Detecting when the script has been executed</h1> <p>Now, there is a big issue you must know about. Doing that implies that <em>you remotely load the code</em>. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance. (This applies to both the jQuery method and the manual dynamic script loading method.)</p> <p>It means that if you use these tricks directly, <em>you won't be able to use your newly loaded code the next line after you asked it to be loaded</em>, because it will be still loading.</p> <p>For example: <code>my_lovely_script.js</code> contains <code>MySuperObject</code>:</p> <pre class="lang-javascript prettyprint-override"><code>var js = document.createElement(&quot;script&quot;); js.type = &quot;text/javascript&quot;; js.src = jsFilePath; document.body.appendChild(js); var s = new MySuperObject(); Error : MySuperObject is undefined </code></pre> <p>Then you reload the page hitting <kbd>F5</kbd>. And it works! Confusing...</p> <p><strong>So what to do about it ?</strong></p> <p>Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses an event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. For example:</p> <pre class="lang-javascript prettyprint-override"><code>function loadScript(url, callback) { // Adding the script tag to the head as suggested before var head = document.head; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; // Then bind the event to the callback function. // There are several events for cross browser compatibility. script.onreadystatechange = callback; script.onload = callback; // Fire the loading head.appendChild(script); } </code></pre> <p>Then you write the code you want to use AFTER the script is loaded in a <a href="http://en.wikipedia.org/wiki/Anonymous_function" rel="noreferrer">lambda function</a>:</p> <pre class="lang-javascript prettyprint-override"><code>var myPrettyCode = function() { // Here, do whatever you want }; </code></pre> <p>Then you run all that:</p> <pre class="lang-javascript prettyprint-override"><code>loadScript(&quot;my_lovely_script.js&quot;, myPrettyCode); </code></pre> <p>Note that the script may execute after the DOM has loaded, or before, depending on the browser and whether you included the line <code>script.async = false;</code>. There's a <a href="http://www.html5rocks.com/en/tutorials/speed/script-loading/" rel="noreferrer">great article on Javascript loading in general</a> which discusses this.</p> <h1>Source Code Merge/Preprocessing</h1> <p>As mentioned at the top of this answer, many developers use build/transpilation tool(s) like Parcel, Webpack, or Babel in their projects, allowing them to use upcoming JavaScript syntax, provide backward compatibility for older browsers, combine files, minify, perform code splitting etc.</p>
{ "question_id": 950087, "question_date": "2009-06-04T11:59:50.987Z", "question_score": 6067, "tags": "javascript|file|import|include", "answer_id": 950146, "answer_date": "2009-06-04T12:13:28.403Z", "answer_score": 5227 }
Please answer the following Stack Overflow question: Title: What is the difference between "let" and "var"? <p>ECMAScript 6 introduced <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let" rel="noreferrer">the <code>let</code> statement</a>.</p> <p>I've heard that it's described as a local variable, but I'm still not quite sure how it behaves differently than the var keyword.</p> <p>What are the differences? When should <code>let</code> be used instead of <code>var</code>?</p>
<h1>Scoping rules</h1> <p>The main difference is scoping rules. Variables declared by <code>var</code> keyword are scoped to the immediate function body (hence the function scope) while <code>let</code> variables are scoped to the immediate <em>enclosing</em> block denoted by <code>{ }</code> (hence the block scope).</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 run() { var foo = "Foo"; let bar = "Bar"; console.log(foo, bar); // Foo Bar { var moo = "Mooo" let baz = "Bazz"; console.log(moo, baz); // Mooo Bazz } console.log(moo); // Mooo console.log(baz); // ReferenceError } run();</code></pre> </div> </div> </p> <p>The reason why <code>let</code> keyword was introduced to the language was function scope is confusing and was one of the main sources of bugs in JavaScript.</p> <p>Take a look at this example from <a href="https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example">another Stack Overflow question</a>:</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 = []; // let's create 3 functions for (var i = 0; i &lt; 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 &lt; 3; j++) { // and now let's run each one to see funcs[j](); }</code></pre> </div> </div> </p> <p><code>My value: 3</code> was output to console each time <code>funcs[j]();</code> was invoked since anonymous functions were bound to the same variable.</p> <p>People had to create immediately invoked functions to capture correct values from the loops but that was also hairy.</p> <h1>Hoisting</h1> <p>While variables declared with <code>var</code> keyword are <a href="https://dev.to/godcrampy/the-secret-of-hoisting-in-javascript-egi" rel="noreferrer">hoisted</a> (initialized with <code>undefined</code> before the code is run) which means they are accessible in their enclosing scope even before they are declared:</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 run() { console.log(foo); // undefined var foo = "Foo"; console.log(foo); // Foo } run();</code></pre> </div> </div> </p> <p><code>let</code> variables are not initialized until their definition is evaluated. Accessing them before the initialization results in a <code>ReferenceError</code>. The variable is said to be in &quot;temporal dead zone&quot; from the start of the block until the initialization is processed.</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 checkHoisting() { console.log(foo); // ReferenceError let foo = "Foo"; console.log(foo); // Foo } checkHoisting();</code></pre> </div> </div> </p> <h1>Creating global object property</h1> <p>At the top level, <code>let</code>, unlike <code>var</code>, does not create a property on the global object:</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 foo = "Foo"; // globally scoped let bar = "Bar"; // not allowed to be globally scoped console.log(window.foo); // Foo console.log(window.bar); // undefined</code></pre> </div> </div> </p> <h1>Redeclaration</h1> <p>In strict mode, <code>var</code> will let you re-declare the same variable in the same scope while <code>let</code> raises a SyntaxError.</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>'use strict'; var foo = "foo1"; var foo = "foo2"; // No problem, 'foo1' is replaced with 'foo2'. let bar = "bar1"; let bar = "bar2"; // SyntaxError: Identifier 'bar' has already been declared</code></pre> </div> </div> </p>
{ "question_id": 762011, "question_date": "2009-04-17T20:09:26.777Z", "question_score": 5908, "tags": "javascript|scope|ecmascript-6|var|let", "answer_id": 11444416, "answer_date": "2012-07-12T02:53:34.897Z", "answer_score": 7819 }
Please answer the following Stack Overflow question: Title: How do I discard unstaged changes in Git? <p>How do I discard changes in my working copy that are not in the index?</p>
<p>Another quicker way is:</p> <pre><code>git stash save --keep-index --include-untracked </code></pre> <p>You don't need to include <code>--include-untracked</code> if you don't want to be thorough about it.</p> <p>After that, you can drop that stash with a <code>git stash drop</code> command if you like.</p>
{ "question_id": 52704, "question_date": "2008-09-09T19:33:59.133Z", "question_score": 5867, "tags": "git|version-control", "answer_id": 52719, "answer_date": "2008-09-09T19:39:24.970Z", "answer_score": 3074 }
Please answer the following Stack Overflow question: Title: How do I get the directory where a Bash script is located from within the script itself? <p>How do I get the path of the directory in which a <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash</a> script is located, <em>inside</em> that script?</p> <p>I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:</p> <pre><code>$ ./application </code></pre>
<pre><code>#!/usr/bin/env bash SCRIPT_DIR=$( cd -- &quot;$( dirname -- &quot;${BASH_SOURCE[0]}&quot; )&quot; &amp;&gt; /dev/null &amp;&amp; pwd ) </code></pre> <p>is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.</p> <p>It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:</p> <pre><code>#!/usr/bin/env bash SOURCE=${BASH_SOURCE[0]} while [ -L &quot;$SOURCE&quot; ]; do # resolve $SOURCE until the file is no longer a symlink DIR=$( cd -P &quot;$( dirname &quot;$SOURCE&quot; )&quot; &gt;/dev/null 2&gt;&amp;1 &amp;&amp; pwd ) SOURCE=$(readlink &quot;$SOURCE&quot;) [[ $SOURCE != /* ]] &amp;&amp; SOURCE=$DIR/$SOURCE # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located done DIR=$( cd -P &quot;$( dirname &quot;$SOURCE&quot; )&quot; &gt;/dev/null 2&gt;&amp;1 &amp;&amp; pwd ) </code></pre> <p>This last one will work with any combination of aliases, <code>source</code>, <code>bash -c</code>, symlinks, etc.</p> <p><strong>Beware:</strong> if you <code>cd</code> to a different directory before running this snippet, the result may be incorrect!</p> <p>Also, watch out for <a href="http://bosker.wordpress.com/2012/02/12/bash-scripters-beware-of-the-cdpath/" rel="noreferrer"><code>$CDPATH</code> gotchas</a>, and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling <code>update_terminal_cwd &gt;&amp;2</code> on Mac). Adding <code>&gt;/dev/null 2&gt;&amp;1</code> at the end of your <code>cd</code> command will take care of both possibilities.</p> <p>To understand how it works, try running this more verbose form:</p> <pre><code>#!/usr/bin/env bash SOURCE=${BASH_SOURCE[0]} while [ -L &quot;$SOURCE&quot; ]; do # resolve $SOURCE until the file is no longer a symlink TARGET=$(readlink &quot;$SOURCE&quot;) if [[ $TARGET == /* ]]; then echo &quot;SOURCE '$SOURCE' is an absolute symlink to '$TARGET'&quot; SOURCE=$TARGET else DIR=$( dirname &quot;$SOURCE&quot; ) echo &quot;SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')&quot; SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located fi done echo &quot;SOURCE is '$SOURCE'&quot; RDIR=$( dirname &quot;$SOURCE&quot; ) DIR=$( cd -P &quot;$( dirname &quot;$SOURCE&quot; )&quot; &gt;/dev/null 2&gt;&amp;1 &amp;&amp; pwd ) if [ &quot;$DIR&quot; != &quot;$RDIR&quot; ]; then echo &quot;DIR '$RDIR' resolves to '$DIR'&quot; fi echo &quot;DIR is '$DIR'&quot; </code></pre> <p>And it will print something like:</p> <pre class="lang-none prettyprint-override"><code>SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.') SOURCE is './sym2/scriptdir.sh' DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2' DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2' </code></pre>
{ "question_id": 59895, "question_date": "2008-09-12T20:39:56.860Z", "question_score": 5843, "tags": "bash|directory", "answer_id": 246128, "answer_date": "2008-10-29T08:36:45.740Z", "answer_score": 7670 }
Please answer the following Stack Overflow question: Title: How do I execute a program or call a system command? <p>How do I call an external command within Python as if I'd typed it in a shell or command prompt?</p>
<p>Use the <a href="https://docs.python.org/library/subprocess.html" rel="noreferrer"><code>subprocess</code></a> module in the standard library:</p> <pre class="lang-py prettyprint-override"><code>import subprocess subprocess.run([&quot;ls&quot;, &quot;-l&quot;]) </code></pre> <p>The advantage of <a href="https://docs.python.org/library/subprocess.html#subprocess.run" rel="noreferrer"><code>subprocess.run</code></a> over <a href="https://docs.python.org/library/os.html#os.system" rel="noreferrer"><code>os.system</code></a> is that it is more flexible (you can get the <a href="https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stdout" rel="noreferrer"><code>stdout</code></a>, <a href="https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stderr" rel="noreferrer"><code>stderr</code></a>, the <a href="https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.returncode" rel="noreferrer">&quot;real&quot; status code</a>, better <a href="https://docs.python.org/library/subprocess.html#subprocess.CalledProcessError" rel="noreferrer">error handling</a>, etc...).</p> <p>Even <a href="https://docs.python.org/library/os.html#os.system" rel="noreferrer">the documentation for <code>os.system</code></a> recommends using <code>subprocess</code> instead:</p> <blockquote> <p>The <code>subprocess</code> module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the <a href="https://docs.python.org/library/subprocess.html#subprocess-replacements" rel="noreferrer">Replacing Older Functions with the subprocess Module</a> section in the <a href="https://docs.python.org/library/subprocess.html" rel="noreferrer"><code>subprocess</code></a> documentation for some helpful recipes.</p> </blockquote> <p>On Python 3.4 and earlier, use <code>subprocess.call</code> instead of <code>.run</code>:</p> <pre class="lang-py prettyprint-override"><code>subprocess.call([&quot;ls&quot;, &quot;-l&quot;]) </code></pre>
{ "question_id": 89228, "question_date": "2008-09-18T01:35:30.273Z", "question_score": 5790, "tags": "python|shell|terminal|subprocess|command", "answer_id": 89243, "answer_date": "2008-09-18T01:39:35.257Z", "answer_score": 5512 }
Please answer the following Stack Overflow question: Title: Which equals operator (== vs ===) should be used in JavaScript comparisons? <p>I'm using <a href="http://en.wikipedia.org/wiki/JSLint" rel="noreferrer">JSLint</a> to go through JavaScript, and it's returning many suggestions to replace <code>==</code> (two equals signs) with <code>===</code> (three equals signs) when doing things like comparing <code>idSele_UNVEHtype.value.length == 0</code> inside of an <code>if</code> statement.</p> <p>Is there a performance benefit to replacing <code>==</code> with <code>===</code>? </p> <p>Any performance improvement would be welcomed as many comparison operators exist.</p> <p>If no type conversion takes place, would there be a performance gain over <code>==</code>?</p>
<p>The strict equality operator (<code>===</code>) behaves identically to the abstract equality operator (<code>==</code>) except no type conversion is done, and the types must be the same to be considered equal.</p> <p>Reference: <a href="http://www.c-point.com/javascript_tutorial/jsgrpComparison.htm" rel="noreferrer">Javascript Tutorial: Comparison Operators</a></p> <p>The <code>==</code> operator will compare for equality <em>after doing any necessary type conversions</em>. The <code>===</code> operator will <strong>not</strong> do the conversion, so if two values are not the same type <code>===</code> will simply return <code>false</code>. Both are equally quick.</p> <p>To quote Douglas Crockford's excellent <a href="https://rads.stackoverflow.com/amzn/click/com/0596517742" rel="noreferrer" rel="nofollow noreferrer">JavaScript: The Good Parts</a>,</p> <blockquote> <p>JavaScript has two sets of equality operators: <code>===</code> and <code>!==</code>, and their evil twins <code>==</code> and <code>!=</code>. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then <code>===</code> produces <code>true</code> and <code>!==</code> produces <code>false</code>. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:</p> <pre><code>'' == '0' // false 0 == '' // true 0 == '0' // true false == 'false' // false false == '0' // true false == undefined // false false == null // false null == undefined // true ' \t\r\n ' == 0 // true </code></pre> </blockquote> <p><a href="https://i.stack.imgur.com/yISob.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yISob.png" alt="Equality Comparison Table "></a></p> <blockquote> <p>The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use <code>===</code> and <code>!==</code>. All of the comparisons just shown produce <code>false</code> with the <code>===</code> operator.</p> </blockquote> <hr> <h3>Update:</h3> <p>A good point was brought up by <a href="https://stackoverflow.com/users/165495/casebash">@Casebash</a> in the comments and in <a href="https://stackoverflow.com/users/113570/philippe-leybaert">@Phillipe Laybaert's</a> <a href="https://stackoverflow.com/a/957602/1288">answer</a> concerning objects. For objects, <code>==</code> and <code>===</code> act consistently with one another (except in a special case).</p> <pre><code>var a = [1,2,3]; var b = [1,2,3]; var c = { x: 1, y: 2 }; var d = { x: 1, y: 2 }; var e = "text"; var f = "te" + "xt"; a == b // false a === b // false c == d // false c === d // false e == f // true e === f // true </code></pre> <p>The special case is when you compare a primitive with an object that evaluates to the same primitive, due to its <code>toString</code> or <code>valueOf</code> method. For example, consider the comparison of a string primitive with a string object created using the <code>String</code> constructor.</p> <pre><code>"abc" == new String("abc") // true "abc" === new String("abc") // false </code></pre> <p>Here the <code>==</code> operator is checking the values of the two objects and returning <code>true</code>, but the <code>===</code> is seeing that they're not the same type and returning <code>false</code>. Which one is correct? That really depends on what you're trying to compare. My advice is to bypass the question entirely and just don't use the <code>String</code> constructor to create string objects from string literals.</p> <p><strong>Reference</strong><br> <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3" rel="noreferrer">http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3</a></p>
{ "question_id": 359494, "question_date": "2008-12-11T14:19:49.123Z", "question_score": 5652, "tags": "javascript|operators|equality|equality-operator|identity-operator", "answer_id": 359509, "answer_date": "2008-12-11T14:25:06.430Z", "answer_score": 7047 }
Please answer the following Stack Overflow question: Title: How do I change the URI (URL) for a remote Git repository? <p>I have a repo (origin) on a USB key that I cloned on my hard drive (local). I moved &quot;origin&quot; to a NAS and successfully tested cloning it from here.</p> <p>I would like to know if I can change the URI of &quot;origin&quot; in the settings of &quot;local&quot; so it will now pull from the NAS, and not from the USB key.</p> <p>For now, I can see two solutions:</p> <ul> <li><p>push everything to the USB origin, and copy it to the NAS again (implies a lot of work due to new commits to NAS origin);</p> </li> <li><p>add a new remote to &quot;local&quot; and delete the old one (I fear I'll break my history).</p> </li> </ul>
<p>You can</p> <pre><code>git remote set-url origin new.git.url/here </code></pre> <p>See <a href="https://git-scm.com/docs/git-remote" rel="noreferrer"><code>git help remote</code></a>. You also can edit <code>.git/config</code> and change the URLs there.</p> <p>You're not in any danger of losing history unless you do something very silly (and if you're worried, just make a copy of your repo, since your repo <em>is</em> your history.)</p>
{ "question_id": 2432764, "question_date": "2010-03-12T12:48:47.280Z", "question_score": 5538, "tags": "git|url|git-remote", "answer_id": 2432799, "answer_date": "2010-03-12T12:55:50.670Z", "answer_score": 8868 }
Please answer the following Stack Overflow question: Title: What is the maximum length of a URL in different browsers? <p>What is the maximum length of a URL for each browser?</p> <p>Is a maximum URL length part of the HTTP specification?</p>
<h2>Short answer - de facto limit of 2000 characters</h2> <p>If you keep URLs under 2000 characters, they'll work in virtually any combination of client and server software.</p> <p>If you are targeting particular browsers, see below for more details on specific limits.</p> <h2>Longer answer - first, the standards...</h2> <p><a href="http://www.faqs.org/rfcs/rfc2616.html" rel="noreferrer">RFC 2616</a> (Hypertext Transfer Protocol HTTP/1.1) section 3.2.1 says</p> <blockquote> <p>The HTTP protocol does not place any a priori limit on the length of a URI. Servers MUST be able to handle the URI of any resource they serve, and SHOULD be able to handle URIs of unbounded length if they provide GET-based forms that could generate such URIs. A server SHOULD return 414 (Request-URI Too Long) status if a URI is longer than the server can handle (see section 10.4.15).</p> </blockquote> <p>That RFC has been obsoleted by <a href="https://www.rfc-editor.org/rfc/rfc7230#section-3.1.1" rel="noreferrer">RFC7230</a> which is a refresh of the HTTP/1.1 specification. It contains similar language, but also goes on to suggest this:</p> <blockquote> <p>Various ad hoc limitations on request-line length are found in practice. It is RECOMMENDED that all HTTP senders and recipients support, at a minimum, request-line lengths of 8000 octets.</p> </blockquote> <h2>...and the reality</h2> <p>That's what the <em>standards</em> say. For the <em>reality</em>, there was an article on <a href="https://web.archive.org/web/20190902193246/https://boutell.com/newfaq/misc/urllength.html" rel="noreferrer">boutell.com</a> (link goes to Internet Archive backup) that discussed what individual browser and server implementations will support. The executive summary is:</p> <blockquote> <p>Extremely long URLs are usually a mistake. <strong>URLs over 2,000 characters will not work in the most popular web browsers.</strong> Don't use them if you intend your site to work for the majority of Internet users.</p> </blockquote> <p>(Note: this is a quote from an article written in <em>2006</em>, but in 2015 IE's declining usage means that longer URLs <em>do</em> work for the majority. However, IE still has the limitation...)</p> <h2>Internet Explorer's limitations...</h2> <p><a href="https://support.microsoft.com/en-us/kb/208427" rel="noreferrer">IE8's maximum URL length is 2083 chars</a>, and it seems <a href="https://stackoverflow.com/questions/3721034/how-long-an-url-can-internet-explorer-9-take">IE9 has a similar limit</a>.</p> <p>I've tested IE10 and the address bar will only accept 2083 chars. You can <em>click</em> a URL which is longer than this, but the address bar will still only show 2083 characters of this link.</p> <p>There's a <a href="https://blogs.msdn.microsoft.com/ieinternals/2014/08/13/url-length-limits/" rel="noreferrer">nice writeup on the IE Internals blog</a> which goes into some of the background to this.</p> <p>There are mixed reports IE11 supports longer URLs - see comments below. Given some people report issues, the general advice still stands.</p> <h2>Search engines like URLs &lt; 2048 chars...</h2> <p>Be aware that the <a href="http://www.sitemaps.org/protocol.html" rel="noreferrer">sitemaps protocol</a>, which allows a site to inform search engines about available pages, has a limit of 2048 characters in a URL. If you intend to use sitemaps, a limit has been decided for you! (see <a href="https://stackoverflow.com/a/7056886/6521">Calin-Andrei Burloiu's answer</a> below)</p> <p>There's also some research from 2010 into the <a href="https://web.archive.org/web/20111110004006/http://www.seomofo.com/experiments/title-and-h1-of-this-post-but-for-the-sake-of-keyword-prominence-stuffing-im-going-to-mention-it-again-using-various-synonyms-stemmed-variations-and-of-coursea-big-fat-prominent-font-size-heres-the-stumper-that-stumped-me-what-is-the-max-number-of-chars-in-a-url-that-google-is-willing-to-crawl-and-index-for-whatever-reason-i-thought-i-had-read-somewhere-that-googles-limit-on-urls-was-255-characters-but-that-turned-out-to-be-wrong-so-maybe-i-just-made-that-number-up-the-best-answer-i-could-find-was-this-quote-from-googles-webmaster-trends-analyst-john-mueller-we-can-certainly-crawl-and-index-urls-over-1000-characters-long-but-that-doesnt-mean-that-its-a-good-practice-the-setup-for-this-experiment-is-going-to-be-pretty-simple-im-going-to-edit-the-permalink-of-this-post-to-be-really-really-long-then-im-going-to-see-if-google-indexes-it-i-might-even-see-if-yahoo-and-bing-index-iteven-though-no-one-really-cares-what-those-assholes-are-doing-url-character-limits-unrelated-to-google-the-question-now-is-how-many-characters-should-i-make-the-url-of-this-post-there-are-a-couple-of-sources-ill-reference-to-help-me-make-this-decision-the-first-is-this-quote-from-the-microsoft-support-pages-microsoft-internet-explorer-has-a-maximum-uniform-resource-locator-url-length-of-2083-characters-internet-explorer-also-has-a-maximum-path-length-of-2048-characters-this-limit-applies-to-both-post-request-and-get-request-urls-the-second-source-ill-cite-is-the-http-11-protocol-which-says-the-http-protocol-does-not-place-any-a-priori-limit-on-the-length-of-a-uri-servers-must-be-able-to-handle-the-uri-of-any-resource-they-serve-and-should-be-able-to-handle-uris-of-unbounded-length-if-they-provide-get-based-forms-that-could-generate-such-uris-a-server-should-return-414-request-uri-too-long-status-if-a-uri-is-longer.html" rel="noreferrer">maximum URL length that search engines will crawl and index</a>. They found the limit was 2047 chars, which appears allied to the sitemap protocol spec. However, they also found the Google <a href="http://en.wikipedia.org/wiki/Search_engine_results_page" rel="noreferrer">SERP</a> tool wouldn't cope with URLs longer than 1855 chars.</p> <h2>CDNs have limits</h2> <p>CDNs also impose limits on URI length, and will return a <code>414 Too long request</code> when these limits are reached, for example:</p> <ul> <li><a href="https://docs.fastly.com/en/guides/resource-limits#request-and-header-limits" rel="noreferrer">Fastly</a> 8Kb</li> <li><a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html#limits-general" rel="noreferrer">CloudFront</a> 8Kb</li> <li><a href="https://support.cloudflare.com/hc/en-us/articles/115003014512-4xx-Client-Error#code_414" rel="noreferrer">CloudFlare</a> 16Kb</li> </ul> <p>(credit to timrs2998 for providing that info in the comments)</p> <h2>Additional browser roundup</h2> <p>I tested the following against an Apache 2.4 server configured with a very large <a href="https://httpd.apache.org/docs/current/mod/core.html#limitrequestline" rel="noreferrer">LimitRequestLine</a> and <a href="https://httpd.apache.org/docs/current/mod/core.html#limitrequestfieldsize" rel="noreferrer">LimitRequestFieldSize</a>.</p> <pre><code>Browser Address bar document.location or anchor tag ------------------------------------------ Chrome 32779 &gt;64k Android 8192 &gt;64k Firefox &gt;64k &gt;64k Safari &gt;64k &gt;64k IE11 2047 5120 Edge 16 2047 10240 </code></pre> <p>See also <a href="https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers/31250734#31250734">this answer</a> from Matas Vaitkevicius below.</p> <h2>Is this information up to date?</h2> <p>This is a popular question, and as the original research is ~14 years old I'll try to keep it up to date: As of <strong>Jan 2021</strong>, the advice still stands. Even though IE11 may possibly accept longer URLs, the ubiquity of older IE installations plus the search engine limitations mean staying under 2000 chars is the best general policy.</p>
{ "question_id": 417142, "question_date": "2009-01-06T16:14:30.410Z", "question_score": 5471, "tags": "http|url|browser", "answer_id": 417184, "answer_date": "2009-01-06T16:22:18.443Z", "answer_score": 5691 }
Please answer the following Stack Overflow question: Title: How can I validate an email address in JavaScript? <p>I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?</p>
<p>Using <a href="http://en.wikipedia.org/wiki/Regular_expression" rel="noreferrer">regular expressions</a> is probably the best way. You can see a bunch of tests <a href="http://jsfiddle.net/ghvj4gy9/embedded/result,js/" rel="noreferrer">here</a> (taken from <a href="https://cs.chromium.org/chromium/src/third_party/blink/web_tests/fast/forms/resources/ValidityState-typeMismatch-email.js?q=ValidityState-typeMismatch-email.js&amp;sq=package:chromium&amp;dr" rel="noreferrer">chromium</a>)</p> <pre class="lang-js prettyprint-override"><code>const validateEmail = (email) =&gt; { return String(email) .toLowerCase() .match( /^(([^&lt;&gt;()[\]\\.,;:\s@&quot;]+(\.[^&lt;&gt;()[\]\\.,;:\s@&quot;]+)*)|(&quot;.+&quot;))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ); }; </code></pre> <p>Here's the example of a regular expression that accepts unicode:</p> <pre class="lang-js prettyprint-override"><code>const re = /^(([^&lt;&gt;()[\]\.,;:\s@\&quot;]+(\.[^&lt;&gt;()[\]\.,;:\s@\&quot;]+)*)|(\&quot;.+\&quot;))@(([^&lt;&gt;()[\]\.,;:\s@\&quot;]+\.)+[^&lt;&gt;()[\]\.,;:\s@\&quot;]{2,})$/i; </code></pre> <p>But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well.</p> <p>Here's an example of the above in action:</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 validateEmail = (email) =&gt; { return email.match( /^(([^&lt;&gt;()[\]\\.,;:\s@\"]+(\.[^&lt;&gt;()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ); }; const validate = () =&gt; { const $result = $('#result'); const email = $('#email').val(); $result.text(''); if (validateEmail(email)) { $result.text(email + ' is valid :)'); $result.css('color', 'green'); } else { $result.text(email + ' is not valid :('); $result.css('color', 'red'); } return false; } $('#email').on('input', validate);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;label for="email"&gt;Enter an email address: &lt;/label&gt; &lt;input id="email" /&gt; &lt;h2 id="result"&gt;&lt;/h2&gt;</code></pre> </div> </div> </p>
{ "question_id": 46155, "question_date": "2008-09-05T16:10:11.093Z", "question_score": 5434, "tags": "javascript|html|regex|email-validation", "answer_id": 46181, "answer_date": "2008-09-05T16:15:34.747Z", "answer_score": 6290 }
Please answer the following Stack Overflow question: Title: How do I reset or revert a file to a specific revision? <p>How do I revert a modified file to its previous revision at a specific commit hash (which I determined via <a href="https://git-scm.com/docs/git-log" rel="noreferrer"><code>git log</code></a> and <a href="https://git-scm.com/docs/git-diff" rel="noreferrer"><code>git diff</code></a>)?</p>
<p>Assuming the hash of the commit you want is <code>c5f567</code>:</p> <pre><code>git checkout c5f567 -- file1/to/restore file2/to/restore </code></pre> <p>The <a href="https://git-scm.com/docs/git-checkout" rel="noreferrer">git checkout</a> man page gives more information.</p> <p>If you want to revert to the commit before <code>c5f567</code>, append <code>~1</code> (where 1 is the number of commits you want to go back, it can be anything):</p> <pre><code>git checkout c5f567~1 -- file1/to/restore file2/to/restore </code></pre> <p>As a side note, I've always been uncomfortable with this command because it's used for both ordinary things (changing between branches) and unusual, destructive things (discarding changes in the working directory).</p> <hr /> <p>There is also a new <a href="https://git-scm.com/docs/git-restore" rel="noreferrer"><code>git restore</code></a> command that is specifically designed for restoring working copy files that have been modified. If your git is new enough you can use this command, but the documentation comes with a warning:</p> <blockquote> <p>THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.</p> </blockquote>
{ "question_id": 215718, "question_date": "2008-10-18T23:34:02.570Z", "question_score": 5426, "tags": "git|version-control|git-checkout", "answer_id": 215731, "answer_date": "2008-10-18T23:39:35.210Z", "answer_score": 7335 }
Please answer the following Stack Overflow question: Title: How can I safely create a nested directory? <p>How do I check if the directory into which a file is going to be written does exist, and if it does not, create the directory using Python?</p>
<p>On Python ≥ 3.5, use <a href="https://docs.python.org/library/pathlib.html#pathlib.Path.mkdir" rel="noreferrer"><code>pathlib.Path.mkdir</code></a>:</p> <pre><code>from pathlib import Path Path("/my/directory").mkdir(parents=True, exist_ok=True) </code></pre> <p>For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:</p> <p>Try <a href="https://docs.python.org/library/os.path.html#os.path.exists" rel="noreferrer"><code>os.path.exists</code></a>, and consider <a href="https://docs.python.org/library/os.html#os.makedirs" rel="noreferrer"><code>os.makedirs</code></a> for the creation.</p> <pre><code>import os if not os.path.exists(directory): os.makedirs(directory) </code></pre> <p>As noted in comments and elsewhere, there's a race condition &ndash; if the directory is created between the <code>os.path.exists</code> and the <code>os.makedirs</code> calls, the <code>os.makedirs</code> will fail with an <code>OSError</code>. Unfortunately, blanket-catching <code>OSError</code> and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.</p> <p>One option would be to trap the <code>OSError</code> and examine the embedded error code (see <a href="https://stackoverflow.com/questions/273698/is-there-a-cross-platform-way-of-getting-information-from-pythons-oserror">Is there a cross-platform way of getting information from Python’s OSError</a>):</p> <pre><code>import os, errno try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise </code></pre> <p>Alternatively, there could be a second <code>os.path.exists</code>, but suppose another created the directory after the first check, then removed it before the second one &ndash; we could still be fooled. </p> <p>Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.</p> <p>Modern versions of Python improve this code quite a bit, both by exposing <a href="https://docs.python.org/3.3/library/exceptions.html?#FileExistsError" rel="noreferrer"><code>FileExistsError</code></a> (in 3.3+)...</p> <pre><code>try: os.makedirs("path/to/directory") except FileExistsError: # directory already exists pass </code></pre> <p>...and by allowing <a href="https://docs.python.org/3.2/library/os.html#os.makedirs" rel="noreferrer">a keyword argument to <code>os.makedirs</code> called <code>exist_ok</code></a> (in 3.2+).</p> <pre><code>os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists. </code></pre>
{ "question_id": 273192, "question_date": "2008-11-07T18:56:45.670Z", "question_score": 5316, "tags": "python|exception|path|directory|operating-system", "answer_id": 273227, "answer_date": "2008-11-07T19:06:07.663Z", "answer_score": 6675 }
Please answer the following Stack Overflow question: Title: How do I push a new local branch to a remote Git repository and track it too? <p>How do I:</p> <ol> <li><p>Create a local branch from another branch (via <code>git branch</code> or <code>git checkout -b</code>).</p> </li> <li><p>Push the local branch to the remote repository (i.e. publish), but make it trackable so that <code>git pull</code> and <code>git push</code> will work.</p> </li> </ol>
<p>In Git 1.7.0 and later, you can checkout a new branch:</p> <pre><code>git checkout -b &lt;branch&gt; </code></pre> <p>Edit files, add and commit. Then <a href="https://git-scm.com/docs/git-push" rel="noreferrer">push with the <code>-u</code> (short for <code>--set-upstream</code>)</a> option:</p> <pre><code>git push -u origin &lt;branch&gt; </code></pre> <p>Git will set up the tracking information during the push.</p>
{ "question_id": 2765421, "question_date": "2010-05-04T12:58:34.517Z", "question_score": 5295, "tags": "git|repository|git-branch|git-push|git-remote", "answer_id": 6232535, "answer_date": "2011-06-03T20:50:29.507Z", "answer_score": 7955 }
Please answer the following Stack Overflow question: Title: How do I replace all occurrences of a string in JavaScript? <p>Given a string:</p> <pre><code>s = &quot;Test abc test test abc test test test abc test test abc&quot;; </code></pre> <p>This seems to only remove the first occurrence of <code>abc</code> in the string above:</p> <pre><code>s = s.replace('abc', ''); </code></pre> <p>How do I replace <em>all</em> occurrences of it?</p>
<p>In the latest versions of most popular browsers, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll" rel="nofollow noreferrer"><code>replaceAll</code></a> as shown here:</p> <pre class="lang-js prettyprint-override"><code>let result = &quot;1 abc 2 abc 3&quot;.replaceAll(&quot;abc&quot;, &quot;xyz&quot;); // `result` is &quot;1 xyz 2 xyz 3&quot; </code></pre> <p>But check <a href="https://caniuse.com/?search=replaceAll" rel="nofollow noreferrer">Can I use</a> or another compatibility table first to make sure the browsers you're targeting have added support for it first.</p> <hr /> <p>For Node.js and compatibility with older/non-current browsers:</p> <p><strong>Note: Don't use the following solution in performance critical code.</strong></p> <p>As an alternative to regular expressions for a simple literal string, you could use</p> <pre class="lang-js prettyprint-override"><code>str = &quot;Test abc test test abc test...&quot;.split(&quot;abc&quot;).join(&quot;&quot;); </code></pre> <p>The general pattern is</p> <pre class="lang-js prettyprint-override"><code>str.split(search).join(replacement) </code></pre> <p>This used to be faster in some cases than using <code>replaceAll</code> and a regular expression, but that doesn't seem to be the case anymore in modern browsers.</p> <p>Benchmark: <a href="https://jsben.ch/TZYzj" rel="nofollow noreferrer">https://jsben.ch/TZYzj</a></p> <h3>Conclusion:</h3> <p>If you have a performance-critical use case (e.g., processing hundreds of strings), use the regular expression method. But for most typical use cases, this is well worth not having to worry about special characters.</p>
{ "question_id": 1144783, "question_date": "2009-07-17T17:53:46.750Z", "question_score": 5261, "tags": "javascript|string|replace", "answer_id": 1145525, "answer_date": "2009-07-17T20:29:12.147Z", "answer_score": 2320 }
Please answer the following Stack Overflow question: Title: What is a plain English explanation of "Big O" notation? <p>I'd prefer as little formal definition as possible and simple mathematics.</p>
<p>Quick note, my answer is almost certainly confusing <a href="http://en.wikipedia.org/wiki/Big_O_notation" rel="noreferrer">Big Oh notation</a> (which is an upper bound) with Big Theta notation &quot;Θ&quot; (which is a two-side bound). But in my experience, this is actually typical of discussions in non-academic settings. Apologies for any confusion caused.</p> <hr /> <p>BigOh complexity can be visualized with this graph:</p> <p><a href="https://i.stack.imgur.com/WcBRI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WcBRI.png" alt="Big Oh Analysis" /></a></p> <p>The simplest definition I can give for Big Oh notation is this:</p> <p><strong>Big Oh notation is a relative representation of the complexity of an algorithm.</strong></p> <p>There are some important and deliberately chosen words in that sentence:</p> <blockquote> <ul> <li><strong>relative:</strong> you can only compare apples to apples. You can't compare an algorithm that does arithmetic multiplication to an algorithm that sorts a list of integers. But a comparison of two algorithms to do arithmetic operations (one multiplication, one addition) will tell you something meaningful;</li> <li><strong>representation:</strong> BigOh (in its simplest form) reduces the comparison between algorithms to a single variable. That variable is chosen based on observations or assumptions. For example, sorting algorithms are typically compared based on comparison operations (comparing two nodes to determine their relative ordering). This assumes that comparison is expensive. But what if the comparison is cheap but swapping is expensive? It changes the comparison; and</li> <li><strong>complexity:</strong> if it takes me one second to sort 10,000 elements, how long will it take me to sort one million? Complexity in this instance is a relative measure to something else.</li> </ul> </blockquote> <p>Come back and reread the above when you've read the rest.</p> <p>The best example of BigOh I can think of is doing arithmetic. Take two numbers (123456 and 789012). The basic arithmetic operations we learned in school were:</p> <blockquote> <ul> <li>addition;</li> <li>subtraction;</li> <li>multiplication; and</li> <li>division.</li> </ul> </blockquote> <p>Each of these is an operation or a problem. A method of solving these is called an <strong>algorithm</strong>.</p> <p>The addition is the simplest. You line the numbers up (to the right) and add the digits in a column writing the last number of that addition in the result. The 'tens' part of that number is carried over to the next column.</p> <p>Let's assume that the addition of these numbers is the most expensive operation in this algorithm. It stands to reason that to add these two numbers together we have to add together 6 digits (and possibly carry a 7th). If we add two 100 digit numbers together we have to do 100 additions. If we add <strong>two</strong> 10,000 digit numbers we have to do 10,000 additions.</p> <p>See the pattern? The <strong>complexity</strong> (being the number of operations) is directly proportional to the number of digits <em>n</em> in the larger number. We call this <strong>O(n)</strong> or <strong>linear complexity</strong>.</p> <p>Subtraction is similar (except you may need to borrow instead of carry).</p> <p>Multiplication is different. You line the numbers up, take the first digit in the bottom number and multiply it in turn against each digit in the top number and so on through each digit. So to multiply our two 6 digit numbers we must do 36 multiplications. We may need to do as many as 10 or 11 column adds to get the end result too.</p> <p>If we have two 100-digit numbers we need to do 10,000 multiplications and 200 adds. For two one million digit numbers we need to do one trillion (10<sup>12</sup>) multiplications and two million adds.</p> <p>As the algorithm scales with n-<em>squared</em>, this is <strong>O(n<sup>2</sup>)</strong> or <strong>quadratic complexity</strong>. This is a good time to introduce another important concept:</p> <p><strong>We only care about the most significant portion of complexity.</strong></p> <p>The astute may have realized that we could express the number of operations as: n<sup>2</sup> + 2n. But as you saw from our example with two numbers of a million digits apiece, the second term (2n) becomes insignificant (accounting for 0.0002% of the total operations by that stage).</p> <p>One can notice that we've assumed the worst case scenario here. While multiplying 6 digit numbers, if one of them has 4 digits and the other one has 6 digits, then we only have 24 multiplications. Still, we calculate the worst case scenario for that 'n', i.e when both are 6 digit numbers. Hence Big Oh notation is about the Worst-case scenario of an algorithm.</p> <h1>The Telephone Book</h1> <p>The next best example I can think of is the telephone book, normally called the White Pages or similar but it varies from country to country. But I'm talking about the one that lists people by surname and then initials or first name, possibly address and then telephone numbers.</p> <p>Now if you were instructing a computer to look up the phone number for &quot;John Smith&quot; in a telephone book that contains 1,000,000 names, what would you do? Ignoring the fact that you could guess how far in the S's started (let's assume you can't), what would you do?</p> <p>A typical implementation might be to open up to the middle, take the 500,000<sup>th</sup> and compare it to &quot;Smith&quot;. If it happens to be &quot;Smith, John&quot;, we just got really lucky. Far more likely is that &quot;John Smith&quot; will be before or after that name. If it's after we then divide the last half of the phone book in half and repeat. If it's before then we divide the first half of the phone book in half and repeat. And so on.</p> <p>This is called a <strong>binary search</strong> and is used every day in programming whether you realize it or not.</p> <p>So if you want to find a name in a phone book of a million names you can actually find any name by doing this at most 20 times. In comparing search algorithms we decide that this comparison is our 'n'.</p> <blockquote> <ul> <li>For a phone book of 3 names it takes 2 comparisons (at most).</li> <li>For 7 it takes at most 3.</li> <li>For 15 it takes 4.</li> <li>…</li> <li>For 1,000,000 it takes 20.</li> </ul> </blockquote> <p>That is staggeringly good, isn't it?</p> <p>In BigOh terms this is <strong>O(log n)</strong> or <strong>logarithmic complexity</strong>. Now the logarithm in question could be ln (base e), log<sub>10</sub>, log<sub>2</sub> or some other base. It doesn't matter it's still O(log n) just like O(2n<sup>2</sup>) and O(100n<sup>2</sup>) are still both O(n<sup>2</sup>).</p> <p>It's worthwhile at this point to explain that BigOh can be used to determine three cases with an algorithm:</p> <blockquote> <ul> <li><strong>Best Case:</strong> In the telephone book search, the best case is that we find the name in one comparison. This is <strong>O(1)</strong> or <strong>constant complexity</strong>;</li> <li><strong>Expected Case:</strong> As discussed above this is O(log n); and</li> <li><strong>Worst Case:</strong> This is also O(log n).</li> </ul> </blockquote> <p>Normally we don't care about the best case. We're interested in the expected and worst case. Sometimes one or the other of these will be more important.</p> <p>Back to the telephone book.</p> <p>What if you have a phone number and want to find a name? The police have a reverse phone book but such look-ups are denied to the general public. Or are they? Technically you can reverse look-up a number in an ordinary phone book. How?</p> <p>You start at the first name and compare the number. If it's a match, great, if not, you move on to the next. You have to do it this way because the phone book is <strong>unordered</strong> (by phone number anyway).</p> <p>So to find a name given the phone number (reverse lookup):</p> <blockquote> <ul> <li><strong>Best Case:</strong> O(1);</li> <li><strong>Expected Case:</strong> O(n) (for 500,000); and</li> <li><strong>Worst Case:</strong> O(n) (for 1,000,000).</li> </ul> </blockquote> <h1>The Traveling Salesman</h1> <p>This is quite a famous problem in computer science and deserves a mention. In this problem, you have N towns. Each of those towns is linked to 1 or more other towns by a road of a certain distance. The Traveling Salesman problem is to find the shortest tour that visits every town.</p> <p>Sounds simple? Think again.</p> <p>If you have 3 towns A, B, and C with roads between all pairs then you could go:</p> <blockquote> <ul> <li>A → B → C</li> <li>A → C → B</li> <li>B → C → A</li> <li>B → A → C</li> <li>C → A → B</li> <li>C → B → A</li> </ul> </blockquote> <p>Well, actually there's less than that because some of these are equivalent (A → B → C and C → B → A are equivalent, for example, because they use the same roads, just in reverse).</p> <p>In actuality, there are 3 possibilities.</p> <blockquote> <ul> <li>Take this to 4 towns and you have (iirc) 12 possibilities.</li> <li>With 5 it's 60.</li> <li>6 becomes 360.</li> </ul> </blockquote> <p>This is a function of a mathematical operation called a <strong>factorial</strong>. Basically:</p> <blockquote> <ul> <li>5! = 5 × 4 × 3 × 2 × 1 = 120</li> <li>6! = 6 × 5 × 4 × 3 × 2 × 1 = 720</li> <li>7! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040</li> <li>…</li> <li>25! = 25 × 24 × … × 2 × 1 = 15,511,210,043,330,985,984,000,000</li> <li>…</li> <li>50! = 50 × 49 × … × 2 × 1 = 3.04140932 × 10<sup>64</sup></li> </ul> </blockquote> <p>So the BigOh of the Traveling Salesman problem is <strong>O(n!)</strong> or <strong>factorial or combinatorial complexity</strong>.</p> <p><strong>By the time you get to 200 towns there isn't enough time left in the universe to solve the problem with traditional computers.</strong></p> <p>Something to think about.</p> <h1>Polynomial Time</h1> <p>Another point I wanted to make a quick mention of is that any algorithm that has a complexity of <strong>O(n<sup>a</sup>)</strong> is said to have <strong>polynomial complexity</strong> or is solvable in <strong>polynomial time</strong>.</p> <p>O(n), O(n<sup>2</sup>) etc. are all polynomial time. Some problems cannot be solved in polynomial time. Certain things are used in the world because of this. <a href="https://en.wikipedia.org/wiki/Public-key_cryptography" rel="noreferrer">Public Key Cryptography</a> is a prime example. It is computationally hard to find two prime factors of a very large number. If it wasn't, we couldn't use the public key systems we use.</p> <p>Anyway, that's it for my (hopefully plain English) explanation of BigOh (revised).</p>
{ "question_id": 487258, "question_date": "2009-01-28T11:10:32.043Z", "question_score": 5261, "tags": "algorithm|complexity-theory|computer-science|big-o|time-complexity", "answer_id": 487278, "answer_date": "2009-01-28T11:18:57.817Z", "answer_score": 6995 }
Please answer the following Stack Overflow question: Title: How do I resolve merge conflicts in a Git repository? <p>How do I resolve merge conflicts in my Git repository?</p>
<p>Try:</p> <pre class="lang-bash prettyprint-override"><code>git mergetool </code></pre> <p>It opens a GUI that steps you through each conflict, and you get to choose how to merge. Sometimes it requires a bit of hand editing afterwards, but usually it's enough by itself. It is much better than doing the whole thing by hand certainly.</p> <hr /> <p>As per <a href="https://stackoverflow.com/questions/161813/how-to-resolve-merge-conflicts-in-git-repository#comment6881558_163659">Josh Glover's comment</a>:</p> <blockquote> <p>[This command] doesn't necessarily open a GUI unless you install one. Running <code>git mergetool</code> for me resulted in <code>vimdiff</code> being used. You can install one of the following tools to use it instead: <code>meld</code>, <code>opendiff</code>, <code>kdiff3</code>, <code>tkdiff</code>, <code>xxdiff</code>, <code>tortoisemerge</code>, <code>gvimdiff</code>, <code>diffuse</code>, <code>ecmerge</code>, <code>p4merge</code>, <code>araxis</code>, <code>vimdiff</code>, <code>emerge</code>.</p> </blockquote> <hr /> <p>Below is a sample procedure using <code>vimdiff</code> to resolve merge conflicts, based on <a href="http://www.rosipov.com/blog/use-vimdiff-as-git-mergetool/#fromHistor" rel="noreferrer">this link</a>.</p> <ol> <li><p>Run the following commands in your terminal</p> <pre class="lang-bash prettyprint-override"><code>git config merge.tool vimdiff git config merge.conflictstyle diff3 git config mergetool.prompt false </code></pre> <p>This will set <code>vimdiff</code> as the default merge tool.</p> </li> <li><p>Run the following command in your terminal</p> <pre class="lang-bash prettyprint-override"><code>git mergetool </code></pre> </li> <li><p>You will see a <code>vimdiff</code> display in the following format:</p> <pre class="lang-none prettyprint-override"><code> ╔═══════╦══════╦════════╗ ║ ║ ║ ║ ║ LOCAL ║ BASE ║ REMOTE ║ ║ ║ ║ ║ ╠═══════╩══════╩════════╣ ║ ║ ║ MERGED ║ ║ ║ ╚═══════════════════════╝ </code></pre> <p>These 4 views are</p> <ul> <li><strong>LOCAL:</strong> this is the file from the current branch</li> <li><strong>BASE:</strong> the common ancestor, how this file looked before both changes</li> <li><strong>REMOTE:</strong> the file you are merging into your branch</li> <li><strong>MERGED:</strong> the merge result; this is what gets saved in the merge commit and used in the future</li> </ul> <p>You can navigate among these views using <kbd>ctrl</kbd>+<kbd>w</kbd>. You can directly reach the MERGED view using <kbd>ctrl</kbd>+<kbd>w</kbd> followed by <kbd>j</kbd>.</p> <p>More information about <code>vimdiff</code> navigation is <a href="https://stackoverflow.com/questions/4556184/vim-move-window-left-right">here</a> and <a href="https://stackoverflow.com/questions/27151456/how-do-i-jump-to-the-next-prev-diff-in-git-difftool">here</a>.</p> </li> <li><p>You can edit the MERGED view like this:</p> <ul> <li><p>If you want to get changes from REMOTE</p> <pre><code>:diffg RE </code></pre> </li> <li><p>If you want to get changes from BASE</p> <pre><code>:diffg BA </code></pre> </li> <li><p>If you want to get changes from LOCAL</p> <pre><code>:diffg LO </code></pre> </li> </ul> </li> <li><p>Save, Exit, Commit, and Clean up</p> <p><code>:wqa</code> save and exit from vi</p> <p><code>git commit -m &quot;message&quot;</code></p> <p><code>git clean</code> Remove extra files (e.g. <code>*.orig</code>) created by the diff tool.</p> </li> </ol>
{ "question_id": 161813, "question_date": "2008-10-02T11:31:05.777Z", "question_score": 5242, "tags": "git|git-merge|merge-conflict-resolution|git-merge-conflict", "answer_id": 163659, "answer_date": "2008-10-02T17:50:25.100Z", "answer_score": 3288 }
Please answer the following Stack Overflow question: Title: What is the most efficient way to deep clone an object in JavaScript? <p>What is the most efficient way to clone a JavaScript object? I've seen <code>obj = eval(uneval(o));</code> being used, but <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/uneval" rel="noreferrer">that's non-standard and only supported by Firefox</a>.<br/><br/> I've done things like <code>obj = JSON.parse(JSON.stringify(o));</code> but question the efficiency. <br/><br/> I've also seen recursive copying functions with various flaws. <br /> I'm surprised no canonical solution exists.</p>
<h1>Native deep cloning</h1> <p>There's now a JS standard called <a href="https://developer.mozilla.org/en-US/docs/Web/API/structuredClone" rel="noreferrer">&quot;structured cloning&quot;</a>, that works experimentally in Node 11 and later, will land in browsers, and which has <a href="https://www.npmjs.com/package/@ungap/structured-clone" rel="noreferrer">polyfills for existing systems</a>.</p> <pre><code>structuredClone(value) </code></pre> <p>If needed, loading the polyfill first:</p> <pre><code>import structuredClone from '@ungap/structured-clone'; </code></pre> <p>See <a href="https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/10916838#10916838">this answer</a> for more details.</p> <h1>Older answers</h1> <h2>Fast cloning with data loss - JSON.parse/stringify</h2> <p>If you do not use <code>Date</code>s, functions, <code>undefined</code>, <code>Infinity</code>, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types within your object, a very simple one liner to deep clone an object is:</p> <p><code>JSON.parse(JSON.stringify(object))</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>const a = { string: 'string', number: 123, bool: false, nul: null, date: new Date(), // stringified undef: undefined, // lost inf: Infinity, // forced to 'null' re: /.*/, // lost } console.log(a); console.log(typeof a.date); // Date object const clone = JSON.parse(JSON.stringify(a)); console.log(clone); console.log(typeof clone.date); // result of .toISOString()</code></pre> </div> </div> </p> <p>See <a href="https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/5344074#5344074">Corban's answer</a> for benchmarks.</p> <h2>Reliable cloning using a library</h2> <p>Since cloning objects is not trivial (complex types, circular references, function etc.), most major libraries provide function to clone objects. <strong>Don't reinvent the wheel</strong> - if you're already using a library, check if it has an object cloning function. For example,</p> <ul> <li>lodash - <a href="https://lodash.com/docs#cloneDeep" rel="noreferrer"><code>cloneDeep</code></a>; can be imported separately via the <a href="https://www.npmjs.com/package/lodash.clonedeep" rel="noreferrer">lodash.clonedeep</a> module and is probably your best choice if you're not already using a library that provides a deep cloning function</li> <li>AngularJS - <a href="https://docs.angularjs.org/api/ng/function/angular.copy" rel="noreferrer"><code>angular.copy</code></a></li> <li>jQuery - <a href="https://api.jquery.com/jquery.extend/#jQuery-extend-deep-target-object1-objectN" rel="noreferrer"><code>jQuery.extend(true, { }, oldObject)</code></a>; <code>.clone()</code> only clones DOM elements</li> <li>just library - <a href="https://www.npmjs.com/package/just-clone" rel="noreferrer"><code>just-clone</code></a>; Part of a library of zero-dependency npm modules that do just do one thing. Guilt-free utilities for every occasion.</li> </ul>
{ "question_id": 122102, "question_date": "2008-09-23T16:26:09.163Z", "question_score": 5171, "tags": "javascript|object|clone", "answer_id": 122704, "answer_date": "2008-09-23T18:09:37.277Z", "answer_score": 5581 }
Please answer the following Stack Overflow question: Title: Reset local repository branch to be just like remote repository HEAD <p>How do I reset my local branch to be just like the branch on the remote repository?</p> <p>I tried:</p> <pre><code>git reset --hard HEAD </code></pre> <p>But <code>git status</code> claims I have modified files:</p> <pre><code>On branch master Changes to be committed: (use &quot;git reset HEAD &lt;file&gt;...&quot; to unstage) modified: java/com/mycompany/TestContacts.java modified: java/com/mycompany/TestParser.java </code></pre>
<p>Setting your branch to exactly match the remote branch can be done in two steps:</p> <pre><code>git fetch origin git reset --hard origin/master </code></pre> <p>If you want to save your current branch's state before doing this (just in case), you can do:</p> <pre><code>git commit -a -m &quot;Saving my work, just in case&quot; git branch my-saved-work </code></pre> <p>Now your work is saved on the branch &quot;my-saved-work&quot; in case you decide you want it back (or want to look at it later or diff it against your updated branch).</p> <p>Note that the first example assumes that the remote repo's name is &quot;origin&quot; and that the branch named &quot;master&quot; in the remote repo matches the currently checked-out branch in your local repo.</p> <p>BTW, this situation that you're in looks an awful lot like a common case where a push has been done into the currently checked out branch of a non-bare repository. Did you recently push into your local repo? If not, then no worries -- something else must have caused these files to unexpectedly end up modified. Otherwise, you should be aware that it's not recommended to push into a non-bare repository (and not into the currently checked-out branch, in particular).</p>
{ "question_id": 1628088, "question_date": "2009-10-27T00:27:20.543Z", "question_score": 5146, "tags": "git|undo", "answer_id": 1628334, "answer_date": "2009-10-27T01:44:30.760Z", "answer_score": 8868 }
Please answer the following Stack Overflow question: Title: What is the difference between "INNER JOIN" and "OUTER JOIN"? <p>Also, how do <code>LEFT OUTER JOIN</code>, <code>RIGHT OUTER JOIN</code>, and <code>FULL OUTER JOIN</code> fit in?</p>
<p>Assuming you're joining on columns with no duplicates, which is a very common case:</p> <ul> <li><p>An inner join of A and B gives the result of A intersect B, i.e. the inner part of a <a href="http://en.wikipedia.org/wiki/Venn_diagram" rel="noreferrer">Venn diagram</a> intersection.</p> </li> <li><p>An outer join of A and B gives the results of A union B, i.e. the outer parts of a <a href="http://en.wikipedia.org/wiki/Venn_diagram" rel="noreferrer">Venn diagram</a> union.</p> </li> </ul> <p><strong>Examples</strong></p> <p>Suppose you have two tables, with a single column each, and data as follows:</p> <pre><code>A B - - 1 3 2 4 3 5 4 6 </code></pre> <p>Note that (1,2) are unique to A, (3,4) are common, and (5,6) are unique to B.</p> <p><strong>Inner join</strong></p> <p>An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.</p> <pre><code>select * from a INNER JOIN b on a.a = b.b; select a.*, b.* from a,b where a.a = b.b; a | b --+-- 3 | 3 4 | 4 </code></pre> <p><strong>Left outer join</strong></p> <p>A left outer join will give all rows in A, plus any common rows in B.</p> <pre><code>select * from a LEFT OUTER JOIN b on a.a = b.b; select a.*, b.* from a,b where a.a = b.b(+); a | b --+----- 1 | null 2 | null 3 | 3 4 | 4 </code></pre> <p><strong>Right outer join</strong></p> <p>A right outer join will give all rows in B, plus any common rows in A.</p> <pre><code>select * from a RIGHT OUTER JOIN b on a.a = b.b; select a.*, b.* from a,b where a.a(+) = b.b; a | b -----+---- 3 | 3 4 | 4 null | 5 null | 6 </code></pre> <p><strong>Full outer join</strong></p> <p>A full outer join will give you the union of A and B, i.e. all the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa.</p> <pre><code>select * from a FULL OUTER JOIN b on a.a = b.b; a | b -----+----- 1 | null 2 | null 3 | 3 4 | 4 null | 6 null | 5 </code></pre>
{ "question_id": 38549, "question_date": "2008-09-01T22:36:06.940Z", "question_score": 5108, "tags": "sql|join|inner-join|outer-join", "answer_id": 38578, "answer_date": "2008-09-01T22:59:34.840Z", "answer_score": 6574 }
Please answer the following Stack Overflow question: Title: How to determine the URL that a local Git repository was originally cloned from <p>I pulled a project with several forks on GitHub, but forgot which fork it was. How do I determine which fork I pulled?</p>
<p>To obtain only the remote URL:</p> <pre><code>git config --get remote.origin.url </code></pre> <p>If you require full output, and you are on a network that can reach the remote repo where the origin resides:</p> <pre><code>git remote show origin </code></pre> <p>When using <code>git clone</code> (from GitHub, or any source repository for that matter) the default name for the source of the clone is &quot;origin&quot;. Using <code>git remote show</code> will display the information about this remote name. The first few lines should show:</p> <pre><code>C:\Users\jaredpar\VsVim&gt; git remote show origin * remote origin Fetch URL: git@github.com:jaredpar/VsVim.git Push URL: git@github.com:jaredpar/VsVim.git HEAD branch: master Remote branches: </code></pre> <p>If you want to use the value in the script, you would use the first command listed in this answer.</p>
{ "question_id": 4089430, "question_date": "2010-11-03T16:47:46.247Z", "question_score": 5063, "tags": "git|github|git-remote", "answer_id": 4089452, "answer_date": "2010-11-03T16:50:16.040Z", "answer_score": 7046 }
Please answer the following Stack Overflow question: Title: How do I check whether a checkbox is checked in jQuery? <p>I need to check the <code>checked</code> property of a checkbox and perform an action based on the checked property using jQuery.</p> <p>For example, if the <code>age</code> checkbox is checked, then I need to show a textbox to enter <code>age</code>, else hide the textbox.</p> <p>But the following code returns <code>false</code> by default:</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>if ($('#isAgeSelected').attr('checked')) { $("#txtAge").show(); } else { $("#txtAge").hide(); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;input type="checkbox" id="isAgeSelected"/&gt; &lt;div id="txtAge" style="display:none"&gt; Age is selected &lt;/div&gt;</code></pre> </div> </div> </p> <p>How do I successfully query the <code>checked</code> property?</p>
<p>This worked for me:</p> <pre><code>$get("isAgeSelected ").checked == true </code></pre> <p>Where <code>isAgeSelected</code> is the id of the control.</p> <p>Also, @karim79's <a href="https://stackoverflow.com/questions/901712/check-checkbox-checked-property-using-jquery/901727#901727">answer</a> works fine. I am not sure what I missed at the time I tested it.</p> <p><strong>Note, this is answer uses Microsoft Ajax, not jQuery</strong></p>
{ "question_id": 901712, "question_date": "2009-05-23T15:16:39.917Z", "question_score": 5054, "tags": "javascript|jquery|html|checkbox", "answer_id": 903152, "answer_date": "2009-05-24T05:30:25.670Z", "answer_score": 116 }
Please answer the following Stack Overflow question: Title: How do I add an empty directory to a Git repository? <p>How do I add an empty directory (that contains no files) to a Git repository?</p>
<p>Another way to make a directory stay (almost) empty (in the repository) is to create a <code>.gitignore</code> file inside that directory that contains these four lines:</p> <pre><code># Ignore everything in this directory * # Except this file !.gitignore </code></pre> <p>Then you don't have to get the order right the way that you have to do in m104's <a href="https://stackoverflow.com/a/180917/32453">solution</a>.</p> <p>This also gives the benefit that files in that directory won't show up as "untracked" when you do a git status.</p> <p>Making <a href="https://stackoverflow.com/users/554807/greenasjade">@GreenAsJade</a>'s comment persistent:</p> <blockquote> <p>I think it's worth noting that this solution does precisely what the question asked for, but is not perhaps what many people looking at this question will have been looking for. This solution guarantees that the directory remains empty. It says "I truly never want files checked in here". As opposed to "I don't have any files to check in here, yet, but I need the directory here, files may be coming later".</p> </blockquote>
{ "question_id": 115983, "question_date": "2008-09-22T16:41:03.660Z", "question_score": 5046, "tags": "git|directory|git-add", "answer_id": 932982, "answer_date": "2009-05-31T22:10:40.167Z", "answer_score": 4849 }
Please answer the following Stack Overflow question: Title: Regular expression to match a line that doesn't contain a word <p>I know it's possible to match a word and then reverse the matches using other tools (e.g. <code>grep -v</code>). However, is it possible to match lines that do not contain a specific word, e.g. <code>hede</code>, using a regular expression?</p> <h5>Input:</h5> <pre><code>hoho hihi haha hede </code></pre> <h5>Code:</h5> <pre><code>grep &quot;&lt;Regex for 'doesn't contain hede'&gt;&quot; input </code></pre> <h5>Desired output:</h5> <pre><code>hoho hihi haha </code></pre>
<p>The notion that regex doesn't support inverse matching is not entirely true. You can mimic this behavior by using negative look-arounds:</p> <pre><code>^((?!hede).)*$ </code></pre> <p>Non-capturing variant:</p> <pre class="lang-regex prettyprint-override"><code>^(?:(?!:hede).)*$ </code></pre> <p>The regex above will match any string, or line without a line break, <strong>not</strong> containing the (sub)string 'hede'. As mentioned, this is not something regex is &quot;good&quot; at (or should do), but still, it <em>is</em> possible.</p> <p>And if you need to match line break chars as well, use the <a href="http://perldoc.perl.org/perlre.html#Modifiers" rel="noreferrer">DOT-ALL modifier</a> (the trailing <code>s</code> in the following pattern):</p> <pre><code>/^((?!hede).)*$/s </code></pre> <p>or use it inline:</p> <pre><code>/(?s)^((?!hede).)*$/ </code></pre> <p><em>(where the <code>/.../</code> are the regex delimiters, i.e., not part of the pattern)</em></p> <p>If the DOT-ALL modifier is not available, you can mimic the same behavior with the character class <code>[\s\S]</code>:</p> <pre><code>/^((?!hede)[\s\S])*$/ </code></pre> <h2>Explanation</h2> <p>A string is just a list of <code>n</code> characters. Before, and after each character, there's an empty string. So a list of <code>n</code> characters will have <code>n+1</code> empty strings. Consider the string <code>&quot;ABhedeCD&quot;</code>:</p> <pre><code> ┌──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┐ S = │e1│ A │e2│ B │e3│ h │e4│ e │e5│ d │e6│ e │e7│ C │e8│ D │e9│ └──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┘ index 0 1 2 3 4 5 6 7 </code></pre> <p>where the <code>e</code>'s are the empty strings. The regex <code>(?!hede).</code> looks ahead to see if there's no substring <code>&quot;hede&quot;</code> to be seen, and if that is the case (so something else is seen), then the <code>.</code> (dot) will match any character except a line break. Look-arounds are also called <em>zero-width-assertions</em> because they don't <em>consume</em> any characters. They only assert/validate something.</p> <p>So, in my example, every empty string is first validated to see if there's no <code>&quot;hede&quot;</code> up ahead, before a character is consumed by the <code>.</code> (dot). The regex <code>(?!hede).</code> will do that only once, so it is wrapped in a group, and repeated zero or more times: <code>((?!hede).)*</code>. Finally, the start- and end-of-input are anchored to make sure the entire input is consumed: <code>^((?!hede).)*$</code></p> <p>As you can see, the input <code>&quot;ABhedeCD&quot;</code> will fail because on <code>e3</code>, the regex <code>(?!hede)</code> fails (there <em>is</em> <code>&quot;hede&quot;</code> up ahead!).</p>
{ "question_id": 406230, "question_date": "2009-01-02T07:30:16.097Z", "question_score": 5042, "tags": "regex|pattern-matching|regex-negation", "answer_id": 406408, "answer_date": "2009-01-02T09:55:05.323Z", "answer_score": 6952 }
Please answer the following Stack Overflow question: Title: How do I create a GUID / UUID? <p>How do I create GUIDs (globally-unique identifiers) in JavaScript? The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.</p> <p>I'm not sure what routines are available on all browsers, how &quot;random&quot; and seeded the built-in random number generator is, etc.</p>
<p>UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier), according to <a href="https://www.ietf.org/rfc/rfc4122.txt" rel="noreferrer">RFC 4122</a>, are identifiers designed to provide certain uniqueness guarantees.</p> <p>While it is possible to implement RFC-compliant UUIDs in a few lines of JavaScript code (e.g., see <a href="https://stackoverflow.com/a/2117523/109538">@broofa's answer</a>, below) there are several common pitfalls:</p> <ul> <li>Invalid id format (UUIDs must be of the form &quot;<code>xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx</code>&quot;, where x is one of [0-9, a-f] <em>M</em> is one of [1-5], and <em>N</em> is [8, 9, a, or b]</li> <li>Use of a low-quality source of randomness (such as <code>Math.random</code>)</li> </ul> <p>Thus, developers writing code for production environments are encouraged to use a rigorous, well-maintained implementation such as the <a href="https://github.com/uuidjs/uuid" rel="noreferrer">uuid</a> module.</p>
{ "question_id": 105034, "question_date": "2008-09-19T20:01:00.147Z", "question_score": 5019, "tags": "javascript|guid|uuid", "answer_id": 105074, "answer_date": "2008-09-19T20:05:25.003Z", "answer_score": 2593 }
Please answer the following Stack Overflow question: Title: How can I horizontally center an element? <p>How can I horizontally center a <code>&lt;div&gt;</code> within another <code>&lt;div&gt;</code> using CSS?</p> <pre class="lang-html prettyprint-override"><code>&lt;div id=&quot;outer&quot;&gt; &lt;div id=&quot;inner&quot;&gt;Foo foo&lt;/div&gt; &lt;/div&gt; </code></pre>
<p>You can apply this CSS to the inner <code>&lt;div&gt;</code>:</p> <pre class="lang-css prettyprint-override"><code>#inner { width: 50%; margin: 0 auto; } </code></pre> <p>Of course, you don't have to set the <code>width</code> to <code>50%</code>. Any width less than the containing <code>&lt;div&gt;</code> will work. The <code>margin: 0 auto</code> is what does the actual centering.</p> <p>If you are targeting <a href="https://en.wikipedia.org/wiki/Internet_Explorer_8" rel="noreferrer">Internet Explorer 8</a> (and later), it might be better to have this instead:</p> <pre class="lang-css prettyprint-override"><code>#inner { display: table; margin: 0 auto; } </code></pre> <p>It will make the inner element center horizontally and it works without setting a specific <code>width</code>.</p> <p>Working example here:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#inner { display: table; margin: 0 auto; border: 1px solid black; } #outer { border: 1px solid red; width:100% }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="outer"&gt; &lt;div id="inner"&gt;Foo foo&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <hr /> <h2>EDIT</h2> <p>With <code>flexbox</code> it is very easy to style the div horizontally and vertically centered.</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-css lang-css prettyprint-override"><code>#inner { border: 0.05em solid black; } #outer { border: 0.05em solid red; width:100%; display: flex; justify-content: center; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="outer"&gt; &lt;div id="inner"&gt;Foo foo&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>To align the div vertically centered, use the property <code>align-items: center</code>.</p>
{ "question_id": 114543, "question_date": "2008-09-22T12:27:57.510Z", "question_score": 4905, "tags": "html|css|alignment|centering", "answer_id": 114549, "answer_date": "2008-09-22T12:29:07.710Z", "answer_score": 5375 }
Please answer the following Stack Overflow question: Title: How do I exit Vim? <p>I am stuck and cannot escape. It says:</p> <pre><code>type :quit&lt;Enter&gt; to quit VIM </code></pre> <p>But when I type that it simply appears in the object body.</p>
<p>Hit the <kbd>Esc</kbd> key to enter &quot;Normal mode&quot;. Then you can type <code>:</code> to enter &quot;Command-line mode&quot;. A colon (<code>:</code>) will appear at the bottom of the screen and you can type in one of the following commands. To execute a command, press the <kbd>Enter</kbd> key.</p> <ul> <li><code>:q</code> to quit (short for <code>:quit</code>)</li> <li><code>:q!</code> to quit without saving (short for <code>:quit!</code>)</li> <li><code>:wq</code> to write and quit</li> <li><code>:wq!</code> to write and quit even if file has only read permission (if file does not have write permission: force write)</li> <li><code>:x</code> to write and quit (similar to <code>:wq</code>, but only write if there are changes)</li> <li><code>:exit</code> to write and exit (same as <code>:x</code>)</li> <li><code>:qa</code> to quit all (short for <code>:quitall</code>)</li> <li><code>:cq</code> to quit without saving and make Vim return non-zero error (i.e. exit with error)</li> </ul> <p>You can also exit Vim directly from &quot;Normal mode&quot; by typing <code>ZZ</code> to save and quit (same as <code>:x</code>) or <code>ZQ</code> to just quit (same as <code>:q!</code>). (Note that case is important here. <code>ZZ</code> and <code>zz</code> do not mean the same thing.)</p> <p>Vim has extensive help - that you can access with the <code>:help</code> command - where you can find answers to all your questions and a tutorial for beginners.</p>
{ "question_id": 11828270, "question_date": "2012-08-06T12:25:47.927Z", "question_score": 4851, "tags": "vim|vi", "answer_id": 11828573, "answer_date": "2012-08-06T12:46:16.327Z", "answer_score": 5931 }
Please answer the following Stack Overflow question: Title: Accessing the index in 'for' loops <p>How do I access the index while iterating over a sequence with a <code>for</code> loop?</p> <pre><code>xs = [8, 23, 45] for x in xs: print(&quot;item #{} = {}&quot;.format(index, x)) </code></pre> <p>Desired output:</p> <pre class="lang-none prettyprint-override"><code>item #1 = 8 item #2 = 23 item #3 = 45 </code></pre>
<p>Use the built-in function <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="noreferrer" title="enumerate"><code>enumerate()</code></a>:</p> <pre><code>for idx, x in enumerate(xs): print(idx, x) </code></pre> <p>It is <em><a href="https://stackoverflow.com/questions/25011078/what-does-pythonic-mean">non-pythonic</a></em> to manually index via <code>for i in range(len(xs)): x = xs[i]</code> or manually manage an additional state variable.</p> <p>Check out <a href="https://www.python.org/dev/peps/pep-0279/" rel="noreferrer" title="PEP 279">PEP 279</a> for more.</p>
{ "question_id": 522563, "question_date": "2009-02-06T22:47:54.433Z", "question_score": 4845, "tags": "python|loops|list", "answer_id": 522578, "answer_date": "2009-02-06T22:52:36.357Z", "answer_score": 8044 }
Please answer the following Stack Overflow question: Title: How do I make a flat list out of a list of lists? <p>I have a list of lists like <code>[[1, 2, 3], [4, 5, 6], [7], [8, 9]]</code>. How can I flatten it to get <code>[1, 2, 3, 4, 5, 6, 7, 8, 9]</code>?</p> <hr /> <p><sub>If your list of lists comes from a nested list comprehension, the problem can be solved more simply/directly by fixing the comprehension; please see <a href="https://stackoverflow.com/questions/1077015">python list comprehensions; compressing a list of lists?</a>.</sub></p> <p><sub>The most popular solutions here generally only flatten one &quot;level&quot; of the nested list. See <a href="https://stackoverflow.com/questions/2158395">Flatten an irregular (arbitrarily nested) list of lists</a> for solutions that completely flatten a deeply nested structure (recursively, in general).</sub></p>
<p>Given a list of lists <code>l</code>,</p> <pre><code>flat_list = [item for sublist in l for item in sublist] </code></pre> <p>which means:</p> <pre><code>flat_list = [] for sublist in l: for item in sublist: flat_list.append(item) </code></pre> <p>is faster than the shortcuts posted so far. (<code>l</code> is the list to flatten.)</p> <p>Here is the corresponding function:</p> <pre><code>def flatten(l): return [item for sublist in l for item in sublist] </code></pre> <p>As evidence, you can use the <code>timeit</code> module in the standard library:</p> <pre><code>$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]' 10000 loops, best of 3: 143 usec per loop $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])' 1000 loops, best of 3: 969 usec per loop $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)' 1000 loops, best of 3: 1.1 msec per loop </code></pre> <p>Explanation: the shortcuts based on <code>+</code> (including the implied use in <code>sum</code>) are, of necessity, <code>O(L**2)</code> when there are L sublists -- as the intermediate result list keeps getting longer, at each step a new intermediate result list object gets allocated, and all the items in the previous intermediate result must be copied over (as well as a few new ones added at the end). So, for simplicity and without actual loss of generality, say you have L sublists of I items each: the first I items are copied back and forth L-1 times, the second I items L-2 times, and so on; total number of copies is I times the sum of x for x from 1 to L excluded, i.e., <code>I * (L**2)/2</code>.</p> <p>The list comprehension just generates one list, once, and copies each item over (from its original place of residence to the result list) also exactly once.</p>
{ "question_id": 952914, "question_date": "2009-06-04T20:30:05.527Z", "question_score": 4832, "tags": "python|list|multidimensional-array|flatten", "answer_id": 952952, "answer_date": "2009-06-04T20:37:01.207Z", "answer_score": 6719 }
Please answer the following Stack Overflow question: Title: What is the difference between a URI, a URL, and a URN? <p>What is the difference between a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="noreferrer"><strong>URL</strong></a>, a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Identifier" rel="noreferrer"><strong>URI</strong></a>, and a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Name" rel="noreferrer"><strong>URN</strong></a>?</p>
<p>From <a href="http://www.ietf.org/rfc/rfc3986.txt" rel="noreferrer">RFC 3986</a>:</p> <blockquote> <p>A URI can be further classified as a locator, a name, or both. The term &quot;Uniform Resource Locator&quot; (URL) refers to the subset of URIs that, in addition to identifying a resource, provide a means of locating the resource by describing its primary access mechanism (e.g., its network &quot;location&quot;). The term &quot;Uniform Resource Name&quot; (URN) has been used historically to refer to both URIs under the &quot;urn&quot; scheme <a href="https://www.ietf.org/rfc/rfc2141.txt" rel="noreferrer">[RFC2141]</a>, which are required to remain globally unique and persistent even when the resource ceases to exist or becomes unavailable, and to any other URI with the properties of a name.</p> </blockquote> <p>So all URLs are URIs, and all URNs are URIs - but URNs and URLs are different, so you can't say that all URIs are URLs.</p> <p>If you haven't already read <a href="https://stackoverflow.com/a/1984225/22656">Roger Pate's answer</a>, I'd advise doing so as well.</p>
{ "question_id": 176264, "question_date": "2008-10-06T21:26:58.073Z", "question_score": 4823, "tags": "http|url|uri|urn|rfc3986", "answer_id": 176274, "answer_date": "2008-10-06T21:29:48.410Z", "answer_score": 1900 }
Please answer the following Stack Overflow question: Title: How do I squash my last N commits together? <p>How do I squash my last N commits together into one commit?</p>
<p>Use <code>git rebase -i &lt;after-this-commit&gt;</code> and replace "pick" on the second and subsequent commits with "squash" or "fixup", as described in <a href="http://git-scm.com/docs/git-rebase#_interactive_mode">the manual</a>.</p> <p>In this example, <code>&lt;after-this-commit&gt;</code> is either the SHA1 hash or the relative location from the HEAD of the current branch from which commits are analyzed for the rebase command. For example, if the user wishes to view 5 commits from the current HEAD in the past the command is <code>git rebase -i HEAD~5</code>. </p>
{ "question_id": 5189560, "question_date": "2011-03-04T04:11:26.517Z", "question_score": 4782, "tags": "git|rebase|squash|git-squash", "answer_id": 5189600, "answer_date": "2011-03-04T04:18:49.737Z", "answer_score": 2749 }
Please answer the following Stack Overflow question: Title: How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3 <p>We have an employee whose surname is Null. Our employee lookup application is killed when that last name is used as the search term (which happens to be quite often now). The error received (thanks Fiddler!) is:</p> <pre class="lang-none prettyprint-override"><code>&lt;soapenv:Fault&gt; &lt;faultcode&gt;soapenv:Server.userException&lt;/faultcode&gt; &lt;faultstring&gt;coldfusion.xml.rpc.CFCInvocationException: [coldfusion.runtime.MissingArgumentException : The SEARCHSTRING parameter to the getFacultyNames function is required but was not passed in.]&lt;/faultstring&gt; </code></pre> <p>Cute, huh?</p> <p>The parameter type is <code>string</code>.</p> <p>I am using:</p> <ul> <li><a href="http://en.wikipedia.org/wiki/Web_Services_Description_Language" rel="noreferrer">WSDL</a> (<a href="http://en.wikipedia.org/wiki/SOAP" rel="noreferrer">SOAP</a>)</li> <li>Flex 3.5</li> <li>ActionScript 3</li> <li>ColdFusion 8</li> </ul> <p>Note that the error <strong>does not</strong> occur when calling the webservice as an object from a ColdFusion page.</p>
<h1> Tracking it down </h1> <p>At first I thought this was a coercion bug where <code>null</code> was getting coerced to <code>"null"</code> and a test of <code>"null" == null</code> was passing. It's not. <strong>I was close, but so very, very wrong. Sorry about that!</strong></p> <p>I've since done lots of <a href="http://wonderfl.net/c/dd23/read" rel="noreferrer">fiddling on wonderfl.net</a> and tracing through the code in <code>mx.rpc.xml.*</code>. At line 1795 of <code>XMLEncoder</code> (in the 3.5 source), in <code>setValue</code>, all of the XMLEncoding boils down to </p> <pre><code>currentChild.appendChild(xmlSpecialCharsFilter(Object(value))); </code></pre> <p>which is essentially the same as:</p> <pre><code>currentChild.appendChild("null"); </code></pre> <p>This code, according to my original fiddle, returns an empty XML element. But why?</p> <p><H1> Cause </H1></p> <p>According to commenter Justin Mclean on bug report <a href="https://issues.apache.org/jira/browse/FLEX-33644" rel="noreferrer">FLEX-33664</a>, the following is the culprit (see last two tests in my <a href="http://wonderfl.net/c/dd23/read" rel="noreferrer">fiddle</a> which verify this):</p> <pre><code>var thisIsNotNull:XML = &lt;root&gt;null&lt;/root&gt;; if(thisIsNotNull == null){ // always branches here, as (thisIsNotNull == null) strangely returns true // despite the fact that thisIsNotNull is a valid instance of type XML } </code></pre> <p>When <code>currentChild.appendChild</code> is passed the string <code>"null"</code>, it first converts it to a root XML element with text <code>null</code>, and then tests that element against the null literal. This is a weak equality test, so either the XML containing null is coerced to the null type, or the null type is coerced to a root xml element containing the string "null", and the test passes where it arguably should fail. One fix might be to always use <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/operators.html#strict_equality" rel="noreferrer">strict equality</a> tests when checking XML (or anything, really) for "nullness."</p> <p><H1>Solution</H1> The only reasonable workaround I can think of, short of fixing this bug in every damn version of ActionScript, is to test fields for "null" and <strong>escape them as <a href="https://stackoverflow.com/q/1239466/203705">CDATA values</a>.</strong> </p> <p><strong>CDATA values are the most appropriate way to mutate an entire text value that would otherwise cause encoding/decoding problems.</strong> Hex encoding, for instance, is meant for individual characters. CDATA values are preferred when you're escaping the entire text of an element. The biggest reason for this is that it maintains human readability.</p>
{ "question_id": 4456438, "question_date": "2010-12-16T00:42:14.013Z", "question_score": 4738, "tags": "apache-flex|actionscript|soap|coldfusion|wsdl", "answer_id": 18000768, "answer_date": "2013-08-01T17:31:46.023Z", "answer_score": 1140 }
Please answer the following Stack Overflow question: Title: What's the difference between tilde(~) and caret(^) in package.json? <p>After I upgraded to the latest stable <code>node</code> and <code>npm</code>, I tried <code>npm install moment --save</code>. It saves the entry in the <code>package.json</code> with the caret <code>^</code> prefix. Previously, it was a tilde <code>~</code> prefix.</p> <ol> <li>Why are these changes made in <code>npm</code>?</li> <li>What is the difference between tilde <code>~</code> and caret <code>^</code>?</li> <li>What are the advantages over others?</li> </ol>
<p>See the <a href="https://docs.npmjs.com/cli/v8/configuring-npm/package-json#dependencies" rel="noreferrer">NPM docs</a> and <a href="https://docs.npmjs.com/cli/v6/using-npm/semver" rel="noreferrer">semver docs</a>:</p> <ul> <li><p><code>~version</code> <strong>“Approximately equivalent to version”</strong>, will update you to all future patch versions, without incrementing the minor version. <code>~1.2.3</code> will use releases from 1.2.3 to &lt;1.3.0.</p> </li> <li><p><code>^version</code> <strong>“Compatible with version”</strong>, will update you to all future minor/patch versions, without incrementing the major version. <code>^2.3.4</code> will use releases from 2.3.4 to &lt;3.0.0.</p> </li> </ul> <p>See Comments below for exceptions, in particular <a href="https://stackoverflow.com/questions/22343224/whats-the-difference-between-tilde-and-caret-in-package-json#comment53973834_22345808">for pre-one versions, such as ^0.2.3</a></p>
{ "question_id": 22343224, "question_date": "2014-03-12T06:02:21.987Z", "question_score": 4706, "tags": "node.js|npm|package.json|semantic-versioning", "answer_id": 22345808, "answer_date": "2014-03-12T08:28:07.070Z", "answer_score": 5404 }
Please answer the following Stack Overflow question: Title: How do I check if an array includes a value in JavaScript? <p>What is the most concise and efficient way to find out if a JavaScript array contains a value?</p> <p>This is the only way I know to do it:</p> <pre><code>function contains(a, obj) { for (var i = 0; i &lt; a.length; i++) { if (a[i] === obj) { return true; } } return false; } </code></pre> <p>Is there a better and more concise way to accomplish this?</p> <p>This is very closely related to Stack Overflow question <em><a href="https://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array">Best way to find an item in a JavaScript Array?</a></em> which addresses finding objects in an array using <code>indexOf</code>.</p>
<p>Modern browsers have <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#browser_compatibility" rel="noreferrer"><code>Array#includes</code></a>, which does <em>exactly</em> that and <a href="https://kangax.github.io/compat-table/es2016plus/#test-Array.prototype.includes" rel="noreferrer">is widely supported</a> by everyone except IE:</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>console.log(['joe', 'jane', 'mary'].includes('jane')); //true</code></pre> </div> </div> </p> <p>You can also use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf" rel="noreferrer"><code>Array#indexOf</code></a>, which is less direct, but doesn't require polyfills for outdated browsers.</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>console.log(['joe', 'jane', 'mary'].indexOf('jane') &gt;= 0); //true</code></pre> </div> </div> </p> <hr /> <p>Many frameworks also offer similar methods:</p> <ul> <li>jQuery: <a href="https://api.jquery.com/jquery.inarray/" rel="noreferrer"><code>$.inArray(value, array, [fromIndex])</code></a></li> <li>Underscore.js: <a href="https://underscorejs.org/#contains" rel="noreferrer"><code>_.contains(array, value)</code></a> (also aliased as <code>_.include</code> and <code>_.includes</code>)</li> <li>Dojo Toolkit: <a href="https://dojotoolkit.org/reference-guide/1.10/dojo/indexOf.html" rel="noreferrer"><code>dojo.indexOf(array, value, [fromIndex, findLast])</code></a></li> <li>Prototype: <a href="http://api.prototypejs.org/language/Array/prototype/indexOf/" rel="noreferrer"><code>array.indexOf(value)</code></a></li> <li>MooTools: <a href="https://mootools.net/core/docs/1.6.0/Types/Array#Array:indexOf" rel="noreferrer"><code>array.indexOf(value)</code></a></li> <li>MochiKit: <a href="http://mochi.github.io/mochikit/doc/html/MochiKit/Base.html#fn-findvalue" rel="noreferrer"><code>findValue(array, value)</code></a></li> <li>MS Ajax: <a href="https://web.archive.org/web/20140819232945/http://www.asp.net/ajaxlibrary/Reference.Array-indexOf-Function.ashx" rel="noreferrer"><code>array.indexOf(value)</code></a></li> <li>Ext: <a href="https://docs.sencha.com/extjs/7.5.1/modern/Ext.Array.html#method-contains" rel="noreferrer"><code>Ext.Array.contains(array, value)</code></a></li> <li>Lodash: <a href="https://lodash.com/docs#includes" rel="noreferrer"><code>_.includes(array, value, [from])</code></a> (is <code>_.contains</code> prior 4.0.0)</li> <li>Ramda: <a href="https://ramdajs.com/docs/#includes" rel="noreferrer"><code>R.includes(value, array)</code></a></li> </ul> <p>Notice that some frameworks implement this as a function, while others add the function to the array prototype.</p>
{ "question_id": 237104, "question_date": "2008-10-25T22:14:40.913Z", "question_score": 4695, "tags": "javascript|arrays|algorithm|time-complexity|javascript-objects", "answer_id": 1473742, "answer_date": "2009-09-24T19:35:24.250Z", "answer_score": 5157 }
Please answer the following Stack Overflow question: Title: Undo a Git merge that hasn't been pushed yet <p>I accidentally ran <code>git merge some_other_branch</code> on my local master branch. I haven't pushed the changes to origin master. How do I undo the merge?</p> <hr /> <p>After merging, <code>git status</code> says:</p> <pre><code># On branch master # Your branch is ahead of 'origin/master' by 5 commits. </code></pre> <p>How do I undo all these commits?</p>
<p>With <code>git reflog</code> check which commit is one prior the merge (<code>git reflog</code> will be a better option than <code>git log</code>). Then you can reset it using:</p> <pre><code>git reset --hard commit_sha </code></pre> <p>There's also another way:</p> <pre><code>git reset --hard HEAD~1 </code></pre> <p>It will get you back 1 commit.</p> <p><strong>Be aware that any modified and uncommitted/unstashed files will be reset to their unmodified state</strong>. To keep them either stash changes away or see <code>--merge</code> option below. </p> <hr> <p>As @Velmont suggested below in his answer, in this direct case using:</p> <pre><code>git reset --hard ORIG_HEAD </code></pre> <p>might yield better results, as it should preserve your changes. <code>ORIG_HEAD</code> will point to a commit directly before merge has occurred, so you don't have to hunt for it yourself.</p> <hr> <p>A further tip is to use the <code>--merge</code> switch instead of <code>--hard</code> since it doesn't reset files unnecessarily:</p> <pre><code>git reset --merge ORIG_HEAD </code></pre> <blockquote> <p>--merge</p> <p>Resets the index and updates the files in the working tree that are different between &lt;commit&gt; and HEAD, but keeps those which are different between the index and working tree (i.e. which have changes which have not been added). </p> </blockquote>
{ "question_id": 2389361, "question_date": "2010-03-05T19:24:44.700Z", "question_score": 4657, "tags": "git|undo|git-merge", "answer_id": 2389423, "answer_date": "2010-03-05T19:34:01.440Z", "answer_score": 5293 }
Please answer the following Stack Overflow question: Title: How do I clone all remote branches? <p>My <code>master</code> and <code>development</code> branches are tracked remotely on <a href="http://en.wikipedia.org/wiki/GitHub" rel="noreferrer">GitHub</a>. How do I clone both these branches?</p>
<p>First, clone a remote <a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="noreferrer">Git</a> repository and <a href="http://en.wikipedia.org/wiki/Cd_%28command%29" rel="noreferrer"><code>cd</code></a> into it:</p> <pre><code>$ git clone git://example.com/myproject $ cd myproject </code></pre> <p>Next, look at the local branches in your repository:</p> <pre><code>$ git branch * master </code></pre> <p>But there are other branches hiding in your repository! See these using the <code>-a</code> flag:</p> <pre><code>$ git branch -a * master remotes/origin/HEAD remotes/origin/master remotes/origin/v1.0-stable remotes/origin/experimental </code></pre> <p>To take a quick peek at an upstream branch, check it out directly:</p> <pre><code>$ git checkout origin/experimental </code></pre> <p>To work on that branch, create a local tracking branch, which is done automatically by:</p> <pre><code>$ git checkout experimental Branch experimental set up to track remote branch experimental from origin. Switched to a new branch 'experimental' </code></pre> <p>Here, &quot;new branch&quot; simply means that the branch is taken from the index and created locally for you. As the <em>previous</em> line tells you, the branch is being set up to track the remote branch, which usually means the origin/branch_name branch.</p> <p>Your local branches should now show:</p> <pre><code>$ git branch * experimental master </code></pre> <p>You can track more than one remote repository using <code>git remote</code>:</p> <pre><code>$ git remote add win32 git://example.com/users/joe/myproject-win32-port $ git branch -a * master remotes/origin/HEAD remotes/origin/master remotes/origin/v1.0-stable remotes/origin/experimental remotes/win32/master remotes/win32/new-widgets </code></pre> <p>At this point, things are getting pretty crazy, so run <code>gitk</code> to see what's going on:</p> <pre><code>$ gitk --all &amp; </code></pre>
{ "question_id": 67699, "question_date": "2008-09-15T22:42:07.430Z", "question_score": 4608, "tags": "git|git-branch|git-clone|remote-branch", "answer_id": 72156, "answer_date": "2008-09-16T13:28:22.230Z", "answer_score": 5031 }
Please answer the following Stack Overflow question: Title: How do I get a timestamp in JavaScript? <p>I want a single number that represents the current date and time, like a <a href="https://en.wikipedia.org/wiki/Unix_time" rel="noreferrer">Unix timestamp</a>.</p>
<h3>Timestamp in milliseconds</h3> <p>To get the number of milliseconds since <a href="https://en.wikipedia.org/wiki/Unix_time" rel="noreferrer">Unix epoch</a>, call <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now" rel="noreferrer"><code>Date.now</code></a>:</p> <pre><code>Date.now() </code></pre> <p>Alternatively, use the unary operator <code>+</code> to call <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf" rel="noreferrer"><code>Date.prototype.valueOf</code></a>:</p> <pre><code>+ new Date() </code></pre> <p>Alternatively, call <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf" rel="noreferrer"><code>valueOf</code></a> directly:</p> <pre><code>new Date().valueOf() </code></pre> <p>To support IE8 and earlier (see <a href="http://kangax.github.io/compat-table/es5/#Date.now" rel="noreferrer">compatibility table</a>), create a <em>shim</em> for <code>Date.now</code>:</p> <pre><code>if (!Date.now) { Date.now = function() { return new Date().getTime(); } } </code></pre> <p>Alternatively, call <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime" rel="noreferrer"><code>getTime</code></a> directly:</p> <pre><code>new Date().getTime() </code></pre> <hr /> <h3>Timestamp in seconds</h3> <p>To get the number of seconds since <a href="https://en.wikipedia.org/wiki/Unix_time" rel="noreferrer">Unix epoch</a>, i.e. <em>Unix timestamp</em>:</p> <pre><code>Math.floor(Date.now() / 1000) </code></pre> <p>Alternatively, using bitwise-or to floor is slightly faster, but also less readable and may break in the future (see explanations <a href="https://stackoverflow.com/questions/7487977/using-bitwise-or-0-to-floor-a-number">1</a>, <a href="https://stackoverflow.com/a/11446757/1519836">2</a>):</p> <pre><code>Date.now() / 1000 | 0 </code></pre> <hr /> <h3>Timestamp in milliseconds (higher resolution)</h3> <p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance/now" rel="noreferrer"><code>performance.now</code></a>:</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 isPerformanceSupported = ( window.performance &amp;&amp; window.performance.now &amp;&amp; window.performance.timing &amp;&amp; window.performance.timing.navigationStart ); var timeStampInMs = ( isPerformanceSupported ? window.performance.now() + window.performance.timing.navigationStart : Date.now() ); console.log(timeStampInMs, Date.now());</code></pre> </div> </div> </p>
{ "question_id": 221294, "question_date": "2008-10-21T09:29:33.367Z", "question_score": 4597, "tags": "javascript|datetime|timestamp|date-arithmetic", "answer_id": 221297, "answer_date": "2008-10-21T09:32:32.487Z", "answer_score": 5712 }
Please answer the following Stack Overflow question: Title: How do I read / convert an InputStream into a String in Java? <p>If you have a <code>java.io.InputStream</code> object, how should you process that object and produce a <code>String</code>?</p> <hr /> <p>Suppose I have an <code>InputStream</code> that contains text data, and I want to convert it to a <code>String</code>, so for example I can write that to a log file.</p> <p>What is the easiest way to take the <code>InputStream</code> and convert it to a <code>String</code>?</p> <pre><code>public String convertStreamToString(InputStream is) { // ??? } </code></pre>
<p>A nice way to do this is using <a href="http://commons.apache.org/" rel="noreferrer">Apache commons</a> <code><a href="https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html" rel="noreferrer">IOUtils</a></code> to copy the <code>InputStream</code> into a <code>StringWriter</code>... something like</p> <pre><code>StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, encoding); String theString = writer.toString(); </code></pre> <p>or even</p> <pre><code>// NB: does not close inputStream, you'll have to use try-with-resources for that String theString = IOUtils.toString(inputStream, encoding); </code></pre> <p>Alternatively, you could use <code>ByteArrayOutputStream</code> if you don't want to mix your Streams and Writers</p>
{ "question_id": 309424, "question_date": "2008-11-21T16:47:40.287Z", "question_score": 4560, "tags": "java|string|io|stream|inputstream", "answer_id": 309448, "answer_date": "2008-11-21T16:54:20.960Z", "answer_score": 2733 }
Please answer the following Stack Overflow question: Title: Setting "checked" for a checkbox with jQuery <p>I'd like to do something like this to tick a <code>checkbox</code> using <strong>jQuery</strong>:</p> <pre><code>$(".myCheckBox").checked(true); </code></pre> <p>or</p> <pre><code>$(".myCheckBox").selected(true); </code></pre> <p>Does such a thing exist?</p>
<h2>Modern jQuery</h2> <p>Use <a href="https://api.jquery.com/prop" rel="noreferrer"><code>.prop()</code></a>:</p> <pre><code>$('.myCheckbox').prop('checked', true); $('.myCheckbox').prop('checked', false); </code></pre> <h2>DOM API</h2> <p>If you're working with just one element, you can always just access the underlying <a href="https://developer.mozilla.org/en/docs/Web/API/HTMLInputElement" rel="noreferrer"><code>HTMLInputElement</code></a> and modify its <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#Properties_checkbox_radio" rel="noreferrer"><code>.checked</code></a> property:</p> <pre><code>$('.myCheckbox')[0].checked = true; $('.myCheckbox')[0].checked = false; </code></pre> <p>The benefit to using the <code>.prop()</code> and <code>.attr()</code> methods instead of this is that they will operate on all matched elements.</p> <h2>jQuery 1.5.x and below</h2> <p>The <code>.prop()</code> method is not available, so you need to use <a href="https://api.jquery.com/attr" rel="noreferrer"><code>.attr()</code></a>.</p> <pre><code>$('.myCheckbox').attr('checked', true); $('.myCheckbox').attr('checked', false); </code></pre> <p>Note that this is <a href="https://github.com/jquery/jquery/blob/1.5.2/test/unit/attributes.js#L157" rel="noreferrer">the approach used by jQuery's unit tests prior to version 1.6</a> and is preferable to using <code>$('.myCheckbox').removeAttr('checked');</code> since the latter will, if the box was initially checked, change the behaviour of a call to <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.reset" rel="noreferrer"><code>.reset()</code></a> on any form that contains it – a subtle but probably unwelcome behaviour change.</p> <p>For more context, some incomplete discussion of the changes to the handling of the <code>checked</code> attribute/property in the transition from 1.5.x to 1.6 can be found in the <a href="https://blog.jquery.com/2011/05/03/jquery-16-released/" rel="noreferrer">version 1.6 release notes</a> and the <strong>Attributes vs. Properties</strong> section of the <a href="https://api.jquery.com/prop" rel="noreferrer"><code>.prop()</code> documentation</a>.</p>
{ "question_id": 426258, "question_date": "2009-01-08T22:20:24.913Z", "question_score": 4479, "tags": "javascript|jquery|checkbox|selected|checked", "answer_id": 426276, "answer_date": "2009-01-08T22:25:08.447Z", "answer_score": 6338 }
Please answer the following Stack Overflow question: Title: How do I update or sync a forked repository on GitHub? <p>I forked a project, made changes, and created a pull request which was accepted. New commits were later added to the repository. How do I get those commits into my fork?</p>
<p>In your local clone of your forked repository, you can add the original GitHub repository as a &quot;remote&quot;. (&quot;Remotes&quot; are like nicknames for the URLs of repositories - <code>origin</code> is one, for example.) Then you can fetch all the branches from that upstream repository, and rebase your work to continue working on the upstream version. In terms of commands that might look like:</p> <pre class="lang-sh prettyprint-override"><code># Add the remote, call it &quot;upstream&quot;: git remote add upstream https://github.com/whoever/whatever.git # Fetch all the branches of that remote into remote-tracking branches git fetch upstream # Make sure that you're on your master branch: git checkout master # Rewrite your master branch so that any commits of yours that # aren't already in upstream/master are replayed on top of that # other branch: git rebase upstream/master </code></pre> <p>If you don't want to rewrite the history of your master branch, (for example because other people may have cloned it) then you should replace the last command with <code>git merge upstream/master</code>. However, for making further pull requests that are as clean as possible, it's probably better to rebase.</p> <hr /> <p>If you've rebased your branch onto <code>upstream/master</code> you may need to force the push in order to push it to your own forked repository on GitHub. You'd do that with:</p> <pre><code>git push -f origin master </code></pre> <p>You only need to use the <code>-f</code> the first time after you've rebased.</p>
{ "question_id": 7244321, "question_date": "2011-08-30T13:53:00.447Z", "question_score": 4477, "tags": "git|github|synchronization|repository|git-fork", "answer_id": 7244456, "answer_date": "2011-08-30T14:01:26.267Z", "answer_score": 5098 }
Please answer the following Stack Overflow question: Title: How do I delete a remote tag? <p>How do I delete a Git tag that has already been pushed?</p>
<p>You can push an 'empty' reference to the remote tag name:</p> <pre><code>git push origin :tagname </code></pre> <p>Or, more expressively, use the <code>--delete</code> option (or <code>-d</code> if your git version is older than 1.8.0):</p> <pre><code>git push --delete origin tagname </code></pre> <p>Note that git has tag namespace and branch namespace so you may use the same name for a branch and for a tag. If you want to make sure that you cannot accidentally remove the branch instead of the tag, you can specify full ref which will never delete a branch:</p> <pre><code>git push origin :refs/tags/tagname </code></pre> <p>If you also need to delete the local tag, use:</p> <pre><code>git tag --delete tagname </code></pre> <hr /> <h3>Background</h3> <p>Pushing a branch, tag, or other ref to a remote repository involves specifying &quot;which repo, what source, what destination?&quot;</p> <pre><code>git push remote-repo source-ref:destination-ref </code></pre> <p>A real world example where you push your master branch to the origin's master branch is:</p> <pre><code>git push origin refs/heads/master:refs/heads/master </code></pre> <p>Which because of default paths, can be shortened to:</p> <pre><code>git push origin master:master </code></pre> <p>Tags work the same way:</p> <pre><code>git push origin refs/tags/release-1.0:refs/tags/release-1.0 </code></pre> <p>Which can also be shortened to:</p> <pre><code>git push origin release-1.0:release-1.0 </code></pre> <p>By omitting the source ref (the part before the colon), you push 'nothing' to the destination, deleting the ref on the remote end.</p>
{ "question_id": 5480258, "question_date": "2011-03-29T23:41:56.757Z", "question_score": 4418, "tags": "git|git-tag", "answer_id": 5480292, "answer_date": "2011-03-29T23:45:58.983Z", "answer_score": 7282 }
Please answer the following Stack Overflow question: Title: Difference between @staticmethod and @classmethod <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod" rel="noreferrer"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod" rel="noreferrer"><code>@classmethod</code></a>?</p>
<p>Maybe a bit of example code will help: Notice the difference in the call signatures of <code>foo</code>, <code>class_foo</code> and <code>static_foo</code>:</p> <pre><code>class A(object): def foo(self, x): print(f&quot;executing foo({self}, {x})&quot;) @classmethod def class_foo(cls, x): print(f&quot;executing class_foo({cls}, {x})&quot;) @staticmethod def static_foo(x): print(f&quot;executing static_foo({x})&quot;) a = A() </code></pre> <p>Below is the usual way an object instance calls a method. The object instance, <code>a</code>, is implicitly passed as the first argument.</p> <pre><code>a.foo(1) # executing foo(&lt;__main__.A object at 0xb7dbef0c&gt;, 1) </code></pre> <hr /> <p><strong>With classmethods</strong>, the class of the object instance is implicitly passed as the first argument instead of <code>self</code>.</p> <pre><code>a.class_foo(1) # executing class_foo(&lt;class '__main__.A'&gt;, 1) </code></pre> <p>You can also call <code>class_foo</code> using the class. In fact, if you define something to be a classmethod, it is probably because you intend to call it from the class rather than from a class instance. <code>A.foo(1)</code> would have raised a TypeError, but <code>A.class_foo(1)</code> works just fine:</p> <pre><code>A.class_foo(1) # executing class_foo(&lt;class '__main__.A'&gt;, 1) </code></pre> <p>One use people have found for class methods is to create <a href="https://stackoverflow.com/a/1950927/190597">inheritable alternative constructors</a>.</p> <hr /> <p><strong>With staticmethods</strong>, neither <code>self</code> (the object instance) nor <code>cls</code> (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:</p> <pre><code>a.static_foo(1) # executing static_foo(1) A.static_foo('hi') # executing static_foo(hi) </code></pre> <p>Staticmethods are used to group functions which have some logical connection with a class to the class.</p> <hr /> <p><code>foo</code> is just a function, but when you call <code>a.foo</code> you don't just get the function, you get a &quot;partially applied&quot; version of the function with the object instance <code>a</code> bound as the first argument to the function. <code>foo</code> expects 2 arguments, while <code>a.foo</code> only expects 1 argument.</p> <p><code>a</code> is bound to <code>foo</code>. That is what is meant by the term &quot;bound&quot; below:</p> <pre><code>print(a.foo) # &lt;bound method A.foo of &lt;__main__.A object at 0xb7d52f0c&gt;&gt; </code></pre> <p>With <code>a.class_foo</code>, <code>a</code> is not bound to <code>class_foo</code>, rather the class <code>A</code> is bound to <code>class_foo</code>.</p> <pre><code>print(a.class_foo) # &lt;bound method type.class_foo of &lt;class '__main__.A'&gt;&gt; </code></pre> <p>Here, with a staticmethod, even though it is a method, <code>a.static_foo</code> just returns a good 'ole function with no arguments bound. <code>static_foo</code> expects 1 argument, and <code>a.static_foo</code> expects 1 argument too.</p> <pre><code>print(a.static_foo) # &lt;function static_foo at 0xb7d479cc&gt; </code></pre> <p>And of course the same thing happens when you call <code>static_foo</code> with the class <code>A</code> instead.</p> <pre><code>print(A.static_foo) # &lt;function static_foo at 0xb7d479cc&gt; </code></pre>
{ "question_id": 136097, "question_date": "2008-09-25T21:01:57.843Z", "question_score": 4397, "tags": "python|oop|methods|python-decorators", "answer_id": 1669524, "answer_date": "2009-11-03T19:13:48.353Z", "answer_score": 3735 }
Please answer the following Stack Overflow question: Title: Why does Google prepend while(1); to their JSON responses? <p>Why does Google prepend <code>while(1);</code> to their (private) JSON responses?</p> <p>For example, here's a response while turning a calendar on and off in <a href="https://calendar.google.com/calendar/about/" rel="noreferrer">Google Calendar</a>:</p> <pre><code>while (1); [ ['u', [ ['smsSentFlag', 'false'], ['hideInvitations', 'false'], ['remindOnRespondedEventsOnly', 'true'], ['hideInvitations_remindOnRespondedEventsOnly', 'false_true'], ['Calendar ID stripped for privacy', 'false'], ['smsVerifiedFlag', 'true'] ]] ] </code></pre> <p>I would assume this is to prevent people from doing an <code>eval()</code> on it, but all you'd really have to do is replace the <code>while</code> and then you'd be set. I would assume the eval prevention is to make sure people write safe JSON parsing code.</p> <p>I've seen this used in a couple of other places, too, but a lot more so with Google (Mail, Calendar, Contacts, etc.) Strangely enough, <a href="https://www.google.com/docs/about/" rel="noreferrer">Google Docs</a> starts with <code>&amp;&amp;&amp;START&amp;&amp;&amp;</code> instead, and Google Contacts seems to start with <code>while(1); &amp;&amp;&amp;START&amp;&amp;&amp;</code>.</p> <p>What's going on here?</p>
<p>It prevents <a href="http://haacked.com/archive/2009/06/25/json-hijacking.aspx" rel="noreferrer">JSON hijacking</a>, a major JSON security issue that is formally <a href="https://security.stackexchange.com/questions/155518/why-json-hijacking-attack-doesnt-work-in-modern-browsers-how-was-it-fixed">fixed</a> in all major browsers <a href="https://caniuse.com/#feat=es5" rel="noreferrer">since 2011</a> with ECMAScript 5.</p> <p>Contrived example: say Google has a URL like <code>mail.google.com/json?action=inbox</code> which returns the first 50 messages of your inbox in JSON format. Evil websites on other domains can't make AJAX requests to get this data due to the same-origin policy, but they can include the URL via a <code>&lt;script&gt;</code> tag. The URL is visited with <em>your</em> cookies, and by <a href="http://ejohn.org/blog/re-securing-json/" rel="noreferrer">overriding the global array constructor or accessor methods</a> they can have a method called whenever an object (array or hash) attribute is set, allowing them to read the JSON content.</p> <p>The <code>while(1);</code> or <code>&amp;&amp;&amp;BLAH&amp;&amp;&amp;</code> prevents this: an AJAX request at <code>mail.google.com</code> will have full access to the text content, and can strip it away. But a <code>&lt;script&gt;</code> tag insertion blindly executes the JavaScript without any processing, resulting in either an infinite loop or a syntax error.</p> <p>This does not address the issue of <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery" rel="noreferrer">cross-site request forgery</a>.</p>
{ "question_id": 2669690, "question_date": "2010-04-19T18:00:09.750Z", "question_score": 4376, "tags": "javascript|json|ajax|security", "answer_id": 2669766, "answer_date": "2010-04-19T18:11:41.890Z", "answer_score": 4515 }
Please answer the following Stack Overflow question: Title: Understanding slicing <p>I need a good explanation (references are a plus) on Python slicing.</p>
<p>The syntax is:</p> <pre><code>a[start:stop] # items start through stop-1 a[start:] # items start through the rest of the array a[:stop] # items from the beginning through stop-1 a[:] # a copy of the whole array </code></pre> <p>There is also the <code>step</code> value, which can be used with any of the above:</p> <pre><code>a[start:stop:step] # start through not past stop, by step </code></pre> <p>The key point to remember is that the <code>:stop</code> value represents the first value that is <em>not</em> in the selected slice. So, the difference between <code>stop</code> and <code>start</code> is the number of elements selected (if <code>step</code> is 1, the default).</p> <p>The other feature is that <code>start</code> or <code>stop</code> may be a <em>negative</em> number, which means it counts from the end of the array instead of the beginning. So:</p> <pre><code>a[-1] # last item in the array a[-2:] # last two items in the array a[:-2] # everything except the last two items </code></pre> <p>Similarly, <code>step</code> may be a negative number:</p> <pre><code>a[::-1] # all items in the array, reversed a[1::-1] # the first two items, reversed a[:-3:-1] # the last two items, reversed a[-3::-1] # everything except the last two items, reversed </code></pre> <p>Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for <code>a[:-2]</code> and <code>a</code> only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.</p> <h3>Relationship with the <code>slice</code> object</h3> <p>A <a href="https://www.w3schools.com/python/ref_func_slice.asp" rel="noreferrer"><code>slice</code> object</a> can represent a slicing operation, i.e.:</p> <pre><code>a[start:stop:step] </code></pre> <p>is equivalent to:</p> <pre><code>a[slice(start, stop, step)] </code></pre> <p>Slice objects also behave slightly differently depending on the number of arguments, similarly to <code>range()</code>, i.e. both <code>slice(stop)</code> and <code>slice(start, stop[, step])</code> are supported. To skip specifying a given argument, one might use <code>None</code>, so that e.g. <code>a[start:]</code> is equivalent to <code>a[slice(start, None)]</code> or <code>a[::-1]</code> is equivalent to <code>a[slice(None, None, -1)]</code>.</p> <p>While the <code>:</code>-based notation is very helpful for simple slicing, the explicit use of <code>slice()</code> objects simplifies the programmatic generation of slicing.</p>
{ "question_id": 509211, "question_date": "2009-02-03T22:31:02.787Z", "question_score": 4336, "tags": "python|slice|sequence", "answer_id": 509295, "answer_date": "2009-02-03T22:48:24.687Z", "answer_score": 6143 }
Please answer the following Stack Overflow question: Title: Avoiding NullPointerException in Java <p>I use <code>x != null</code> to avoid <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/NullPointerException.html" rel="noreferrer"><code>NullPointerException</code></a>. Is there an alternative?</p> <pre class="lang-java prettyprint-override"><code>if (x != null) { // ... } </code></pre>
<p>This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.</p> <p>To put this another way, there are two instances where null checking comes up:</p> <ol> <li><p>Where null is a valid response in terms of the contract; and</p> </li> <li><p>Where it isn't a valid response.</p> </li> </ol> <p>(2) is easy. As of Java 1.7 you can use <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Objects.html#requireNonNull(T)" rel="noreferrer"><code>Objects.requireNonNull(foo)</code></a>. (If you are stuck with a previous version then <a href="https://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html" rel="noreferrer"><code>assert</code>ions</a> may be a good alternative.)</p> <p>&quot;Proper&quot; usage of this method would be like below. The method returns the object passed into it and throws a <code>NullPointerException</code> if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters.</p> <pre><code>public Foo(Bar bar) { this.bar = Objects.requireNonNull(bar); } </code></pre> <p>It can also be used like an <code>assert</code>ion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message.</p> <pre><code>Objects.requireNonNull(someobject, &quot;if someobject is null then something is wrong&quot;); someobject.doCalc(); </code></pre> <p>Generally throwing a specific exception like <code>NullPointerException</code> when a value is null but shouldn't be is favorable to throwing a more general exception like <code>AssertionError</code>. This is the approach the Java library takes; favoring <code>NullPointerException</code> over <code>IllegalArgumentException</code> when an argument is not allowed to be null.</p> <p>(1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it.</p> <p>If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time.</p> <p>With non-collections it might be harder. Consider this as an example: if you have these interfaces:</p> <pre><code>public interface Action { void doSomething(); } public interface Parser { Action findAction(String userInput); } </code></pre> <p>where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about.</p> <p>An alternative solution is to never return null and instead use the <a href="https://en.wikipedia.org/wiki/Null_Object_pattern" rel="noreferrer">Null Object pattern</a>:</p> <pre><code>public class MyParser implements Parser { private static Action DO_NOTHING = new Action() { public void doSomething() { /* do nothing */ } }; public Action findAction(String userInput) { // ... if ( /* we can't find any actions */ ) { return DO_NOTHING; } } } </code></pre> <p>Compare:</p> <pre><code>Parser parser = ParserFactory.getParser(); if (parser == null) { // now what? // this would be an example of where null isn't (or shouldn't be) a valid response } Action action = parser.findAction(someInput); if (action == null) { // do nothing } else { action.doSomething(); } </code></pre> <p>to</p> <pre><code>ParserFactory.getParser().findAction(someInput).doSomething(); </code></pre> <p>which is a much better design because it leads to more concise code.</p> <p>That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.</p> <pre><code>try { ParserFactory.getParser().findAction(someInput).doSomething(); } catch(ActionNotFoundException anfe) { userConsole.err(anfe.getMessage()); } </code></pre> <p>Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.</p> <pre><code>public Action findAction(final String userInput) { /* Code to return requested Action if found */ return new Action() { public void doSomething() { userConsole.err(&quot;Action not found: &quot; + userInput); } } } </code></pre>
{ "question_id": 271526, "question_date": "2008-11-07T08:31:40.203Z", "question_score": 4315, "tags": "java|nullpointerexception|null", "answer_id": 271874, "answer_date": "2008-11-07T12:06:40.507Z", "answer_score": 2804 }
Please answer the following Stack Overflow question: Title: Change a HTML5 input's placeholder color with CSS <p>Chrome supports the <a href="http://www.w3.org/html/wg/drafts/html/master/single-page.html#the-placeholder-attribute" rel="noreferrer" title="The placeholder attribute">placeholder attribute</a> on <code>input[type=text]</code> elements (others probably do too).</p> <p>But the following CSS doesn't do anything to the placeholder's value:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>input[placeholder], [placeholder], *[placeholder] { color: red !important; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="text" placeholder="Value"&gt;</code></pre> </div> </div> </p> <p>But <code>Value</code> will still remain <code>grey</code> instead of <code>red</code>.</p> <p><strong>Is there a way to change the color of the placeholder text?</strong></p>
<h2>Implementation</h2> <p>There are three different implementations: pseudo-elements, pseudo-classes, and nothing.</p> <ul> <li>WebKit, Blink (Safari, Google Chrome, Opera 15+) and Microsoft Edge are using a pseudo-element: <code>::-webkit-input-placeholder</code>. <sup>[<a href="https://bugs.webkit.org/show_bug.cgi?id=21227" rel="noreferrer">Ref</a>]</sup></li> <li>Mozilla Firefox 4 to 18 is using a pseudo-class: <code>:-moz-placeholder</code> (<em>one</em> colon). <sup>[<a href="https://developer.mozilla.org/en/CSS/:-moz-placeholder" rel="noreferrer">Ref</a>]</sup></li> <li>Mozilla Firefox 19+ is using a pseudo-element: <code>::-moz-placeholder</code>, but the old selector will still work for a while. <sup>[<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/%3A%3A-moz-placeholder" rel="noreferrer">Ref</a>]</sup></li> <li>Internet Explorer 10 and 11 are using a pseudo-class: <code>:-ms-input-placeholder</code>. <sup>[<a href="http://msdn.microsoft.com/en-us/library/ie/hh772745(v=vs.85).aspx" rel="noreferrer">Ref</a>]</sup></li> <li>April 2017: <strong>Most modern browsers support the simple pseudo-element <code>::placeholder</code> <sup>[<a href="https://caniuse.com/#feat=css-placeholder" rel="noreferrer">Ref</a>]</sup></strong></li> </ul> <p>Internet Explorer 9 and lower does not support the <code>placeholder</code> attribute at all, while <a href="http://web.archive.org/web/20131206060908/http://my.opera.com/community/forums/topic.dml?id=841252&amp;t=1296553904&amp;page=1#comment8072202" rel="noreferrer">Opera 12 and lower do not support</a> any CSS selector for placeholders.</p> <p>The discussion about the best implementation is still going on. Note the pseudo-elements act like real elements in the <a href="http://glazkov.com/2011/01/14/what-the-heck-is-shadow-dom/" rel="noreferrer">Shadow DOM</a>. A <code>padding</code> on an <code>input</code> will not get the same background color as the pseudo-element.</p> <h2>CSS selectors</h2> <p>User agents are required to ignore a rule with an unknown selector. See <a href="http://www.w3.org/TR/selectors/#Conformance" rel="noreferrer">Selectors Level 3</a>:</p> <blockquote> <p>a <a href="http://www.w3.org/TR/selectors/#grouping" rel="noreferrer">group</a> of selectors containing an invalid selector is invalid.</p> </blockquote> <p>So we need separate rules for each browser. Otherwise the whole group would be ignored by all browsers. <div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>::-webkit-input-placeholder { /* WebKit, Blink, Edge */ color: #909; } :-moz-placeholder { /* Mozilla Firefox 4 to 18 */ color: #909; opacity: 1; } ::-moz-placeholder { /* Mozilla Firefox 19+ */ color: #909; opacity: 1; } :-ms-input-placeholder { /* Internet Explorer 10-11 */ color: #909; } ::-ms-input-placeholder { /* Microsoft Edge */ color: #909; } ::placeholder { /* Most modern browsers support this now. */ color: #909; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input placeholder="Stack Snippets are awesome!"&gt;</code></pre> </div> </div> </p> <h2>Usage notes</h2> <ul> <li>Be careful to avoid bad contrasts. Firefox's placeholder appears to be defaulting with a reduced opacity, so needs to use <code>opacity: 1</code> here.</li> <li>Note that placeholder text is just cut off if it doesn’t fit – size your input elements in <code>em</code> and test them with big minimum font size settings. Don’t forget translations: some languages <a href="http://www.w3.org/International/articles/article-text-size.en" rel="noreferrer">need more room</a> for the same word.</li> <li>Browsers with HTML support for <code>placeholder</code> but without CSS support for that (like Opera) should be tested too.</li> <li>Placeholders are no replacement for labels, so make sure you have a label, too</li> <li>Some browsers use additional default CSS for some <code>input</code> types (<code>email</code>, <code>search</code>). These might affect the rendering in unexpected ways. Use the <a href="https://developer.mozilla.org/en-US/docs/CSS/-moz-appearance" rel="noreferrer">properties</a> <code>-webkit-appearance</code> and <code>-moz-appearance</code> to change that. Example:</li> </ul> <pre class="lang-css prettyprint-override"><code> [type=&quot;search&quot;] { -moz-appearance: textfield; -webkit-appearance: textfield; appearance: textfield; } </code></pre>
{ "question_id": 2610497, "question_date": "2010-04-09T19:54:53.263Z", "question_score": 4278, "tags": "css|html|placeholder|html-input", "answer_id": 2610741, "answer_date": "2010-04-09T20:36:56.707Z", "answer_score": 5052 }
Please answer the following Stack Overflow question: Title: How is Docker different from a virtual machine? <p>I keep rereading <a href="https://docs.docker.com/" rel="noreferrer">the Docker documentation</a> to try to understand the difference between Docker and a full VM. How does it manage to provide a full filesystem, isolated networking environment, etc. without being as heavy?</p> <p>Why is deploying software to a Docker image (if that's the right term) easier than simply deploying to a consistent production environment?</p>
<p>Docker originally used <a href="https://linuxcontainers.org/lxc/" rel="noreferrer">LinuX Containers</a> (LXC), but later switched to <a href="https://github.com/opencontainers/runc" rel="noreferrer">runC</a> (formerly known as <strong>libcontainer</strong>), which runs in the same operating system as its host. This allows it to share a lot of the host operating system resources. Also, it uses a layered filesystem (<a href="http://aufs.sourceforge.net/" rel="noreferrer">AuFS</a>) and manages networking.</p> <p>AuFS is a layered file system, so you can have a read only part and a write part which are merged together. One could have the common parts of the operating system as read only (and shared amongst all of your containers) and then give each container its own mount for writing.</p> <p>So, let's say you have a 1&nbsp;GB container image; if you wanted to use a full VM, you would need to have 1&nbsp;GB x number of VMs you want. With Docker and AuFS you can share the bulk of the 1&nbsp;GB between all the containers and if you have 1000 containers you still might only have a little over 1&nbsp;GB of space for the containers OS (assuming they are all running the same OS image).</p> <p>A full virtualized system gets its own set of resources allocated to it, and does minimal sharing. You get more isolation, but it is much heavier (requires more resources). With Docker you get less isolation, but the containers are lightweight (require fewer resources). So you could easily run thousands of containers on a host, and it won't even blink. Try doing that with Xen, and unless you have a really big host, I don't think it is possible.</p> <p>A full virtualized system usually takes minutes to start, whereas Docker/LXC/runC containers take seconds, and often even less than a second.</p> <p>There are pros and cons for each type of virtualized system. If you want full isolation with guaranteed resources, a full VM is the way to go. If you just want to isolate processes from each other and want to run a ton of them on a reasonably sized host, then Docker/LXC/runC seems to be the way to go.</p> <p>For more information, check out <a href="http://web.archive.org/web/20150326185901/http://blog.dotcloud.com/under-the-hood-linux-kernels-on-dotcloud-part" rel="noreferrer">this set of blog posts</a> which do a good job of explaining how LXC works.</p> <blockquote> <p>Why is deploying software to a docker image (if that's the right term) easier than simply deploying to a consistent production environment?</p> </blockquote> <p>Deploying a consistent production environment is easier said than done. Even if you use tools like <a href="https://en.wikipedia.org/wiki/Chef_%28software%29" rel="noreferrer">Chef</a> and <a href="https://en.wikipedia.org/wiki/Puppet_%28software%29" rel="noreferrer">Puppet</a>, there are always OS updates and other things that change between hosts and environments.</p> <p>Docker gives you the ability to snapshot the OS into a shared image, and makes it easy to deploy on other Docker hosts. Locally, dev, qa, prod, etc.: all the same image. Sure you can do this with other tools, but not nearly as easily or fast.</p> <p>This is great for testing; let's say you have thousands of tests that need to connect to a database, and each test needs a pristine copy of the database and will make changes to the data. The classic approach to this is to reset the database after every test either with custom code or with tools like <a href="https://flywaydb.org/" rel="noreferrer">Flyway</a> - this can be very time-consuming and means that tests must be run serially. However, with Docker you could create an image of your database and run up one instance per test, and then run all the tests in parallel since you know they will all be running against the same snapshot of the database. Since the tests are running in parallel and in Docker containers they could run all on the same box at the same time and should finish much faster. Try doing that with a full VM.</p> <p>From comments...</p> <blockquote> <p>Interesting! I suppose I'm still confused by the notion of "snapshot[ting] the OS". How does one do that without, well, making an image of the OS?</p> </blockquote> <p>Well, let's see if I can explain. You start with a base image, and then make your changes, and commit those changes using docker, and it creates an image. This image contains only the differences from the base. When you want to run your image, you also need the base, and it layers your image on top of the base using a layered file system: as mentioned above, Docker uses AuFS. AuFS merges the different layers together and you get what you want; you just need to run it. You can keep adding more and more images (layers) and it will continue to only save the diffs. Since Docker typically builds on top of ready-made images from a <a href="https://registry.hub.docker.com/" rel="noreferrer">registry</a>, you rarely have to "snapshot" the whole OS yourself.</p>
{ "question_id": 16047306, "question_date": "2013-04-16T21:19:47.263Z", "question_score": 4245, "tags": "docker|virtual-machine", "answer_id": 16048358, "answer_date": "2013-04-16T22:35:27.317Z", "answer_score": 3852 }
Please answer the following Stack Overflow question: Title: How to close/hide the Android soft keyboard programmatically? <p>I have an <code>EditText</code> and a <code>Button</code> in my layout.</p> <p>After writing in the edit field and clicking on the <code>Button</code>, I want to hide the virtual keyboard when touching it outside the keyboard. I assume that this is a simple piece of code, but where can I find an example of it?</p>
<p>To help clarify this madness, I'd like to begin by apologizing on behalf of all Android users for Google's downright ridiculous treatment of the soft keyboard. The reason there are so many answers, each different, for the same simple question is that this API, like many others in Android, is horribly designed. I can think of no polite way to state it.</p> <p>I want to hide the keyboard. I expect to provide Android with the following statement: <code>Keyboard.hide()</code>. The end. Thank you very much. But Android has a problem. You must use the <code>InputMethodManager</code> to hide the keyboard. OK, fine, this is Android's API to the keyboard. BUT! You are required to have a <code>Context</code> in order to get access to the IMM. Now we have a problem. I may want to hide the keyboard from a static or utility class that has no use or need for any <code>Context</code>. or And FAR worse, the IMM requires that you specify what <code>View</code> (or even worse, what <code>Window</code>) you want to hide the keyboard FROM.</p> <p>This is what makes hiding the keyboard so challenging. Dear Google: When I'm looking up the recipe for a cake, there is no <code>RecipeProvider</code> on Earth that would refuse to provide me with the recipe unless I first answer WHO the cake will be eaten by AND where it will be eaten!!</p> <p>This sad story ends with the ugly truth: to hide the Android keyboard, you will be required to provide 2 forms of identification: a <code>Context</code> and either a <code>View</code> or a <code>Window</code>.</p> <p>I have created a static utility method that can do the job VERY solidly, provided you call it from an <code>Activity</code>.</p> <pre><code>public static void hideKeyboard(Activity activity) { InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); //Find the currently focused view, so we can grab the correct window token from it. View view = activity.getCurrentFocus(); //If no view currently has focus, create a new one, just so we can grab a window token from it if (view == null) { view = new View(activity); } imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } </code></pre> <p>Be aware that this utility method ONLY works when called from an <code>Activity</code>! The above method calls <code>getCurrentFocus</code> of the target <code>Activity</code> to fetch the proper window token.</p> <p>But suppose you want to hide the keyboard from an <code>EditText</code> hosted in a <code>DialogFragment</code>? You can't use the method above for that:</p> <pre><code>hideKeyboard(getActivity()); //won't work </code></pre> <p>This won't work because you'll be passing a reference to the <code>Fragment</code>'s host <code>Activity</code>, which will have no focused control while the <code>Fragment</code> is shown! Wow! So, for hiding the keyboard from fragments, I resort to the lower-level, more common, and uglier:</p> <pre><code>public static void hideKeyboardFrom(Context context, View view) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } </code></pre> <p>Below is some additional information gleaned from more time wasted chasing this solution:</p> <p><strong>About windowSoftInputMode</strong></p> <p>There's yet another point of contention to be aware of. By default, Android will automatically assign initial focus to the first <code>EditText</code> or focusable control in your <code>Activity</code>. It naturally follows that the InputMethod (typically the soft keyboard) will respond to the focus event by showing itself. The <code>windowSoftInputMode</code> attribute in <code>AndroidManifest.xml</code>, when set to <code>stateAlwaysHidden</code>, instructs the keyboard to ignore this automatically-assigned initial focus.</p> <pre><code>&lt;activity android:name=&quot;.MyActivity&quot; android:windowSoftInputMode=&quot;stateAlwaysHidden&quot;/&gt; </code></pre> <p>Almost unbelievably, it appears to do nothing to prevent the keyboard from opening when you touch the control (unless <code>focusable=&quot;false&quot;</code> and/or <code>focusableInTouchMode=&quot;false&quot;</code> are assigned to the control). Apparently, the windowSoftInputMode setting applies only to automatic focus events, not to focus events triggered by touch events.</p> <p>Therefore, <code>stateAlwaysHidden</code> is VERY poorly named indeed. It should perhaps be called <code>ignoreInitialFocus</code> instead.</p> <hr /> <p><strong>UPDATE: More ways to get a window token</strong></p> <p>If there is no focused view (e.g. can happen if you just changed fragments), there are other views that will supply a useful window token.</p> <p>These are alternatives for the above code <code>if (view == null) view = new View(activity);</code> These don't refer explicitly to your activity.</p> <p>Inside a fragment class:</p> <pre><code>view = getView().getRootView().getWindowToken(); </code></pre> <p>Given a fragment <code>fragment</code> as a parameter:</p> <pre><code>view = fragment.getView().getRootView().getWindowToken(); </code></pre> <p>Starting from your content body:</p> <pre><code>view = findViewById(android.R.id.content).getRootView().getWindowToken(); </code></pre> <hr /> <p><strong>UPDATE 2: Clear focus to avoid showing keyboard again if you open the app from the background</strong></p> <p>Add this line to the end of the method:</p> <p><code>view.clearFocus();</code></p>
{ "question_id": 1109022, "question_date": "2009-07-10T11:27:17.090Z", "question_score": 4238, "tags": "android|android-edittext|android-softkeyboard|android-input-method|soft-keyboard", "answer_id": 17789187, "answer_date": "2013-07-22T13:44:29.240Z", "answer_score": 2493 }
Please answer the following Stack Overflow question: Title: How to enumerate an enum <p>How can you enumerate an <code>enum</code> in C#?</p> <p>E.g. the following code does not compile:</p> <pre class="lang-cs prettyprint-override"><code>public enum Suit { Spades, Hearts, Clubs, Diamonds } public void EnumerateAllSuitsDemoMethod() { foreach (Suit suit in Suit) { DoSomething(suit); } } </code></pre> <p>And it gives the following compile-time error:</p> <blockquote> <p>'Suit' is a 'type' but is used like a 'variable'</p> </blockquote> <p>It fails on the <code>Suit</code> keyword, the second one.</p>
<pre><code>foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit))) { } </code></pre> <p><strong>Note</strong>: The cast to <code>(Suit[])</code> is not strictly necessary, <a href="https://gist.github.com/bartoszkp/9e059c3edccc07a5e588#gistcomment-2625454" rel="noreferrer">but it does make the code 0.5 ns faster</a>.</p>
{ "question_id": 105372, "question_date": "2008-09-19T20:34:50.797Z", "question_score": 4236, "tags": "c#|.net|loops|enums|enumeration", "answer_id": 105402, "answer_date": "2008-09-19T20:37:18.187Z", "answer_score": 5136 }
Please answer the following Stack Overflow question: Title: How do I copy to the clipboard in JavaScript? <p>How do I copy text to the clipboard (multi-browser)?</p> <p>Related: <em><a href="https://stackoverflow.com/questions/17527870/how-does-trello-access-the-users-clipboard">How does Trello access the user&#39;s clipboard?</a></em></p>
<h1>Overview</h1> <p>There are three primary browser APIs for copying to the clipboard:</p> <ol> <li><p><a href="https://www.w3.org/TR/clipboard-apis/#async-clipboard-api" rel="noreferrer">Async Clipboard API</a> <code>[navigator.clipboard.writeText]</code></p> <ul> <li>Text-focused portion available in <a href="https://developers.google.com/web/updates/2018/03/clipboardapi" rel="noreferrer">Chrome 66 (March 2018)</a></li> <li>Access is asynchronous and uses <a href="https://developers.google.com/web/fundamentals/primers/promises" rel="noreferrer">JavaScript Promises</a>, can be written so security user prompts (if displayed) don't interrupt the JavaScript in the page.</li> <li>Text can be copied to the clipboard directly from a variable.</li> <li>Only supported on pages served over HTTPS.</li> <li>In Chrome 66 pages inactive tabs can write to the clipboard without a permissions prompt.</li> </ul> </li> <li><p><code>document.execCommand('copy')</code> (<em><strong><a href="https://developer.mozilla.org/docs/Web/API/Document/execCommand#browser_compatibility" rel="noreferrer">deprecated</a></strong></em>) </p> <ul> <li>Most browsers support this as of ~April 2015 (see Browser Support below).</li> <li>Access is synchronous, i.e. stops JavaScript in the page until complete including displaying and user interacting with any security prompts.</li> <li>Text is read from the DOM and placed on the clipboard.</li> <li>During testing ~April 2015 only Internet Explorer was noted as displaying permissions prompts whilst writing to the clipboard.</li> </ul> </li> <li><p>Overriding the copy event</p> <ul> <li>See Clipboard API documentation on <a href="https://w3c.github.io/clipboard-apis/#override-copy" rel="noreferrer">Overriding the copy event</a>.</li> <li>Allows you to modify what appears on the clipboard from any copy event, can include other formats of data other than plain text.</li> <li>Not covered here as it doesn't directly answer the question.</li> </ul> </li> </ol> <h1>General development notes</h1> <p>Don't expect clipboard related commands to work whilst you are testing code in the console. Generally, the page is required to be active (Async Clipboard API) or requires user interaction (e.g. a user click) to allow (<code>document.execCommand('copy')</code>) to access the clipboard see below for more detail.</p> <h2><strong>IMPORTANT</strong> (noted here 2020/02/20)</h2> <p>Note that since this post was originally written <a href="https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-permissions-in-cross-origin-iframes" rel="noreferrer">deprecation of permissions in cross-origin IFRAMEs</a> and other <a href="https://blog.chromium.org/2010/05/security-in-depth-html5s-sandbox.html" rel="noreferrer">IFRAME &quot;sandboxing&quot;</a> prevents the embedded demos &quot;Run code snippet&quot; buttons and &quot;codepen.io example&quot; from working in some browsers (including Chrome and Microsoft Edge).</p> <p>To develop create your own web page, serve that page over an HTTPS connection to test and develop against.</p> <p>Here is a test/demo page which demonstrates the code working: <a href="https://deanmarktaylor.github.io/clipboard-test/" rel="noreferrer">https://deanmarktaylor.github.io/clipboard-test/</a></p> <h1>Async + Fallback</h1> <p>Due to the level of browser support for the new Async Clipboard API, you will likely want to fall back to the <code>document.execCommand('copy')</code> method to get good browser coverage.</p> <p>Here is a simple example (may not work embedded in this site, read &quot;important&quot; note 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>function fallbackCopyTextToClipboard(text) { var textArea = document.createElement("textarea"); textArea.value = text; // Avoid scrolling to bottom textArea.style.top = "0"; textArea.style.left = "0"; textArea.style.position = "fixed"; document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Fallback: Copying text command was ' + msg); } catch (err) { console.error('Fallback: Oops, unable to copy', err); } document.body.removeChild(textArea); } function copyTextToClipboard(text) { if (!navigator.clipboard) { fallbackCopyTextToClipboard(text); return; } navigator.clipboard.writeText(text).then(function() { console.log('Async: Copying to clipboard was successful!'); }, function(err) { console.error('Async: Could not copy text: ', err); }); } var copyBobBtn = document.querySelector('.js-copy-bob-btn'), copyJaneBtn = document.querySelector('.js-copy-jane-btn'); copyBobBtn.addEventListener('click', function(event) { copyTextToClipboard('Bob'); }); copyJaneBtn.addEventListener('click', function(event) { copyTextToClipboard('Jane'); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="display:inline-block; vertical-align:top;"&gt; &lt;button class="js-copy-bob-btn"&gt;Set clipboard to BOB&lt;/button&gt;&lt;br /&gt;&lt;br /&gt; &lt;button class="js-copy-jane-btn"&gt;Set clipboard to JANE&lt;/button&gt; &lt;/div&gt; &lt;div style="display:inline-block;"&gt; &lt;textarea class="js-test-textarea" cols="35" rows="4"&gt;Try pasting into here to see what you have on your clipboard: &lt;/textarea&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>(codepen.io example may not work, read &quot;important&quot; note above) Note that this snippet is not working well in Stack Overflow's embedded preview you can try it here: <a href="https://codepen.io/DeanMarkTaylor/pen/RMRaJX?editors=1011" rel="noreferrer">https://codepen.io/DeanMarkTaylor/pen/RMRaJX?editors=1011</a></p> <h1>Async Clipboard API</h1> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API" rel="noreferrer">MDN Reference</a></li> <li><a href="https://developers.google.com/web/updates/2018/03/clipboardapi" rel="noreferrer">Chrome 66 announcement post (March 2018)</a></li> <li>Reference <a href="https://www.w3.org/TR/clipboard-apis/#async-clipboard-api" rel="noreferrer">Async Clipboard API</a> draft documentation</li> </ul> <p>Note that there is an ability to &quot;request permission&quot; and test for access to the clipboard via the permissions API in Chrome 66.</p> <pre><code>var text = &quot;Example text to appear on clipboard&quot;; navigator.clipboard.writeText(text).then(function() { console.log('Async: Copying to clipboard was successful!'); }, function(err) { console.error('Async: Could not copy text: ', err); }); </code></pre> <h1>document.execCommand('copy')</h1> <p>The rest of this post goes into the nuances and detail of the <code>document.execCommand('copy')</code> API.</p> <h2>Browser Support</h2> <p><del>The JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand" rel="noreferrer"><code>document.execCommand('copy')</code></a> support has grown, see the links below for browser updates:</del> (<em><strong><a href="https://developer.mozilla.org/docs/Web/API/Document/execCommand#browser_compatibility" rel="noreferrer">deprecated</a></strong></em>) </p> <ul> <li>Internet Explorer 10+ (although <a href="https://msdn.microsoft.com/en-us/library/ms537834(v=vs.85).aspx" rel="noreferrer">this document</a> indicates some support was there from Internet Explorer 5.5+).</li> <li><a href="https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en" rel="noreferrer">Google Chrome 43+ (~April 2015)</a></li> <li><a href="https://developer.mozilla.org/en-US/Firefox/Releases/41#Interfaces.2FAPIs.2FDOM" rel="noreferrer">Mozilla Firefox 41+ (shipping ~September 2015)</a></li> <li><a href="https://dev.opera.com/blog/opera-29/#cut-and-copy-commands" rel="noreferrer">Opera 29+ (based on Chromium 42, ~April 2015)</a></li> </ul> <h2>Simple Example</h2> <p>(may not work embedded in this site, read &quot;important&quot; note above) <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 copyTextareaBtn = document.querySelector('.js-textareacopybtn'); copyTextareaBtn.addEventListener('click', function(event) { var copyTextarea = document.querySelector('.js-copytextarea'); copyTextarea.focus(); copyTextarea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Copying text command was ' + msg); } catch (err) { console.log('Oops, unable to copy'); } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p&gt; &lt;button class="js-textareacopybtn" style="vertical-align:top;"&gt;Copy Textarea&lt;/button&gt; &lt;textarea class="js-copytextarea"&gt;Hello I'm some text&lt;/textarea&gt; &lt;/p&gt;</code></pre> </div> </div> </p> <h2>Complex Example: Copy to clipboard without displaying input</h2> <p>The above simple example works great if there is a <code>textarea</code> or <code>input</code> element visible on the screen.</p> <p>In some cases, you might wish to copy text to the clipboard without displaying an <code>input</code> / <code>textarea</code> element. This is one example of a way to work around this (basically insert an element, copy to clipboard, remove element):</p> <p>Tested with Google Chrome 44, Firefox 42.0a1, and Internet Explorer 11.0.8600.17814.</p> <p>(may not work embedded in this site, read &quot;important&quot; note above) <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 copyTextToClipboard(text) { var textArea = document.createElement("textarea"); // // *** This styling is an extra step which is likely not required. *** // // Why is it here? To ensure: // 1. the element is able to have focus and selection. // 2. if the element was to flash render it has minimal visual impact. // 3. less flakyness with selection and copying which **might** occur if // the textarea element is not visible. // // The likelihood is the element won't even render, not even a // flash, so some of these are just precautions. However in // Internet Explorer the element is visible whilst the popup // box asking the user for permission for the web page to // copy to the clipboard. // // Place in the top-left corner of screen regardless of scroll position. textArea.style.position = 'fixed'; textArea.style.top = 0; textArea.style.left = 0; // Ensure it has a small width and height. Setting to 1px / 1em // doesn't work as this gives a negative w/h on some browsers. textArea.style.width = '2em'; textArea.style.height = '2em'; // We don't need padding, reducing the size if it does flash render. textArea.style.padding = 0; // Clean up any borders. textArea.style.border = 'none'; textArea.style.outline = 'none'; textArea.style.boxShadow = 'none'; // Avoid flash of the white box if rendered for any reason. textArea.style.background = 'transparent'; textArea.value = text; document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Copying text command was ' + msg); } catch (err) { console.log('Oops, unable to copy'); } document.body.removeChild(textArea); } var copyBobBtn = document.querySelector('.js-copy-bob-btn'), copyJaneBtn = document.querySelector('.js-copy-jane-btn'); copyBobBtn.addEventListener('click', function(event) { copyTextToClipboard('Bob'); }); copyJaneBtn.addEventListener('click', function(event) { copyTextToClipboard('Jane'); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="display:inline-block; vertical-align:top;"&gt; &lt;button class="js-copy-bob-btn"&gt;Set clipboard to BOB&lt;/button&gt;&lt;br /&gt;&lt;br /&gt; &lt;button class="js-copy-jane-btn"&gt;Set clipboard to JANE&lt;/button&gt; &lt;/div&gt; &lt;div style="display:inline-block;"&gt; &lt;textarea class="js-test-textarea" cols="35" rows="4"&gt;Try pasting into here to see what you have on your clipboard: &lt;/textarea&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <h2>Additional notes</h2> <h3>Only works if the user takes an action</h3> <p>All <code>document.execCommand('copy')</code> calls must take place as a direct result of a user action, e.g. click event handler. This is a measure to prevent messing with the user's clipboard when they don't expect it.</p> <p>See the <a href="https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en" rel="noreferrer">Google Developers post here</a> for more info.</p> <h3>Clipboard API</h3> <p>Note the full Clipboard API draft specification can be found here: <a href="https://w3c.github.io/clipboard-apis/" rel="noreferrer">https://w3c.github.io/clipboard-apis/</a></p> <h3>Is it supported?</h3> <ul> <li><code>document.queryCommandSupported('copy')</code> should return <code>true</code> if the command &quot;is supported by the browser&quot;.</li> <li>and <code>document.queryCommandEnabled('copy')</code> return <code>true</code> if the <code>document.execCommand('copy')</code> will succeed if called now. Checking to ensure the command was called from a user-initiated thread and other requirements are met.</li> </ul> <p>However, as an example of browser compatibility issues, Google Chrome from ~April to ~October 2015 only returned <code>true</code> from <code>document.queryCommandSupported('copy')</code> if the command was called from a user-initiated thread.</p> <p>Note compatibility detail below.</p> <h3>Browser Compatibility Detail</h3> <p>Whilst a simple call to <code>document.execCommand('copy')</code> wrapped in a <code>try</code>/<code>catch</code> block called as a result of a user click will get you the most compatibility use the following has some provisos:</p> <p>Any call to <code>document.execCommand</code>, <code>document.queryCommandSupported</code> or <code>document.queryCommandEnabled</code> should be wrapped in a <code>try</code>/<code>catch</code> block.</p> <p>Different browser implementations and browser versions throw differing types of exceptions when called instead of returning <code>false</code>.</p> <p>Different browser implementations are still in flux and the <a href="https://w3c.github.io/clipboard-apis/" rel="noreferrer">Clipboard API</a> is still in draft, so remember to do your testing.</p>
{ "question_id": 400212, "question_date": "2008-12-30T13:09:05.777Z", "question_score": 4218, "tags": "javascript|clipboard|copy-paste", "answer_id": 30810322, "answer_date": "2015-06-12T18:56:18.323Z", "answer_score": 3187 }
Please answer the following Stack Overflow question: Title: How do I check if a directory exists in a Bash shell script? <p>What command checks if a directory exists or not within a Bash shell script?</p>
<p>To check if a directory exists:</p> <pre><code>if [ -d &quot;$DIRECTORY&quot; ]; then echo &quot;$DIRECTORY does exist.&quot; fi </code></pre> <p>To check if a directory does not exist:</p> <pre><code>if [ ! -d &quot;$DIRECTORY&quot; ]; then echo &quot;$DIRECTORY does not exist.&quot; fi </code></pre> <hr /> <p>However, as <a href="https://stackoverflow.com/users/1438/jon-ericson">Jon Ericson</a> points out, subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check. E.g. running this:</p> <pre><code>ln -s &quot;$ACTUAL_DIR&quot; &quot;$SYMLINK&quot; if [ -d &quot;$SYMLINK&quot; ]; then rmdir &quot;$SYMLINK&quot; fi </code></pre> <p>Will produce the error message:</p> <pre class="lang-none prettyprint-override"><code>rmdir: failed to remove `symlink': Not a directory </code></pre> <p>So symbolic links may have to be treated differently, if subsequent commands expect directories:</p> <pre><code>if [ -d &quot;$LINK_OR_DIR&quot; ]; then if [ -L &quot;$LINK_OR_DIR&quot; ]; then # It is a symlink! # Symbolic link specific commands go here. rm &quot;$LINK_OR_DIR&quot; else # It's a directory! # Directory command goes here. rmdir &quot;$LINK_OR_DIR&quot; fi fi </code></pre> <hr /> <p>Take particular note of the double-quotes used to wrap the variables. The reason for this is explained by 8jean <a href="https://stackoverflow.com/a/67458/102401">in another answer</a>.</p> <p>If the variables contain spaces or other unusual characters it will probably cause the script to fail.</p>
{ "question_id": 59838, "question_date": "2008-09-12T20:06:25.757Z", "question_score": 4207, "tags": "bash|shell|unix|posix", "answer_id": 59839, "answer_date": "2008-09-12T20:07:06.113Z", "answer_score": 5666 }
Please answer the following Stack Overflow question: Title: How do I remove a submodule? <p>How do I remove a Git submodule? Why can't I do <code>git submodule rm module_name</code>?</p>
<p>Since <a href="https://github.com/git/git/blob/v1.8.3-rc0/Documentation/RelNotes/1.8.3.txt#L135-L137" rel="noreferrer">git1.8.3 (April 22d, 2013)</a>:</p> <blockquote> <p>There was no Porcelain way to say &quot;I no longer am interested in this submodule&quot;, once you express your interest in a submodule with &quot;<code>git submodule init</code>&quot;.<br /> &quot;<strong><code>git submodule deinit</code></strong>&quot; is the way to do so.</p> </blockquote> <p>The deletion process also uses <code>git rm</code> (since git1.8.5 October 2013).</p> <h2>Summary</h2> <p>The 3-steps removal process would then be:</p> <pre><code>0. mv a/submodule a/submodule_tmp 1. git submodule deinit -f -- a/submodule 2. rm -rf .git/modules/a/submodule 3. git rm -f a/submodule # Note: a/submodule (no trailing slash) # or, if you want to leave it in your working tree and have done step 0 3. git rm --cached a/submodule 3bis mv a/submodule_tmp a/submodule </code></pre> <h2>Explanation</h2> <p><code>rm -rf</code>: This is mentioned in <a href="https://stackoverflow.com/users/2753241/daniel-schroeder">Daniel Schroeder</a>'s <a href="https://stackoverflow.com/a/26505847/6309">answer</a>, and summarized by <a href="https://stackoverflow.com/users/246776/eonil">Eonil</a> in <a href="https://stackoverflow.com/questions/1260748/how-do-i-remove-a-git-submodule/16162000?noredirect=1#comment41729982_16162000">the comments</a>:</p> <blockquote> <p>This leaves <code>.git/modules/&lt;path-to-submodule&gt;/</code> unchanged.<br /> So if you once delete a submodule with this method and re-add them again, it will not be possible because repository already been corrupted.</p> </blockquote> <hr /> <p><code>git rm</code>: See <a href="https://github.com/git/git/commit/95c16418f0375e2fc325f32c3d7578fba9cfd7ef" rel="noreferrer">commit 95c16418</a>:</p> <blockquote> <p>Currently using &quot;<code>git rm</code>&quot; on a submodule removes the submodule's work tree from that of the superproject and the gitlink from the index.<br /> But the submodule's section in <code>.gitmodules</code> is left untouched, which is a leftover of the now removed submodule and might irritate users (as opposed to the setting in <code>.git/config</code>, this must stay as a reminder that the user showed interest in this submodule so it will be repopulated later when an older commit is checked out).</p> </blockquote> <blockquote> <p>Let &quot;<code>git rm</code>&quot; help the user by not only removing the submodule from the work tree but by also removing the &quot;<code>submodule.&lt;submodule name&gt;</code>&quot; section from the <code>.gitmodules</code> file and stage both.</p> </blockquote> <hr /> <p><code>git submodule deinit</code>: It stems from <a href="http://git.661346.n2.nabble.com/PATCH-v3-submodule-add-deinit-command-td7576946.html" rel="noreferrer">this patch</a>:</p> <blockquote> <p>With &quot;<code>git submodule init</code>&quot; the user is able to tell git they care about one or more submodules and wants to have it populated on the next call to &quot;<code>git submodule update</code>&quot;.<br /> But currently there is no easy way they can tell git they do not care about a submodule anymore and wants to get rid of the local work tree (unless the user knows a lot about submodule internals and removes the &quot;<code>submodule.$name.url</code>&quot; setting from <code>.git/config</code> together with the work tree himself).</p> </blockquote> <blockquote> <p>Help those users by providing a '<strong><code>deinit</code></strong>' command.<br /> This <strong>removes the whole <code>submodule.&lt;name&gt;</code> section from <code>.git/config</code> either for the given submodule(s)</strong> (or for all those which have been initialized if '<code>.</code>' is given).<br /> Fail if the current work tree contains modifications unless forced.<br /> Complain when for a submodule given on the command line the url setting can't be found in <code>.git/config</code>, but nonetheless don't fail.</p> </blockquote> <p>This takes care if the (de)initialization steps (<code>.git/config</code> and <code>.git/modules/xxx</code>)</p> <p>Since git1.8.5, the <code>git rm</code> takes <em>also</em> care of the:</p> <ul> <li>'<code>add</code>' step which records the url of a submodule in the <code>.gitmodules</code> file: it is need to removed for you.</li> <li>the submodule <strong><a href="https://stackoverflow.com/questions/1992018/git-submodule-update-needed-only-initially/2227598#2227598">special entry</a></strong> (as illustrated by <a href="https://stackoverflow.com/q/16574625/6309">this question</a>): the git rm removes it from the index:<br /> <code>git rm --cached path_to_submodule</code> (no trailing slash)<br /> That will remove that directory stored in the index with a special mode &quot;160000&quot;, marking it as a submodule root directory.</li> </ul> <p>If you forget that last step, and try to add what was a submodule as a regular directory, you would get error message like:</p> <pre><code>git add mysubmodule/file.txt Path 'mysubmodule/file.txt' is in submodule 'mysubmodule' </code></pre> <hr /> <p>Note: since Git 2.17 (Q2 2018), git submodule deinit is no longer a shell script.<br /> It is a call to a C function.</p> <p>See <a href="https://github.com/git/git/commit/2e612731b55f1a83fb5b7f4ecb9391f0cba63cb2" rel="noreferrer">commit 2e61273</a>, <a href="https://github.com/git/git/commit/13424764db3273091d136bd470cf14852255c98c" rel="noreferrer">commit 1342476</a> (14 Jan 2018) by <a href="https://github.com/pratham-pc" rel="noreferrer">Prathamesh Chavan (<code>pratham-pc</code>)</a>.<br /> <sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/ead8dbe2e14ee9a2a18ccd0ad7bca806e1be0d54" rel="noreferrer">commit ead8dbe</a>, 13 Feb 2018)</sup></p> <pre><code>git ${wt_prefix:+-C &quot;$wt_prefix&quot;} submodule--helper deinit \ ${GIT_QUIET:+--quiet} \ ${prefix:+--prefix &quot;$prefix&quot;} \ ${force:+--force} \ ${deinit_all:+--all} &quot;$@&quot; </code></pre>
{ "question_id": 1260748, "question_date": "2009-08-11T14:31:24.183Z", "question_score": 4194, "tags": "git|git-submodules", "answer_id": 16162000, "answer_date": "2013-04-23T05:57:49.983Z", "answer_score": 2585 }
Please answer the following Stack Overflow question: Title: What are the differences between a HashMap and a Hashtable in Java? <p>What are the differences between a <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/HashMap.html" rel="noreferrer"><code>HashMap</code></a> and a <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Hashtable.html" rel="noreferrer"><code>Hashtable</code></a> in Java?</p> <p>Which is more efficient for non-threaded applications?</p>
<p>There are several differences between <a href="http://java.sun.com/javase/7/docs/api/java/util/HashMap.html" rel="noreferrer"><code>HashMap</code></a> and <a href="http://java.sun.com/javase/7/docs/api/java/util/Hashtable.html" rel="noreferrer"><code>Hashtable</code></a> in Java:</p> <ol> <li><p><code>Hashtable</code> is <a href="https://stackoverflow.com/questions/1085709/what-does-synchronized-mean">synchronized</a>, whereas <code>HashMap</code> is not. This makes <code>HashMap</code> better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.</p></li> <li><p><code>Hashtable</code> does not allow <code>null</code> keys or values. <code>HashMap</code> allows one <code>null</code> key and any number of <code>null</code> values.</p></li> <li><p>One of HashMap's subclasses is <a href="http://java.sun.com/javase/7/docs/api/java/util/LinkedHashMap.html" rel="noreferrer"><code>LinkedHashMap</code></a>, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the <code>HashMap</code> for a <code>LinkedHashMap</code>. This wouldn't be as easy if you were using <code>Hashtable</code>.</p></li> </ol> <p>Since synchronization is not an issue for you, I'd recommend <code>HashMap</code>. If synchronization becomes an issue, you may also look at <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="noreferrer"><code>ConcurrentHashMap</code></a>.</p>
{ "question_id": 40471, "question_date": "2008-09-02T20:12:00.117Z", "question_score": 4191, "tags": "java|collections|hashmap|hashtable", "answer_id": 40878, "answer_date": "2008-09-02T23:02:37.180Z", "answer_score": 4141 }
Please answer the following Stack Overflow question: Title: Finding the index of an item in a list <p>Given a list <code>[&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;]</code> and an item in the list <code>&quot;bar&quot;</code>, how do I get its index <code>1</code>?</p>
<pre><code>&gt;&gt;&gt; [&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;].index(&quot;bar&quot;) 1 </code></pre> <p>Reference: <a href="https://docs.python.org/tutorial/datastructures.html#more-on-lists" rel="noreferrer">Data Structures &gt; More on Lists</a></p> <h1>Caveats follow</h1> <p>Note that while this is perhaps the cleanest way to answer the question <em>as asked</em>, <code>index</code> is a rather weak component of the <code>list</code> API, and I can't remember the last time I used it in anger. It's been pointed out to me in the comments that because this answer is heavily referenced, it should be made more complete. Some caveats about <code>list.index</code> follow. It is probably worth initially taking a look at the documentation for it:</p> <blockquote> <pre><code>list.index(x[, start[, end]]) </code></pre> <p>Return zero-based index in the list of the first item whose value is equal to <em>x</em>. Raises a <a href="https://docs.python.org/library/exceptions.html#ValueError" rel="noreferrer"><code>ValueError</code></a> if there is no such item.</p> <p>The optional arguments <em>start</em> and <em>end</em> are interpreted as in the <a href="https://docs.python.org/tutorial/introduction.html#lists" rel="noreferrer">slice notation</a> and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.</p> </blockquote> <h2>Linear time-complexity in list length</h2> <p>An <code>index</code> call checks every element of the list in order, until it finds a match. If your list is long, and you don't know roughly where in the list it occurs, this search could become a bottleneck. In that case, you should consider a different data structure. Note that if you know roughly where to find the match, you can give <code>index</code> a hint. For instance, in this snippet, <code>l.index(999_999, 999_990, 1_000_000)</code> is roughly five orders of magnitude faster than straight <code>l.index(999_999)</code>, because the former only has to search 10 entries, while the latter searches a million:</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000) 9.356267921015387 &gt;&gt;&gt; timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000) 0.0004404920036904514 </code></pre> <h2>Only returns the index of the <em>first match</em> to its argument</h2> <p>A call to <code>index</code> searches through the list in order until it finds a match, and <em>stops there.</em> If you expect to need indices of more matches, you should use a list comprehension, or generator expression.</p> <pre><code>&gt;&gt;&gt; [1, 1].index(1) 0 &gt;&gt;&gt; [i for i, e in enumerate([1, 2, 1]) if e == 1] [0, 2] &gt;&gt;&gt; g = (i for i, e in enumerate([1, 2, 1]) if e == 1) &gt;&gt;&gt; next(g) 0 &gt;&gt;&gt; next(g) 2 </code></pre> <p>Most places where I once would have used <code>index</code>, I now use a list comprehension or generator expression because they're more generalizable. So if you're considering reaching for <code>index</code>, take a look at these excellent Python features.</p> <h2>Throws if element not present in list</h2> <p>A call to <code>index</code> results in a <a href="https://docs.python.org/library/exceptions.html#ValueError" rel="noreferrer"><code>ValueError</code></a> if the item's not present.</p> <pre><code>&gt;&gt;&gt; [1, 1].index(2) Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; ValueError: 2 is not in list </code></pre> <p>If the item might not be present in the list, you should either</p> <ol> <li>Check for it first with <code>item in my_list</code> (clean, readable approach), or</li> <li>Wrap the <code>index</code> call in a <code>try/except</code> block which catches <code>ValueError</code> (probably faster, at least when the list to search is long, and the item is usually present.)</li> </ol>
{ "question_id": 176918, "question_date": "2008-10-07T01:39:38.437Z", "question_score": 4141, "tags": "python|list|indexing", "answer_id": 176921, "answer_date": "2008-10-07T01:40:49.213Z", "answer_score": 5671 }
Please answer the following Stack Overflow question: Title: What is RESTful programming? <p>What exactly is <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" rel="noreferrer">RESTful programming</a>?</p>
<p>An <strong>architectural style</strong> called <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" rel="noreferrer"><strong>REST (Representational State Transfer)</strong></a> advocates that web applications should use HTTP as it was <strong>originally envisioned</strong>. Lookups should use <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods" rel="noreferrer"><code>GET</code></a> requests. <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods" rel="noreferrer"><code>PUT</code>, <code>POST</code>, and <code>DELETE</code> requests</a> should be used for <strong>mutation</strong>, <strong>creation</strong>, and <strong>deletion</strong> respectively.</p> <p>REST proponents tend to favor URLs, such as</p> <pre><code>http://myserver.com/catalog/item/1729 </code></pre> <p>but the REST architecture does not require these &quot;pretty URLs&quot;. A GET request with a parameter</p> <pre><code>http://myserver.com/catalog?item=1729 </code></pre> <p>is every bit as RESTful.</p> <p>Keep in mind that GET requests should never be used for updating information. For example, a GET request for adding an item to a cart</p> <pre><code>http://myserver.com/addToCart?cart=314159&amp;item=1729 </code></pre> <p>would not be appropriate. GET requests should be <a href="https://en.wikipedia.org/wiki/Idempotence" rel="noreferrer">idempotent</a>. That is, issuing a request twice should be no different from issuing it once. That's what makes the requests cacheable. An &quot;add to cart&quot; request is not idempotent—issuing it twice adds two copies of the item to the cart. A POST request is clearly appropriate in this context. Thus, even a <strong>RESTful web application</strong> needs its share of POST requests.</p> <p>This is taken from the excellent book <em>Core JavaServer faces</em> book by David M. Geary.</p>
{ "question_id": 671118, "question_date": "2009-03-22T14:45:39.317Z", "question_score": 4139, "tags": "rest|http|architecture|definition", "answer_id": 29648972, "answer_date": "2015-04-15T11:26:17.950Z", "answer_score": 806 }
Please answer the following Stack Overflow question: Title: How can I pair socks from a pile efficiently? <p>Yesterday I was pairing the socks from the clean laundry and figured out the way I was doing it is not very efficient. I was doing a naive search&nbsp;— picking one sock and "iterating" the pile in order to find its pair. This requires iterating over n/2 * n/4 = n<sup>2</sup>/8 socks on average.</p> <p>As a computer scientist I was thinking what I could do? Sorting (according to size/color/...) of course came to mind to achieve an O(NlogN) solution.</p> <p>Hashing or other not-in-place solutions are not an option, because I am not able to duplicate my socks (though it could be nice if I could).</p> <p><strong>So, the question is basically:</strong></p> <p>Given a pile of <code>n</code> pairs of socks, containing <code>2n</code> elements (assume each sock has exactly one matching pair), what is the best way to pair them up efficiently with up to logarithmic extra space? (I believe I can remember that amount of info if needed.)</p> <p>I will appreciate an answer that addresses the following aspects:</p> <ul> <li>A general <em>theoretical</em> solution for a huge number of socks.</li> <li>The actual number of socks is not that large, I don't believe my spouse and I have more than 30 pairs. (And it is fairly easy to distinguish between my socks and hers; can this be used as well?)</li> <li>Is it equivalent to the <a href="http://en.wikipedia.org/wiki/Element_distinctness_problem" rel="noreferrer">element distinctness problem</a>?</li> </ul>
<p>Sorting solutions have been proposed, but <strong>sorting is a little too much</strong>: We don't need order; <strong>we just need equality groups</strong>.</p> <p>So <strong>hashing</strong> would be enough (and faster).</p> <ol> <li>For each color of socks, <strong>form a pile</strong>. Iterate over all socks in your input basket <strong>and distribute them onto the color piles</strong>.</li> <li>Iterate over each pile and <strong>distribute it by some other metric</strong> (e.g. pattern) into the second set of piles</li> <li><strong>Recursively apply this scheme</strong> until you have distributed all socks onto <strong>very small piles that you can visually process immediately</strong></li> </ol> <p>This kind of recursive hash partitioning is actually being done by <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="noreferrer">SQL Server</a> when it needs to hash join or hash aggregate over huge data sets. It distributes its build input stream into many partitions which are independent. This scheme scales to arbitrary amounts of data and multiple CPUs linearly.</p> <p>You don't need recursive partitioning if you can find a distribution key (hash key) that <strong>provides enough buckets</strong> that each bucket is small enough to be processed very quickly. Unfortunately, I don't think socks have such a property.</p> <p>If each sock had an integer called "PairID" one could easily distribute them into 10 buckets according to <code>PairID % 10</code> (the last digit).</p> <p>The best real-world partitioning I can think of is creating a <strong>rectangle of piles</strong>: one dimension is color, the other is the pattern. Why a rectangle? Because we need O(1) random-access to piles. (A 3D <a href="http://en.wikipedia.org/wiki/Cuboid" rel="noreferrer">cuboid</a> would also work, but that is not very practical.)</p> <hr/> <p>Update:</p> <p>What about <strong>parallelism</strong>? Can multiple humans match the socks faster?</p> <ol> <li>The simplest parallelization strategy is to have multiple workers take from the input basket and put the socks onto the piles. This only scales up so much - imagine 100 people fighting over 10 piles. <strong>The synchronization costs</strong> (manifesting themselves as hand-collisions and human communication) <strong>destroy efficiency and speed-up</strong> (see the <a href="http://www.perfdynamics.com/Manifesto/USLscalability.html" rel="noreferrer">Universal Scalability Law</a>!). Is this prone to <strong>deadlocks</strong>? No, because each worker only needs to access one pile at a time. With just one "lock" there cannot be a deadlock. <strong>Livelocks</strong> might be possible depending on how the humans coordinate access to piles. They might just use <a href="http://en.wikipedia.org/wiki/Exponential_backoff" rel="noreferrer">random backoff</a> like network cards do that on a physical level to determine what card can exclusively access the network wire. If it works for <a href="http://en.wikipedia.org/wiki/Network_interface_controller" rel="noreferrer">NICs</a>, it should work for humans as well.</li> <li>It scales nearly indefinitely if <strong>each worker has its own set of piles</strong>. Workers can then take big chunks of socks from the input basket (very little contention as they are doing it rarely) and they do not need to synchronise when distributing the socks at all (because they have thread-local piles). At the end, all workers need to union their pile-sets. I believe that can be done in O(log (worker count * piles per worker)) if the workers form an <strong>aggregation tree</strong>.</li> </ol> <p>What about the <a href="http://en.wikipedia.org/wiki/Element_distinctness_problem" rel="noreferrer">element distinctness problem</a>? As the article states, the element distinctness problem can be solved in <code>O(N)</code>. This is the same for the socks problem (also <code>O(N)</code>, if you need only one distribution step (I proposed multiple steps only because humans are bad at calculations - one step is enough if you distribute on <code>md5(color, length, pattern, ...)</code>, i.e. a <strong>perfect hash</strong> of all attributes)).</p> <p>Clearly, one cannot go faster than <code>O(N)</code>, so we have reached the <strong>optimal lower bound</strong>.</p> <p>Although the outputs are not exactly the same (in one case, just a boolean. In the other case, the pairs of socks), the asymptotic complexities are the same.</p>
{ "question_id": 14415881, "question_date": "2013-01-19T15:34:35.667Z", "question_score": 4122, "tags": "algorithm|sorting|language-agnostic|matching", "answer_id": 14419556, "answer_date": "2013-01-19T22:27:57.507Z", "answer_score": 2553 }
Please answer the following Stack Overflow question: Title: How do I UPDATE from a SELECT in SQL Server? <p>In <strong>SQL Server</strong>, it is possible to insert rows into a table with an <code>INSERT.. SELECT</code> statement:</p> <pre><code>INSERT INTO Table (col1, col2, col3) SELECT col1, col2, col3 FROM other_table WHERE sql = 'cool' </code></pre> <p>Is it also possible to <em>update</em> a table with <code>SELECT</code>? I have a temporary table containing the values and would like to update another table using those values. Perhaps something like this:</p> <pre><code>UPDATE Table SET col1, col2 SELECT col1, col2 FROM other_table WHERE sql = 'cool' WHERE Table.id = other_table.id </code></pre>
<pre><code>UPDATE Table_A SET Table_A.col1 = Table_B.col1, Table_A.col2 = Table_B.col2 FROM Some_Table AS Table_A INNER JOIN Other_Table AS Table_B ON Table_A.id = Table_B.id WHERE Table_A.col3 = 'cool' </code></pre>
{ "question_id": 2334712, "question_date": "2010-02-25T14:36:53.113Z", "question_score": 4114, "tags": "sql|sql-server|tsql|select|sql-update", "answer_id": 2334741, "answer_date": "2010-02-25T14:39:55.367Z", "answer_score": 5851 }
Please answer the following Stack Overflow question: Title: Iterating over dictionaries using 'for' loops <pre><code>d = {'x': 1, 'y': 2, 'z': 3} for key in d: print(key, 'corresponds to', d[key]) </code></pre> <p>How does Python recognize that it needs only to read the <code>key</code> from the dictionary? Is <code>key</code> a special keyword, or is it simply a variable?</p>
<p><code>key</code> is just a variable name. </p> <pre><code>for key in d: </code></pre> <p>will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:</p> <p>For Python 3.x:</p> <pre><code>for key, value in d.items(): </code></pre> <p>For Python 2.x:</p> <pre><code>for key, value in d.iteritems(): </code></pre> <p>To test for yourself, change the word <code>key</code> to <code>poop</code>.</p> <p>In Python 3.x, <code>iteritems()</code> was replaced with simply <code>items()</code>, which returns a set-like view backed by the dict, like <code>iteritems()</code> but even better. This is also available in 2.7 as <code>viewitems()</code>. </p> <p>The operation <code>items()</code> will work for both 2 and 3, but in 2 it will return a list of the dictionary's <code>(key, value)</code> pairs, which will not reflect changes to the dict that happen after the <code>items()</code> call. If you want the 2.x behavior in 3.x, you can call <code>list(d.items())</code>.</p>
{ "question_id": 3294889, "question_date": "2010-07-20T22:27:42.460Z", "question_score": 4000, "tags": "python|dictionary", "answer_id": 3294899, "answer_date": "2010-07-20T22:29:33.213Z", "answer_score": 6490 }
Please answer the following Stack Overflow question: Title: Create ArrayList from array <p>Given an array of type <code>Element[]</code>:</p> <pre><code>Element[] array = {new Element(1), new Element(2), new Element(3)}; </code></pre> <p>How do I convert this array into an object of type <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html" rel="noreferrer"><code>ArrayList&lt;Element&gt;</code></a>?</p> <pre><code>ArrayList&lt;Element&gt; arrayList = ???; </code></pre>
<pre><code>new ArrayList&lt;&gt;(Arrays.asList(array)); </code></pre>
{ "question_id": 157944, "question_date": "2008-10-01T14:38:32.667Z", "question_score": 3994, "tags": "java|arrays|arraylist|type-conversion", "answer_id": 157950, "answer_date": "2008-10-01T14:39:12.010Z", "answer_score": 4998 }
Please answer the following Stack Overflow question: Title: grep: show lines surrounding each match <p>How do I <code>grep</code> and show the preceding and following 5 lines surrounding each matched line?</p>
<p>For <strong>BSD</strong> or <strong>GNU</strong> <code>grep</code> you can use <code>-B num</code> to set how many lines before the match and <code>-A num</code> for the number of lines after the match.</p> <pre><code>grep -B 3 -A 2 foo README.txt </code></pre> <p>If you want the same number of lines before and after you can use <code>-C num</code>.</p> <pre><code>grep -C 3 foo README.txt </code></pre> <p>This will show 3 lines before and 3 lines after.</p>
{ "question_id": 9081, "question_date": "2008-08-12T17:55:32.813Z", "question_score": 3973, "tags": "search|logging|grep|command-line-interface", "answer_id": 9083, "answer_date": "2008-08-12T17:57:43.307Z", "answer_score": 5233 }
Please answer the following Stack Overflow question: Title: How do I delete a commit from a branch? <p>How do I delete a commit from my branch history? Should I use <code>git reset --hard HEAD</code>?</p>
<p><strong>Careful:</strong> <code>git reset --hard</code> <em>WILL DELETE YOUR WORKING DIRECTORY CHANGES</em>. Be sure to <strong>stash any local changes you want to keep</strong> before running this command.</p> <p>Assuming you are sitting on that commit, then this command will wack it...</p> <pre><code>git reset --hard HEAD~1 </code></pre> <p>The <code>HEAD~1</code> means the commit before head.</p> <p>Or, you could look at the output of <code>git log</code>, find the commit id of the commit you want to back up to, and then do this:</p> <pre><code>git reset --hard &lt;sha1-commit-id&gt; </code></pre> <hr/> <p>If you already pushed it, you will need to do a force push to get rid of it...</p> <pre><code>git push origin HEAD --force </code></pre> <p><strong>However</strong>, if others may have pulled it, then you would be better off starting a new branch. Because when they pull, it will just merge it into their work, and you will get it pushed back up again.</p> <p>If you already pushed, it may be better to use <code>git revert</code>, to create a "mirror image" commit that will undo the changes. However, both commits will be in the log.</p> <hr /> <p>FYI -- <code>git reset --hard HEAD</code> is great if you want to get rid of WORK IN PROGRESS. It will reset you back to the most recent commit, and erase all the changes in your working tree and index.</p> <hr /> <p>Lastly, if you need to find a commit that you "deleted", it is typically present in <code>git reflog</code> unless you have garbage collected your repository.</p>
{ "question_id": 1338728, "question_date": "2009-08-27T03:39:50.927Z", "question_score": 3972, "tags": "git|git-rebase|git-reset", "answer_id": 1338744, "answer_date": "2009-08-27T03:44:04.727Z", "answer_score": 5075 }
Please answer the following Stack Overflow question: Title: Undoing a git rebase <p>How do I easily undo a git rebase? A lengthy manual method is:</p> <ol> <li>checkout the commit parent to both of the branches</li> <li>create and checkout a temporary branch</li> <li>cherry-pick all commits by hand</li> <li>reset the faulty rebased branch to point to the temporary branch</li> </ol> <p>In my current situation, this works because I can easily spot commits from both branches (one was my stuff, the other was my colleague's stuff). However, my approach strikes me as suboptimal and error-prone (let's say I had just rebased with two of my own branches).</p> <p>Clarification: I am talking about a rebase during which <em>multiple</em> commits were replayed, not only one.</p>
<p>The easiest way would be to find the head commit of the branch as it was immediately before the rebase started in the <a href="https://git-scm.com/docs/git-reflog" rel="noreferrer">reflog</a>...</p> <pre><code>git reflog </code></pre> <p>and to reset the current branch to it (with the usual caveats about being absolutely sure before reseting with the <code>--hard</code> option).</p> <p>Suppose the old commit was <code>HEAD@{2}</code> in the ref log:</p> <pre><code>git reset --hard HEAD@{2} </code></pre> <p><em>In Windows, you may need to quote the reference:</em></p> <pre><code>git reset --hard &quot;HEAD@{2}&quot; </code></pre> <p>You can check the history of the candidate old head by just doing a <code>git log HEAD@{2}</code> (<em>Windows:</em> <code>git log &quot;HEAD@{2}&quot;</code>).</p> <p>If you've not disabled per branch reflogs you should be able to simply do <code>git reflog branchname@{1}</code> as a rebase detaches the branch head before reattaching to the final head. I would double check this, though as I haven't verified this recently.</p> <p>Per default, all reflogs are activated for non-bare repositories:</p> <pre><code>[core] logAllRefUpdates = true </code></pre>
{ "question_id": 134882, "question_date": "2008-09-25T17:59:22.230Z", "question_score": 3944, "tags": "git|rebase|git-rebase|undo", "answer_id": 135614, "answer_date": "2008-09-25T19:56:28.343Z", "answer_score": 5435 }
Please answer the following Stack Overflow question: Title: What is the !! (not not) operator in JavaScript? <p>I saw some code that seems to use an operator I don't recognize, in the form of two exclamation points, like so: <code>!!</code>. Can someone please tell me what this operator does?</p> <p>The context in which I saw this was,</p> <pre><code>this.vertical = vertical !== undefined ? !!vertical : this.vertical; </code></pre>
<p>It converts <code>Object</code> to <code>boolean</code>. If it was falsey (e.g., <code>0</code>, <code>null</code>, <code>undefined</code>, etc.), it would be <code>false</code>, otherwise, <code>true</code>.</p> <pre><code>!object // Inverted Boolean !!object // Noninverted Boolean, so true Boolean representation </code></pre> <p>So <code>!!</code> is not an operator; it's just the <code>!</code> operator twice.</p> <p>It may be simpler to do:</p> <pre><code>Boolean(object) // Boolean </code></pre> <p>Real World Example &quot;Test IE version&quot;:</p> <pre><code>const isIE8 = !! navigator.userAgent.match(/MSIE 8.0/); console.log(isIE8); // Returns true or false </code></pre> <p>If you ⇒</p> <pre><code>console.log(navigator.userAgent.match(/MSIE 8.0/)); // Returns either an Array or null </code></pre> <p>But if you ⇒</p> <pre><code>console.log(!!navigator.userAgent.match(/MSIE 8.0/)); // Returns either true or false </code></pre>
{ "question_id": 784929, "question_date": "2009-04-24T08:13:58.470Z", "question_score": 3935, "tags": "javascript|operators", "answer_id": 784946, "answer_date": "2009-04-24T08:18:07.963Z", "answer_score": 3509 }
Please answer the following Stack Overflow question: Title: Proper use cases for Android UserManager.isUserAGoat()? <p>I was looking at the new APIs introduced in <a href="http://en.wikipedia.org/wiki/Android_version_history#Android_4.1.2F4.2_Jelly_Bean" rel="noreferrer">Android 4.2</a>. While looking at the <a href="http://developer.android.com/reference/android/os/UserManager.html" rel="noreferrer"><code>UserManager</code></a> class I came across the following method:</p> <blockquote> <pre><code>public boolean isUserAGoat() </code></pre> <p>Used to determine whether the user making this call is subject to teleportations.</p> <p>Returns whether the user making this call is a goat.</p> </blockquote> <p>How and when should this be used?</p>
<h3>Android R Update:</h3> <p>From Android R, this method always returns false. Google says that this is done &quot;to protect goat privacy&quot;:</p> <pre><code>/** * Used to determine whether the user making this call is subject to * teleportations. * * &lt;p&gt;As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can * now automatically identify goats using advanced goat recognition technology.&lt;/p&gt; * * &lt;p&gt;As of {@link android.os.Build.VERSION_CODES#R}, this method always returns * {@code false} in order to protect goat privacy.&lt;/p&gt; * * @return Returns whether the user making this call is a goat. */ public boolean isUserAGoat() { if (mContext.getApplicationInfo().targetSdkVersion &gt;= Build.VERSION_CODES.R) { return false; } return mContext.getPackageManager() .isPackageAvailable(&quot;com.coffeestainstudios.goatsimulator&quot;); } </code></pre> <hr /> <h3>Previous answer:</h3> <p>From their <strong><a href="https://android.googlesource.com/platform/frameworks/base/+/android-5.0.0_r6/core/java/android/os/UserManager.java#433" rel="noreferrer">source</a></strong>, the method used to return <code>false</code> until it was changed in API 21.</p> <pre><code>/** * Used to determine whether the user making this call is subject to * teleportations. * @return whether the user making this call is a goat */ public boolean isUserAGoat() { return false; } </code></pre> <p>It looks like the method has no real use for us as developers. Someone has previously stated that it might be an <strong><a href="http://en.wikipedia.org/wiki/Easter_egg_(media)" rel="noreferrer">Easter egg</a></strong>.</p> <p>In API 21 the implementation was changed to check if there is an installed app with the package <code>com.coffeestainstudios.goatsimulator</code></p> <pre><code>/** * Used to determine whether the user making this call is subject to * teleportations. * * &lt;p&gt;As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can * now automatically identify goats using advanced goat recognition technology.&lt;/p&gt; * * @return Returns true if the user making this call is a goat. */ public boolean isUserAGoat() { return mContext.getPackageManager() .isPackageAvailable(&quot;com.coffeestainstudios.goatsimulator&quot;); } </code></pre> <p>Here is the <a href="https://android.googlesource.com/platform/frameworks/base/+/android-5.0.0_r6/core/java/android/os/UserManager.java#442" rel="noreferrer">source</a> and the <a href="https://android.googlesource.com/platform/frameworks/base/+/e4ab16ad98b183afbf7a21ad7314372de41a8b57%5E%21/#F1" rel="noreferrer">change</a>.</p>
{ "question_id": 13375357, "question_date": "2012-11-14T08:34:01.523Z", "question_score": 3935, "tags": "java|android|usermanager", "answer_id": 13375461, "answer_date": "2012-11-14T08:40:30.647Z", "answer_score": 1953 }
Please answer the following Stack Overflow question: Title: How can I validate an email address using a regular expression? <p>Over the years I have slowly developed a <a href="http://en.wikipedia.org/wiki/Regular_expression" rel="noreferrer">regular expression</a> that validates <em>most</em> email addresses correctly, assuming they don't use an IP address as the server part.</p> <p>I use it in several PHP programs, and it works most of the time. However, from time to time I get contacted by someone that is having trouble with a site that uses it, and I end up having to make some adjustment (most recently I realized that I wasn't allowing four-character <a href="https://en.wikipedia.org/wiki/Top-level_domain" rel="noreferrer">TLDs</a>).</p> <p><em>What is the best regular expression you have or have seen for validating emails?</em></p> <p>I've seen several solutions that use functions that use several shorter expressions, but I'd rather have one long complex expression in a simple function instead of several short expression in a more complex function.</p>
<p>The <a href="http://ex-parrot.com/%7Epdw/Mail-RFC822-Address.html" rel="noreferrer">fully RFC 822 compliant regex</a> is inefficient and obscure because of its length. Fortunately, RFC 822 was superseded twice and the current specification for email addresses is <a href="https://datatracker.ietf.org/doc/html/rfc5322" rel="noreferrer">RFC 5322</a>. RFC 5322 leads to a regex that can be understood if studied for a few minutes and is efficient enough for actual use.</p> <p>One RFC 5322 compliant regex can be found at the top of the page at <a href="http://emailregex.com/" rel="noreferrer">http://emailregex.com/</a> but uses the IP address pattern that is floating around the internet with a bug that allows <code>00</code> for any of the unsigned byte decimal values in a dot-delimited address, which is illegal. The rest of it appears to be consistent with the RFC 5322 grammar and passes several tests using <code>grep -Po</code>, including cases domain names, IP addresses, bad ones, and account names with and without quotes.</p> <p>Correcting the <code>00</code> bug in the IP pattern, we obtain a working and fairly fast regex. (Scrape the rendered version, not the markdown, for actual code.)</p> <blockquote> <p>(?:[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*|&quot;(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*&quot;)@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])</p> </blockquote> <p>or:</p> <pre><code>(?:[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*|&quot;(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*&quot;)@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]) </code></pre> <p>Here is <a href="https://regexper.com/#(%3F%3A%5Ba-z0-9!%23%24%25%26%27*%2B%2F%3D%3F%5E_%60%7B%7C%7D%7E-%5D%2B(%3F%3A%5C.%5Ba-z0-9!%23%24%25%26%27*%2B%2F%3D%3F%5E_%60%7B%7C%7D%7E-%5D%2B)*%7C%22(%3F%3A%5B%5Cx01-%5Cx08%5Cx0b%5Cx0c%5Cx0e-%5Cx1f%5Cx21%5Cx23-%5Cx5b%5Cx5d-%5Cx7f%5D%7C%5C%5C%5B%5Cx01-%5Cx09%5Cx0b%5Cx0c%5Cx0e-%5Cx7f%5D)*%22)%40(%3F%3A(%3F%3A%5Ba-z0-9%5D(%3F%3A%5Ba-z0-9-%5D*%5Ba-z0-9%5D)%3F%5C.)%2B%5Ba-z0-9%5D(%3F%3A%5Ba-z0-9-%5D*%5Ba-z0-9%5D)%3F%7C%5C%5B(%3F%3A(%3F%3A(2(5%5B0-5%5D%7C%5B0-4%5D%5B0-9%5D)%7C1%5B0-9%5D%5B0-9%5D%7C%5B1-9%5D%3F%5B0-9%5D))%5C.)%7B3%7D(%3F%3A(2(5%5B0-5%5D%7C%5B0-4%5D%5B0-9%5D)%7C1%5B0-9%5D%5B0-9%5D%7C%5B1-9%5D%3F%5B0-9%5D)%7C%5Ba-z0-9-%5D*%5Ba-z0-9%5D%3A(%3F%3A%5B%5Cx01-%5Cx08%5Cx0b%5Cx0c%5Cx0e-%5Cx1f%5Cx21-%5Cx5a%5Cx53-%5Cx7f%5D%7C%5C%5C%5B%5Cx01-%5Cx09%5Cx0b%5Cx0c%5Cx0e-%5Cx7f%5D)%2B)%5C%5D)" rel="noreferrer">diagram</a> of <a href="https://en.wikipedia.org/wiki/Finite-state_machine" rel="noreferrer">finite state machine</a> for above regexp which is more clear than regexp itself <a href="https://i.stack.imgur.com/YI6KR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YI6KR.png" alt="enter image description here" /></a></p> <p>The more sophisticated patterns in Perl and PCRE (regex library used e.g. in PHP) can <a href="https://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/1917982#1917982">correctly parse RFC 5322 without a hitch</a>. Python and C# can do that too, but they use a different syntax from those first two. However, if you are forced to use one of the many less powerful pattern-matching languages, then it’s best to use a real parser.</p> <p>It's also important to understand that validating it per the RFC tells you absolutely nothing about whether that address actually exists at the supplied domain, or whether the person entering the address is its true owner. People sign others up to mailing lists this way all the time. Fixing that requires a fancier kind of validation that involves sending that address a message that includes a confirmation token meant to be entered on the same web page as was the address.</p> <p>Confirmation tokens are the only way to know you got the address of the person entering it. This is why most mailing lists now use that mechanism to confirm sign-ups. After all, anybody can put down <code>president@whitehouse.gov</code>, and that will even parse as legal, but it isn't likely to be the person at the other end.</p> <p>For PHP, you should <em>not</em> use the pattern given in <a href="http://www.linuxjournal.com/article/9585" rel="noreferrer">Validate an E-Mail Address with PHP, the Right Way</a> from which I quote:</p> <blockquote> <p>There is some danger that common usage and widespread sloppy coding will establish a de facto standard for e-mail addresses that is more restrictive than the recorded formal standard.</p> </blockquote> <p>That is no better than all the other non-RFC patterns. It isn’t even smart enough to handle even <a href="https://datatracker.ietf.org/doc/html/rfc822" rel="noreferrer">RFC 822</a>, let alone RFC 5322. <a href="https://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/1917982#1917982">This one</a>, however, is.</p> <p>If you want to get fancy and pedantic, <a href="http://cubicspot.blogspot.com/2012/06/correct-way-to-validate-e-mail-address.html" rel="noreferrer">implement a complete state engine</a>. A regular expression can only act as a rudimentary filter. The problem with regular expressions is that telling someone that their perfectly valid e-mail address is invalid (a false positive) because your regular expression can't handle it is just rude and impolite from the user's perspective. A state engine for the purpose can both validate and even correct e-mail addresses that would otherwise be considered invalid as it disassembles the e-mail address according to each RFC. This allows for a potentially more pleasing experience, like</p> <blockquote> <p>The specified e-mail address 'myemail@address,com' is invalid. Did you mean 'myemail@address.com'?</p> </blockquote> <p>See also <a href="http://worsethanfailure.com/Articles/Validating_Email_Addresses.aspx" rel="noreferrer">Validating Email Addresses</a>, including the comments. Or <a href="http://fightingforalostcause.net/misc/2006/compare-email-regex.php" rel="noreferrer">Comparing E-mail Address Validating Regular Expressions</a>.</p> <p><a href="https://i.stack.imgur.com/SrUwP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SrUwP.png" alt="Regular expression visualization" /></a></p> <p><a href="https://www.debuggex.com/r/aH_x42NflV8G-GS7" rel="noreferrer">Debuggex Demo</a></p>
{ "question_id": 201323, "question_date": "2008-10-14T14:14:34.980Z", "question_score": 3929, "tags": "regex", "answer_id": 201378, "answer_date": "2008-10-14T14:26:43.723Z", "answer_score": 3118 }
Please answer the following Stack Overflow question: Title: How to insert an item into an array at a specific index (JavaScript) <p>I am looking for a JavaScript array insert method, in the style of:</p> <pre><code>arr.insert(index, item) </code></pre> <p>Preferably in jQuery, but any JavaScript implementation will do at this point.</p>
<p>You want the <strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice" rel="noreferrer"><code>splice</code></a></strong> function on the native array object.</p> <p><code>arr.splice(index, 0, item);</code> will insert <code>item</code> into <code>arr</code> at the specified <code>index</code> (deleting <code>0</code> items first, that is, it's just an insert).</p> <p>In this example we will create an array and add an element to it into index 2:</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 arr = []; arr[0] = "Jani"; arr[1] = "Hege"; arr[2] = "Stale"; arr[3] = "Kai Jim"; arr[4] = "Borge"; console.log(arr.join()); // Jani,Hege,Stale,Kai Jim,Borge arr.splice(2, 0, "Lene"); console.log(arr.join()); // Jani,Hege,Lene,Stale,Kai Jim,Borge</code></pre> </div> </div> </p>
{ "question_id": 586182, "question_date": "2009-02-25T14:29:30.877Z", "question_score": 3923, "tags": "javascript|arrays", "answer_id": 586189, "answer_date": "2009-02-25T14:32:56.157Z", "answer_score": 6284 }
Please answer the following Stack Overflow question: Title: How do I test for an empty JavaScript object? <p>After an AJAX request, sometimes my application may return an empty object, like:</p> <pre><code>var a = {}; </code></pre> <p>How can I check whether that's the case?</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys#Browser_compatibility" rel="noreferrer">ECMA 5+</a>:</p> <pre><code>// because Object.keys(new Date()).length === 0; // we have to do some additional check obj // null and undefined check &amp;&amp; Object.keys(obj).length === 0 &amp;&amp; Object.getPrototypeOf(obj) === Object.prototype </code></pre> <p>Note, though, that this creates an unnecessary array (the return value of <code>keys</code>).</p> <p>Pre-ECMA 5:</p> <pre><code>function isEmpty(obj) { for(var prop in obj) { if(Object.prototype.hasOwnProperty.call(obj, prop)) { return false; } } return JSON.stringify(obj) === JSON.stringify({}); } </code></pre> <p><a href="https://api.jquery.com/jQuery.isEmptyObject/" rel="noreferrer">jQuery</a>:</p> <pre><code>jQuery.isEmptyObject({}); // true </code></pre> <p><a href="https://lodash.com/docs#isEmpty" rel="noreferrer">lodash</a>:</p> <pre><code>_.isEmpty({}); // true </code></pre> <p><a href="https://underscorejs.org/#isEmpty" rel="noreferrer">Underscore</a>:</p> <pre><code>_.isEmpty({}); // true </code></pre> <p><a href="https://github.com/hapijs/hoek" rel="noreferrer">Hoek</a></p> <pre><code>Hoek.deepEqual({}, {}); // true </code></pre> <p><a href="https://docs.sencha.com/extjs/6.0.2/modern/Ext.Object.html#method-isEmpty" rel="noreferrer">ExtJS</a></p> <pre><code>Ext.Object.isEmpty({}); // true </code></pre> <p><a href="https://docs.angularjs.org/api/ng/function/angular.equals" rel="noreferrer">AngularJS (version 1)</a></p> <pre><code>angular.equals({}, {}); // true </code></pre> <p><a href="https://ramdajs.com/docs/#isEmpty" rel="noreferrer">Ramda</a></p> <pre><code>R.isEmpty({}); // true </code></pre>
{ "question_id": 679915, "question_date": "2009-03-25T01:39:45.860Z", "question_score": 3894, "tags": "javascript|javascript-objects", "answer_id": 32108184, "answer_date": "2015-08-20T01:32:52.957Z", "answer_score": 7213 }