input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Is there a link to the "latest" jQuery library on Google APIs? <p>I use the following for a jQuery link in my <code>&lt;script&gt;</code> tags:</p> <pre><code>http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js </code></pre> <p>Is there a link to the "latest" version? Something like the following (which doesn't work):</p> <pre><code>http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js </code></pre> <p>(Obviously not necessarily a great plan to link your code to potentially changing libraries but useful in development.)</p>
<p><strong>Up until jQuery 1.11.1</strong>, you could use the following URLs to get the latest version of jQuery:</p> <ul> <li><a href="https://code.jquery.com/jquery-latest.min.js" rel="noreferrer">https://code.jquery.com/jquery-latest.min.js</a> - jQuery hosted (minified)</li> <li><a href="https://code.jquery.com/jquery-latest.js" rel="noreferrer">https://code.jquery.com/jquery-latest.js</a> - jQuery hosted (uncompressed)</li> <li><a href="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" rel="noreferrer">https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js</a> - Google hosted (minified)</li> <li><a href="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js" rel="noreferrer">https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js</a> - Google hosted (uncompressed)</li> </ul> <p>For example:</p> <pre><code>&lt;script src="https://code.jquery.com/jquery-latest.min.js"&gt;&lt;/script&gt; </code></pre> <hr> <p>However, since jQuery 1.11.1, both jQuery and Google stopped updating these URL's; they will <em>forever</em> be fixed at 1.11.1. There is no supported alternative URL to use. For an explanation of why this is the case, see this blog post; <a href="http://blog.jquery.com/2014/07/03/dont-use-jquery-latest-js/" rel="noreferrer">Don't use jquery-latest.js</a>.</p> <p>Both hosts support <code>https</code> as well as <code>http</code>, so change the protocol as you see fit (or use a <a href="http://www.paulirish.com/2010/the-protocol-relative-url/" rel="noreferrer">protocol relative URI</a>)</p> <p>See also: <a href="https://developers.google.com/speed/libraries/devguide" rel="noreferrer">https://developers.google.com/speed/libraries/devguide</a></p>
{ "question_id": 441412, "question_date": "2009-01-14T00:08:57.947Z", "question_score": 799, "tags": "javascript|jquery|google-api", "answer_id": 441429, "answer_date": "2009-01-14T00:16:33.953Z", "answer_score": 1021 }
Please answer the following Stack Overflow question: Title: What is the use of the JavaScript 'bind' method? <p>What is the use of <code>bind()</code> in JavaScript?</p>
<p>Bind creates a new function that will force the <code>this</code> inside the function to be the parameter passed to <code>bind()</code>.</p> <p>Here's an example that shows how to use <code>bind</code> to pass a member method around that has the correct <code>this</code>:</p> <pre><code>var myButton = { content: 'OK', click() { console.log(this.content + ' clicked'); } }; myButton.click(); var looseClick = myButton.click; looseClick(); // not bound, 'this' is not myButton - it is the globalThis var boundClick = myButton.click.bind(myButton); boundClick(); // bound, 'this' is myButton </code></pre> <p>Which prints out:</p> <pre><code>OK clicked undefined clicked OK clicked </code></pre> <p>You can also add extra parameters after the 1st (<code>this</code>) parameter and <code>bind</code> will pass in those values to the original function. Any additional parameters you later pass to the bound function will be passed in after the bound parameters:</p> <pre><code>// Example showing binding some parameters var sum = function(a, b) { return a + b; }; var add5 = sum.bind(null, 5); console.log(add5(10)); </code></pre> <p>Which prints out:</p> <pre><code>15 </code></pre> <p>Check out <a href="http://www.javascripture.com/Function#bind" rel="noreferrer">JavaScript Function bind</a> for more info and interactive examples.</p> <p>Update: ECMAScript 2015 adds support for <code>=&gt;</code> functions. <code>=&gt;</code> functions are more compact and do not change the <code>this</code> pointer from their defining scope, so you may not need to use <code>bind()</code> as often. For example, if you wanted a function on <code>Button</code> from the first example to hook up the <code>click</code> callback to a DOM event, the following are all valid ways of doing that:</p> <pre><code>var myButton = { ... // As above hookEvent(element) { // Use bind() to ensure 'this' is the 'this' inside click() element.addEventListener('click', this.click.bind(this)); } }; </code></pre> <p>Or: </p> <pre><code>var myButton = { ... // As above hookEvent(element) { // Use a new variable for 'this' since 'this' inside the function // will not be the 'this' inside hookEvent() var me = this; element.addEventListener('click', function() { me.click() }); } }; </code></pre> <p>Or:</p> <pre><code>var myButton = { ... // As above hookEvent(element) { // =&gt; functions do not change 'this', so you can use it directly element.addEventListener('click', () =&gt; this.click()); } }; </code></pre>
{ "question_id": 2236747, "question_date": "2010-02-10T12:33:48.180Z", "question_score": 799, "tags": "javascript|function|bind", "answer_id": 10115970, "answer_date": "2012-04-12T00:46:51.493Z", "answer_score": 798 }
Please answer the following Stack Overflow question: Title: Loaded nib but the 'view' outlet was not set <p>I added a new nib file to my project, and tried to load it.</p> <p>However, when I click on the toolbar icon that is supposed to take me to the view that I created, I get an <code>NSInternalInconsistencyException</code> with the message:</p> <blockquote> <p>Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "..." nib but the view outlet was not set.'</p> </blockquote> <p>So I opened up my nib file, and I see for the view that there are no referencing outlets set. However, I try to click and drag the circle for "new referencing outlet" to File's Owner, but it won't let me...what do I need to do to get my view to display?</p>
<p>The View Identity - Class Identity was not set. After setting it to the appropriate class, the issue was resolved.</p>
{ "question_id": 4763519, "question_date": "2011-01-21T20:35:37.860Z", "question_score": 799, "tags": "ios|cocoa-touch|interface-builder|xib", "answer_id": 4798782, "answer_date": "2011-01-25T21:03:40.070Z", "answer_score": 64 }
Please answer the following Stack Overflow question: Title: ECMAScript 6 arrow function that returns an object <p>When returning an object from an arrow function, it seems that it is necessary to use an extra set of <code>{}</code> and a <code>return</code> keyword because of an ambiguity in the grammar.</p> <p>That means I can’t write <code>p =&gt; {foo: "bar"}</code>, but have to write <code>p =&gt; { return {foo: "bar"}; }</code>.</p> <p>If the arrow function returns anything other than an object, the <code>{}</code> and <code>return</code> are unnecessary, e.g.: <code>p =&gt; "foo"</code>.</p> <p><code>p =&gt; {foo: "bar"}</code> returns <code>undefined</code>.</p> <p>A modified <code>p =&gt; {"foo": "bar"}</code> throws <em>“<code>SyntaxError</code>: unexpected token: '<code>:</code>'”</em>.</p> <p>Is there something obvious I am missing?</p>
<p>You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. The following works:</p> <pre><code>p =&gt; ({ foo: 'bar' }); </code></pre> <p>You don't need to wrap any other expression into parentheses:</p> <pre><code>p =&gt; 10; p =&gt; 'foo'; p =&gt; true; p =&gt; [1,2,3]; p =&gt; null; p =&gt; /^foo$/; </code></pre> <p>and so on.</p> <p>Reference: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Returning_object_literals" rel="noreferrer">MDN - Returning object literals</a></p>
{ "question_id": 28770415, "question_date": "2015-02-27T17:02:25.510Z", "question_score": 799, "tags": "javascript|ecmascript-6|arrow-functions", "answer_id": 28770578, "answer_date": "2015-02-27T17:10:23.373Z", "answer_score": 1352 }
Please answer the following Stack Overflow question: Title: How to change a string into uppercase <p>I have problem in changing a string into uppercase with Python. In my research, I got <code>string.ascii_uppercase</code> but it doesn't work.</p> <p>The following code:</p> <pre><code> &gt;&gt;s = 'sdsd' &gt;&gt;s.ascii_uppercase </code></pre> <p>Gives this error message:</p> <pre><code>Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; AttributeError: 'str' object has no attribute 'ascii_uppercase' </code></pre> <p>My question is: <strong>how can I convert a string into uppercase in Python?</strong></p>
<p>Use <a href="https://docs.python.org/3/library/stdtypes.html#str.upper" rel="noreferrer"><code>str.upper()</code></a>:</p> <pre><code>&gt;&gt;&gt; s = 'sdsd' &gt;&gt;&gt; s.upper() 'SDSD' </code></pre> <p>See <a href="https://docs.python.org/3/library/stdtypes.html#string-methods" rel="noreferrer">String Methods</a>.</p>
{ "question_id": 9257094, "question_date": "2012-02-13T07:48:56.727Z", "question_score": 798, "tags": "python|string|uppercase", "answer_id": 9257122, "answer_date": "2012-02-13T07:51:59.930Z", "answer_score": 1317 }
Please answer the following Stack Overflow question: Title: Best way to strip punctuation from a string <p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
<p>From an efficiency perspective, you're not going to beat </p> <pre><code>s.translate(None, string.punctuation) </code></pre> <p>For higher versions of Python use the following code:</p> <pre><code>s.translate(str.maketrans('', '', string.punctuation)) </code></pre> <p>It's performing raw string operations in C with a lookup table - there's not much that will beat that but writing your own C code.</p> <p>If speed isn't a worry, another option though is:</p> <pre><code>exclude = set(string.punctuation) s = ''.join(ch for ch in s if ch not in exclude) </code></pre> <p>This is faster than s.replace with each char, but won't perform as well as non-pure python approaches such as regexes or string.translate, as you can see from the below timings. For this type of problem, doing it at as low a level as possible pays off.</p> <p>Timing code:</p> <pre><code>import re, string, timeit s = "string. With. Punctuation" exclude = set(string.punctuation) table = string.maketrans("","") regex = re.compile('[%s]' % re.escape(string.punctuation)) def test_set(s): return ''.join(ch for ch in s if ch not in exclude) def test_re(s): # From Vinko's solution, with fix. return regex.sub('', s) def test_trans(s): return s.translate(table, string.punctuation) def test_repl(s): # From S.Lott's solution for c in string.punctuation: s=s.replace(c,"") return s print "sets :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000) print "regex :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000) print "translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000) print "replace :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000) </code></pre> <p>This gives the following results:</p> <pre><code>sets : 19.8566138744 regex : 6.86155414581 translate : 2.12455511093 replace : 28.4436721802 </code></pre>
{ "question_id": 265960, "question_date": "2008-11-05T17:30:32.363Z", "question_score": 798, "tags": "python|string|punctuation", "answer_id": 266162, "answer_date": "2008-11-05T18:36:11.530Z", "answer_score": 1210 }
Please answer the following Stack Overflow question: Title: How do I store an array in localStorage? <p>If I didn't need localStorage, my code would look like this:</p> <pre><code>var names=new Array(); names[0]=prompt("New member name?"); </code></pre> <p>This works. However, I need to store this variable in localStorage and it's proving quite stubborn. I've tried:</p> <pre><code>var localStorage[names] = new Array(); localStorage.names[0] = prompt("New member name?"); </code></pre> <p>Where am I going wrong?</p>
<p><code>localStorage</code> only supports strings. Use <code>JSON.stringify()</code> and <code>JSON.parse()</code>.</p> <pre><code>var names = []; names[0] = prompt(&quot;New member name?&quot;); localStorage.setItem(&quot;names&quot;, JSON.stringify(names)); //... var storedNames = JSON.parse(localStorage.getItem(&quot;names&quot;)); </code></pre> <p>You can also use direct access to set/get item:</p> <pre><code>localstorage.names = JSON.stringify(names); var storedNames = JSON.parse(localStorage.names); </code></pre>
{ "question_id": 3357553, "question_date": "2010-07-28T21:14:27.207Z", "question_score": 798, "tags": "javascript|arrays|html|local-storage", "answer_id": 3357615, "answer_date": "2010-07-28T21:23:36.660Z", "answer_score": 1517 }
Please answer the following Stack Overflow question: Title: Difference between single and double quotes in Bash <p>In Bash, what are the differences between single quotes (<code>''</code>) and double quotes (<code>""</code>)?</p>
<p>Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain <code>\</code> escapes, etc. </p> <p>Example:</p> <pre><code>$ echo "$(echo "upg")" upg $ echo '$(echo "upg")' $(echo "upg") </code></pre> <p>The Bash manual has this to say:</p> <blockquote> <p><a href="http://www.gnu.org/software/bash/manual/html_node/Single-Quotes.html" rel="noreferrer">3.1.2.2 Single Quotes</a></p> <p>Enclosing characters in single quotes (<code>'</code>) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. </p> <p><a href="http://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html" rel="noreferrer">3.1.2.3 Double Quotes</a></p> <p>Enclosing characters in double quotes (<code>"</code>) preserves the literal value of all characters within the quotes, with the exception of <code>$</code>, <code>`</code>, <code>\</code>, and, when history expansion is enabled, <code>!</code>. The characters <code>$</code> and <code>`</code> retain their special meaning within double quotes (see <a href="https://www.gnu.org/software/bash/manual/html_node/Shell-Expansions.html#Shell-Expansions" rel="noreferrer">Shell Expansions</a>). The backslash retains its special meaning only when followed by one of the following characters: <code>$</code>, <code>`</code>, <code>"</code>, <code>\</code>, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an <code>!</code> appearing in double quotes is escaped using a backslash. The backslash preceding the <code>!</code> is not removed.</p> <p>The special parameters <code>*</code> and <code>@</code> have special meaning when in double quotes (see <a href="https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion" rel="noreferrer">Shell Parameter Expansion</a>). </p> </blockquote>
{ "question_id": 6697753, "question_date": "2011-07-14T17:55:27.297Z", "question_score": 798, "tags": "bash|shell|quotes|double-quotes|single-quotes", "answer_id": 6697781, "answer_date": "2011-07-14T17:57:44.733Z", "answer_score": 825 }
Please answer the following Stack Overflow question: Title: View a file in a different Git branch without changing branches <p>Is it possible to open a file in a git branch without checking out that branch? How?</p> <p>Essentially I want to be able to open a file in my <a href="http://pages.github.com/">github pages</a> branch without switching branches all the time. I don't want to modify it, just want to view it.</p>
<p>This should work:</p> <pre><code>git show branch:file </code></pre> <p>Where <em>branch</em> can be any ref (branch, tag, HEAD, ...) and <em>file</em> is the full path of the file. To export it you could use</p> <pre><code>git show branch:file &gt; exported_file </code></pre> <p>You should also look at <a href="https://stackoverflow.com/users/6309/vonc">VonC</a>'s answers to some related questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/610208/how-to-retrieve-a-single-file-from-specific-revision-in-git/610315#610315">How to retrieve a single file from specific revision in Git?</a></li> <li><a href="https://stackoverflow.com/questions/2364147/how-to-get-just-one-file-from-another-branch/2364223#2364223">How to get just one file from another branch</a></li> </ul> <p>UPDATE 2015-01-19:</p> <p>Nowadays you can use relative paths with <code>git show a1b35:./file.txt</code>.</p>
{ "question_id": 7856416, "question_date": "2011-10-21T23:39:47.313Z", "question_score": 798, "tags": "git|version-control|branch|git-branch", "answer_id": 7856446, "answer_date": "2011-10-21T23:47:30.667Z", "answer_score": 1121 }
Please answer the following Stack Overflow question: Title: What are the differences between Rust's `String` and `str`? <p>Why does Rust have <code>String</code> and <code>str</code>? What are the differences between <code>String</code> and <code>str</code>? When does one use <code>String</code> instead of <code>str</code> and vice versa? Is one of them getting deprecated?</p>
<p><code>String</code> is the dynamic heap string type, like <code>Vec</code>: use it when you need to own or modify your string data.</p> <p><code>str</code> is an immutable<sup>1</sup> sequence of UTF-8 bytes of dynamic length somewhere in memory. Since the size is unknown, one can only handle it behind a pointer. This means that <code>str</code> most commonly<sup>2</sup> appears as <code>&amp;str</code>: a reference to some UTF-8 data, normally called a &quot;string slice&quot; or just a &quot;slice&quot;. <a href="https://doc.rust-lang.org/book/ch04-03-slices.html" rel="noreferrer">A slice</a> is just a view onto some data, and that data can be anywhere, e.g.</p> <ul> <li><p><strong>In static storage</strong>: a string literal <code>&quot;foo&quot;</code> is a <code>&amp;'static str</code>. The data is hardcoded into the executable and loaded into memory when the program runs.</p> </li> <li><p><strong>Inside a heap allocated <code>String</code></strong>: <a href="https://doc.rust-lang.org/std/string/struct.String.html#deref" rel="noreferrer"><code>String</code> dereferences to a <code>&amp;str</code> view</a> of the <code>String</code>'s data.</p> </li> <li><p><strong>On the stack</strong>: e.g. the following creates a stack-allocated byte array, and then gets a <a href="https://doc.rust-lang.org/std/str/fn.from_utf8.html" rel="noreferrer">view of that data as a <code>&amp;str</code></a>:</p> <pre><code>use std::str; let x: &amp;[u8] = &amp;[b'a', b'b', b'c']; let stack_str: &amp;str = str::from_utf8(x).unwrap(); </code></pre> </li> </ul> <p>In summary, use <code>String</code> if you need owned string data (like passing strings to other threads, or building them at runtime), and use <code>&amp;str</code> if you only need a view of a string.</p> <p>This is identical to the relationship between a vector <code>Vec&lt;T&gt;</code> and a slice <code>&amp;[T]</code>, and is similar to the relationship between by-value <code>T</code> and by-reference <code>&amp;T</code> for general types.</p> <hr /> <p><sup>1</sup> A <code>str</code> is fixed-length; you cannot write bytes beyond the end, or leave trailing invalid bytes. Since UTF-8 is a variable-width encoding, this effectively forces all <code>str</code>s to be immutable in many cases. In general, mutation requires writing more or fewer bytes than there were before (e.g. replacing an <code>a</code> (1 byte) with an <code>ä</code> (2+ bytes) would require making more room in the <code>str</code>). There are specific methods that can modify a <code>&amp;mut str</code> in place, mostly those that handle only ASCII characters, like <a href="https://doc.rust-lang.org/std/primitive.str.html#method.make_ascii_uppercase" rel="noreferrer"><code>make_ascii_uppercase</code></a>.</p> <p><sup>2</sup> <a href="http://smallcultfollowing.com/babysteps/blog/2014/01/05/dst-take-5/" rel="noreferrer">Dynamically sized types</a> allow things like <code>Rc&lt;str&gt;</code> for a sequence of reference counted UTF-8 bytes since Rust 1.2. Rust 1.21 allows easily creating these types.</p>
{ "question_id": 24158114, "question_date": "2014-06-11T08:29:34.557Z", "question_score": 798, "tags": "string|rust", "answer_id": 24159933, "answer_date": "2014-06-11T09:56:21.990Z", "answer_score": 913 }
Please answer the following Stack Overflow question: Title: How do I check for null values in JavaScript? <p>How can I check for null values in JavaScript? I wrote the code below but it didn't work.</p> <pre><code>if (pass == null || cpass == null || email == null || cemail == null || user == null) { alert("fill all columns"); return false; } </code></pre> <p>And how can I find errors in my JavaScript programs?</p>
<p>JavaScript is very flexible with regards to checking for &quot;null&quot; values. I'm guessing you're actually looking for empty strings, in which case this simpler code will work:</p> <pre><code>if(!pass || !cpass || !email || !cemail || !user){ </code></pre> <p>Which will check for empty strings (<code>&quot;&quot;</code>), <code>null</code>, <code>undefined</code>, <code>false</code> and the numbers <code>0</code> and <code>NaN</code>.</p> <p>Please note that if you are specifically checking for numbers, it is a common mistake to miss <code>0</code> with this method, and <code>num !== 0</code> is preferred (or <code>num !== -1</code> or <code>~num</code> (hacky code that also checks against <code>-1</code>)) for functions that return <code>-1</code>, e.g. <code>indexOf</code>).</p>
{ "question_id": 6003884, "question_date": "2011-05-14T18:15:34.943Z", "question_score": 797, "tags": "javascript|null|compare|comparison|equality", "answer_id": 6003920, "answer_date": "2011-05-14T18:20:04.657Z", "answer_score": 990 }
Please answer the following Stack Overflow question: Title: Implements vs extends: When to use? What's the difference? <p>Please explain in an easy to understand language or a link to some article.</p>
<p><code>extends</code> is for <em>extending</em> a class.</p> <p><code>implements</code> is for <em>implementing</em> an interface</p> <p>The difference between an interface and a regular class is that in an interface you can not implement any of the declared methods. Only the class that &quot;implements&quot; the interface can implement the methods. The C++ equivalent of an interface would be an abstract class (not EXACTLY the same but pretty much).</p> <p>Also java doesn't support <strong>multiple inheritance</strong> for classes. This is solved by using multiple interfaces.</p> <pre><code> public interface ExampleInterface { public void doAction(); public String doThis(int number); } public class sub implements ExampleInterface { public void doAction() { //specify what must happen } public String doThis(int number) { //specfiy what must happen } } </code></pre> <p>now extending a class</p> <pre><code> public class SuperClass { public int getNb() { //specify what must happen return 1; } public int getNb2() { //specify what must happen return 2; } } public class SubClass extends SuperClass { //you can override the implementation @Override public int getNb2() { return 3; } } </code></pre> <p>in this case</p> <pre><code> Subclass s = new SubClass(); s.getNb(); //returns 1 s.getNb2(); //returns 3 SuperClass sup = new SuperClass(); sup.getNb(); //returns 1 sup.getNb2(); //returns 2 </code></pre> <p>Also, note that an <code>@Override</code> tag is not required for implementing an interface, as there is nothing in the original interface methods <em>to be overridden</em></p> <p>I suggest you do some more research on <strong>dynamic binding, polymorphism and in general inheritance in Object-oriented programming</strong></p>
{ "question_id": 10839131, "question_date": "2012-05-31T18:25:47.120Z", "question_score": 796, "tags": "java|inheritance|interface|extends|implements", "answer_id": 10839155, "answer_date": "2012-05-31T18:27:30.093Z", "answer_score": 826 }
Please answer the following Stack Overflow question: Title: What is sr-only in Bootstrap 3? <p>What is the class <code>sr-only</code> used for? Is it important or can I remove it? Works fine without.</p> <p>Here's my example:</p> <pre><code>&lt;div class="btn-group"&gt; &lt;button type="button" class="btn btn-info btn-md"&gt;Departments&lt;/button&gt; &lt;button type="button" class="btn btn-info dropdown-toggle btn-md" data-toggle="dropdown"&gt; &lt;span class="caret"&gt;&lt;/span&gt; &lt;span class="sr-only"&gt;Toggle Dropdown&lt;/span&gt; &lt;/button&gt; &lt;ul class="dropdown-menu" role="menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Sales&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Technical&lt;/a&gt;&lt;/li&gt; &lt;li class="divider"&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Show all&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre>
<p>According to <a href="http://getbootstrap.com/css/#helper-classes-screen-readers" rel="noreferrer">bootstrap's documentation</a>, the class is used to hide information intended only for <a href="https://webaccess.berkeley.edu/ask-pecan/what-is-a-screen-reader" rel="noreferrer"><strong>screen readers</strong></a> from the layout of the rendered page.</p> <blockquote> <p>Screen readers will have trouble with your forms if you don't include a label for every input. For these inline forms, you can hide the labels using the .sr-only class.</p> </blockquote> <p>Here is an <a href="http://jsfiddle.net/s9LFQ/" rel="noreferrer">example</a> styling used:</p> <pre class="lang-css prettyprint-override"><code>.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); border: 0; } </code></pre> <blockquote> <p>Is it important or can I remove it? Works fine without.</p> </blockquote> <p>It's important, don't remove it.</p> <p>You should always consider screen readers for accessibility purposes. Usage of the class will hide the element anyways, therefore you shouldn't see a visual difference.</p> <p>If you're interested in reading about accessibility:</p> <ul> <li><p><a href="http://www.w3.org/WAI/" rel="noreferrer">Web Accessibility Initiative (WAI)</a></p></li> <li><p><a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility?redirectlocale=en-US&amp;redirectslug=Accessibility" rel="noreferrer">MDN Accessibility documentation</a></p></li> </ul>
{ "question_id": 19758598, "question_date": "2013-11-03T21:51:16.207Z", "question_score": 796, "tags": "html|css|twitter-bootstrap|twitter-bootstrap-3", "answer_id": 19758620, "answer_date": "2013-11-03T21:53:03.530Z", "answer_score": 828 }
Please answer the following Stack Overflow question: Title: What is the difference between Builder Design pattern and Factory Design pattern? <p>What is the difference between the Builder design pattern and the Factory design pattern? </p> <p>Which one is more advantageous and why ? </p> <p>How do I represent my findings as a graph if I want to test and compare/contrast these patterns ?</p>
<p>With design patterns, there usually is no "more advantageous" solution that works for all cases. It depends on what you need to implement.</p> <p>From Wikipedia: </p> <blockquote> <ul> <li>Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.</li> <li>Builder often builds a Composite.</li> <li>Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.</li> <li>Sometimes creational patterns are complementary: Builder can use one of the other patterns to implement which components get built. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.</li> </ul> </blockquote> <p>Wikipedia entry for factory design pattern: <a href="http://en.wikipedia.org/wiki/Factory_method_pattern" rel="noreferrer">http://en.wikipedia.org/wiki/Factory_method_pattern</a></p> <p>Wikipedia entry for builder design pattern: <a href="http://en.wikipedia.org/wiki/Builder_pattern" rel="noreferrer">http://en.wikipedia.org/wiki/Builder_pattern</a></p>
{ "question_id": 757743, "question_date": "2009-04-16T19:39:04.753Z", "question_score": 796, "tags": "design-patterns|factory-pattern|factory-method|builder-pattern", "answer_id": 757773, "answer_date": "2009-04-16T19:46:52.940Z", "answer_score": 553 }
Please answer the following Stack Overflow question: Title: What does the Ellipsis object do? <p>While idly surfing the namespace I noticed an odd looking object called <code>Ellipsis</code>, it does not seem to be or do anything special, but it's a globally available builtin. </p> <p>After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else. </p> <p>Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all?</p> <pre><code>D:\workspace\numpy&gt;python Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; Ellipsis Ellipsis </code></pre>
<p>This came up in another <a href="https://stackoverflow.com/questions/752602/slicing-in-python-expressions-documentation">question</a> recently. I'll elaborate on my <a href="https://stackoverflow.com/questions/752602/slicing-in-python-expressions-documentation/753260#753260">answer</a> from there:</p> <p><a href="http://docs.python.org/dev/library/constants.html#Ellipsis" rel="noreferrer">Ellipsis</a> is an object that can appear in slice notation. For example:</p> <pre><code>myList[1:2, ..., 0] </code></pre> <p>Its interpretation is purely up to whatever implements the <code>__getitem__</code> function and sees <code>Ellipsis</code> objects there, but its main (and intended) use is in the <a href="http://www.numpy.org/" rel="noreferrer">numpy</a> third-party library, which adds a multidimensional array type. Since there are more than one dimensions, slicing becomes more complex than just a start and stop index; it is useful to be able to slice in multiple dimensions as well. E.g., given a 4 × 4 array, the top left area would be defined by the slice <code>[:2, :2]</code>:</p> <pre><code>&gt;&gt;&gt; a array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]]) &gt;&gt;&gt; a[:2, :2] # top left array([[1, 2], [5, 6]]) </code></pre> <p>Extending this further, Ellipsis is used here to indicate a placeholder for the rest of the array dimensions not specified. Think of it as indicating the full slice <code>[:]</code> for all the dimensions in the gap it is placed, so for a 3d array, <code>a[..., 0]</code> is the same as <code>a[:, :, 0]</code> and for 4d <code>a[:, :, :, 0]</code>, similarly, <code>a[0, ..., 0]</code> is <code>a[0, :, :, 0]</code> (with however many colons in the middle make up the full number of dimensions in the array).</p> <p>Interestingly, in python3, the Ellipsis literal (<code>...</code>) is usable outside the slice syntax, so you can actually write:</p> <pre><code>&gt;&gt;&gt; ... Ellipsis </code></pre> <p>EDIT: Ellipsis is also used in the standard library <code>typing</code> module: e.g. <code>Callable[..., int]</code> to indicate a callable that returns an <code>int</code> without specifying the signature, or <code>tuple[str, ...]</code> to indicate a variable-length homogeneous tuple of strings.</p>
{ "question_id": 772124, "question_date": "2009-04-21T11:21:12.787Z", "question_score": 796, "tags": "python|ellipsis", "answer_id": 773472, "answer_date": "2009-04-21T16:26:07.937Z", "answer_score": 790 }
Please answer the following Stack Overflow question: Title: python exception message capturing <pre><code>import ftplib import urllib2 import os import logging logger = logging.getLogger('ftpuploader') hdlr = logging.FileHandler('ftplog.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) FTPADDR = "some ftp address" def upload_to_ftp(con, filepath): try: f = open(filepath,'rb') # file to send con.storbinary('STOR '+ filepath, f) # Send the file f.close() # Close file and FTP logger.info('File successfully uploaded to '+ FTPADDR) except, e: logger.error('Failed to upload to ftp: '+ str(e)) </code></pre> <p>This doesn't seem to work, I get syntax error, what is the proper way of doing this for logging all kind of exceptions to a file</p>
<p>You have to define which type of exception you want to catch. So write <code>except Exception, e:</code> instead of <code>except, e:</code> for a general exception (that will be logged anyway).</p> <p>Other possibility is to write your whole try/except code this way:</p> <pre><code>try: with open(filepath,'rb') as f: con.storbinary('STOR '+ filepath, f) logger.info('File successfully uploaded to '+ FTPADDR) except Exception, e: # work on python 2.x logger.error('Failed to upload to ftp: '+ str(e)) </code></pre> <p>in Python 3.x and modern versions of Python 2.x use <code>except Exception as e</code> instead of <code>except Exception, e</code>:</p> <pre><code>try: with open(filepath,'rb') as f: con.storbinary('STOR '+ filepath, f) logger.info('File successfully uploaded to '+ FTPADDR) except Exception as e: # work on python 3.x logger.error('Failed to upload to ftp: '+ str(e)) </code></pre>
{ "question_id": 4690600, "question_date": "2011-01-14T11:33:50.477Z", "question_score": 795, "tags": "python|exception|logging|except", "answer_id": 4690655, "answer_date": "2011-01-14T11:40:46.040Z", "answer_score": 1059 }
Please answer the following Stack Overflow question: Title: How do I generate all permutations of a list? <p>How do I generate all the permutations of a list? For example:</p> <pre><code>permutations([]) [] permutations([1]) [1] permutations([1, 2]) [1, 2] [2, 1] permutations([1, 2, 3]) [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] </code></pre>
<p>Use <a href="https://docs.python.org/3/library/itertools.html#itertools.permutations" rel="noreferrer"><code>itertools.permutations</code></a> from the <strong>standard library</strong>:</p> <pre><code>import itertools list(itertools.permutations([1, 2, 3])) </code></pre> <hr /> <p>Adapted from <a href="http://code.activestate.com/recipes/252178/" rel="noreferrer">here</a> is a demonstration of how <code>itertools.permutations</code> might be implemented:</p> <pre><code>def permutations(elements): if len(elements) &lt;= 1: yield elements return for perm in permutations(elements[1:]): for i in range(len(elements)): # nb elements[0:1] works in both string and list contexts yield perm[:i] + elements[0:1] + perm[i:] </code></pre> <p>A couple of alternative approaches are listed in the documentation of <code>itertools.permutations</code>. Here's one:</p> <pre><code>def permutations(iterable, r=None): # permutations('ABCD', 2) --&gt; AB AC AD BA BC BD CA CB CD DA DB DC # permutations(range(3)) --&gt; 012 021 102 120 201 210 pool = tuple(iterable) n = len(pool) r = n if r is None else r if r &gt; n: return indices = range(n) cycles = range(n, n-r, -1) yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return </code></pre> <p>And another, based on <code>itertools.product</code>:</p> <pre><code>def permutations(iterable, r=None): pool = tuple(iterable) n = len(pool) r = n if r is None else r for indices in product(range(n), repeat=r): if len(set(indices)) == r: yield tuple(pool[i] for i in indices) </code></pre>
{ "question_id": 104420, "question_date": "2008-09-19T18:41:03.397Z", "question_score": 795, "tags": "python|algorithm|permutation|combinatorics", "answer_id": 104436, "answer_date": "2008-09-19T18:43:09.380Z", "answer_score": 713 }
Please answer the following Stack Overflow question: Title: Bash tool to get nth line from a file <p>Is there a "canonical" way of doing that? I've been using <code>head -n | tail -1</code> which does the trick, but I've been wondering if there's a Bash tool that specifically extracts a line (or a range of lines) from a file.</p> <p>By "canonical" I mean a program whose main function is doing that.</p>
<p><code>head</code> and pipe with <code>tail</code> will be slow for a huge file. I would suggest <code>sed</code> like this:</p> <pre><code>sed 'NUMq;d' file </code></pre> <p>Where <code>NUM</code> is the number of the line you want to print; so, for example, <code>sed '10q;d' file</code> to print the 10th line of <code>file</code>.</p> <p>Explanation:</p> <p><code>NUMq</code> will quit immediately when the line number is <code>NUM</code>.</p> <p><code>d</code> will delete the line instead of printing it; this is inhibited on the last line because the <code>q</code> causes the rest of the script to be skipped when quitting.</p> <p>If you have <code>NUM</code> in a variable, you will want to use double quotes instead of single:</p> <pre><code>sed "${NUM}q;d" file </code></pre>
{ "question_id": 6022384, "question_date": "2011-05-16T19:33:42.480Z", "question_score": 795, "tags": "bash|shell|unix|awk|sed", "answer_id": 6022431, "answer_date": "2011-05-16T19:38:33.190Z", "answer_score": 1029 }
Please answer the following Stack Overflow question: Title: How do I push amended commit to the remote Git repository? <p>When I've worked a bit with my source code, I did my usual thing commit and then I pushed to a remote repository. But then I noticed I forgot to organize my imports in the source code. So I do the amend command to replace the previous commit:</p> <pre><code>&gt; git commit --amend </code></pre> <p>Unfortunately the commit can't be pushed back to the repository. It is rejected like this:</p> <pre><code>&gt; git push origin To //my.remote.repo.com/stuff.git/ ! [rejected] master -&gt; master (non-fast forward) error: failed to push some refs to '//my.remote.repo.com/stuff.git/' </code></pre> <p>What should I do? (I can access the remote repository.)</p>
<p>I actually once pushed with <code>--force</code> and <code>.git</code> repository and got scolded by Linus <strong>BIG TIME</strong>. In general this will create a lot of problems for other people. A simple answer is "Don't do it".</p> <p>I see others gave the recipe for doing so anyway, so I won't repeat them here. But here is a tip to recover from the situation <em>after</em> you have pushed out the amended commit with --force (or +master).</p> <ol> <li>Use <code>git reflog</code> to find the old commit that you amended (call it <code>old</code>, and we'll call the new commit you created by amending <code>new</code>).</li> <li>Create a merge between <code>old</code> and <code>new</code>, recording the tree of <code>new</code>, like <code>git checkout new &amp;&amp; git merge -s ours old</code>.</li> <li>Merge that to your master with <code>git merge master</code></li> <li>Update your master with the result with <code>git push . HEAD:master</code></li> <li>Push the result out.</li> </ol> <p>Then people who were unfortunate enough to have based their work on the commit you obliterated by amending and forcing a push will see the resulting merge will see that you favor <code>new</code> over <code>old</code>. Their later merges will not see the conflicts between <code>old</code> and <code>new</code> that resulted from your amending, so they do not have to suffer.</p>
{ "question_id": 253055, "question_date": "2008-10-31T10:23:14.497Z", "question_score": 795, "tags": "git|git-commit|git-amend", "answer_id": 432518, "answer_date": "2009-01-11T07:36:32.787Z", "answer_score": 593 }
Please answer the following Stack Overflow question: Title: How to check if a string is a substring of items in a list of strings <p>How do I search for items that contain the string <code>'abc'</code> in the following list?</p> <pre><code>xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456'] </code></pre> <p>The following checks if <code>'abc'</code> is in the list, but does not detect <code>'abc-123'</code> and <code>'abc-456'</code>:</p> <pre><code>if 'abc' in xs: </code></pre>
<p>To check for the presence of <code>'abc'</code> in any string in the list:</p> <pre><code>xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456'] if any(&quot;abc&quot; in s for s in xs): ... </code></pre> <hr /> <p>To get all the items containing <code>'abc'</code>:</p> <pre><code>matching = [s for s in xs if &quot;abc&quot; in s] </code></pre>
{ "question_id": 4843158, "question_date": "2011-01-30T13:29:48.060Z", "question_score": 794, "tags": "python|string|list", "answer_id": 4843172, "answer_date": "2011-01-30T13:32:06.987Z", "answer_score": 1259 }
Please answer the following Stack Overflow question: Title: Using Node.JS, how do I read a JSON file into (server) memory? <h2>Background</h2> <p>I am doing some experimentation with Node.js and would like to read a JSON object, either from a text file or a .js file (which is better??) into memory so that I can access that object quickly from code. I realize that there are things like Mongo, Alfred, etc out there, but that is not what I need right now.</p> <h2>Question</h2> <p>How do I read a JSON object out of a text or js file and into server memory using JavaScript/Node?</p>
<p>Sync:</p> <pre><code>var fs = require('fs'); var obj = JSON.parse(fs.readFileSync('file', 'utf8')); </code></pre> <p>Async:</p> <pre><code>var fs = require('fs'); var obj; fs.readFile('file', 'utf8', function (err, data) { if (err) throw err; obj = JSON.parse(data); }); </code></pre>
{ "question_id": 10011011, "question_date": "2012-04-04T12:22:40.073Z", "question_score": 794, "tags": "javascript|json|node.js", "answer_id": 10011078, "answer_date": "2012-04-04T12:27:19.797Z", "answer_score": 1468 }
Please answer the following Stack Overflow question: Title: Node.js quick file server (static files over HTTP) <p>Is there Node.js ready-to-use tool (installed with <code>npm</code>), that would help me expose folder content as file server over HTTP.</p> <p>Example, if I have</p> <pre><code>D:\Folder\file.zip D:\Folder\file2.html D:\Folder\folder\file-in-folder.jpg </code></pre> <p>Then starting in <code>D:\Folder\</code> <code>node node-file-server.js</code> I could access file via</p> <pre><code>http://hostname/file.zip http://hostname/file2.html http://hostname/folder/file-in-folder.jpg </code></pre> <p><a href="https://stackoverflow.com/questions/11024052/why-is-my-node-static-file-server-dropping-requests">Why is my node static file server dropping requests?</a> reference some mystical </p> <blockquote> <p>standard node.js static file server</p> </blockquote> <p>If there's no such tool, what framework should I use?</p> <p>Related: <a href="https://stackoverflow.com/questions/7268033/basic-static-file-server-in-nodejs">Basic static file server in NodeJS</a></p>
<p>A good "ready-to-use tool" option could be http-server:</p> <pre><code>npm install http-server -g </code></pre> <p>To use it:</p> <pre><code>cd D:\Folder http-server </code></pre> <p>Or, like this:</p> <pre><code>http-server D:\Folder </code></pre> <p>Check it out: <a href="https://github.com/nodeapps/http-server" rel="noreferrer">https://github.com/nodeapps/http-server</a></p>
{ "question_id": 16333790, "question_date": "2013-05-02T08:45:51.653Z", "question_score": 794, "tags": "node.js|http|fileserver", "answer_id": 16350826, "answer_date": "2013-05-03T02:48:41.357Z", "answer_score": 1296 }
Please answer the following Stack Overflow question: Title: Why are Python's 'private' methods not actually private? <p>Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this</p> <pre><code>&gt;&gt;&gt;&gt; class MyClass: ... def myPublicMethod(self): ... print 'public method' ... def __myPrivateMethod(self): ... print 'this is private!!' ... &gt;&gt;&gt; obj = MyClass() &gt;&gt;&gt; obj.myPublicMethod() public method &gt;&gt;&gt; obj.__myPrivateMethod() Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; AttributeError: MyClass instance has no attribute '__myPrivateMethod' &gt;&gt;&gt; dir(obj) ['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod'] &gt;&gt;&gt; obj._MyClass__myPrivateMethod() this is private!! </code></pre> <p>What's the deal?!</p> <p>I'll explain this a little for those who didn't quite get that.</p> <pre><code>&gt;&gt;&gt; class MyClass: ... def myPublicMethod(self): ... print 'public method' ... def __myPrivateMethod(self): ... print 'this is private!!' ... &gt;&gt;&gt; obj = MyClass() </code></pre> <p>I create a class with a public method and a private method and instantiate it.</p> <p>Next, I call its public method.</p> <pre><code>&gt;&gt;&gt; obj.myPublicMethod() public method </code></pre> <p>Next, I try and call its private method.</p> <pre><code>&gt;&gt;&gt; obj.__myPrivateMethod() Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; AttributeError: MyClass instance has no attribute '__myPrivateMethod' </code></pre> <p>Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running <code>dir()</code> on the object reveals a new magical method that Python creates magically for all of your 'private' methods.</p> <pre><code>&gt;&gt;&gt; dir(obj) ['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod'] </code></pre> <p>This new method's name is always an underscore, followed by the class name, followed by the method name.</p> <pre><code>&gt;&gt;&gt; obj._MyClass__myPrivateMethod() this is private!! </code></pre> <p>So much for encapsulation, eh?</p> <p>In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?</p>
<p>The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from outside.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; class Foo(object): ... def __init__(self): ... self.__baz = 42 ... def foo(self): ... print self.__baz ... &gt;&gt;&gt; class Bar(Foo): ... def __init__(self): ... super(Bar, self).__init__() ... self.__baz = 21 ... def bar(self): ... print self.__baz ... &gt;&gt;&gt; x = Bar() &gt;&gt;&gt; x.foo() 42 &gt;&gt;&gt; x.bar() 21 &gt;&gt;&gt; print x.__dict__ {'_Bar__baz': 21, '_Foo__baz': 42} </code></pre> <p>Of course, it breaks down if two different classes have the same name.</p>
{ "question_id": 70528, "question_date": "2008-09-16T08:59:32.377Z", "question_score": 794, "tags": "python|encapsulation|information-hiding", "answer_id": 70900, "answer_date": "2008-09-16T10:06:07.943Z", "answer_score": 686 }
Please answer the following Stack Overflow question: Title: Git command to show which specific files are ignored by .gitignore <p>I am getting my feet wet with Git and have the following issue:</p> <p>My project source tree:</p> <pre><code>/ | +--src/ +----refs/ +----... | +--vendor/ +----... </code></pre> <p>I have code (currently MEF) in my vendor branch that I will compile there and then move the references into <code>/src/refs</code> which is where the project picks them up from.</p> <p>My issue is that I have my <code>.gitignore</code> set to ignore <code>*.dll</code> and <code>*.pdb</code>. I can do a <code>git add -f bar.dll</code> to force the addition of the ignored file which is ok, the problem is I can not figure out to list what files exist that are ignored.</p> <p>I want to list the ignored files to make sure that I don't forget to add them.</p> <p>I have read the man page on <code>git ls-files</code> and can not make it work. It seems to me that <code>git ls-files --exclude-standard -i</code> should do what I want. What am I missing?</p>
<p>Notes:</p> <ul> <li><a href="https://stackoverflow.com/users/814145/xiaobai">xiaobai</a>'s <a href="https://stackoverflow.com/a/12080920/6309">answer</a> is simpler (git1.7.6+): <strong><code>git status --ignored</code></strong><br /> (as detailed in &quot;<a href="https://stackoverflow.com/a/12080857/6309">Is there a way to tell git-status to ignore the effects of <code>.gitignore</code> files?</a>&quot;)</li> <li><a href="https://stackoverflow.com/users/242933/mattdipasquale">MattDiPasquale</a>'s <a href="https://stackoverflow.com/questions/466764/show-ignored-files-in-git/2196755#2196755">answer</a> (to be upvoted) <strong><code>git clean -ndX</code></strong> works on older gits, displaying a <em>preview</em> of what ignored files could be removed (without removing anything)</li> </ul> <hr /> <p>Also interesting (mentioned in <a href="https://stackoverflow.com/users/465546/qwertymk">qwertymk</a>'s <a href="https://stackoverflow.com/a/26580088/6309">answer</a>), you can also use the <a href="http://git-scm.com/docs/git-check-ignore" rel="noreferrer"><strong><code>git check-ignore -v</code></strong></a> command, at least on Unix (<strong>doesn't work</strong> in a CMD <strong>Windows</strong> session)</p> <pre><code>git check-ignore * git check-ignore -v * </code></pre> <p>The second one displays the actual rule of the <code>.gitignore</code> which makes a file to be ignored in your git repo.<br /> On Unix, using &quot;<a href="https://stackoverflow.com/questions/1690809/what-expands-to-all-files-in-current-directory-recursively">What expands to all files in current directory recursively?</a>&quot; and a bash4+:</p> <pre><code>git check-ignore **/* </code></pre> <p>(or a <code>find -exec</code> command)</p> <p>Note: <a href="https://stackoverflow.com/users/351947/c">https://stackoverflow.com/users/351947/Rafi B.</a> suggests <a href="https://stackoverflow.com/questions/466764/git-command-to-show-which-specific-files-are-ignored-by-gitignore/467053?noredirect=1#comment105393217_467053">in the comments</a> to <strong>avoid the (risky) globstar</strong>:</p> <pre><code>git check-ignore -v $(find . -type f -print) </code></pre> <p>Make sure to exclude the files from the <code>.git/</code> subfolder though.</p> <p><a href="https://stackoverflow.com/users/1507124/cerved">CervEd</a> suggests in <a href="https://stackoverflow.com/questions/466764/git-command-to-show-which-specific-files-are-ignored-by-gitignore/467053#comment120476196_467053">the comments</a>, to avoid <code>.git/</code>:</p> <pre><code>find . -not -path './.git/*' | git check-ignore --stdin </code></pre> <hr /> <p>Original answer 42009)</p> <pre><code>git ls-files -i </code></pre> <p>should work, except <a href="http://www.mail-archive.com/[email protected]/msg03245.html" rel="noreferrer">its source code</a> indicates:</p> <pre><code>if (show_ignored &amp;&amp; !exc_given) { fprintf(stderr, &quot;%s: --ignored needs some exclude pattern\n&quot;, argv[0]); </code></pre> <p><code>exc_given</code> ?</p> <p>It turns out it need one more parameter after the <code>-i</code> to actually list anything:</p> <p>Try:</p> <pre><code>git ls-files -i --exclude-from=[Path_To_Your_Global].gitignore </code></pre> <p>(but that would only list your <em>cached</em> (non-ignored) object, with a filter, so that is not quite what you want)</p> <hr /> <p>Example:</p> <pre><code>$ cat .git/ignore # ignore objects and archives, anywhere in the tree. *.[oa] $ cat Documentation/.gitignore # ignore generated html files, *.html # except foo.html which is maintained by hand !foo.html $ git ls-files --ignored \ --exclude='Documentation/*.[0-9]' \ --exclude-from=.git/ignore \ --exclude-per-directory=.gitignore </code></pre> <hr /> <p>Actually, in my 'gitignore' file (called 'exclude'), I find a command line that could help you:</p> <pre><code>F:\prog\git\test\.git\info&gt;type exclude # git ls-files --others --exclude-from=.git/info/exclude # Lines that start with '#' are comments. # For a project mostly in C, the following would be a good set of # exclude patterns (uncomment them if you want to use them): # *.[oa] # *~ </code></pre> <p>So....</p> <pre><code>git ls-files --ignored --exclude-from=.git/info/exclude git ls-files -i --exclude-from=.git/info/exclude git ls-files --others --ignored --exclude-standard git ls-files -o -i --exclude-standard </code></pre> <p>should do the trick.</p> <p>(Thanks to <a href="https://stackoverflow.com/users/271996/honzajde">honzajde</a> pointing out <a href="https://stackoverflow.com/questions/466764/git-command-to-show-which-specific-files-are-ignored-by-gitignore/467053?noredirect=1#comment115090587_467053">in the comments</a> that <code>git ls-files -o -i --exclude-from...</code> does <em>not</em> include cached files: only <code>git ls-files -i --exclude-from...</code> (<em>without</em> <code>-o</code>) does.)</p> <p>As mentioned in the <a href="http://www.kernel.org/pub/software/scm/git/docs/git-ls-files.html" rel="noreferrer">ls-files man page</a>, <code>--others</code> is the important part, in order to show you non-cached, non-committed, normally-ignored files.</p> <p><code>--exclude_standard</code> is not just a shortcut, but a way to include <em>all</em> standard &quot;ignored patterns&quot; settings.</p> <blockquote> <p><code>exclude-standard</code><br /> Add the standard git exclusions: <code>.git/info/exclude</code>, <code>.gitignore</code> in each directory, and the <code>user's global exclusion file</code>.</p> </blockquote>
{ "question_id": 466764, "question_date": "2009-01-21T20:09:36.230Z", "question_score": 794, "tags": "git|ignore", "answer_id": 467053, "answer_date": "2009-01-21T21:17:24.157Z", "answer_score": 873 }
Please answer the following Stack Overflow question: Title: How to kill a process on a port on ubuntu <p>I am trying to kill a process in the command line for a specific port in ubuntu.</p> <p>If I run this command I get the port:</p> <pre><code>sudo lsof -t -i:9001 </code></pre> <p>so...now I want to run:</p> <pre><code>sudo kill 'sudo lsof -t -i:9001' </code></pre> <p>I get this error message:</p> <pre><code>ERROR: garbage process ID "lsof -t -i:9001". Usage: kill pid ... Send SIGTERM to every process listed. kill signal pid ... Send a signal to every process listed. kill -s signal pid ... Send a signal to every process listed. kill -l List all signal names. kill -L List all signal names in a nice table. kill -l signal Convert between signal numbers and names. </code></pre> <p>I tried <code>sudo kill 'lsof -t -i:9001'</code> as well</p>
<p>You want to use backtick, not regular tick:</p> <pre class="lang-sh prettyprint-override"><code>sudo kill -9 `sudo lsof -t -i:9001` </code></pre> <p>If that doesn't work, you could also use <code>$()</code> for command interpolation:</p> <pre class="lang-sh prettyprint-override"><code>sudo kill -9 $(sudo lsof -t -i:9001) </code></pre>
{ "question_id": 9346211, "question_date": "2012-02-19T02:44:33.583Z", "question_score": 793, "tags": "ubuntu|port|kill", "answer_id": 9346231, "answer_date": "2012-02-19T02:47:28.933Z", "answer_score": 1568 }
Please answer the following Stack Overflow question: Title: Strip HTML from Text JavaScript <p>Is there an easy way to take a string of html in JavaScript and strip out the html? </p>
<p>If you're running in a browser, then the easiest way is just to <a href="http://jsfiddle.net/8JSZX/" rel="noreferrer">let the browser do it for you...</a></p> <pre><code>function stripHtml(html) { let tmp = document.createElement(&quot;DIV&quot;); tmp.innerHTML = html; return tmp.textContent || tmp.innerText || &quot;&quot;; } </code></pre> <p>Note: as folks have noted in the comments, this is best avoided if you don't control the source of the HTML (for example, don't run this on anything that could've come from user input). For those scenarios, you can <em>still</em> let the browser do the work for you - <a href="https://stackoverflow.com/questions/822452/strip-html-from-text-javascript/47140708#47140708">see Saba's answer on using the now widely-available DOMParser</a>.</p>
{ "question_id": 822452, "question_date": "2009-05-04T22:39:54.607Z", "question_score": 793, "tags": "javascript|html|string", "answer_id": 822486, "answer_date": "2009-05-04T22:48:21.233Z", "answer_score": 881 }
Please answer the following Stack Overflow question: Title: How to check if object property exists with a variable holding the property name? <p>I am checking for the existence of an object property with a variable holding the property name in question. </p> <pre><code>var myObj; myObj.prop = "exists"; var myProp = "p"+"r"+"o"+"p"; if(myObj.myProp){ alert("yes, i have that property"); }; </code></pre> <p>This is <code>undefined</code> because it's looking for <code>myObj.myProp</code> but I want it to check for <code>myObj.prop</code></p>
<pre><code>var myProp = 'prop'; if(myObj.hasOwnProperty(myProp)){ alert("yes, i have that property"); } </code></pre> <p>Or</p> <pre><code>var myProp = 'prop'; if(myProp in myObj){ alert("yes, i have that property"); } </code></pre> <p>Or</p> <pre><code>if('prop' in myObj){ alert("yes, i have that property"); } </code></pre> <p>Note that <code>hasOwnProperty</code> doesn't check for inherited properties, whereas <code>in</code> does. For example <code>'constructor' in myObj</code> is true, but <code>myObj.hasOwnProperty('constructor')</code> is not.</p>
{ "question_id": 11040472, "question_date": "2012-06-14T19:58:45.113Z", "question_score": 793, "tags": "javascript|object", "answer_id": 11040508, "answer_date": "2012-06-14T20:01:03.240Z", "answer_score": 1495 }
Please answer the following Stack Overflow question: Title: Differences between Oracle JDK and OpenJDK <blockquote> <p>NOTE: This question is from 2014. As of Java 11 OpenJDK and Oracle JDK are converging.</p> </blockquote> <p>Are there any crucial differences between Oracle and OpenJDK?</p> <p>For example, are the garbage collection and other JVM parameters the same?</p> <p>Does GC work differently between the two?</p>
<p>Both OpenJDK and Oracle JDK are created and maintained currently by Oracle only.</p> <p>OpenJDK and Oracle JDK are implementations of the same Java specification passed the TCK (Java Technology Certification Kit).</p> <p>Most of the vendors of JDK are written on top of OpenJDK by doing a few tweaks to [mostly to replace licensed proprietary parts / replace with more high-performance items that only work on specific OS] components without breaking the TCK compatibility.</p> <p>Many vendors implemented the Java specification and got TCK passed. For example, IBM J9, Azul Zulu, Azul Zing, and Oracle JDK.</p> <p>Almost every existing JDK is derived from OpenJDK.</p> <p>As suggested by many, licensing is a change between JDKs. </p> <p>Starting with JDK 11 accessing the long time support Oracle JDK/Java SE will now require a commercial license. You should now pay attention to which JDK you're installing as Oracle JDK without subscription could stop working. <a href="https://www.infoworld.com/article/3284164/java/oracle-now-requires-a-subscription-to-use-java-se.html" rel="noreferrer">source</a></p> <p>Ref: <em><a href="https://en.wikipedia.org/wiki/List_of_Java_virtual_machines#Proprietary_implementations" rel="noreferrer">List of Java virtual machines</a></em></p>
{ "question_id": 22358071, "question_date": "2014-03-12T16:36:32.633Z", "question_score": 793, "tags": "java|difference", "answer_id": 38685948, "answer_date": "2016-07-31T16:11:41.953Z", "answer_score": 405 }
Please answer the following Stack Overflow question: Title: How do I properly clean up Excel interop objects? <p>I'm using the Excel interop in C# (<code>ApplicationClass</code>) and have placed the following code in my finally clause:</p> <pre><code>while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { } excelSheet = null; GC.Collect(); GC.WaitForPendingFinalizers(); </code></pre> <p>Although this kind of works, the <code>Excel.exe</code> process is still in the background even after I close Excel. It is only released once my application is manually closed.</p> <p>What am I doing wrong, or is there an alternative to ensure interop objects are properly disposed of?</p>
<p>Excel does not quit because your application is still holding references to COM objects.</p> <p><strong>I guess you're invoking at least one member of a COM object without assigning it to a variable.</strong></p> <p>For me it was the <em>excelApp.Worksheets</em> object which I directly used without assigning it to a variable:</p> <pre><code>Worksheet sheet = excelApp.Worksheets.Open(...); ... Marshal.ReleaseComObject(sheet); </code></pre> <p>I didn't know that internally C# created a wrapper for the <strong>Worksheets</strong> COM object which didn't get released by my code (because I wasn't aware of it) and was the cause why Excel was not unloaded.</p> <p>I found the solution to my problem on <a href="http://www.velocityreviews.com/forums/showpost.php?s=f87f0674feda4442dcbd40019cbca65b&amp;p=528575&amp;postcount=2" rel="noreferrer">this page</a>, which also has a nice rule for the usage of COM objects in C#:</p> <blockquote> <p>Never use two dots with COM objects.</p> </blockquote> <hr> <p>So with this knowledge the right way of doing the above is:</p> <pre><code>Worksheets sheets = excelApp.Worksheets; // &lt;-- The important part Worksheet sheet = sheets.Open(...); ... Marshal.ReleaseComObject(sheets); Marshal.ReleaseComObject(sheet); </code></pre> <p><strong>POST MORTEM UPDATE:</strong></p> <p>I want every reader to read this answer by Hans Passant very carefully as it explains the trap I and lots of other developers stumbled into. When I wrote this answer years ago I didn't know about the effect the debugger has to the garbage collector and drew the wrong conclusions. I keep my answer unaltered for the sake of history but please read this link and <strong>don't</strong> go the way of "the two dots": <a href="https://stackoverflow.com/questions/17130382/understanding-garbage-collection-in-net/17131389#17131389">Understanding garbage collection in .NET</a> and <a href="https://stackoverflow.com/questions/25134024/clean-up-excel-interop-objects-with-idisposable/25135685#25135685">Clean up Excel Interop Objects with IDisposable</a></p>
{ "question_id": 158706, "question_date": "2008-10-01T17:18:43.513Z", "question_score": 793, "tags": "c#|excel|interop|com-interop", "answer_id": 158752, "answer_date": "2008-10-01T17:30:41.020Z", "answer_score": 703 }
Please answer the following Stack Overflow question: Title: Why Does OAuth v2 Have Both Access and Refresh Tokens? <p>Section 4.2 of the draft OAuth 2.0 protocol indicates that an authorization server can return both an <code>access_token</code> (which is used to authenticate oneself with a resource) as well as a <code>refresh_token</code>, which is used purely to create a new <code>access_token</code>:</p> <p><a href="https://www.rfc-editor.org/rfc/rfc6749#section-4.2" rel="noreferrer">https://www.rfc-editor.org/rfc/rfc6749#section-4.2</a></p> <p>Why have both? Why not just make the <code>access_token</code> last as long as the <code>refresh_token</code> and not have a <code>refresh_token</code>?</p>
<p>The idea of refresh tokens is that if an access token is compromised, because it is short-lived, the attacker has a limited window in which to abuse it.</p> <p>Refresh tokens, if compromised, are useless because the attacker requires the client id and secret in addition to the refresh token in order to gain an access token.</p> <p><strong>Having said that</strong>, because every call to both the authorization server and the resource server is done over SSL - including the original client id and secret when they request the access/refresh tokens - I am unsure as to how the access token is any more "compromisable" than the long-lived refresh token and clientid/secret combination.</p> <p>This of course is different to implementations where you don't control both the authorization and resource servers.</p> <p>Here is a good thread talking about uses of refresh tokens: <a href="http://www.ietf.org/mail-archive/web/oauth/current/msg06687.html">OAuth Archives</a>.</p> <p>A quote from the above, talking about the security purposes of the refresh token:</p> <blockquote> <p>Refresh tokens... mitigates the risk of a long-lived access_token leaking (query param in a log file on an insecure resource server, beta or poorly coded resource server app, JS SDK client on a non https site that puts the access_token in a cookie, etc)</p> </blockquote>
{ "question_id": 3487991, "question_date": "2010-08-15T15:25:41.220Z", "question_score": 793, "tags": "security|oauth-2.0|oauth|access-token|refresh-token", "answer_id": 7209263, "answer_date": "2011-08-26T18:52:07.443Z", "answer_score": 537 }
Please answer the following Stack Overflow question: Title: Import a module from a relative path <p>How do I import a Python module given its relative path?</p> <p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p> <p>Here's a visual representation:</p> <pre><code>dirFoo\ Foo.py dirBar\ Bar.py </code></pre> <p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
<p>Assuming that both your directories are real Python packages (do have the <code>__init__.py</code> file inside them), here is a safe solution for inclusion of modules relatively to the location of the script.</p> <p>I assume that you want to do this, because you need to include a set of modules with your script. I use this in production in several products and works in many special scenarios like: scripts called from another directory or executed with python execute instead of opening a new interpreter.</p> <pre><code> import os, sys, inspect # realpath() will make your script run, even if you symlink it :) cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0])) if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) # Use this if you want to include modules from a subfolder cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder"))) if cmd_subfolder not in sys.path: sys.path.insert(0, cmd_subfolder) # Info: # cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!! # __file__ fails if the script is called in different ways on Windows. # __file__ fails if someone does os.chdir() before. # sys.argv[0] also fails, because it doesn't not always contains the path. </code></pre> <p>As a bonus, this approach does let you force Python to use your module instead of the ones installed on the system.</p> <p>Warning! I don't really know what is happening when current module is inside an <code>egg</code> file. It probably fails too.</p>
{ "question_id": 279237, "question_date": "2008-11-10T21:28:48.060Z", "question_score": 792, "tags": "python|relative-path|python-import", "answer_id": 6098238, "answer_date": "2011-05-23T14:00:43.530Z", "answer_score": 350 }
Please answer the following Stack Overflow question: Title: Docker how to change repository name or rename image? <p>I'm trying to change repository name of the image:</p> <pre><code>REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE server latest d583c3ac45fd 26 minutes ago 685.5 MB </code></pre> <p>Hence I want to change the name <code>server</code> to something like <code>myname/server</code>:</p> <pre><code>REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE myname/server latest d583c3ac45fd 26 minutes ago 685.5 MB </code></pre> <p>How can I do this?</p>
<pre><code>docker image tag server:latest myname/server:latest </code></pre> <p>or</p> <pre><code>docker image tag d583c3ac45fd myname/server:latest </code></pre> <p>Tags are just human-readable aliases for the full image name (<code>d583c3ac45fd...</code>). </p> <p>So you can have as many of them associated with the same image as you like. If you don't like the old name you can remove it after you've retagged it:</p> <pre><code>docker rmi server </code></pre> <p>That will just remove the <code>alias/tag</code>. Since <code>d583c3ac45fd</code> has other names, the actual image won't be deleted.</p>
{ "question_id": 25211198, "question_date": "2014-08-08T19:48:36.153Z", "question_score": 792, "tags": "docker|linux-containers", "answer_id": 25214186, "answer_date": "2014-08-09T00:50:30.450Z", "answer_score": 1430 }
Please answer the following Stack Overflow question: Title: Redirect stderr and stdout in Bash <p>I want to redirect both <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29" rel="noreferrer">standard output</a> and <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)" rel="noreferrer">standard error</a> of a process to a single file. How do I do that in Bash?</p>
<p>Take a look <a href="http://tldp.org/LDP/abs/html/io-redirection.html" rel="noreferrer">here</a>. It should be:</p> <pre><code>yourcommand &amp;&gt; filename </code></pre> <p>It redirects both standard output and standard error to file <em>filename</em>.</p>
{ "question_id": 637827, "question_date": "2009-03-12T09:14:05.580Z", "question_score": 791, "tags": "bash|shell|stdout|io-redirection|stderr", "answer_id": 637839, "answer_date": "2009-03-12T09:17:25.790Z", "answer_score": 880 }
Please answer the following Stack Overflow question: Title: How to truncate a foreign key constrained table? <p>Why doesn't a <strong>TRUNCATE</strong> on <code>mygroup</code> work? Even though I have <code>ON DELETE CASCADE SET</code> I get:</p> <blockquote> <p>ERROR 1701 (42000): Cannot truncate a table referenced in a foreign key constraint (<code>mytest</code>.<code>instance</code>, CONSTRAINT <code>instance_ibfk_1</code> FOREIGN KEY (<code>GroupID</code>) REFERENCES <code>mytest</code>.<code>mygroup</code> (<code>ID</code>))</p> </blockquote> <pre><code>drop database mytest; create database mytest; use mytest; CREATE TABLE mygroup ( ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY ) ENGINE=InnoDB; CREATE TABLE instance ( ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, GroupID INT NOT NULL, DateTime DATETIME DEFAULT NULL, FOREIGN KEY (GroupID) REFERENCES mygroup(ID) ON DELETE CASCADE, UNIQUE(GroupID) ) ENGINE=InnoDB; </code></pre>
<p>You cannot <code>TRUNCATE</code> a table that has FK constraints applied on it (<code>TRUNCATE</code> is not the same as <code>DELETE</code>).</p> <p>To work around this, use either of these solutions. Both present risks of damaging the data integrity.</p> <p><strong>Option 1:</strong></p> <ol> <li>Remove constraints</li> <li>Perform <code>TRUNCATE</code></li> <li>Delete manually the rows that now have references to <strong>nowhere</strong></li> <li>Create constraints</li> </ol> <p><strong>Option 2:</strong> <em>suggested by <strong>user447951</strong> in <a href="https://stackoverflow.com/a/8074510/662581">their answer</a></em></p> <pre><code>SET FOREIGN_KEY_CHECKS = 0; TRUNCATE table $table_name; SET FOREIGN_KEY_CHECKS = 1; </code></pre>
{ "question_id": 5452760, "question_date": "2011-03-27T21:57:42.843Z", "question_score": 791, "tags": "mysql|foreign-keys|constraints|truncate|dml", "answer_id": 5452798, "answer_date": "2011-03-27T22:03:44.433Z", "answer_score": 1195 }
Please answer the following Stack Overflow question: Title: Why is my program slow when looping over exactly 8192 elements? <p>Here is the extract from the program in question. The matrix <code>img[][]</code> has the size SIZE×SIZE, and is initialized at:</p> <p><code>img[j][i] = 2 * j + i</code></p> <p>Then, you make a matrix <code>res[][]</code>, and each field in here is made to be the average of the 9 fields around it in the img matrix. The border is left at 0 for simplicity.</p> <pre><code>for(i=1;i&lt;SIZE-1;i++) for(j=1;j&lt;SIZE-1;j++) { res[j][i]=0; for(k=-1;k&lt;2;k++) for(l=-1;l&lt;2;l++) res[j][i] += img[j+l][i+k]; res[j][i] /= 9; } </code></pre> <p>That's all there's to the program. For completeness' sake, here is what comes before. No code comes after. As you can see, it's just initialization.</p> <pre><code>#define SIZE 8192 float img[SIZE][SIZE]; // input image float res[SIZE][SIZE]; //result of mean filter int i,j,k,l; for(i=0;i&lt;SIZE;i++) for(j=0;j&lt;SIZE;j++) img[j][i] = (2*j+i)%8196; </code></pre> <p>Basically, this program is slow when SIZE is a multiple of 2048, e.g. the execution times:</p> <pre><code>SIZE = 8191: 3.44 secs SIZE = 8192: 7.20 secs SIZE = 8193: 3.18 secs </code></pre> <p>The compiler is GCC. From what I know, this is because of memory management, but I don't really know too much about that subject, which is why I'm asking here.</p> <p>Also how to fix this would be nice, but if someone could explain these execution times I'd already be happy enough.</p> <p>I already know of malloc/free, but the problem is not amount of memory used, it's merely execution time, so I don't know how that would help.</p>
<p>The difference is caused by the same super-alignment issue from the following related questions:</p> <ul> <li><a href="https://stackoverflow.com/q/11413855/922184">Why is transposing a matrix of 512x512 much slower than transposing a matrix of 513x513?</a></li> <li><a href="https://stackoverflow.com/q/7905760/922184">Matrix multiplication: Small difference in matrix size, large difference in timings</a></li> </ul> <p>But that's only because there's one other problem with the code.</p> <p>Starting from the original loop:</p> <pre><code>for(i=1;i&lt;SIZE-1;i++) for(j=1;j&lt;SIZE-1;j++) { res[j][i]=0; for(k=-1;k&lt;2;k++) for(l=-1;l&lt;2;l++) res[j][i] += img[j+l][i+k]; res[j][i] /= 9; } </code></pre> <p>First notice that the two inner loops are trivial. They can be unrolled as follows:</p> <pre><code>for(i=1;i&lt;SIZE-1;i++) { for(j=1;j&lt;SIZE-1;j++) { res[j][i]=0; res[j][i] += img[j-1][i-1]; res[j][i] += img[j ][i-1]; res[j][i] += img[j+1][i-1]; res[j][i] += img[j-1][i ]; res[j][i] += img[j ][i ]; res[j][i] += img[j+1][i ]; res[j][i] += img[j-1][i+1]; res[j][i] += img[j ][i+1]; res[j][i] += img[j+1][i+1]; res[j][i] /= 9; } } </code></pre> <p>So that leaves the two outer-loops that we're interested in.</p> <p>Now we can see the problem is the same in this question: <a href="https://stackoverflow.com/q/9936132/922184">Why does the order of the loops affect performance when iterating over a 2D array?</a></p> <p>You are iterating the matrix column-wise instead of row-wise.</p> <hr> <p>To solve this problem, you should interchange the two loops.</p> <pre><code>for(j=1;j&lt;SIZE-1;j++) { for(i=1;i&lt;SIZE-1;i++) { res[j][i]=0; res[j][i] += img[j-1][i-1]; res[j][i] += img[j ][i-1]; res[j][i] += img[j+1][i-1]; res[j][i] += img[j-1][i ]; res[j][i] += img[j ][i ]; res[j][i] += img[j+1][i ]; res[j][i] += img[j-1][i+1]; res[j][i] += img[j ][i+1]; res[j][i] += img[j+1][i+1]; res[j][i] /= 9; } } </code></pre> <p>This eliminates all the non-sequential access completely so you no longer get random slow-downs on large powers-of-two.</p> <hr> <p><strong>Core i7 920 @ 3.5 GHz</strong></p> <p>Original code:</p> <pre><code>8191: 1.499 seconds 8192: 2.122 seconds 8193: 1.582 seconds </code></pre> <p>Interchanged Outer-Loops:</p> <pre><code>8191: 0.376 seconds 8192: 0.357 seconds 8193: 0.351 seconds </code></pre>
{ "question_id": 12264970, "question_date": "2012-09-04T13:51:31.017Z", "question_score": 791, "tags": "c++|performance|memory-management|gcc", "answer_id": 12265928, "answer_date": "2012-09-04T14:43:25.417Z", "answer_score": 994 }
Please answer the following Stack Overflow question: Title: How do I resolve "Cannot find module" error using Node.js? <p>After pulling down a module from GitHub and following the instructions to build it, I try pulling it into an existing project using:</p> <pre><code>&gt; npm install ../faye </code></pre> <p>This appears to do the trick:</p> <pre><code>&gt; npm list /home/dave/src/server └─┬ [email protected] ├── [email protected] ├── [email protected] └── [email protected] </code></pre> <p>But Node.js can't find the module:</p> <pre><code>&gt; node app.js node.js:201 throw e; // process.nextTick error, or 'error' event on first tick ^ Error: Cannot find module 'faye' at Function._resolveFilename (module.js:334:11) at Function._load (module.js:279:25) at Module.require (module.js:357:17) at require (module.js:368:17) at Object.&lt;anonymous&gt; (/home/dave/src/server/app.js:2:12) at Module._compile (module.js:432:26) at Object..js (module.js:450:10) at Module.load (module.js:351:31) at Function._load (module.js:310:12) at Array.0 (module.js:470:10) </code></pre> <p>I really want to understand what is going on here, but I'm at a bit of a loss as to where to look next. Any suggestions?</p>
<p>Using <code>npm install</code> installs the module into the current directory only (in a subdirectory called <code>node_modules</code>). Is app.js located under <code>home/dave/src/server/</code>? If not and you want to use the module from any directory, you need to install it globally using <code>npm install -g</code>.</p> <p>I usually install most packages locally so that they get checked in along with my project code.</p> <p><strong><em>Update (8/2019):</em></strong></p> <p>Nowadays you can use <a href="https://docs.npmjs.com/files/package-lock.json" rel="noreferrer">package-lock.json</a> file, which is automatically generated when npm modifies your node_modules directory. Therefore you can leave out checking in packages, because the <code>package-lock.json</code> tracks the exact versions of your node_modules, you're currently using. To install packages from <code>package-lock.json</code> instead of <code>package.json</code> use the command <code>npm ci</code>.</p> <p><strong><em>Update (3/2016):</em></strong></p> <p>I've received a lot of flak for my response, specifically that I check in the packages that my code depends on. A few days ago, somebody unpublished all of their packages (<a href="https://kodfabrik.com/journal/i-ve-just-liberated-my-modules" rel="noreferrer">https://kodfabrik.com/journal/i-ve-just-liberated-my-modules</a>) which broke React, Babel, and just about everything else. Hopefully it's clear now that if you have production code, you can't rely on NPM actually maintaining your dependencies for you. </p>
{ "question_id": 9023672, "question_date": "2012-01-26T18:57:42.580Z", "question_score": 790, "tags": "node.js", "answer_id": 9023864, "answer_date": "2012-01-26T19:15:00.383Z", "answer_score": 628 }
Please answer the following Stack Overflow question: Title: Syntax for a single-line while loop in Bash <p>I am having trouble coming up with the right combination of semicolons and/or braces. I'd like to do this, but as a one-liner from the command line:</p> <pre><code>while [ 1 ] do foo sleep 2 done </code></pre>
<pre><code>while true; do foo; sleep 2; done </code></pre> <p>By the way, if you type it as a multiline (as you are showing) at the command prompt and then call the history with arrow up, you will get it on a single line, correctly punctuated.</p> <pre><code>$ while true &gt; do &gt; echo "hello" &gt; sleep 2 &gt; done hello hello hello ^C $ &lt;arrow up&gt; while true; do echo "hello"; sleep 2; done </code></pre>
{ "question_id": 1289026, "question_date": "2009-08-17T16:31:47.247Z", "question_score": 790, "tags": "bash|loops|while-loop", "answer_id": 1289029, "answer_date": "2009-08-17T16:32:32.533Z", "answer_score": 1501 }
Please answer the following Stack Overflow question: Title: Capture HTML Canvas as gif/jpg/png/pdf? <p>Is it possible to capture or print what's displayed in an html canvas as an image or pdf? </p> <p>I'd like to generate an image via canvas, and be able to generate a png from that image.</p>
<p>Original answer was specific to a similar question. This has been revised:</p> <pre><code>const canvas = document.getElementById('mycanvas') const img = canvas.toDataURL('image/png') </code></pre> <p>with the value in IMG you can write it out as a new Image like so:</p> <pre><code>document.getElementById('existing-image-id').src = img </code></pre> <p>or</p> <pre><code>document.write('&lt;img src=&quot;'+img+'&quot;/&gt;'); </code></pre>
{ "question_id": 923885, "question_date": "2009-05-29T00:28:27.797Z", "question_score": 790, "tags": "javascript|html|canvas|export|png", "answer_id": 3514404, "answer_date": "2010-08-18T16:37:57.370Z", "answer_score": 815 }
Please answer the following Stack Overflow question: Title: How can I run multiple npm scripts in parallel? <p>In my <code>package.json</code> I have these two scripts:</p> <pre><code> "scripts": { "start-watch": "nodemon run-babel index.js", "wp-server": "webpack-dev-server", } </code></pre> <p>I have to run these 2 scripts <strong>in parallel</strong> everytime I start developing in Node.js. The first thing I thought of was adding a third script like this:</p> <pre><code>"dev": "npm run start-watch &amp;&amp; npm run wp-server" </code></pre> <p>... but that will wait for <code>start-watch</code> to finish before running <code>wp-server</code>.</p> <p><strong>How can I run these in parallel?</strong> Please keep in mind that I need to see the <code>output</code> of these commands. Also, if your solution involves a build tool, I'd rather use <code>gulp</code> instead of <code>grunt</code> because I already use it in another project.</p>
<p>Use a package called <a href="http://npmjs.org/package/concurrently" rel="noreferrer">concurrently</a>.</p> <pre><code>npm i concurrently --save-dev </code></pre> <p>Then setup your <code>npm run dev</code> task as so:</p> <pre><code>&quot;dev&quot;: &quot;concurrently --kill-others \&quot;npm run start-watch\&quot; \&quot;npm run wp-server\&quot;&quot; </code></pre>
{ "question_id": 30950032, "question_date": "2015-06-20T03:42:47.207Z", "question_score": 790, "tags": "javascript|node.js|build", "answer_id": 30950298, "answer_date": "2015-06-20T04:37:32.800Z", "answer_score": 895 }
Please answer the following Stack Overflow question: Title: How to redirect Windows cmd stdout and stderr to a single file? <p>I'm trying to redirect all output (stdout + stderr) of a <a href="https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands" rel="noreferrer">Windows command</a> to a single file:</p> <pre><code>C:\&gt;dir 1&gt; a.txt 2&gt; a.txt The process cannot access the file because it is being used by another process. </code></pre> <p>Is it possible, or should I just redirect to two separate files?</p>
<p>You want:</p> <pre><code>dir &gt; a.txt 2&gt;&amp;1 </code></pre> <p>The syntax <code>2&gt;&amp;1</code> will redirect <code>2</code> (stderr) to <code>1</code> (stdout). You can also hide messages by redirecting to <code>NUL</code>. More explanation and examples are on the Microsoft documentation page <a href="https://docs.microsoft.com/en-US/troubleshoot/developer/visualstudio/cpp/language-compilers/redirecting-error-command-prompt" rel="noreferrer">Redirecting error messages from Command Prompt: STDERR/STDOUT</a>.</p>
{ "question_id": 1420965, "question_date": "2009-09-14T11:20:41.390Z", "question_score": 790, "tags": "windows|command-line|cmd|pipe", "answer_id": 1420981, "answer_date": "2009-09-14T11:23:51.967Z", "answer_score": 1249 }
Please answer the following Stack Overflow question: Title: How to calculate the difference between two dates using PHP? <p>I have two dates of the form:</p> <pre><code>Start Date: 2007-03-24 End Date: 2009-06-26 </code></pre> <p>Now I need to find the difference between these two in the following form:</p> <pre><code>2 years, 3 months and 2 days </code></pre> <p>How can I do this in PHP?</p>
<blockquote> <p>Use this for legacy code (PHP &lt; 5.3). For up to date solution see jurka's answer below</p> </blockquote> <p>You can use strtotime() to convert two dates to unix time and then calculate the number of seconds between them. From this it's rather easy to calculate different time periods.</p> <pre><code>$date1 = "2007-03-24"; $date2 = "2009-06-26"; $diff = abs(strtotime($date2) - strtotime($date1)); $years = floor($diff / (365*60*60*24)); $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24)); printf("%d years, %d months, %d days\n", $years, $months, $days); </code></pre> <p><strong>Edit:</strong> Obviously the preferred way of doing this is like described by jurka below. My code is generally only recommended if you don't have PHP 5.3 or better. </p> <p>Several people in the comments have pointed out that the code above is only an approximation. I still believe that for most purposes that's fine, since the usage of a range is more to provide a sense of how much time has passed or remains rather than to provide precision - if you want to do that, just output the date. </p> <p>Despite all that, I've decided to address the complaints. If you truly need an exact range but haven't got access to PHP 5.3, use the code below (it should work in PHP 4 as well). This is a direct port of the code that PHP uses internally to calculate ranges, with the exception that it doesn't take daylight savings time into account. That means that it's off by an hour at most, but except for that it should be correct.</p> <pre><code>&lt;?php /** * Calculate differences between two dates with precise semantics. Based on PHPs DateTime::diff() * implementation by Derick Rethans. Ported to PHP by Emil H, 2011-05-02. No rights reserved. * * See here for original code: * http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/tm2unixtime.c?revision=302890&amp;view=markup * http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/interval.c?revision=298973&amp;view=markup */ function _date_range_limit($start, $end, $adj, $a, $b, $result) { if ($result[$a] &lt; $start) { $result[$b] -= intval(($start - $result[$a] - 1) / $adj) + 1; $result[$a] += $adj * intval(($start - $result[$a] - 1) / $adj + 1); } if ($result[$a] &gt;= $end) { $result[$b] += intval($result[$a] / $adj); $result[$a] -= $adj * intval($result[$a] / $adj); } return $result; } function _date_range_limit_days($base, $result) { $days_in_month_leap = array(31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); $days_in_month = array(31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); _date_range_limit(1, 13, 12, "m", "y", &amp;$base); $year = $base["y"]; $month = $base["m"]; if (!$result["invert"]) { while ($result["d"] &lt; 0) { $month--; if ($month &lt; 1) { $month += 12; $year--; } $leapyear = $year % 400 == 0 || ($year % 100 != 0 &amp;&amp; $year % 4 == 0); $days = $leapyear ? $days_in_month_leap[$month] : $days_in_month[$month]; $result["d"] += $days; $result["m"]--; } } else { while ($result["d"] &lt; 0) { $leapyear = $year % 400 == 0 || ($year % 100 != 0 &amp;&amp; $year % 4 == 0); $days = $leapyear ? $days_in_month_leap[$month] : $days_in_month[$month]; $result["d"] += $days; $result["m"]--; $month++; if ($month &gt; 12) { $month -= 12; $year++; } } } return $result; } function _date_normalize($base, $result) { $result = _date_range_limit(0, 60, 60, "s", "i", $result); $result = _date_range_limit(0, 60, 60, "i", "h", $result); $result = _date_range_limit(0, 24, 24, "h", "d", $result); $result = _date_range_limit(0, 12, 12, "m", "y", $result); $result = _date_range_limit_days(&amp;$base, &amp;$result); $result = _date_range_limit(0, 12, 12, "m", "y", $result); return $result; } /** * Accepts two unix timestamps. */ function _date_diff($one, $two) { $invert = false; if ($one &gt; $two) { list($one, $two) = array($two, $one); $invert = true; } $key = array("y", "m", "d", "h", "i", "s"); $a = array_combine($key, array_map("intval", explode(" ", date("Y m d H i s", $one)))); $b = array_combine($key, array_map("intval", explode(" ", date("Y m d H i s", $two)))); $result = array(); $result["y"] = $b["y"] - $a["y"]; $result["m"] = $b["m"] - $a["m"]; $result["d"] = $b["d"] - $a["d"]; $result["h"] = $b["h"] - $a["h"]; $result["i"] = $b["i"] - $a["i"]; $result["s"] = $b["s"] - $a["s"]; $result["invert"] = $invert ? 1 : 0; $result["days"] = intval(abs(($one - $two)/86400)); if ($invert) { _date_normalize(&amp;$a, &amp;$result); } else { _date_normalize(&amp;$b, &amp;$result); } return $result; } $date = "1986-11-10 19:37:22"; print_r(_date_diff(strtotime($date), time())); print_r(_date_diff(time(), strtotime($date))); </code></pre>
{ "question_id": 676824, "question_date": "2009-03-24T10:33:07.443Z", "question_score": 789, "tags": "php|datetime|datediff", "answer_id": 676828, "answer_date": "2009-03-24T10:35:11.307Z", "answer_score": 581 }
Please answer the following Stack Overflow question: Title: Gradle build without tests <p>I want to execute <code>gradle build</code> without executing the unit tests. I tried: </p> <pre><code>$ gradle -Dskip.tests build </code></pre> <p>That doesn't seem to do anything. Is there some other command I could use?</p>
<p>You should use the <code>-x</code> command line argument which excludes any task.</p> <p>Try: </p> <pre><code>gradle build -x test </code></pre> <p><strong>Update:</strong></p> <p>The link in Peter's comment changed. Here is the <a href="https://docs.gradle.org/current/userguide/img/javaPluginTasks.png" rel="noreferrer">diagram</a> from the <a href="https://docs.gradle.org/current/userguide/java_plugin.html" rel="noreferrer">Gradle user's guide</a></p>
{ "question_id": 4597850, "question_date": "2011-01-04T20:01:23.480Z", "question_score": 789, "tags": "java|gradle", "answer_id": 4714118, "answer_date": "2011-01-17T14:12:30.110Z", "answer_score": 1499 }
Please answer the following Stack Overflow question: Title: RESTful Authentication <p>What does RESTful Authentication mean and how does it work? I can't find a good overview on Google. My only understanding is that you pass the session key (remeberal) in the URL, but this could be horribly wrong.</p>
<p>How to handle authentication in a RESTful Client-Server architecture is a matter of debate.</p> <p>Commonly, it can be achieved, in the SOA over HTTP world via:</p> <ul> <li>HTTP basic auth over HTTPS;</li> <li>Cookies and session management;</li> <li>Token in HTTP headers (e.g. <em>OAuth</em> 2.0 + JWT);</li> <li>Query Authentication with additional signature parameters.</li> </ul> <p>You'll have to adapt, or even better mix those techniques, to match your software architecture at best.</p> <p>Each authentication scheme has its own PROs and CONs, depending on the purpose of your security policy and software architecture.</p> <p><strong>HTTP basic auth over HTTPS</strong></p> <p>This first solution, based on the standard HTTPS protocol, is used by most web services.</p> <pre><code>GET /spec.html HTTP/1.1 Host: www.example.org Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== </code></pre> <p>It's easy to implement, available by default on all browsers, but has some known drawbacks, like the awful authentication window displayed on the Browser, which will persist (there is no LogOut-like feature here), some server-side additional CPU consumption, and the fact that the user-name and password are transmitted (over HTTPS) into the Server (it should be more secure to let the password stay only on the client side, during keyboard entry, and be stored as secure hash on the Server).</p> <p>We may use <a href="https://www.rfc-editor.org/rfc/rfc2617" rel="noreferrer">Digest Authentication</a>, but it requires also HTTPS, since it is vulnerable to <a href="http://en.wikipedia.org/wiki/Man-in-the-middle_attack" rel="noreferrer">MiM</a> or <a href="http://en.wikipedia.org/wiki/Replay_attack" rel="noreferrer">Replay</a> attacks, and is specific to HTTP.</p> <p><strong>Session via Cookies</strong></p> <p>To be honest, a session managed on the Server is not truly Stateless.</p> <p>One possibility could be to maintain all data within the cookie content. And, by design, the cookie is handled on the Server side (Client, in fact, does even not try to interpret this cookie data: it just hands it back to the server on each successive request). But this cookie data is application state data, so the client should manage it, not the server, in a pure Stateless world.</p> <pre><code>GET /spec.html HTTP/1.1 Host: www.example.org Cookie: theme=light; sessionToken=abc123 </code></pre> <p>The cookie technique itself is HTTP-linked, so it's not truly RESTful, which should be protocol-independent, IMHO. It is vulnerable to <a href="http://en.wikipedia.org/wiki/Man-in-the-middle_attack" rel="noreferrer">MiM</a> or <a href="http://en.wikipedia.org/wiki/Replay_attack" rel="noreferrer">Replay</a> attacks.</p> <p><strong>Granted via Token (OAuth2)</strong></p> <p>An alternative is to put a token within the HTTP headers so that the request is authenticated. This is what <em>OAuth</em> 2.0 does, for instance. See <a href="https://www.rfc-editor.org/rfc/rfc6749#section-7" rel="noreferrer">the RFC 6749</a>:</p> <pre><code> GET /resource/1 HTTP/1.1 Host: example.com Authorization: Bearer mF_9.B5f-4.1JqM </code></pre> <p>In short, this is very similar to a cookie and suffers to the same issues: not stateless, relying on HTTP transmission details, and subject to <a href="https://www.rfc-editor.org/rfc/rfc6819" rel="noreferrer">a lot of security weaknesses</a> - including MiM and Replay - so is to be used only over HTTPS. Typically, a <a href="https://jwt.io" rel="noreferrer">JWT</a> is used as a token.</p> <p><strong>Query Authentication</strong></p> <p>Query Authentication consists in signing each RESTful request via some additional parameters on the URI. See <a href="http://broadcast.oreilly.com/2009/12/principles-for-standardized-rest-authentication.html" rel="noreferrer">this reference article</a>.</p> <p>It was defined as such in this article:</p> <blockquote> <p>All REST queries must be authenticated by signing the query parameters sorted in lower-case, alphabetical order using the private credential as the signing token. Signing should occur before URL encoding the query string.</p> </blockquote> <p>This technique is perhaps the more compatible with a Stateless architecture, and can also be implemented with a light session management (using in-memory sessions instead of DB persistence).</p> <p>For instance, here is a generic URI sample from the link above:</p> <pre><code>GET /object?apiKey=Qwerty2010 </code></pre> <p>should be transmitted as such:</p> <pre><code>GET /object?timestamp=1261496500&amp;apiKey=Qwerty2010&amp;signature=abcdef0123456789 </code></pre> <p>The string being signed is <code>/object?apikey=Qwerty2010&amp;timestamp=1261496500</code> and the signature is the SHA256 hash of that string using the private component of the API key.</p> <p>Server-side data caching can be always available. For instance, in our framework, we cache the responses at the SQL level, not at the URI level. So adding this extra parameter doesn't break the cache mechanism.</p> <p>See <a href="http://synopse.info/files/html/Synopse%20mORMot%20Framework%20SAD%201.18.html#TITL_98" rel="noreferrer">this article</a> for some details about RESTful authentication in our client-server ORM/SOA/MVC framework, based on JSON and REST. Since we allow communication not only over HTTP/1.1, but also named pipes or GDI messages (locally), we tried to implement a truly RESTful authentication pattern, and not rely on HTTP specificity (like header or cookies).</p> <p><em>Later Note</em>: adding a signature in the URI can be seen as bad practice (since for instance it will appear in the http server logs) so it has to be mitigated, e.g. by a proper TTL to avoid replays. But if your http logs are compromised, you will certainly have bigger security problems.</p> <p>In practice, the upcoming <a href="https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-http-mac-05" rel="noreferrer">MAC Tokens Authentication for OAuth 2.0</a> may be a huge improvement in respect to the &quot;Granted by Token&quot; current scheme. But this is still a work in progress and is tied to HTTP transmission.</p> <p><strong>Conclusion</strong></p> <p>It's worth concluding that REST is not only HTTP-based, even if, in practice, it's also mostly implemented over HTTP. REST can use other communication layers. So a RESTful authentication is not just a synonym of HTTP authentication, whatever Google answers. It should even not use the HTTP mechanism at all but shall be abstracted from the communication layer. And if you use HTTP communication, thanks to the <a href="https://letsencrypt.org/" rel="noreferrer">Let's Encrypt initiative</a> there is no reason not to use proper HTTPS, which is required in addition to any authentication scheme.</p>
{ "question_id": 319530, "question_date": "2008-11-26T01:47:29.850Z", "question_score": 789, "tags": "rest|authentication|restful-authentication|rest-security", "answer_id": 7158864, "answer_date": "2011-08-23T09:29:08.410Z", "answer_score": 626 }
Please answer the following Stack Overflow question: Title: Multiple Indexes vs Multi-Column Indexes <p>What is the difference between creating one index across multiple columns versus creating multiple indexes, one <em>per</em> column?</p> <p>Are there reasons why one should be used over the other?</p> <p>For example:</p> <pre><code>Create NonClustered Index IX_IndexName On TableName (Column1 Asc, Column2 Asc, Column3 Asc) </code></pre> <p>Versus:</p> <pre><code>Create NonClustered Index IX_IndexName1 On TableName (Column1 Asc) Create NonClustered Index IX_IndexName2 On TableName (Column2 Asc) Create NonClustered Index IX_IndexName3 On TableName (Column3 Asc) </code></pre>
<p>I agree with <a href="https://stackoverflow.com/a/179109/50776">Cade Roux</a>.</p> <p>This article should get you on the right track:</p> <ul> <li><a href="http://www.sqlskills.com/BLOGS/KIMBERLY/post.aspx?id=19f0ce1c-0d2f-4ad5-9b13-a615418422e0" rel="noreferrer">Indexes in SQL Server 2005/2008 – Best Practices, Part 1</a></li> <li><a href="http://www.sqlskills.com/blogs/kimberly/indexes-in-sql-server-20052008-part-2-internals/" rel="noreferrer">Indexes in SQL Server 2005/2008 – Part 2 – Internals</a> </li> </ul> <p>One thing to note, clustered indexes should have a unique key (an identity column I would recommend) as the first column. Basically it helps your data insert at the end of the index and not cause lots of disk IO and Page splits.</p> <p>Secondly, if you are creating other indexes on your data and they are constructed cleverly they will be reused. </p> <p>e.g. imagine you search a table on three columns</p> <p>state, county, zip. </p> <ul> <li>you sometimes search by state only. </li> <li>you sometimes search by state and county.</li> <li>you frequently search by state, county, zip. </li> </ul> <p>Then an index with state, county, zip. will be used in all three of these searches.</p> <p>If you search by zip alone quite a lot then the above index will not be used (by SQL Server anyway) as zip is the third part of that index and the query optimiser will not see that index as helpful. </p> <p>You could then create an index on Zip alone that would be used in this instance.</p> <p>By the way <a href="https://use-the-index-luke.com/sql/where-clause/the-equals-operator/concatenated-keys" rel="noreferrer">We can take advantage of the fact that with Multi-Column indexing the first index column is always usable for searching</a> and when you search only by 'state' it is efficient but yet not as efficient as Single-Column index on 'state'</p> <p>I guess the answer you are looking for is that it depends on your where clauses of your frequently used queries and also your group by's.</p> <p>The article will help a lot. :-)</p>
{ "question_id": 179085, "question_date": "2008-10-07T15:36:44.597Z", "question_score": 789, "tags": "sql-server|database|indexing", "answer_id": 179224, "answer_date": "2008-10-07T16:10:57.883Z", "answer_score": 387 }
Please answer the following Stack Overflow question: Title: Repeat a string in JavaScript a number of times <p>In Perl I can repeat a character multiple times using the syntax:</p> <pre><code>$a = "a" x 10; // results in "aaaaaaaaaa" </code></pre> <p>Is there a simple way to accomplish this in Javascript? I can obviously use a function, but I was wondering if there was any built in approach, or some other clever technique.</p>
<p>These days, the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat" rel="noreferrer"><code>repeat</code> string method</a> is implemented <em>almost</em> everywhere. (It is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat#Browser_compatibility" rel="noreferrer">not in Internet Explorer</a>.) So unless you need to support older browsers, you can simply write:</p> <pre><code>&quot;a&quot;.repeat(10) </code></pre> <p>Before <code>repeat</code>, we used this hack:</p> <pre><code>Array(11).join(&quot;a&quot;) // create string with 10 a's: &quot;aaaaaaaaaa&quot; </code></pre> <p>(Note that an array of length 11 gets you only 10 &quot;a&quot;s, since <code>Array.join</code> puts the argument <em>between</em> the array elements.)</p> <p>Simon also points out that according to <a href="https://jsben.ch/PqOXU" rel="noreferrer">this benchmark</a>, it appears that it's faster in Safari and Chrome (but not Firefox) to repeat a character multiple times by simply appending using a for loop (although a bit less concise).</p>
{ "question_id": 1877475, "question_date": "2009-12-09T22:48:37.227Z", "question_score": 789, "tags": "javascript|string|character|repeat", "answer_id": 1877479, "answer_date": "2009-12-09T22:49:23.723Z", "answer_score": 1535 }
Please answer the following Stack Overflow question: Title: How do I determine whether my calculation of pi is accurate? <p>I was trying various methods to implement a program that gives the digits of pi sequentially. I tried the <a href="http://en.wikipedia.org/wiki/Taylor_series" rel="noreferrer">Taylor series</a> method, but it proved to converge extremely slowly (when I compared my result with the online values after some time). Anyway, I am trying better algorithms.</p> <p>So, while writing the program I got stuck on a problem, as with all algorithms: How do I know that the <code>n</code> digits that I've calculated are accurate?</p>
<p>Since I'm the current world record holder for the most digits of pi, I'll add my <a href="http://en.wiktionary.org/wiki/two_cents#Noun" rel="noreferrer">two cents</a>:</p> <p>Unless you're actually setting a new world record, the common practice is just to verify the computed digits against the known values. So that's simple enough.</p> <p>In fact, I have a webpage that lists snippets of digits for the purpose of verifying computations against them: <a href="http://www.numberworld.org/digits/Pi/" rel="noreferrer">http://www.numberworld.org/digits/Pi/</a></p> <hr> <p>But when you get into world-record territory, there's nothing to compare against.</p> <p>Historically, the standard approach for verifying that computed digits are correct is to recompute the digits using a second algorithm. So if either computation goes bad, the digits at the end won't match.</p> <p>This does typically more than double the amount of time needed (since the second algorithm is usually slower). But it's the only way to verify the computed digits once you've wandered into the uncharted territory of never-before-computed digits and a new world record.</p> <hr> <p>Back in the days where supercomputers were setting the records, two different <a href="http://en.wikipedia.org/wiki/AGM_method" rel="noreferrer">AGM algorithms</a> were commonly used:</p> <ul> <li><a href="http://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_algorithm" rel="noreferrer">Gauss–Legendre algorithm</a></li> <li><a href="http://en.wikipedia.org/wiki/Borwein%27s_algorithm" rel="noreferrer">Borwein's algorithm</a></li> </ul> <p>These are both <code>O(N log(N)^2)</code> algorithms that were fairly easy to implement.</p> <p>However, nowadays, things are a bit different. In the last three world records, instead of performing two computations, we performed only one computation using the fastest known formula (<a href="http://en.wikipedia.org/wiki/Chudnovsky_algorithm" rel="noreferrer">Chudnovsky Formula</a>):</p> <p><a href="https://i.stack.imgur.com/YO0MI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YO0MI.png" alt="Enter image description here"></a></p> <p>This algorithm is much harder to implement, but it is a lot faster than the AGM algorithms.</p> <p>Then we verify the binary digits using the <a href="http://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula" rel="noreferrer">BBP formulas for digit extraction</a>.</p> <p><a href="https://i.stack.imgur.com/yC73N.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yC73N.png" alt="Enter image description here"></a></p> <p>This formula allows you to compute arbitrary binary digits <em>without</em> computing all the digits before it. So it is used to verify the last few computed binary digits. Therefore it is <strong><em>much</em></strong> faster than a full computation.</p> <p>The advantage of this is:</p> <ol> <li>Only one expensive computation is needed.</li> </ol> <p>The disadvantage is:</p> <ol> <li>An implementation of the <a href="http://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula" rel="noreferrer">Bailey–Borwein–Plouffe</a> (BBP) formula is needed.</li> <li>An additional step is needed to verify the radix conversion from binary to decimal.</li> </ol> <p><sub>I've glossed over some details of why verifying the last few digits implies that all the digits are correct. But it is easy to see this since any computation error will propagate to the last digits.</sub></p> <hr> <p>Now this last step (verifying the conversion) is actually fairly important. One of the previous world record holders <strong><em>actually called us out</em></strong> on this because, initially, I didn't give a sufficient description of how it worked.</p> <p>So I've pulled this snippet from my blog:</p> <pre><code>N = # of decimal digits desired p = 64-bit prime number </code></pre> <p><a href="https://i.stack.imgur.com/eM9bu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eM9bu.png" alt="Enter image description here"></a></p> <p>Compute A using base 10 arithmetic and B using binary arithmetic.</p> <p><a href="https://i.stack.imgur.com/pyxWt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pyxWt.png" alt="Enter image description here"></a></p> <p>If <code>A = B</code>, then with "extremely high probability", the conversion is correct.</p> <hr> <p>For further reading, see my blog post <strong><a href="http://www.numberworld.org/misc_runs/pi-5t/details.html" rel="noreferrer">Pi - 5 Trillion Digits</a></strong>.</p>
{ "question_id": 14283270, "question_date": "2013-01-11T17:15:32.447Z", "question_score": 789, "tags": "algorithm|math|language-agnostic|pi", "answer_id": 14283481, "answer_date": "2013-01-11T17:28:04.953Z", "answer_score": 1653 }
Please answer the following Stack Overflow question: Title: How to get the CUDA version? <p>Is there any quick command or script to check for the version of CUDA installed?</p> <p>I found the manual of 4.0 under the installation directory but I'm not sure whether it is of the actual installed version or not.</p>
<p>As Jared mentions in a comment, from the command line: </p> <pre><code>nvcc --version </code></pre> <p>(or <code>/usr/local/cuda/bin/nvcc --version</code>) gives the CUDA compiler version (which matches the toolkit version). </p> <p>From application code, you can query the runtime API version with</p> <pre><code>cudaRuntimeGetVersion() </code></pre> <p>or the driver API version with</p> <pre><code>cudaDriverGetVersion() </code></pre> <p>As Daniel points out, deviceQuery is an SDK sample app that queries the above, along with device capabilities.</p> <p>As others note, you can also check the contents of the <code>version.txt</code> using (e.g., on Mac or Linux) </p> <pre><code>cat /usr/local/cuda/version.txt </code></pre> <p>However, if there is another version of the CUDA toolkit installed other than the one symlinked from <code>/usr/local/cuda</code>, this may report an inaccurate version if another version is earlier in your <code>PATH</code> than the above, so use with caution.</p>
{ "question_id": 9727688, "question_date": "2012-03-15T20:30:53.420Z", "question_score": 788, "tags": "cuda", "answer_id": 9730706, "answer_date": "2012-03-16T01:39:21.827Z", "answer_score": 1032 }
Please answer the following Stack Overflow question: Title: Detect click outside React component <p>I'm looking for a way to detect if a click event happened outside of a component, as described in this <a href="https://css-tricks.com/dangers-stopping-event-propagation/" rel="noreferrer">article</a>. jQuery closest() is used to see if the target from a click event has the dom element as one of its parents. If there is a match the click event belongs to one of the children and is thus not considered to be outside of the component.</p> <p>So in my component, I want to attach a click handler to the <code>window</code>. When the handler fires I need to compare the target with the dom children of my component.</p> <p>The click event contains properties like &quot;path&quot; which seems to hold the dom path that the event has traveled. I'm not sure what to compare or how to best traverse it, and I'm thinking someone must have already put that in a clever utility function... No?</p>
<p>The following solution uses ES6 and follows best practices for binding as well as setting the ref through a method.</p> <p>To see it in action:</p> <ul> <li><a href="https://codesandbox.io/s/outside-alerter-hooks-lmr2y?module=%2Fsrc%2FOutsideAlerter.js" rel="noreferrer">Hooks Implementation</a></li> <li><a href="https://codesandbox.io/s/outside-alerter-react-16-3-0-bn267m?file=/src/OutsideAlerter.js" rel="noreferrer">Class Implementation After React 16.3</a></li> <li><a href="https://codesandbox.io/s/30q3mzjv91?module=%2Fsrc%2FOutsideAlerter.js" rel="noreferrer">Class Implementation Before React 16.3</a></li> </ul> <h2>Hooks Implementation:</h2> <pre class="lang-js prettyprint-override"><code>import React, { useRef, useEffect } from &quot;react&quot;; /** * Hook that alerts clicks outside of the passed ref */ function useOutsideAlerter(ref) { useEffect(() =&gt; { /** * Alert if clicked on outside of element */ function handleClickOutside(event) { if (ref.current &amp;&amp; !ref.current.contains(event.target)) { alert(&quot;You clicked outside of me!&quot;); } } // Bind the event listener document.addEventListener(&quot;mousedown&quot;, handleClickOutside); return () =&gt; { // Unbind the event listener on clean up document.removeEventListener(&quot;mousedown&quot;, handleClickOutside); }; }, [ref]); } /** * Component that alerts if you click outside of it */ export default function OutsideAlerter(props) { const wrapperRef = useRef(null); useOutsideAlerter(wrapperRef); return &lt;div ref={wrapperRef}&gt;{props.children}&lt;/div&gt;; } </code></pre> <h2>Class Implementation:</h2> <p><strong>After 16.3</strong></p> <pre class="lang-js prettyprint-override"><code>import React, { Component } from &quot;react&quot;; /** * Component that alerts if you click outside of it */ export default class OutsideAlerter extends Component { constructor(props) { super(props); this.wrapperRef = React.createRef(); this.handleClickOutside = this.handleClickOutside.bind(this); } componentDidMount() { document.addEventListener(&quot;mousedown&quot;, this.handleClickOutside); } componentWillUnmount() { document.removeEventListener(&quot;mousedown&quot;, this.handleClickOutside); } /** * Alert if clicked on outside of element */ handleClickOutside(event) { if (this.wrapperRef &amp;&amp; !this.wrapperRef.current.contains(event.target)) { alert(&quot;You clicked outside of me!&quot;); } } render() { return &lt;div ref={this.wrapperRef}&gt;{this.props.children}&lt;/div&gt;; } } </code></pre> <p><strong>Before 16.3</strong></p> <pre class="lang-js prettyprint-override"><code>import React, { Component } from &quot;react&quot;; /** * Component that alerts if you click outside of it */ export default class OutsideAlerter extends Component { constructor(props) { super(props); this.setWrapperRef = this.setWrapperRef.bind(this); this.handleClickOutside = this.handleClickOutside.bind(this); } componentDidMount() { document.addEventListener(&quot;mousedown&quot;, this.handleClickOutside); } componentWillUnmount() { document.removeEventListener(&quot;mousedown&quot;, this.handleClickOutside); } /** * Set the wrapper ref */ setWrapperRef(node) { this.wrapperRef = node; } /** * Alert if clicked on outside of element */ handleClickOutside(event) { if (this.wrapperRef &amp;&amp; !this.wrapperRef.contains(event.target)) { alert(&quot;You clicked outside of me!&quot;); } } render() { return &lt;div ref={this.setWrapperRef}&gt;{this.props.children}&lt;/div&gt;; } } </code></pre>
{ "question_id": 32553158, "question_date": "2015-09-13T18:34:00.807Z", "question_score": 788, "tags": "javascript|dom|reactjs", "answer_id": 42234988, "answer_date": "2017-02-14T19:51:19.960Z", "answer_score": 1347 }
Please answer the following Stack Overflow question: Title: What is the best collation to use for MySQL with PHP? <p>I'm wondering if there is a "best" choice for collation in MySQL for a general website where you aren't 100% sure of what will be entered? I understand that all the encodings should be the same, such as MySQL, Apache, the HTML and anything inside PHP.</p> <p>In the past I have set PHP to output in "UTF-8", but which collation does this match in MySQL? I'm thinking it's one of the UTF-8 ones, but I have used <code>utf8_unicode_ci</code>, <code>utf8_general_ci</code>, and <code>utf8_bin</code> before.</p>
<p>The main difference is sorting accuracy (when comparing characters in the language) and performance. The only special one is utf8_bin which is for comparing characters in binary format.</p> <p><code>utf8_general_ci</code> is somewhat faster than <code>utf8_unicode_ci</code>, but less accurate (for sorting). The <em>specific language utf8 encoding</em> (such as <code>utf8_swedish_ci</code>) contain additional language rules that make them the most accurate to sort for those languages. Most of the time I use <code>utf8_unicode_ci</code> (I prefer accuracy to small performance improvements), unless I have a good reason to prefer a specific language.</p> <p>You can read more on specific unicode character sets on the MySQL manual - <a href="http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html</a></p>
{ "question_id": 367711, "question_date": "2008-12-15T07:48:36.683Z", "question_score": 788, "tags": "php|mysql|encoding|collation", "answer_id": 367725, "answer_date": "2008-12-15T07:58:27.243Z", "answer_score": 667 }
Please answer the following Stack Overflow question: Title: What are the differences between unit tests, integration tests, smoke tests, and regression tests? <p>What are unit tests, integration tests, smoke tests, and regression tests? What are the differences between them and which tools can I use for each of them?</p> <p>For example, I use <a href="https://en.wikipedia.org/wiki/JUnit" rel="noreferrer">JUnit</a> and <a href="https://en.wikipedia.org/wiki/NUnit" rel="noreferrer">NUnit</a> for <em>unit testing</em> and <em>integration testing</em>. Are there any tools for the last two, <em>smoke testing</em> or <em>regression testing</em>?</p>
<ul> <li><p><strong>Unit test</strong>: Specify and test one point of the contract of single method of a class. This should have a very narrow and well defined scope. Complex dependencies and interactions to the outside world are <a href="http://martinfowler.com/articles/mocksArentStubs.html" rel="noreferrer">stubbed or mocked</a>.</p></li> <li><p><strong>Integration test</strong>: Test the correct inter-operation of multiple subsystems. There is whole spectrum there, from testing integration between two classes, to testing integration with the production environment.</p></li> <li><p><strong>Smoke test (aka</strong> <strong><em>sanity</em></strong> <strong>check)</strong>: A simple integration test where we just check that when the system under test is invoked it returns normally and does not blow up.</p> <ul> <li>Smoke testing is both an analogy with electronics, where the first test occurs when powering up a circuit (if it smokes, it's bad!)...</li> <li>... and, <a href="https://stackoverflow.com/questions/520064/what-is-unit-test-integration-test-smoke-test-regression-test#comment13627138_520116">apparently</a>, with <a href="https://en.wikipedia.org/wiki/Smoke_testing_(mechanical)" rel="noreferrer">plumbing</a>, where a system of pipes is literally filled by smoke and then checked visually. If anything smokes, the system is leaky.</li> </ul></li> <li><p><strong>Regression test</strong>: A test that was written when a bug was fixed. It ensures that this specific bug will not occur again. The full name is "non-regression test". It can also be a test made prior to changing an application to make sure the application provides the same outcome.</p></li> </ul> <p>To this, I will add:</p> <ul> <li><p><strong>Acceptance test</strong>: Test that a feature or use case is correctly implemented. It is similar to an integration test, but with a focus on the use case to provide rather than on the components involved.</p></li> <li><p><strong>System test</strong>: Tests a system as a black box. Dependencies on other systems are often mocked or stubbed during the test (otherwise it would be more of an integration test).</p></li> <li><p><strong>Pre-flight check</strong>: Tests that are repeated in a production-like environment, to alleviate the 'builds on my machine' syndrome. Often this is realized by doing an acceptance or smoke test in a production like environment.</p></li> </ul>
{ "question_id": 520064, "question_date": "2009-02-06T12:08:34.317Z", "question_score": 788, "tags": "unit-testing|testing|definition", "answer_id": 520116, "answer_date": "2009-02-06T12:28:48.880Z", "answer_score": 1147 }
Please answer the following Stack Overflow question: Title: How do I convert a Map to List in Java? <p>How do I convert a <code>Map&lt;key,value&gt;</code> to a <code>List&lt;value&gt;</code>? Should I iterate over all map values and insert them into a list?</p>
<pre><code>List&lt;Value&gt; list = new ArrayList&lt;Value&gt;(map.values()); </code></pre> <p>assuming:</p> <pre><code>Map&lt;Key,Value&gt; map; </code></pre>
{ "question_id": 1026723, "question_date": "2009-06-22T11:45:28.380Z", "question_score": 787, "tags": "java|list|dictionary|collections", "answer_id": 1026736, "answer_date": "2009-06-22T11:48:42.740Z", "answer_score": 1467 }
Please answer the following Stack Overflow question: Title: How do I test if a variable is a number in Bash? <p>I just can't figure out how do I make sure an argument passed to my script is a number or not.</p> <p>All I want to do is something like this:</p> <pre><code>test *isnumber* $1 &amp;&amp; VAR=$1 || echo "need a number" </code></pre> <p>Any help?</p>
<p>One approach is to use a regular expression, like so:</p> <pre><code>re='^[0-9]+$' if ! [[ $yournumber =~ $re ]] ; then echo "error: Not a number" &gt;&amp;2; exit 1 fi </code></pre> <p>If the value is not necessarily an integer, consider amending the regex appropriately; for instance:</p> <pre><code>^[0-9]+([.][0-9]+)?$ </code></pre> <p>...or, to handle numbers with a sign:</p> <pre><code>^[+-]?[0-9]+([.][0-9]+)?$ </code></pre>
{ "question_id": 806906, "question_date": "2009-04-30T13:30:16.100Z", "question_score": 787, "tags": "linux|bash|shell", "answer_id": 806923, "answer_date": "2009-04-30T13:32:20.760Z", "answer_score": 1053 }
Please answer the following Stack Overflow question: Title: How to send multipart/form-data request using Postman <p>I am currently using the Chrome Addon Postman - REST Client to easily create POST / GET request.</p> <p>Now I want to debug an upload script and I am <strong>looking for a way to make requests encoded as "multipart/form-data"</strong> so that I can send also a file.</p>
<p><strong>UPDATE:</strong> I have created a <a href="https://youtu.be/c07IsbSNqfI" rel="noreferrer">video on sending multipart/form-data requests</a> to explain this better.</p> <hr /> <p>Actually, <a href="https://www.postman.com" rel="noreferrer">Postman</a> can do this.</p> <p><a href="https://i.stack.imgur.com/955xK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/955xK.png" alt="enter image description here" /></a></p> <p>Full example:</p> <p><a href="https://i.stack.imgur.com/cjZPw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cjZPw.png" alt="enter image description here" /></a></p> <p>You DON'T need to add any headers, Postman will do this for you automatically.</p> <p><a href="https://i.stack.imgur.com/DT7tH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DT7tH.png" alt="enter image description here" /></a></p> <p>Make sure you check the comment from @maxkoryukov</p> <blockquote> <p>Be careful with explicit Content-Type header. Better - do not set it's value, the Postman is smart enough to fill this header for you. BUT, if you want to set the Content-Type: multipart/form-data - do not forget about <a href="http://stackoverflow.com/a/20321259/1115187">boundary field</a>.</p> </blockquote>
{ "question_id": 16015548, "question_date": "2013-04-15T12:48:47.637Z", "question_score": 787, "tags": "multipartform-data", "answer_id": 16022213, "answer_date": "2013-04-15T18:26:44.823Z", "answer_score": 1698 }
Please answer the following Stack Overflow question: Title: Can I underline text in an Android layout? <p>How can I define <em>underlined</em> text in an Android layout <code>xml</code> file?</p>
<p>It can be achieved if you are using a <a href="http://developer.android.com/guide/topics/resources/available-resources.html#stringresources" rel="noreferrer"><strong>string resource</strong></a> xml file, which supports HTML tags like <code>&lt;b&gt;&lt;/b&gt;</code>, <code>&lt;i&gt;&lt;/i&gt;</code> and <code>&lt;u&gt;&lt;/u&gt;</code>.</p> <pre><code>&lt;resources&gt; &lt;string name=&quot;your_string_here&quot;&gt;&lt;![CDATA[This is an &lt;u&gt;underline&lt;/u&gt;.]]&gt;&lt;/string&gt; &lt;/resources&gt; </code></pre> <p>If you want to underline something from code use:</p> <pre><code>TextView textView = (TextView) view.findViewById(R.id.textview); SpannableString content = new SpannableString(&quot;Content&quot;); content.setSpan(new UnderlineSpan(), 0, content.length(), 0); textView.setText(content); </code></pre>
{ "question_id": 2394935, "question_date": "2010-03-07T02:26:35.263Z", "question_score": 787, "tags": "android|android-layout|fonts", "answer_id": 2394939, "answer_date": "2010-03-07T02:29:57.760Z", "answer_score": 1294 }
Please answer the following Stack Overflow question: Title: How do I "Add Existing Item" an entire directory structure in Visual Studio? <p>I have a free standing set of files not affiliated with any C# project at all that reside in a complicated nested directory structure.</p> <p>I want to add them in that format to a different directory in an ASP.NET web application I am working on; while retaining the same structure. So, I copied the folder into the target location of my project and I tried to “add existing item” only to lose the previous folder hierarchy.</p> <p>Usually I have re-created the directories by hand, copied across on a one-to-one basis, and then added existing items. There are simply too many directories/items in this case.</p> <p>So how do you add existing directories and files in Visual Studio 2008?</p>
<p>Drag the files / folders from Windows Explorer into the Solution Explorer. It will add them all. Note this doesn't work if Visual Studio is in Administrator Mode, because Windows Explorer is a User Mode process.</p>
{ "question_id": 57776, "question_date": "2008-09-11T22:09:48.743Z", "question_score": 787, "tags": "visual-studio|ide", "answer_id": 57778, "answer_date": "2008-09-11T22:10:14.500Z", "answer_score": 750 }
Please answer the following Stack Overflow question: Title: Can I embed a custom font in an iPhone application? <p>I would like to have an app include a custom font for rendering text, load it, and then use it with standard <code>UIKit</code> elements like <code>UILabel</code>. Is this possible?</p>
<p>iOS 3.2 and later support this. Straight from the <em>What's New in iPhone OS 3.2</em> doc:</p> <blockquote> <p><strong>Custom Font Support</strong><br> Applications that want to use custom fonts can now include those fonts in their application bundle and register those fonts with the system by including the UIAppFonts key in their Info.plist file. The value of this key is an array of strings identifying the font files in the application’s bundle. When the system sees the key, it loads the specified fonts and makes them available to the application.</p> </blockquote> <p>Once the fonts have been set in the <code>Info.plist</code>, you can use your custom fonts as any other font in IB or programatically.</p> <p>There is an ongoing thread on Apple Developer Forums: <br> <a href="https://devforums.apple.com/thread/37824" rel="noreferrer">https://devforums.apple.com/thread/37824</a> (login required)</p> <p>And here's an excellent and simple 3 steps tutorial on how to achieve this (broken link removed)</p> <ol> <li>Add your custom font files into your project using Xcode as a resource</li> <li>Add a key to your <code>Info.plist</code> file called <code>UIAppFonts</code>.</li> <li>Make this key an array</li> <li>For each font you have, enter the full name of your font file (including the extension) as items to the <code>UIAppFonts</code> array</li> <li>Save <code>Info.plist</code></li> <li>Now in your application you can simply call <code>[UIFont fontWithName:@"CustomFontName" size:12]</code> to get the custom font to use with your <strong>UILabels</strong> and <strong>UITextViews</strong>, etc…</li> </ol> <p>Also: Make sure the fonts are in your Copy Bundle Resources.</p>
{ "question_id": 360751, "question_date": "2008-12-11T20:21:11.203Z", "question_score": 787, "tags": "ios|cocoa-touch|fonts", "answer_id": 2616101, "answer_date": "2010-04-11T05:01:05.527Z", "answer_score": 647 }
Please answer the following Stack Overflow question: Title: Creating an empty Pandas DataFrame, and then filling it <p>I'm starting from the pandas DataFrame documentation here: <em><a href="http://pandas.pydata.org/pandas-docs/stable/dsintro.html" rel="nofollow noreferrer">Introduction to data structures</a></em></p> <p>I'd like to iteratively fill the DataFrame with values in a time series kind of calculation. So basically, I'd like to initialize the DataFrame with columns A, B and timestamp rows, all 0 or all NaN.</p> <p>I'd then add initial values and go over this data calculating the new row from the row before, say <code>row[A][t] = row[A][t-1]+1</code> or so.</p> <p>I'm currently using the code as below, but I feel it's kind of ugly and there must be a way to do this with a DataFrame directly, or just a better way in general.</p> <p>Note: I'm using Python 2.7.</p> <pre><code>import datetime as dt import pandas as pd import scipy as s if __name__ == '__main__': base = dt.datetime.today().date() dates = [ base - dt.timedelta(days=x) for x in range(0,10) ] dates.sort() valdict = {} symbols = ['A','B', 'C'] for symb in symbols: valdict[symb] = pd.Series( s.zeros( len(dates)), dates ) for thedate in dates: if thedate &gt; dates[0]: for symb in valdict: valdict[symb][thedate] = 1+valdict[symb][thedate - dt.timedelta(days=1)] print valdict </code></pre>
<p>Here's a couple of suggestions:</p> <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html" rel="nofollow noreferrer"><code>date_range</code></a> for the index:</p> <pre><code>import datetime import pandas as pd import numpy as np todays_date = datetime.datetime.now().date() index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D') columns = ['A','B', 'C'] </code></pre> <p><em>Note: we could create an empty DataFrame (with <code>NaN</code>s) simply by writing:</em></p> <pre><code>df_ = pd.DataFrame(index=index, columns=columns) df_ = df_.fillna(0) # With 0s rather than NaNs </code></pre> <p>To do these type of calculations for the data, use a <a href="https://en.wikipedia.org/wiki/NumPy" rel="nofollow noreferrer">NumPy</a> array:</p> <pre><code>data = np.array([np.arange(10)]*3).T </code></pre> <p>Hence we can create the DataFrame:</p> <pre class="lang-none prettyprint-override"><code>In [10]: df = pd.DataFrame(data, index=index, columns=columns) In [11]: df Out[11]: A B C 2012-11-29 0 0 0 2012-11-30 1 1 1 2012-12-01 2 2 2 2012-12-02 3 3 3 2012-12-03 4 4 4 2012-12-04 5 5 5 2012-12-05 6 6 6 2012-12-06 7 7 7 2012-12-07 8 8 8 2012-12-08 9 9 9 </code></pre>
{ "question_id": 13784192, "question_date": "2012-12-09T02:50:38.060Z", "question_score": 786, "tags": "python|dataframe|pandas", "answer_id": 13786327, "answer_date": "2012-12-09T09:40:46.303Z", "answer_score": 416 }
Please answer the following Stack Overflow question: Title: How to print a date in a regular format? <p>This is my code:</p> <pre><code>import datetime today = datetime.date.today() print(today) </code></pre> <p>This prints: <code>2008-11-22</code> which is exactly what I want.</p> <p>But, I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p> <pre><code>import datetime mylist = [] today = datetime.date.today() mylist.append(today) print(mylist) </code></pre> <p>This prints the following: </p> <pre><code>[datetime.date(2008, 11, 22)] </code></pre> <p>How can I get just a simple date like <code>2008-11-22</code>?</p>
<h2>The WHY: dates are objects</h2> <p>In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings or timestamps.</p> <p>Any object in Python has TWO string representations:</p> <ul> <li><p>The regular representation that is used by <code>print</code> can be get using the <code>str()</code> function. It is most of the time the most common human readable format and is used to ease display. So <code>str(datetime.datetime(2008, 11, 22, 19, 53, 42))</code> gives you <code>'2008-11-22 19:53:42'</code>.</p> </li> <li><p>The alternative representation that is used to represent the object nature (as a data). It can be get using the <code>repr()</code> function and is handy to know what kind of data your manipulating while you are developing or debugging. <code>repr(datetime.datetime(2008, 11, 22, 19, 53, 42))</code> gives you <code>'datetime.datetime(2008, 11, 22, 19, 53, 42)'</code>.</p> </li> </ul> <p>What happened is that when you have printed the date using <code>print</code>, it used <code>str()</code> so you could see a nice date string. But when you have printed <code>mylist</code>, you have printed a list of objects and Python tried to represent the set of data, using <code>repr()</code>.</p> <h2>The How: what do you want to do with that?</h2> <p>Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects.</p> <p>When you want to display them, just use <code>str()</code>. In Python, the good practice is to explicitly cast everything. So just when it's time to print, get a string representation of your date using <code>str(date)</code>.</p> <p>One last thing. When you tried to print the dates, you printed <code>mylist</code>. If you want to print a date, you must print the date objects, not their container (the list).</p> <p>E.G, you want to print all the date in a list :</p> <pre><code>for date in mylist : print str(date) </code></pre> <p>Note that <em><strong>in that specific case</strong></em>, you can even omit <code>str()</code> because print will use it for you. But it should not become a habit :-)</p> <h2>Practical case, using your code</h2> <pre><code>import datetime mylist = [] today = datetime.date.today() mylist.append(today) print mylist[0] # print the date object, not the container ;-) 2008-11-22 # It's better to always use str() because : print &quot;This is a new day : &quot;, mylist[0] # will work &gt;&gt;&gt; This is a new day : 2008-11-22 print &quot;This is a new day : &quot; + mylist[0] # will crash &gt;&gt;&gt; cannot concatenate 'str' and 'datetime.date' objects print &quot;This is a new day : &quot; + str(mylist[0]) &gt;&gt;&gt; This is a new day : 2008-11-22 </code></pre> <h2>Advanced date formatting</h2> <p>Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the <code>strftime()</code> method.</p> <p><code>strftime()</code> expects a string pattern explaining how you want to format your date.</p> <p>E.G :</p> <pre><code>print today.strftime('We are the %d, %b %Y') &gt;&gt;&gt; 'We are the 22, Nov 2008' </code></pre> <p>All the letter after a <code>&quot;%&quot;</code> represent a format for something:</p> <ul> <li><code>%d</code> is the day number (2 digits, prefixed with leading zero's if necessary)</li> <li><code>%m</code> is the month number (2 digits, prefixed with leading zero's if necessary)</li> <li><code>%b</code> is the month abbreviation (3 letters)</li> <li><code>%B</code> is the month name in full (letters)</li> <li><code>%y</code> is the year number abbreviated (last 2 digits)</li> <li><code>%Y</code> is the year number full (4 digits)</li> </ul> <p>etc.</p> <p><a href="http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="noreferrer">Have a look at the official documentation</a>, or <a href="http://strftime.org" rel="noreferrer">McCutchen's quick reference</a> you can't know them all.</p> <p>Since <a href="http://www.python.org/dev/peps/pep-3101/" rel="noreferrer">PEP3101</a>, every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in strftime. So you can do the same as above like this:</p> <pre><code>print &quot;We are the {:%d, %b %Y}&quot;.format(today) &gt;&gt;&gt; 'We are the 22, Nov 2008' </code></pre> <p>The advantage of this form is that you can also convert other objects at the same time.<br /> With the introduction of <a href="https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals" rel="noreferrer">Formatted string literals</a> (since Python 3.6, 2016-12-23) this can be written as</p> <pre><code>import datetime f&quot;{datetime.datetime.now():%Y-%m-%d}&quot; &gt;&gt;&gt; '2017-06-15' </code></pre> <h2>Localization</h2> <p>Dates can automatically adapt to the local language and culture if you use them the right way, but it's a bit complicated. Maybe for another question on SO(Stack Overflow) ;-)</p>
{ "question_id": 311627, "question_date": "2008-11-22T18:37:07.927Z", "question_score": 786, "tags": "python|datetime|date", "answer_id": 311655, "answer_date": "2008-11-22T19:07:07.570Z", "answer_score": 1068 }
Please answer the following Stack Overflow question: Title: How do you roll back (reset) a Git repository to a particular commit? <p>I cloned a Git repository and then tried to roll it back to a particular commit early on in the development process. Everything that was added to the repository after that point is unimportant to me so I want to omit all subsequent changes from my local source code.</p> <p>However, when I try to roll back in the GUI tool it doesn't update my local file system - I always end up with the latest source code for the project.</p> <p>What's the correct way to just get the source for a repository as of a particular commit in the project's history and omit all later updates?</p>
<pre><code>git reset --hard &lt;tag/branch/commit id&gt; </code></pre> <hr> <p><strong><em>Notes:</em></strong></p> <ul> <li><p><code>git reset</code> without the <code>--hard</code> option resets the commit history, but not the files. With the <code>--hard</code> option the files in working tree are also reset. (<a href="https://stackoverflow.com/users/964/kauppi">credited user</a>)</p></li> <li><p>If you wish to commit that state so that the remote repository also points to the rolled back commit do: <code>git push &lt;reponame&gt; -f</code> (<a href="https://stackoverflow.com/users/96806/mariusz-nowak">credited user</a>)</p></li> </ul>
{ "question_id": 1616957, "question_date": "2009-10-24T04:22:27.310Z", "question_score": 786, "tags": "git", "answer_id": 1616959, "answer_date": "2009-10-24T04:24:35.097Z", "answer_score": 1243 }
Please answer the following Stack Overflow question: Title: Split a String into an array in Swift? <p>Say I have a string here:</p> <pre><code>var fullName: String = "First Last" </code></pre> <p>I want to split the string base on white space and assign the values to their respective variables</p> <pre><code>var fullNameArr = // something like: fullName.explode(" ") var firstName: String = fullNameArr[0] var lastName: String? = fullnameArr[1] </code></pre> <p>Also, sometimes users might not have a last name.</p>
<p>The Swift way is to use the global <code>split</code> function, like so:</p> <pre><code>var fullName = "First Last" var fullNameArr = split(fullName) {$0 == " "} var firstName: String = fullNameArr[0] var lastName: String? = fullNameArr.count &gt; 1 ? fullNameArr[1] : nil </code></pre> <p>with <strong>Swift 2</strong> </p> <p>In Swift 2 the use of split becomes a bit more complicated due to the introduction of the internal CharacterView type. This means that String no longer adopts the SequenceType or CollectionType protocols and you must instead use the <code>.characters</code> property to access a CharacterView type representation of a String instance. (Note: CharacterView does adopt SequenceType and CollectionType protocols).</p> <pre><code>let fullName = "First Last" let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init) // or simply: // let fullNameArr = fullName.characters.split{" "}.map(String.init) fullNameArr[0] // First fullNameArr[1] // Last </code></pre>
{ "question_id": 25678373, "question_date": "2014-09-05T03:51:01.450Z", "question_score": 786, "tags": "ios|arrays|swift|string|split", "answer_id": 26270721, "answer_date": "2014-10-09T05:06:46.657Z", "answer_score": 818 }
Please answer the following Stack Overflow question: Title: How can I reverse the order of lines in a file? <p>I'd like to reverse the order of lines in a text file (or stdin), preserving the contents of each line.</p> <p>So, i.e., starting with:</p> <pre><code>foo bar baz </code></pre> <p>I'd like to end up with </p> <pre><code>baz bar foo </code></pre> <p>Is there a standard UNIX commandline utility for this?</p>
<p>BSD tail:</p> <pre><code>tail -r myfile.txt </code></pre> <p>Reference: <a href="https://www.freebsd.org/cgi/man.cgi?query=tail&amp;apropos=0&amp;sektion=1" rel="noreferrer">FreeBSD</a>, <a href="http://netbsd.gw.com/cgi-bin/man-cgi?tail+1" rel="noreferrer">NetBSD</a>, <a href="http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tail.1?query=tail&amp;sec=1" rel="noreferrer">OpenBSD</a> and <a href="https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/tail.1.html" rel="noreferrer">OS X</a> manual pages.</p>
{ "question_id": 742466, "question_date": "2009-04-12T21:34:53.810Z", "question_score": 786, "tags": "shell|unix|command-line", "answer_id": 742469, "answer_date": "2009-04-12T21:36:30.437Z", "answer_score": 502 }
Please answer the following Stack Overflow question: Title: Merge, update, and pull Git branches without using checkouts <p>I work on a project that has 2 branches, A and B. I typically work on branch A, and merge stuff from branch B. For the merging, I would typically do:</p> <pre><code>git merge origin/branchB </code></pre> <p>However, I would also like to keep a local copy of branch B, as I may occasionally check out the branch without first merging with my branch A. For this, I would do:</p> <pre><code>git checkout branchB git pull git checkout branchA </code></pre> <p>Is there a way to do the above in one command, and without having to switch branch back and forth? Should I be using <code>git update-ref</code> for that? How?</p>
<h2>The Short Answer</h2> <p>As long as you're doing a <strong>fast-forward</strong> merge, then you can simply use</p> <pre><code>git fetch &lt;remote&gt; &lt;sourceBranch&gt;:&lt;destinationBranch&gt; </code></pre> <p>Examples:</p> <pre class="lang-bash prettyprint-override"><code># Merge local branch foo into local branch master, # without having to checkout master first. # Here `.` means to use the local repository as the &quot;remote&quot;: git fetch . foo:master # Merge remote branch origin/foo into local branch foo, # without having to checkout foo first: git fetch origin foo:foo </code></pre> <p>While <a href="https://stackoverflow.com/a/4157106/456814">Amber's answer</a> will also work in fast-forward cases, using <code>git fetch</code> in this way instead is a little safer than just force-moving the branch reference, since <code>git fetch</code> will automatically prevent accidental non-fast-forwards as long as you don't use <code>+</code> in the refspec.</p> <h2>The Long Answer</h2> <p>You cannot merge a branch B into branch A without checking out A first if it would result in a non-fast-forward merge. This is because a working copy is needed to resolve any potential conflicts.</p> <p>However, <strong>in the case of fast-forward merges, this is possible</strong>, because such merges can never result in conflicts, by definition. To do this without checking out a branch first, you can use <code>git fetch</code> with a refspec.</p> <p>Here's an example of updating <code>master</code> (disallowing non-fast-forward changes) if you have another branch <code>feature</code> checked out:</p> <pre><code>git fetch upstream master:master </code></pre> <p>This use-case is so common, that you'll probably want to make an alias for it in your git configuration file, like this one:</p> <pre><code>[alias] sync = !sh -c 'git checkout --quiet HEAD; git fetch upstream master:master; git checkout --quiet -' </code></pre> <p>What this alias does is the following:</p> <ol> <li><p><code>git checkout HEAD</code>: this puts your working copy into a detached-head state. This is useful if you want to update <code>master</code> while you happen to have it checked-out. I think it was necessary to do with because otherwise the branch reference for <code>master</code> won't move, but I don't remember if that's really right off-the-top of my head.</p> </li> <li><p><code>git fetch upstream master:master</code>: this fast-forwards your local <code>master</code> to the same place as <code>upstream/master</code>.</p> </li> <li><p><code>git checkout -</code> checks out your previously checked-out branch (that's what the <code>-</code> does in this case).</p> </li> </ol> <h2>The syntax of <code>git fetch</code> for (non-)fast-forward merges</h2> <p>If you want the <code>fetch</code> command to fail if the update is non-fast-forward, then you simply use a refspec of the form</p> <pre><code>git fetch &lt;remote&gt; &lt;remoteBranch&gt;:&lt;localBranch&gt; </code></pre> <p>If you want to allow non-fast-forward updates, then you add a <code>+</code> to the front of the refspec:</p> <pre><code>git fetch &lt;remote&gt; +&lt;remoteBranch&gt;:&lt;localBranch&gt; </code></pre> <p>Note that you can pass your local repo as the &quot;remote&quot; parameter using <code>.</code>:</p> <pre><code>git fetch . &lt;sourceBranch&gt;:&lt;destinationBranch&gt; </code></pre> <h2>The Documentation</h2> <p>From the <a href="http://jk.gs/git-fetch.html" rel="noreferrer"><code>git fetch</code> documentation that explains this syntax</a> (emphasis mine):</p> <blockquote> <p><code>&lt;refspec&gt;</code></p> <p>The format of a <code>&lt;refspec&gt;</code> parameter is an optional plus <code>+</code>, followed by the source ref <code>&lt;src&gt;</code>, followed by a colon <code>:</code>, followed by the destination ref <code>&lt;dst&gt;</code>.</p> <p><em><strong>The remote ref that matches <code>&lt;src&gt;</code> is fetched, and if <code>&lt;dst&gt;</code> is not empty string, the local ref that matches it is fast-forwarded using <code>&lt;src&gt;</code></strong></em>. If the optional plus <code>+</code> is used, the local ref is updated even if it does not result in a fast-forward update.</p> </blockquote> <h2>See Also</h2> <ol> <li><p><a href="https://stackoverflow.com/questions/1402993/git-checkout-and-merge-without-touching-working-tree">Git checkout and merge without touching working tree</a></p> </li> <li><p><a href="https://stackoverflow.com/questions/3408532/merging-without-changing-the-working-directory">Merging without changing the working directory</a></p> </li> </ol>
{ "question_id": 3216360, "question_date": "2010-07-09T20:32:52.137Z", "question_score": 786, "tags": "git|git-merge|git-pull|git-checkout", "answer_id": 17722977, "answer_date": "2013-07-18T12:06:05.933Z", "answer_score": 1209 }
Please answer the following Stack Overflow question: Title: Using @property versus getters and setters <p>What advantages does the <code>@property</code> notation hold over the classic getter+setter? In which specific cases/situations should a programmer choose to use one over the other?</p> <p><strong>With properties:</strong></p> <pre><code>class MyClass(object): @property def my_attr(self): return self._my_attr @my_attr.setter def my_attr(self, value): self._my_attr = value </code></pre> <p><strong>Without properties:</strong></p> <pre><code>class MyClass(object): def get_my_attr(self): return self._my_attr def set_my_attr(self, value): self._my_attr = value </code></pre>
<p><em>Prefer properties</em>. It's what they're there for.</p> <p>The reason is that all attributes are public in Python. Starting names with an underscore or two is just a warning that the given attribute is an implementation detail that may not stay the same in future versions of the code. It doesn't prevent you from actually getting or setting that attribute. Therefore, standard attribute access is the normal, Pythonic way of, well, accessing attributes.</p> <p>The advantage of properties is that they are syntactically identical to attribute access, so you can change from one to another without any changes to client code. You could even have one version of a class that uses properties (say, for code-by-contract or debugging) and one that doesn't for production, without changing the code that uses it. At the same time, you don't have to write getters and setters for everything just in case you might need to better control access later.</p>
{ "question_id": 6618002, "question_date": "2011-07-07T22:42:25.843Z", "question_score": 785, "tags": "python|properties|getter-setter", "answer_id": 6618176, "answer_date": "2011-07-07T23:06:42.267Z", "answer_score": 659 }
Please answer the following Stack Overflow question: Title: How can I combine two or more querysets in a Django view? <p>I am trying to build the search for a Django site I am building, and in that search, I am searching in three different models. And to get pagination on the search result list, I would like to use a generic object_list view to display the results. But to do that, I have to merge three querysets into one.</p> <p>How can I do that? I've tried this:</p> <pre><code>result_list = [] page_list = Page.objects.filter( Q(title__icontains=cleaned_search_term) | Q(body__icontains=cleaned_search_term)) article_list = Article.objects.filter( Q(title__icontains=cleaned_search_term) | Q(body__icontains=cleaned_search_term) | Q(tags__icontains=cleaned_search_term)) post_list = Post.objects.filter( Q(title__icontains=cleaned_search_term) | Q(body__icontains=cleaned_search_term) | Q(tags__icontains=cleaned_search_term)) for x in page_list: result_list.append(x) for x in article_list: result_list.append(x) for x in post_list: result_list.append(x) return object_list( request, queryset=result_list, template_object_name='result', paginate_by=10, extra_context={ 'search_term': search_term}, template_name=&quot;search/result_list.html&quot;) </code></pre> <p>But this doesn't work. I get an error when I try to use that list in the generic view. The list is missing the clone attribute.</p> <p>How can I merge the three lists, <code>page_list</code>, <code>article_list</code> and <code>post_list</code>?</p>
<p>Concatenating the querysets into a list is the simplest approach. If the database will be hit for all querysets anyway (e.g. because the result needs to be sorted), this won't add further cost.</p> <pre><code>from itertools import chain result_list = list(chain(page_list, article_list, post_list)) </code></pre> <p>Using <code>itertools.chain</code> is faster than looping each list and appending elements one by one, since <code>itertools</code> is implemented in C. It also consumes less memory than converting each queryset into a list before concatenating.</p> <p>Now it's possible to sort the resulting list e.g. by date (as requested in hasen j's comment to another answer). The <code>sorted()</code> function conveniently accepts a generator and returns a list:</p> <pre><code>result_list = sorted( chain(page_list, article_list, post_list), key=lambda instance: instance.date_created) </code></pre> <p>If you're using Python 2.4 or later, you can use <code>attrgetter</code> instead of a lambda. I remember reading about it being faster, but I didn't see a noticeable speed difference for a million item list.</p> <pre><code>from operator import attrgetter result_list = sorted( chain(page_list, article_list, post_list), key=attrgetter('date_created')) </code></pre>
{ "question_id": 431628, "question_date": "2009-01-10T19:51:43.317Z", "question_score": 785, "tags": "django|search|django-queryset|django-q", "answer_id": 434755, "answer_date": "2009-01-12T08:00:46.823Z", "answer_score": 1203 }
Please answer the following Stack Overflow question: Title: Remove directory from remote repository after adding them to .gitignore <p>I committed and pushed some directory to github. After that, I altered the <code>.gitignore</code> file adding a directory that should be ignored. Everything works fine, but the (now ignored) directory stays on github.</p> <p>How do I delete that directory from github and the repository history?</p>
<p>The rules in your <code>.gitignore</code> file only apply to untracked files. Since the files under that directory were already committed in your repository, you have to unstage them, create a commit, and push that to GitHub:</p> <pre><code>git rm -r --cached some-directory git commit -m 'Remove the now ignored directory "some-directory"' git push origin master </code></pre> <p>You can't delete the file from your history without rewriting the history of your repository - you shouldn't do this if anyone else is working with your repository, or you're using it from multiple computers. If you still want to do that, you can use <code>git filter-branch</code> to rewrite the history - <a href="http://help.github.com/remove-sensitive-data/" rel="noreferrer">there is a helpful guide to that here</a>.</p> <p>Additionally, note the output from <code>git rm -r --cached some-directory</code> will be something like:</p> <pre><code>rm 'some-directory/product/cache/1/small_image/130x130/small_image.jpg' rm 'some-directory/product/cache/1/small_image/135x/small_image.jpg' rm 'some-directory/.htaccess' rm 'some-directory/logo.jpg' </code></pre> <p>The <code>rm</code> is feedback from git about the repository; the files are still in the working directory.</p>
{ "question_id": 7927230, "question_date": "2011-10-28T09:08:08.580Z", "question_score": 785, "tags": "git|github|gitignore", "answer_id": 7927283, "answer_date": "2011-10-28T09:12:49.013Z", "answer_score": 1336 }
Please answer the following Stack Overflow question: Title: Xcode process launch failed: Security <p>I have been developing an app for 1 or 2 weeks now and just yesterday I have updated my iPhone 5S to the iOS 8 GM. Everything worked fine and I could test on my device as well until I deleted the app from my phone and wanted to build again. The following error appeared:</p> <pre><code>Could not launch "My App" process launch failed: Security </code></pre> <p><a href="https://i.stack.imgur.com/TzLwB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TzLwB.png" alt="Screenshot added"></a></p> <p>When I test with the simulator it works fine. Is this because of the iOS 8 GM update and how can I fix this launch problem? I want to be able to test on my iPhone and in the simulator.</p>
<p>If you get this, the app has installed on your device. You have to tap the icon. It will ask you if you <em>really</em> want to run it. Say “<code>yes</code>” and then <code>Build &amp; Run again</code>.</p> <p>As from <code>iOS 9</code>, it is required to go to <kbd>Settings</kbd> → <kbd>General</kbd> → <kbd>Device Management</kbd> → <kbd>Developer App</kbd> → <kbd>Trust</kbd>`.</p> <p>On <em>some</em> versions of <code>iOS</code>, you will have to go to <kbd>Settings</kbd> → <kbd>General</kbd> → <kbd>Profile</kbd> instead.</p>
{ "question_id": 25824908, "question_date": "2014-09-13T15:50:07.637Z", "question_score": 785, "tags": "ios|xcode|process|build", "answer_id": 25837245, "answer_date": "2014-09-14T19:36:40.013Z", "answer_score": 1645 }
Please answer the following Stack Overflow question: Title: Why does array[idx++]+="a" increase idx once in Java 8 but twice in Java 9 and 10? <p>For a challenge, <a href="https://stackoverflow.com/users/1682559/kevin-cruijssen">a fellow code golfer</a> <a href="https://codegolf.stackexchange.com/questions/166012/exchange-capitalization/166081?noredirect=1#comment401670_166081">wrote the following code</a>:</p> <pre><code>import java.util.*; public class Main { public static void main(String[] args) { int size = 3; String[] array = new String[size]; Arrays.fill(array, &quot;&quot;); for (int i = 0; i &lt;= 100;) { array[i++ % size] += i + &quot; &quot;; } for (String element: array) { System.out.println(element); } } } </code></pre> <p><a href="https://tio.run/##TY3BTsMwEETv@YpRJKSEgFXEjZADH8CpxyoH07rVps46sjdFFcq3BzduKafdnXkz2@mTfnaD4W53nGfqB@cFXRTVKGTVY51lw/hlaYut1SHgUxPjJwOuahAtcZwc7dBHr1iLJz5sWmh/COWCAsQCRoPXejn/MV6fo87m@yZym5iPixXUnqwtFuwJeV4mb@98camkGF3Vcbw3eFnF7fYPqXlDVfXALaomMhVy5Ck//bWkpzDW9IblLcXuLetzENMrN4oaIiiWiyta3pumbJrnXw" rel="noreferrer">When running this code in Java 8, we get the following result:</a></p> <pre><code>1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55 58 61 64 67 70 73 76 79 82 85 88 91 94 97 100 2 5 8 11 14 17 20 23 26 29 32 35 38 41 44 47 50 53 56 59 62 65 68 71 74 77 80 83 86 89 92 95 98 101 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99 </code></pre> <p><a href="https://tio.run/##TY3NboMwEITvPMUIqRKU1krUWymHPkBPOUYcnMSJlpgF2UuqqOLZiYPz09Puznwz2@iTfm92x2mitu@coAmCGoSsei2TpB82lrbYWu09fjQx/hLgpnrREsapox3a4GUrccSHdQ3tDj6fUYBYwKjwUc7nP8bpc9DZ/N5FriPzfbW82pO12Yy9IU3z6O07l10rKUQXZRhfFZaLsN3/ITavqSheuEZRBaZAijTmx0dLfApjTWtYPmPs2bI6ezGt6gZRfQDFcnZD82fTmIzTdAE" rel="noreferrer">When running this code in Java 10, we get the following result:</a></p> <pre><code>2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100 102 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100 </code></pre> <p>The numbering is entirely off using Java 10. So what is happening here? Is it a bug in Java 10?</p> <h2>Follow ups from the comments:</h2> <ul> <li><p>The issue appears when compiled with Java 9 or later (we found it in Java 10). Compiling this code on Java 8, then running in Java 9 or any later version, including Java 11 early access, gives the expected result.</p> </li> <li><p>This kind of code is non-standard, but is valid according to the spec. It was found by <a href="https://stackoverflow.com/users/1682559/kevin-cruijssen">Kevin Cruijssen</a> in a <a href="https://codegolf.stackexchange.com/questions/166012/exchange-capitalization/166081?noredirect=1#comment401670_166081">discussion in a <strong>golfing challenge</strong></a>, hence the weird use case encountered.</p> </li> <li><p><a href="https://stackoverflow.com/users/525036/didier-l">Didier L</a> simplified the issue with this much smaller and more understandable code:</p> <pre><code> class Main { public static void main(String[] args) { String[] array = { &quot;&quot; }; array[test()] += &quot;a&quot;; } static int test() { System.out.println(&quot;evaluated&quot;); return 0; } } </code></pre> <p><a href="https://tio.run/##TYxBCoMwFET3PcWQVaRUui8eoasuxcWvBomNUZIfQcSzp6lpoYthYN7wBlroMs3KDt0rxtaQ97iTtthOwByeRrfwTJxqmXSHMTH5YKdtXzcg1/viuAJ/o6MVFTYIgf12wGOrWXmWRYNzBUHiQ/aUr15bRj78hKtnNZZT4HJOajZWCrWQCcSqE0UWO8XBWVyzbI/xDQ" rel="noreferrer">Result when compiled in Java 8:</a></p> <pre><code> evaluated </code></pre> <p><a href="https://tio.run/##TYxBCoMwFET3PcWQlaFUui8eoasuxcWvBomNUZIfQcSzp6lpoYthYN7wBlroMnSvGFtD3uNO2mI7AXN4Gt3CM3GqZdIdxsSKBztt@7oBud7L4wr8jY5WVNggBPbbAY@tZuW5kA3OFQSJD9lTvnptGfnwE66e1VhOgcs5qdnYQqiFTCBWnZBZ7BQHZ3HNsj3GNw" rel="noreferrer">Result when compiled in Java 9 and 10:</a></p> <pre><code> evaluated evaluated </code></pre> </li> <li><p>The issue seems to be limited to the string concatenation and assignment operator (<code>+=</code>) with an expression with side effect(s) as the left operand, like in <code>array[test()]+=&quot;a&quot;</code>, <code>array[ix++]+=&quot;a&quot;</code>, <code>test()[index]+=&quot;a&quot;</code>, or <code>test().field+=&quot;a&quot;</code>. To enable string concatenation, at least one of the sides must have type <code>String</code>. Trying to reproduce this on other types or constructs failed.</p> </li> </ul>
<p>This is a bug in <code>javac</code> starting from JDK 9 (which made some changes with regard to string concatenation, which I suspect is part of the problem), <a href="https://bugs.openjdk.java.net/browse/JDK-8204322" rel="noreferrer">as confirmed by the <code>javac</code> team under the bug id JDK-8204322</a>. If you look at the corresponding bytecode for the line:</p> <pre><code>array[i++%size] += i + &quot; &quot;; </code></pre> <p>It is:</p> <pre><code> 21: aload_2 22: iload_3 23: iinc 3, 1 26: iload_1 27: irem 28: aload_2 29: iload_3 30: iinc 3, 1 33: iload_1 34: irem 35: aaload 36: iload_3 37: invokedynamic #5, 0 // makeConcatWithConstants:(Ljava/lang/String;I)Ljava/lang/String; 42: aastore </code></pre> <p>Where the last <code>aaload</code> is the actual load from the array. However, the part</p> <pre><code> 21: aload_2 // load the array reference 22: iload_3 // load 'i' 23: iinc 3, 1 // increment 'i' (doesn't affect the loaded value) 26: iload_1 // load 'size' 27: irem // compute the remainder </code></pre> <p>Which roughly corresponds to the expression <code>array[i++%size]</code> (minus the actual load and store), is in there twice. This is incorrect, as the spec says in <a href="https://docs.oracle.com/javase/specs/jls/se10/html/jls-15.html#jls-15.26.2" rel="noreferrer">jls-15.26.2</a>:</p> <blockquote> <p>A compound assignment expression of the form <code>E1 op= E2</code> is equivalent to <code>E1 = (T) ((E1) op (E2))</code>, where <code>T</code> is the type of <code>E1</code>, <strong>except that <code>E1</code> is evaluated only once.</strong></p> </blockquote> <p>So, for the expression <code>array[i++%size] += i + &quot; &quot;;</code>, the part <code>array[i++%size]</code> should only be evaluated once. But it is evaluated twice (once for the load, and once for the store).</p> <p>So yes, this is a bug.</p> <hr /> <h3>Some updates:</h3> <p>The bug is fixed in JDK 11 and was back-ported to JDK 10 (<a href="https://bugs.openjdk.java.net/browse/JDK-8204873" rel="noreferrer">here</a> and <a href="https://bugs.openjdk.java.net/browse/JDK-8204992" rel="noreferrer">here</a>), but not to JDK 9, since <a href="http://www.oracle.com/technetwork/java/javase/eol-135779.html" rel="noreferrer">it no longer receives public updates</a>.</p> <p>Aleksey Shipilev mentions on the <a href="https://bugs.openjdk.java.net/browse/JDK-8204322?focusedCommentId=14185198&amp;page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-14185198" rel="noreferrer">JBS page</a> (and @DidierL in the comments here):</p> <blockquote> <p>Workaround: compile with <code>-XDstringConcat=inline</code></p> </blockquote> <p>That will revert to using <code>StringBuilder</code> to do the concatenation, and doesn't have the bug.</p>
{ "question_id": 50683786, "question_date": "2018-06-04T15:16:14.077Z", "question_score": 785, "tags": "java|java-8|javac|java-9|java-10", "answer_id": 50686658, "answer_date": "2018-06-04T18:26:06.393Z", "answer_score": 643 }
Please answer the following Stack Overflow question: Title: Get difference between 2 dates in JavaScript? <p>How do I get the difference between 2 dates in full days (I don't want any fractions of a day)</p> <pre><code>var date1 = new Date('7/11/2010'); var date2 = new Date('12/12/2010'); var diffDays = date2.getDate() - date1.getDate(); alert(diffDays) </code></pre> <p>I tried the above but this did not work.</p>
<p><a href="http://jsfiddle.net/JS69L/1/" rel="noreferrer">Here is one way</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 date1 = new Date('7/13/2010'); const date2 = new Date('12/15/2010'); const diffTime = Math.abs(date2 - date1); const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); console.log(diffTime + " milliseconds"); console.log(diffDays + " days");</code></pre> </div> </div> </p> <p>Observe that we need to enclose the date in quotes. The rest of the code gets the time difference in milliseconds and then divides to get the number of days. Date expects mm/dd/yyyy format.</p>
{ "question_id": 3224834, "question_date": "2010-07-11T22:19:54.430Z", "question_score": 784, "tags": "javascript|date", "answer_id": 3224854, "answer_date": "2010-07-11T22:24:46.127Z", "answer_score": 1177 }
Please answer the following Stack Overflow question: Title: Getting today's date in YYYY-MM-DD in Python? <p>Is there a nicer way than the following to return today's date in the <code>YYYY-MM-DD</code> format?</p> <pre><code>str(datetime.datetime.today()).split()[0] </code></pre>
<p>Use <a href="http://strftime.org/" rel="noreferrer"><code>strftime</code></a>:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; datetime.today().strftime('%Y-%m-%d') '2021-01-26' </code></pre> <p>To also include a zero-padded <code>Hour:Minute:Second</code> at the end:</p> <pre><code>&gt;&gt;&gt; datetime.today().strftime('%Y-%m-%d %H:%M:%S') '2021-01-26 16:50:03' </code></pre>
{ "question_id": 32490629, "question_date": "2015-09-09T23:20:25.020Z", "question_score": 784, "tags": "python|datetime|python-datetime", "answer_id": 32490661, "answer_date": "2015-09-09T23:23:57.653Z", "answer_score": 1307 }
Please answer the following Stack Overflow question: Title: Difference between modes a, a+, w, w+, and r+ in built-in open function? <p>In the python built-in <a href="http://docs.python.org/library/functions.html#open" rel="noreferrer">open</a> function, what is the exact difference between the modes <code>w</code>, <code>a</code>, <code>w+</code>, <code>a+</code>, and <code>r+</code>?</p> <p>In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "updating" specifically, but does not define what these terms mean.</p>
<p>The opening modes are exactly the same as those for the C standard library function <strong><code>fopen()</code></strong>.</p> <p><a href="http://www.manpagez.com/man/3/fopen/" rel="noreferrer">The BSD <code>fopen</code> manpage</a> defines them as follows:</p> <pre class="lang-none prettyprint-override"><code> The argument mode points to a string beginning with one of the following sequences (Additional characters may follow these sequences.): ``r'' Open text file for reading. The stream is positioned at the beginning of the file. ``r+'' Open for reading and writing. The stream is positioned at the beginning of the file. ``w'' Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file. ``w+'' Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file. ``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar. ``a+'' Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subse- quent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar. </code></pre>
{ "question_id": 1466000, "question_date": "2009-09-23T13:27:36.450Z", "question_score": 784, "tags": "python", "answer_id": 1466036, "answer_date": "2009-09-23T13:33:20.483Z", "answer_score": 912 }
Please answer the following Stack Overflow question: Title: Using jQuery to center a DIV on the screen <p>How do I go about setting a <code>&lt;div&gt;</code> in the center of the screen using jQuery?</p>
<p>I like adding functions to jQuery so this function would help:</p> <pre><code>jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop()) + "px"); this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft()) + "px"); return this; } </code></pre> <p>Now we can just write:</p> <pre><code>$(element).center(); </code></pre> <p>Demo: <a href="http://jsfiddle.net/DerekL/GbDw9/" rel="noreferrer">Fiddle</a> (with added parameter)</p>
{ "question_id": 210717, "question_date": "2008-10-17T00:11:48.393Z", "question_score": 784, "tags": "javascript|jquery|html|css|layout", "answer_id": 210733, "answer_date": "2008-10-17T00:22:07.140Z", "answer_score": 1080 }
Please answer the following Stack Overflow question: Title: Go to particular revision <p>I cloned a git repository of a certain project. Can I turn the files to the initial state and when I review the files go to revision 2, 3, 4 ... most recent? I'd like to have an overview of how the project was evolving.</p>
<p><strong>Before executing</strong> this command keep in mind that it will leave you in <strong>detached head status</strong></p> <p>Use <code>git checkout &lt;sha1&gt;</code> to check out a particular commit.</p> <p>Where <code>&lt;sha1&gt;</code> is the commit unique number that you can obtain with <code>git log</code></p> <p>Here are some options after you are in detached head status:</p> <ul> <li>Copy the files or make the changes that you need to a folder outside your git folder, checkout the branch were you need them <code>git checkout &lt;existingBranch&gt;</code> and replace files</li> <li>Create a new local branch <code>git checkout -b &lt;new_branch_name&gt; &lt;sha1&gt;</code></li> </ul>
{ "question_id": 7539130, "question_date": "2011-09-24T12:50:26.920Z", "question_score": 783, "tags": "git|revision|revision-history", "answer_id": 7539141, "answer_date": "2011-09-24T12:52:51.397Z", "answer_score": 1181 }
Please answer the following Stack Overflow question: Title: How do I ignore a directory with SVN? <p>I just started using SVN, and I have a cache directory that I don't need under source control. How can I ignore the whole directory/folder with SVN?</p> <p>I am using <a href="https://en.wikipedia.org/wiki/Comparison_of_Subversion_clients#Standalone_Subversion_clients_comparison_table" rel="noreferrer">Versions</a> and <a href="http://en.wikipedia.org/wiki/TextMate" rel="noreferrer">TextMate</a> on OS&nbsp;X and commandline.</p>
<p>Set the <code>svn:ignore</code> property of the parent directory:</p> <pre><code>svn propset svn:ignore dirname . </code></pre> <p>If you have multiple things to ignore, separate by newlines in the property value. In that case it's easier to edit the property value using an external editor:</p> <pre><code>svn propedit svn:ignore . </code></pre>
{ "question_id": 116074, "question_date": "2008-09-22T16:55:59.443Z", "question_score": 783, "tags": "svn|version-control|directory", "answer_id": 116075, "answer_date": "2008-09-22T16:56:30.563Z", "answer_score": 820 }
Please answer the following Stack Overflow question: Title: Git keeps prompting me for a password <p>I've been using Git for a while now, but the constant requests for a password are starting to drive me up the wall.</p> <p>I'm using Mac&nbsp;OS&nbsp;X and GitHub, and I set up Git and my SSH keys as instructed by GitHub's <a href="http://help.github.com/mac-set-up-git/" rel="noreferrer">Set Up Git page</a>. </p> <p>I've also added the github SSH key to my Mac&nbsp;OS&nbsp;X keychain, as mentioned on <a href="http://help.github.com/ssh-key-passphrases/" rel="noreferrer">GitHub's SSH key passphrases page</a>. My public key is registered with Git.</p> <p>Nevertheless, every time I try to Git pull, I have to enter my username and password. Is there something other than an SSH key that I need to set up for this?</p>
<p>I think you may have the wrong Git repository URL. </p> <p>Open <code>.git/config</code> and find the [remote "origin"] section. Make sure you're using the SSH one:</p> <pre><code>ssh://[email protected]/username/repo.git </code></pre> <p>You can see the SSH URL in the main page of your repository if you click <em>Clone or download</em> and choose <em>ssh</em>.</p> <p>And NOT the <code>https</code> or <code>git</code> one:</p> <pre><code>https://github.com/username/repo.git git://github.com/username/repo.git </code></pre> <p>You can now validate with <em>just</em> the SSH key instead of the username and password. </p> <p>If Git complains that <code>'origin' has already been added</code>, open the <code>.config</code> file and edit the <code>url = "..."</code> part after <code>[remote origin]</code> as <code>url = ssh://github/username/repo.git</code></p> <hr> <p>The same goes for other services. Make sure the address looks like: <code>protocol://something@url</code></p> <p>E.g. <code>.git/config</code> for <strong>Azure DevOps:</strong></p> <pre><code>[remote "origin"] url = https://[email protected]/mystore/myproject/ fetch = +refs/heads/*:refs/remotes/origin/* </code></pre>
{ "question_id": 7773181, "question_date": "2011-10-14T20:24:17.560Z", "question_score": 783, "tags": "git|github", "answer_id": 7773605, "answer_date": "2011-10-14T21:10:50.580Z", "answer_score": 897 }
Please answer the following Stack Overflow question: Title: What's the difference between constexpr and const? <p>What's the difference between <code>constexpr</code> and <code>const</code>?</p> <ul> <li>When can I use only one of them? </li> <li>When can I use both and how should I choose one?</li> </ul>
<h2>Basic meaning and syntax</h2> <p>Both keywords can be used in the declaration of objects as well as functions. The basic difference when applied to <em>objects</em> is this:</p> <ul> <li><p><code>const</code> declares an object as <em>constant</em>. This implies a guarantee that once initialized, the value of that object won't change, and the compiler can make use of this fact for optimizations. It also helps prevent the programmer from writing code that modifies objects that were not meant to be modified after initialization.</p> </li> <li><p><code>constexpr</code> declares an object as fit for use in what the Standard calls <em>constant expressions</em>. But note that <code>constexpr</code> is not the only way to do this.</p> </li> </ul> <p>When applied to <em>functions</em> the basic difference is this:</p> <ul> <li><p><code>const</code> can only be used for non-static member functions, not functions in general. It gives a guarantee that the member function does not modify any of the non-static data members (except for mutable data members, which can be modified anyway).</p> </li> <li><p><code>constexpr</code> can be used with both member and non-member functions, as well as constructors. It declares the function fit for use in <em>constant expressions</em>. The compiler will only accept it if the function meets certain criteria (7.1.5/3,4), most importantly <sup>(†)</sup>:</p> <ul> <li>The function body must be non-virtual and extremely simple: Apart from typedefs and static asserts, only a single <code>return</code> statement is allowed. In the case of a constructor, only an initialization list, typedefs, and static assert are allowed. (<code>= default</code> and <code>= delete</code> are allowed, too, though.)</li> <li>As of C++14, the rules are more relaxed, what is allowed since then inside a constexpr function: <code>asm</code> declaration, a <code>goto</code> statement, a statement with a label other than <code>case</code> and <code>default</code>, try-block, the definition of a variable of non-literal type, definition of a variable of static or thread storage duration, the definition of a variable for which no initialization is performed.</li> <li>The arguments and the return type must be <em>literal types</em> (i.e., generally speaking, very simple types, typically scalars or aggregates)</li> </ul> </li> </ul> <h2>Constant expressions</h2> <p>As said above, <code>constexpr</code> declares both objects as well as functions as fit for use in constant expressions. A constant expression is more than merely constant:</p> <ul> <li><p>It can be used in places that require compile-time evaluation, for example, template parameters and array-size specifiers:</p> <pre><code> template&lt;int N&gt; class fixed_size_list { /*...*/ }; fixed_size_list&lt;X&gt; mylist; // X must be an integer constant expression int numbers[X]; // X must be an integer constant expression </code></pre> </li> <li><p>But note:</p> </li> <li><p>Declaring something as <code>constexpr</code> does not necessarily guarantee that it will be evaluated at compile time. It <em>can be used</em> for such, but it can be used in other places that are evaluated at run-time, as well.</p> </li> <li><p>An object <em>may</em> be fit for use in constant expressions <em>without</em> being declared <code>constexpr</code>. Example:</p> <pre><code> int main() { const int N = 3; int numbers[N] = {1, 2, 3}; // N is constant expression } </code></pre> <p>This is possible because <code>N</code>, being constant and initialized at declaration time with a literal, satisfies the criteria for a constant expression, even if it isn't declared <code>constexpr</code>.</p> </li> </ul> <p><strong>So when do I actually have to use <code>constexpr</code>?</strong></p> <ul> <li>An <strong>object</strong> like <code>N</code> above can be used as constant expression <em>without</em> being declared <code>constexpr</code>. This is true for all objects that are:</li> <li><code>const</code></li> <li>of integral or enumeration type <em>and</em></li> <li>initialized at declaration time with an expression that is itself a constant expression <br/><br/></li> </ul> <p><sub>[This is due to §5.19/2: A constant expression must not include a subexpression that involves &quot;an lvalue-to-rvalue modification unless […] a glvalue of integral or enumeration type […]&quot; Thanks to Richard Smith for correcting my earlier claim that this was true for all literal types.]</sub></p> <ul> <li><p>For a <strong>function</strong> to be fit for use in constant expressions, it <strong>must</strong> be explicitly declared <code>constexpr</code>; it is not sufficient for it merely to satisfy the criteria for constant-expression functions. Example:</p> <pre><code> template&lt;int N&gt; class list { }; constexpr int sqr1(int arg) { return arg * arg; } int sqr2(int arg) { return arg * arg; } int main() { const int X = 2; list&lt;sqr1(X)&gt; mylist1; // OK: sqr1 is constexpr list&lt;sqr2(X)&gt; mylist2; // wrong: sqr2 is not constexpr } </code></pre> </li> </ul> <p><strong>When can I / should I use both, <code>const</code> and <code>constexpr</code> <em>together?</em></strong></p> <p><strong>A. In object declarations.</strong> This is never necessary when both keywords refer to the same object to be declared. <code>constexpr</code> implies <code>const</code>.</p> <pre><code>constexpr const int N = 5; </code></pre> <p>is the same as</p> <pre><code>constexpr int N = 5; </code></pre> <p>However, note that there may be situations when the keywords each refer to different parts of the declaration:</p> <pre><code>static constexpr int N = 3; int main() { constexpr const int *NP = &amp;N; } </code></pre> <p>Here, <code>NP</code> is declared as an address constant-expression, i.e. a pointer that is itself a constant expression. (This is possible when the address is generated by applying the address operator to a static/global constant expression.) Here, both <code>constexpr</code> and <code>const</code> are required: <code>constexpr</code> always refers to the expression being declared (here <code>NP</code>), while <code>const</code> refers to <code>int</code> (it declares a pointer-to-const). Removing the <code>const</code> would render the expression illegal (because (a) a pointer to a non-const object cannot be a constant expression, and (b) <code>&amp;N</code> is in-fact a pointer-to-constant).</p> <p><strong>B. In member function declarations.</strong> In C++11, <code>constexpr</code> implies <code>const</code>, while in C++14 and C++17 that is not the case. A member function declared under C++11 as</p> <pre><code>constexpr void f(); </code></pre> <p>needs to be declared as</p> <pre><code>constexpr void f() const; </code></pre> <p>under C++14 in order to still be usable as a <code>const</code> function.</p>
{ "question_id": 14116003, "question_date": "2013-01-02T01:42:28.167Z", "question_score": 783, "tags": "c++|c++11|constants|constexpr", "answer_id": 14117121, "answer_date": "2013-01-02T05:10:47.840Z", "answer_score": 741 }
Please answer the following Stack Overflow question: Title: How do I get the query builder to output its raw SQL query as a string? <p>Given the following code:</p> <pre class="lang-php prettyprint-override"><code>DB::table('users')-&gt;get(); </code></pre> <p>I want to get the raw SQL query string that the database query builder above will generate. In this example, it would be <code>SELECT * FROM users</code>.</p> <p>How do I do this?</p>
<p>To output to the screen the last queries ran you can use this:</p> <pre class="lang-php prettyprint-override"><code>\DB::enableQueryLog(); // Enable query log // Your Eloquent query executed by using get() dd(\DB::getQueryLog()); // Show results of log </code></pre> <p>I believe the most recent queries will be at the bottom of the array.</p> <p>You will have something like that:</p> <pre class="lang-none prettyprint-override"><code>array(1) { [0]=&gt; array(3) { [&quot;query&quot;]=&gt; string(21) &quot;select * from &quot;users&quot;&quot; [&quot;bindings&quot;]=&gt; array(0) { } [&quot;time&quot;]=&gt; string(4) &quot;0.92&quot; } } </code></pre> <p>(Thanks to <a href="https://stackoverflow.com/questions/18236294/how-do-i-get-the-query-builder-to-output-its-raw-sql-query-as-a-string#comment56908005_18236656">Joshua's</a> comment below.)</p>
{ "question_id": 18236294, "question_date": "2013-08-14T15:43:54.813Z", "question_score": 782, "tags": "php|sql|laravel|eloquent|laravel-query-builder", "answer_id": 18236656, "answer_date": "2013-08-14T15:59:16.403Z", "answer_score": 970 }
Please answer the following Stack Overflow question: Title: Split Strings into words with multiple word boundary delimiters <p>I think what I want to do is a fairly common task but I've found no reference on the web. I have text with punctuation, and I want a list of the words. </p> <pre><code>"Hey, you - what are you doing here!?" </code></pre> <p>should be</p> <pre><code>['hey', 'you', 'what', 'are', 'you', 'doing', 'here'] </code></pre> <p>But Python's <code>str.split()</code> only works with one argument, so I have all words with the punctuation after I split with whitespace. Any ideas?</p>
<p>A case where regular expressions are justified:</p> <pre><code>import re DATA = "Hey, you - what are you doing here!?" print re.findall(r"[\w']+", DATA) # Prints ['Hey', 'you', 'what', 'are', 'you', 'doing', 'here'] </code></pre>
{ "question_id": 1059559, "question_date": "2009-06-29T17:49:35.070Z", "question_score": 782, "tags": "python|string|split", "answer_id": 1059596, "answer_date": "2009-06-29T17:56:39.303Z", "answer_score": 533 }
Please answer the following Stack Overflow question: Title: In C#, what is the difference between public, private, protected, and having no access modifier? <p>All my college years I have been using <code>public</code>, and would like to know the difference between <code>public</code>, <code>private</code>, and <code>protected</code>?</p> <p>Also what does <code>static</code> do as opposed to having nothing?</p>
<h2>Access modifiers</h2> <p>From <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers" rel="noreferrer">docs.microsoft.com</a>:</p> <blockquote> <p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/public" rel="noreferrer"><strong><code>public</code></strong></a></p> <p>The type or member can be accessed by any other code in the same assembly or another assembly that references it.</p> <p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private" rel="noreferrer"><strong><code>private</code></strong></a></p> <p>The type or member can only be accessed by code in the same class or struct.</p> <p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected" rel="noreferrer"><strong><code>protected</code></strong></a></p> <p>The type or member can only be accessed by code in the same class or struct, or in a derived class.</p> <p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private-protected" rel="noreferrer"><strong><code>private protected</code></strong></a> (added in C# 7.2)</p> <p>The type or member can only be accessed by code in the same class or struct, or in a derived class from the same assembly, but not from another assembly.</p> <p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/internal" rel="noreferrer"><strong><code>internal</code></strong></a></p> <p>The type or member can be accessed by any code in the same assembly, but not from another assembly.</p> <p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected-internal" rel="noreferrer"><strong><code>protected internal</code></strong></a></p> <p>The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.</p> </blockquote> <p>When <strong>no access modifier</strong> is set, a default access modifier is used. So there is always some form of access modifier even if it's not set.</p> <h2><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static" rel="noreferrer"><code>static</code> modifier</a></h2> <p>The static modifier on a class means that the class cannot be instantiated, and that all of its members are static. A static member has one version regardless of how many instances of its enclosing type are created.</p> <p>A static class is basically the same as a non-static class, but there is one difference: a static class cannot be externally instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself.</p> <p>However, there is a such thing as a <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors" rel="noreferrer">static constructor</a>. Any class can have one of these, including static classes. They cannot be called directly &amp; cannot have parameters (other than any type parameters on the class itself). A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. Looks like this:</p> <pre><code>static class Foo() { static Foo() { Bar = &quot;fubar&quot;; } public static string Bar { get; set; } } </code></pre> <p>Static classes are often used as services, you can use them like so:</p> <pre><code>MyStaticClass.ServiceMethod(...); </code></pre>
{ "question_id": 614818, "question_date": "2009-03-05T13:48:38.163Z", "question_score": 782, "tags": "c#|.net|asp.net|access-modifiers", "answer_id": 614844, "answer_date": "2009-03-05T13:55:02.313Z", "answer_score": 1072 }
Please answer the following Stack Overflow question: Title: wildcard * in CSS for classes <p>I have these divs that I'm styling with <code>.tocolor</code>, but I also need the unique identifier 1,2,3,4 etc. so I'm adding that it as another class <code>tocolor-1</code>. </p> <pre><code>&lt;div class="tocolor tocolor-1"&gt; tocolor 1 &lt;/div&gt; &lt;div class="tocolor tocolor-2"&gt; tocolor 2 &lt;/div&gt; &lt;div class="tocolor tocolor-3"&gt; tocolor 3 &lt;/div&gt; &lt;div class="tocolor tocolor-4"&gt; tocolor 4 &lt;/div&gt; .tocolor{ background: red; } </code></pre> <p>Is there a way to have just 1 class <code>tocolor-*</code>. I tried using a wildcard <code>*</code> as in this css, but it didn't work.</p> <pre><code>.tocolor-*{ background: red; } </code></pre>
<p>What you need is called attribute selector. An example, using your html structure, is the following: </p> <pre><code>div[class^="tocolor-"], div[class*=" tocolor-"] { color:red } </code></pre> <p>In the place of <code>div</code> you can add any element or remove it altogether, and in the place of <code>class</code> you can add any attribute of the specified element.</p> <p><code>[class^="tocolor-"]</code> — starts with "tocolor-".<br> <code>[class*=" tocolor-"]</code> — contains the substring "tocolor-" occurring directly after a space character.</p> <p><strong>Demo:</strong> <a href="http://jsfiddle.net/K3693/1/" rel="noreferrer">http://jsfiddle.net/K3693/1/</a></p> <p>More information on CSS attribute selectors, you can find <a href="http://reference.sitepoint.com/css/attributeselector" rel="noreferrer">here</a> and <a href="http://reference.sitepoint.com/css/css3attributeselectors" rel="noreferrer">here</a>. And from MDN Docs <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors" rel="noreferrer">MDN Docs</a></p>
{ "question_id": 5110249, "question_date": "2011-02-24T20:46:11.377Z", "question_score": 782, "tags": "css|css-selectors|wildcard", "answer_id": 5110337, "answer_date": "2011-02-24T20:53:54.457Z", "answer_score": 1410 }
Please answer the following Stack Overflow question: Title: How to remove all duplicates from an array of objects? <p>I have an object that contains an array of objects.</p> <pre><code>obj = {}; obj.arr = new Array(); obj.arr.push({place:&quot;here&quot;,name:&quot;stuff&quot;}); obj.arr.push({place:&quot;there&quot;,name:&quot;morestuff&quot;}); obj.arr.push({place:&quot;there&quot;,name:&quot;morestuff&quot;}); </code></pre> <p>I'm wondering what is the best method to remove duplicate objects from an array. So for example, <code>obj.arr</code> would become...</p> <pre><code>{place:&quot;here&quot;,name:&quot;stuff&quot;}, {place:&quot;there&quot;,name:&quot;morestuff&quot;} </code></pre>
<p>A primitive method would be:</p> <pre><code>const obj = {}; for (let i = 0, len = things.thing.length; i &lt; len; i++) { obj[things.thing[i]['place']] = things.thing[i]; } things.thing = new Array(); for (const key in obj) { things.thing.push(obj[key]); } </code></pre>
{ "question_id": 2218999, "question_date": "2010-02-08T00:40:33.610Z", "question_score": 781, "tags": "javascript|arrays|object|duplicates", "answer_id": 2219024, "answer_date": "2010-02-08T00:47:32.050Z", "answer_score": 198 }
Please answer the following Stack Overflow question: Title: How to count string occurrence in string? <p>How can I count the number of times a particular string occurs in another string. For example, this is what I am trying to do in Javascript:</p> <pre><code>var temp = "This is a string."; alert(temp.count("is")); //should output '2' </code></pre>
<p>The <code>g</code> in the regular expression (short for <em>global</em>) says to search the whole string rather than just find the first occurrence. This matches <code>is</code> twice:</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 temp = "This is a string."; var count = (temp.match(/is/g) || []).length; console.log(count);</code></pre> </div> </div> </p> <p>And, if there are no matches, it returns <code>0</code>:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var temp = "Hello World!"; var count = (temp.match(/is/g) || []).length; console.log(count);</code></pre> </div> </div> </p>
{ "question_id": 4009756, "question_date": "2010-10-24T18:39:15.003Z", "question_score": 781, "tags": "javascript|regex|string", "answer_id": 4009768, "answer_date": "2010-10-24T18:42:42.177Z", "answer_score": 1298 }
Please answer the following Stack Overflow question: Title: How to git-cherry-pick only changes to certain files? <p>If I want to merge into a Git branch the changes made only to some of the files changed in a particular commit which includes changes to multiple files, how can this be achieved?</p> <p>Suppose the Git commit called <code>stuff</code> has changes to files <code>A</code>, <code>B</code>, <code>C</code>, and <code>D</code> but I want to merge only <code>stuff</code>'s changes to files <code>A</code> and <code>B</code>. It sounds like a job for <code>git cherry-pick</code> but <code>cherry-pick</code> only knows how to merge entire commits, not a subset of the files.</p>
<p>I'd do it with <code>cherry-pick -n</code> (<code>--no-commit</code>) which lets you inspect (and modify) the result before committing:</p> <pre><code>git cherry-pick -n &lt;commit&gt; # unstage modifications you don't want to keep, and remove the # modifications from the work tree as well. # this does work recursively! git checkout HEAD &lt;path&gt; # commit; the message will have been stored for you by cherry-pick git commit </code></pre> <p>If the vast majority of modifications are things you don't want, instead of checking out individual paths (the middle step), you could reset everything back, then add in what you want:</p> <pre><code># unstage everything git reset HEAD # stage the modifications you do want git add &lt;path&gt; # make the work tree match the index # (do this from the top level of the repo) git checkout . </code></pre>
{ "question_id": 5717026, "question_date": "2011-04-19T13:22:54.200Z", "question_score": 781, "tags": "git|github|cherry-pick", "answer_id": 5717615, "answer_date": "2011-04-19T14:04:56.887Z", "answer_score": 914 }
Please answer the following Stack Overflow question: Title: Pull new updates from original GitHub repository into forked GitHub repository <p>I forked someone's repository on GitHub and would like to update my version with commits and updates made in the original repository. These were made after I forked my copy.</p> <p>How can I pull in the changes that were made in the origin and incorporate them into my repository?</p>
<p>You have to add the original repository (the one you forked) as a remote.</p> <p>From the <a href="https://help.github.com/articles/fork-a-repo" rel="noreferrer">GitHub documentation on forking a repository</a>:</p> <p><img src="https://i.stack.imgur.com/ztqaV.jpg" alt="Screenshot of the old GitHub interface with a rectangular lens around the &quot;Fork&quot; button" /></p> <blockquote> <p>Once the clone is complete your repo will have a remote named “<code>origin</code>” that points to your fork on GitHub.<br /> Don’t let the name confuse you, this does not point to the original repo you forked from. To help you keep track of that repo we will add another remote named “upstream”:</p> <pre class="lang-sh prettyprint-override"><code>$ cd PROJECT_NAME $ git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git $ git fetch upstream # then: (like &quot;git pull&quot; which is fetch + merge) $ git merge upstream/master master # or, better, replay your local work on top of the fetched branch # like a &quot;git pull --rebase&quot; $ git rebase upstream/master </code></pre> </blockquote> <p>There's also a <a href="https://cli.github.com/manual/gh" rel="noreferrer">command-line tool (<code>gh</code>) which can facilitate the operations above</a>.</p> <p>Here's a visual of how it works:</p> <p><img src="https://i.stack.imgur.com/cEJjT.png" alt="Flowchart on the result after the commands are executed" /></p> <p>See also &quot;<a href="https://stackoverflow.com/a/6286877/6309">Are Git forks actually Git clones?</a>&quot;.</p>
{ "question_id": 3903817, "question_date": "2010-10-11T06:06:37.153Z", "question_score": 781, "tags": "git|github", "answer_id": 3903835, "answer_date": "2010-10-11T06:12:04.087Z", "answer_score": 889 }
Please answer the following Stack Overflow question: Title: What is the difference between . (dot) and $ (dollar sign)? <p>What is the difference between the dot <code>(.)</code> and the dollar sign <code>($)</code>?</p> <p>As I understand it, they are both syntactic sugar for not needing to use parentheses.</p>
<p>The <code>$</code> operator is for avoiding parentheses. Anything appearing after it will take precedence over anything that comes before.</p> <p>For example, let's say you've got a line that reads:</p> <pre><code>putStrLn (show (1 + 1)) </code></pre> <p>If you want to get rid of those parentheses, any of the following lines would also do the same thing:</p> <pre><code>putStrLn (show $ 1 + 1) putStrLn $ show (1 + 1) putStrLn $ show $ 1 + 1 </code></pre> <p>The primary purpose of the <code>.</code> operator is not to avoid parentheses, but to chain functions. It lets you tie the output of whatever appears on the right to the input of whatever appears on the left. This usually also results in fewer parentheses, but works differently.</p> <p>Going back to the same example:</p> <pre><code>putStrLn (show (1 + 1)) </code></pre> <ol> <li><code>(1 + 1)</code> doesn't have an input, and therefore cannot be used with the <code>.</code> operator.</li> <li><code>show</code> can take an <code>Int</code> and return a <code>String</code>.</li> <li><code>putStrLn</code> can take a <code>String</code> and return an <code>IO ()</code>.</li> </ol> <p>You can chain <code>show</code> to <code>putStrLn</code> like this:</p> <pre><code>(putStrLn . show) (1 + 1) </code></pre> <p>If that's too many parentheses for your liking, get rid of them with the <code>$</code> operator:</p> <pre><code>putStrLn . show $ 1 + 1 </code></pre>
{ "question_id": 940382, "question_date": "2009-06-02T16:06:36.640Z", "question_score": 781, "tags": "haskell|syntax|function-composition", "answer_id": 1290727, "answer_date": "2009-08-17T22:01:59.793Z", "answer_score": 1334 }
Please answer the following Stack Overflow question: Title: How to convert Decimal to Double in C#? <p>I want to assign the decimal variable &quot;trans&quot; to the double variable &quot;this.Opacity&quot;.</p> <pre class="lang-cs prettyprint-override"><code>decimal trans = trackBar1.Value / 5000; this.Opacity = trans; </code></pre> <p>When I build the app it gives the following error:</p> <blockquote> <p>Cannot implicitly convert type decimal to double</p> </blockquote>
<p>An explicit cast to <code>double</code> like this isn't necessary:</p> <pre><code>double trans = (double) trackBar1.Value / 5000.0; </code></pre> <p>Identifying the constant as <code>5000.0</code> (or as <code>5000d</code>) is sufficient:</p> <pre><code>double trans = trackBar1.Value / 5000.0; double trans = trackBar1.Value / 5000d; </code></pre>
{ "question_id": 4, "question_date": "2008-07-31T21:42:52.667Z", "question_score": 781, "tags": "c#|floating-point|type-conversion|double|decimal", "answer_id": 7, "answer_date": "2008-07-31T22:17:57.883Z", "answer_score": 517 }
Please answer the following Stack Overflow question: Title: How to negate specific word in regex? <p>I know that I can negate group of chars as in <code>[^bar]</code> but I need a regular expression where negation applies to the specific word - so in my example how do I negate an actual <code>bar</code>, and not "any chars in bar"?</p>
<p>A great way to do this is to use <a href="http://www.regular-expressions.info/lookaround.html" rel="noreferrer">negative lookahead</a>:</p> <pre><code>^(?!.*bar).*$ </code></pre> <blockquote> <p>The negative lookahead construct is the pair of parentheses, with the opening parenthesis followed by a question mark and an exclamation point. Inside the lookahead [is any regex pattern].</p> </blockquote>
{ "question_id": 1240275, "question_date": "2009-08-06T17:20:45.510Z", "question_score": 780, "tags": "regex", "answer_id": 1240365, "answer_date": "2009-08-06T17:38:49.920Z", "answer_score": 926 }
Please answer the following Stack Overflow question: Title: Fastest Way of Inserting in Entity Framework <p>I'm looking for the fastest way of inserting into Entity Framework.</p> <p>I'm asking this because of the scenario where you have an active <code>TransactionScope</code> and the insertion is huge (4000+). It can potentially last more than 10 minutes (default timeout of transactions), and this will lead to an incomplete transaction.</p>
<p>To your remark in the comments to your question:</p> <blockquote> <p>"...SavingChanges (<strong>for each record</strong>)..."</p> </blockquote> <p>That's the worst thing you can do! Calling <code>SaveChanges()</code> for each record slows bulk inserts extremely down. I would do a few simple tests which will very likely improve the performance:</p> <ul> <li>Call <code>SaveChanges()</code> once after ALL records.</li> <li>Call <code>SaveChanges()</code> after for example 100 records.</li> <li>Call <code>SaveChanges()</code> after for example 100 records and dispose the context and create a new one.</li> <li>Disable change detection</li> </ul> <p>For bulk inserts I am working and experimenting with a pattern like this:</p> <pre><code>using (TransactionScope scope = new TransactionScope()) { MyDbContext context = null; try { context = new MyDbContext(); context.Configuration.AutoDetectChangesEnabled = false; int count = 0; foreach (var entityToInsert in someCollectionOfEntitiesToInsert) { ++count; context = AddToContext(context, entityToInsert, count, 100, true); } context.SaveChanges(); } finally { if (context != null) context.Dispose(); } scope.Complete(); } private MyDbContext AddToContext(MyDbContext context, Entity entity, int count, int commitCount, bool recreateContext) { context.Set&lt;Entity&gt;().Add(entity); if (count % commitCount == 0) { context.SaveChanges(); if (recreateContext) { context.Dispose(); context = new MyDbContext(); context.Configuration.AutoDetectChangesEnabled = false; } } return context; } </code></pre> <p>I have a test program which inserts 560.000 entities (9 scalar properties, no navigation properties) into the DB. With this code it works in less than 3 minutes.</p> <p>For the performance it is important to call <code>SaveChanges()</code> after "many" records ("many" around 100 or 1000). It also improves the performance to dispose the context after SaveChanges and create a new one. This clears the context from all entites, <code>SaveChanges</code> doesn't do that, the entities are still attached to the context in state <code>Unchanged</code>. It is the growing size of attached entities in the context what slows down the insertion step by step. So, it is helpful to clear it after some time.</p> <p>Here are a few measurements for my 560000 entities:</p> <ul> <li>commitCount = 1, recreateContext = false: <strong>many hours</strong> (That's your current procedure)</li> <li>commitCount = 100, recreateContext = false: <strong>more than 20 minutes</strong></li> <li>commitCount = 1000, recreateContext = false: <strong>242 sec</strong></li> <li>commitCount = 10000, recreateContext = false: <strong>202 sec</strong></li> <li>commitCount = 100000, recreateContext = false: <strong>199 sec</strong></li> <li>commitCount = 1000000, recreateContext = false: <strong>out of memory exception</strong></li> <li>commitCount = 1, recreateContext = true: <strong>more than 10 minutes</strong></li> <li>commitCount = 10, recreateContext = true: <strong>241 sec</strong></li> <li>commitCount = 100, recreateContext = true: <strong>164 sec</strong></li> <li>commitCount = 1000, recreateContext = true: <strong>191 sec</strong></li> </ul> <p>The behaviour in the first test above is that the performance is very non-linear and decreases extremely over time. ("Many hours" is an estimation, I never finished this test, I stopped at 50.000 entities after 20 minutes.) This non-linear behaviour is not so significant in all other tests.</p>
{ "question_id": 5940225, "question_date": "2011-05-09T17:14:00.243Z", "question_score": 780, "tags": "c#|sql|entity-framework", "answer_id": 5942176, "answer_date": "2011-05-09T20:33:16.957Z", "answer_score": 1094 }
Please answer the following Stack Overflow question: Title: Add all files to a commit except a single file? <p>I have a bunch of files in a changeset, but I want to specifically ignore a single modified file. Looks like this after <code>git status</code>:</p> <pre><code># modified: main/dontcheckmein.txt # deleted: main/plzcheckmein.c # deleted: main/plzcheckmein2.c ... </code></pre> <p>Is there a way I can do <code>git add</code> but just ignore the one text file I don't want to touch? Something like:</p> <pre><code>git add -u -except main/dontcheckmein.txt </code></pre>
<pre><code>git add -u git reset -- main/dontcheckmein.txt </code></pre> <p><strong>Note</strong>: Git has subsequently added special syntax for this, which is explained in other answers.</p>
{ "question_id": 4475457, "question_date": "2010-12-17T22:53:55.490Z", "question_score": 780, "tags": "git|git-add", "answer_id": 4475506, "answer_date": "2010-12-17T23:00:00.177Z", "answer_score": 1069 }
Please answer the following Stack Overflow question: Title: Should a function have only one return statement? <p>Are there good reasons why it's a better practice to have only one return statement in a function? </p> <p>Or is it okay to return from a function as soon as it is logically correct to do so, meaning there may be many return statements in the function?</p>
<p>I often have several statements at the start of a method to return for "easy" situations. For example, this:</p> <pre class="lang-java prettyprint-override"><code>public void DoStuff(Foo foo) { if (foo != null) { ... } } </code></pre> <p>... can be made more readable (IMHO) like this:</p> <pre class="lang-java prettyprint-override"><code>public void DoStuff(Foo foo) { if (foo == null) return; ... } </code></pre> <p>So yes, I think it's fine to have multiple "exit points" from a function/method.</p>
{ "question_id": 36707, "question_date": "2008-08-31T09:26:55.660Z", "question_score": 780, "tags": "language-agnostic|coding-style", "answer_id": 36714, "answer_date": "2008-08-31T09:31:40.143Z", "answer_score": 741 }
Please answer the following Stack Overflow question: Title: How to convert a Date to UTC? <p>Suppose a user of your website enters a date range.</p> <pre><code>2009-1-1 to 2009-1-3 </code></pre> <p>You need to send this date to a server for some processing, but the server expects all dates and times to be in UTC.</p> <p>Now suppose the user is in Alaska. Since they are in a timezone quite different from UTC, the date range needs to be converted to something like this:</p> <pre><code>2009-1-1T8:00:00 to 2009-1-4T7:59:59 </code></pre> <p>Using the JavaScript <code>Date</code> object, how would you convert the first &quot;localized&quot; date range into something the server will understand?</p>
<blockquote> <p>The <code>toISOString()</code> method returns a string in simplified extended ISO format (<a href="http://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO 8601</a>), which is always 24 or 27 characters long (<code>YYYY-MM-DDTHH:mm:ss.sssZ</code> or <code>±YYYYYY-MM-DDTHH:mm:ss.sssZ</code>, respectively). The timezone is always zero UTC offset, as denoted by the suffix &quot;<code>Z</code>&quot;.</p> </blockquote> <p>Source: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString" rel="noreferrer">MDN web docs</a></p> <p>The format you need is created with the <code>.toISOString()</code> method. For older browsers (ie8 and under), which don't natively support this method, the shim can be found <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toISOString" rel="noreferrer">here</a>:</p> <p>This will give you the ability to do what you need:</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 isoDateString = new Date().toISOString(); console.log(isoDateString);</code></pre> </div> </div> </p> <p>For Timezone work, <a href="http://momentjs.com/" rel="noreferrer">moment.js and moment.js timezone</a> are really invaluable tools...especially for navigating timezones between client and server javascript.</p>
{ "question_id": 948532, "question_date": "2009-06-04T03:54:58.917Z", "question_score": 779, "tags": "javascript|date|utc", "answer_id": 11957822, "answer_date": "2012-08-14T17:43:52.813Z", "answer_score": 540 }
Please answer the following Stack Overflow question: Title: How can I rename a project folder from within Visual Studio? <p>My current solution for renaming the project folder is:</p> <ul> <li>Remove the project from the solution.</li> <li>Rename the folder outside Visual Studio.</li> <li>Re-add the project to the solution.</li> </ul> <p>Is there a better way?</p>
<blockquote> <p><em>TFS users:</em> If you are using source control that requires you to warn it before your rename files/folders then look at <strong><em><a href="https://stackoverflow.com/a/10853509/10245">this answer instead</a></em></strong> which covers the extra steps required.</p> </blockquote> <hr> <p>To rename a project's <strong>folder</strong>, <strong>file</strong> (<code>.*proj</code>) and <strong>display name</strong> in Visual Studio:</p> <ul> <li>Close the solution.</li> <li>Rename the folder(s) outside Visual Studio. (Rename in TFS if using source control)</li> <li>Open the solution, ignoring the warnings (answer "no" if asked to load a project from source control).</li> <li>Go through all the <strong>unavailable</strong> projects and... <ul> <li>Open the <strong>properties</strong> window for the project (highlight the project and press <kbd>Alt</kbd>+<kbd>Enter</kbd> or <kbd>F4</kbd>, or right-click > properties).</li> <li>Set the property '<strong>File Path</strong>' to the new location. <ul> <li>If the property is not editable (as in Visual&nbsp;Studio&nbsp;2012), then open the <code>.sln</code> file directly in another editor such as <a href="http://en.wikipedia.org/wiki/Notepad%2B%2B" rel="noreferrer">Notepad++</a> and update the paths there instead. (You may need to check-out the solution first in TFS, etc.)</li> </ul></li> <li><strong>Reload</strong> the project - right-click > reload project.</li> <li>Change the display name of the project, by highlighting it and pressing <kbd>F2</kbd>, or right-click > <strong>rename</strong>.</li> </ul></li> </ul> <p><strong>Note:</strong> Other suggested solutions that involve removing and then re-adding the project to the solution will break project references.</p> <p>If you perform these steps then you might also consider renaming the following to match:</p> <ol> <li>Assembly</li> <li>Default/Root Namespace</li> <li>Namespace of existing files (use the refactor tools in Visual Studio or <a href="https://en.wikipedia.org/wiki/JetBrains#ReSharper_Ultimate" rel="noreferrer">ReSharper's</a> inconsistent namespaces tool)</li> </ol> <p>Also consider modifying the values of the following <a href="http://msdn.microsoft.com/en-us/library/4w8c1y2s.aspx" rel="noreferrer">assembly attributes</a>:</p> <ol> <li><code>AssemblyProductAttribute</code></li> <li><code>AssemblyDescriptionAttribute</code></li> <li><code>AssemblyTitleAttribute</code></li> </ol>
{ "question_id": 211241, "question_date": "2008-10-17T06:47:46.020Z", "question_score": 779, "tags": "visual-studio|directory|projects-and-solutions", "answer_id": 224788, "answer_date": "2008-10-22T07:55:49.810Z", "answer_score": 841 }
Please answer the following Stack Overflow question: Title: How to kill all processes with a given partial name? <p>I want to kill all processes that I get by:</p> <pre><code>ps aux | grep my_pattern </code></pre> <p>How to do it?</p> <p>This does not work:</p> <pre><code>pkill my_pattern </code></pre>
<p>Use <code>pkill -f</code>, which matches the pattern for any part of the command line</p> <pre><code>pkill -f my_pattern </code></pre> <p>Just in case it doesn't work, try to use this one as well:</p> <pre><code>pkill -9 -f my_pattern </code></pre>
{ "question_id": 8987037, "question_date": "2012-01-24T12:46:13.753Z", "question_score": 779, "tags": "linux|bash|posix", "answer_id": 8987063, "answer_date": "2012-01-24T12:47:56.917Z", "answer_score": 1632 }
Please answer the following Stack Overflow question: Title: How can building a heap be O(n) time complexity? <p>Can someone help explain how can building a heap be <em>O(n)</em> complexity?</p> <p>Inserting an item into a heap is <em>O(log n)</em>, and the insert is repeated n/2 times (the remainder are leaves, and can't violate the heap property). So, this means the complexity should be <em>O(n log n)</em>, I would think.</p> <p>In other words, for each item we &quot;heapify&quot;, it has the potential to have to filter down (i.e., sift down) once for each level for the heap so far (which is <em>log n</em> levels).</p> <p>What am I missing?</p>
<p>I think there are several questions buried in this topic:</p> <ul> <li>How do you implement <code>buildHeap</code> so it runs in <em>O(n)</em> time?</li> <li>How do you show that <code>buildHeap</code> runs in <em>O(n)</em> time when implemented correctly?</li> <li>Why doesn't that same logic work to make heap sort run in <em>O(n)</em> time rather than <em>O(n log n)</em>?</li> </ul> <h2>How do you implement <code>buildHeap</code> so it runs in <em>O(n)</em> time?</h2> <p>Often, answers to these questions focus on the difference between <code>siftUp</code> and <code>siftDown</code>. Making the correct choice between <code>siftUp</code> and <code>siftDown</code> is critical to get <em>O(n)</em> performance for <code>buildHeap</code>, but does nothing to help one understand the difference between <code>buildHeap</code> and <code>heapSort</code> in general. Indeed, proper implementations of both <code>buildHeap</code> and <code>heapSort</code> will <strong>only</strong> use <code>siftDown</code>. The <code>siftUp</code> operation is only needed to perform inserts into an existing heap, so it would be used to implement a priority queue using a binary heap, for example.</p> <p>I've written this to describe how a max heap works. This is the type of heap typically used for heap sort or for a priority queue where higher values indicate higher priority. A min heap is also useful; for example, when retrieving items with integer keys in ascending order or strings in alphabetical order. The principles are exactly the same; simply switch the sort order.</p> <p>The <strong>heap property</strong> specifies that each node in a binary heap must be at least as large as both of its children. In particular, this implies that the largest item in the heap is at the root. Sifting down and sifting up are essentially the same operation in opposite directions: move an offending node until it satisfies the heap property:</p> <ul> <li><code>siftDown</code> swaps a node that is too small with its largest child (thereby moving it down) until it is at least as large as both nodes below it.</li> <li><code>siftUp</code> swaps a node that is too large with its parent (thereby moving it up) until it is no larger than the node above it.</li> </ul> <p>The number of operations required for <code>siftDown</code> and <code>siftUp</code> is proportional to the distance the node may have to move. For <code>siftDown</code>, it is the distance to the bottom of the tree, so <code>siftDown</code> is expensive for nodes at the top of the tree. With <code>siftUp</code>, the work is proportional to the distance to the top of the tree, so <code>siftUp</code> is expensive for nodes at the bottom of the tree. Although both operations are <em>O(log n)</em> in the worst case, in a heap, only one node is at the top whereas half the nodes lie in the bottom layer. So <strong>it shouldn't be too surprising that if we have to apply an operation to every node, we would prefer <code>siftDown</code> over <code>siftUp</code>.</strong></p> <p>The <code>buildHeap</code> function takes an array of unsorted items and moves them until they all satisfy the heap property, thereby producing a valid heap. There are two approaches one might take for <code>buildHeap</code> using the <code>siftUp</code> and <code>siftDown</code> operations we've described.</p> <ol> <li><p>Start at the top of the heap (the beginning of the array) and call <code>siftUp</code> on each item. At each step, the previously sifted items (the items before the current item in the array) form a valid heap, and sifting the next item up places it into a valid position in the heap. After sifting up each node, all items satisfy the heap property.</p> </li> <li><p>Or, go in the opposite direction: start at the end of the array and move backwards towards the front. At each iteration, you sift an item down until it is in the correct location.</p> </li> </ol> <h2>Which implementation for <code>buildHeap</code> is more efficient?</h2> <p>Both of these solutions will produce a valid heap. Unsurprisingly, the more efficient one is the second operation that uses <code>siftDown</code>.</p> <p>Let <em>h = log n</em> represent the height of the heap. The work required for the <code>siftDown</code> approach is given by the sum</p> <pre><code>(0 * n/2) + (1 * n/4) + (2 * n/8) + ... + (h * 1). </code></pre> <p>Each term in the sum has the maximum distance a node at the given height will have to move (zero for the bottom layer, h for the root) multiplied by the number of nodes at that height. In contrast, the sum for calling <code>siftUp</code> on each node is</p> <pre><code>(h * n/2) + ((h-1) * n/4) + ((h-2)*n/8) + ... + (0 * 1). </code></pre> <p>It should be clear that the second sum is larger. The first term alone is <em>hn/2 = 1/2 n log n</em>, so this approach has complexity at best <em>O(n log n)</em>.</p> <h2>How do we prove the sum for the <code>siftDown</code> approach is indeed <em>O(n)</em>?</h2> <p>One method (there are other analyses that also work) is to turn the finite sum into an infinite series and then use Taylor series. We may ignore the first term, which is zero:</p> <p><a href="https://i.stack.imgur.com/959f6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/959f6.png" alt="Taylor series for buildHeap complexity" /></a></p> <p>If you aren't sure why each of those steps works, here is a justification for the process in words:</p> <ul> <li>The terms are all positive, so the finite sum must be smaller than the infinite sum.</li> <li>The series is equal to a power series evaluated at <em>x=1/2</em>.</li> <li>That power series is equal to (a constant times) the derivative of the Taylor series for <em>f(x)=1/(1-x)</em>.</li> <li><em>x=1/2</em> is within the interval of convergence of that Taylor series.</li> <li>Therefore, we can replace the Taylor series with <em>1/(1-x)</em>, differentiate, and evaluate to find the value of the infinite series.</li> </ul> <p>Since the infinite sum is exactly <em>n</em>, we conclude that the finite sum is no larger, and is therefore, <em>O(n)</em>.</p> <h2>Why does heap sort require <em>O(n log n)</em> time?</h2> <p>If it is possible to run <code>buildHeap</code> in linear time, why does heap sort require <em>O(n log n)</em> time? Well, heap sort consists of two stages. First, we call <code>buildHeap</code> on the array, which requires <em>O(n)</em> time if implemented optimally. The next stage is to repeatedly delete the largest item in the heap and put it at the end of the array. Because we delete an item from the heap, there is always an open spot just after the end of the heap where we can store the item. So heap sort achieves a sorted order by successively removing the next largest item and putting it into the array starting at the last position and moving towards the front. It is the complexity of this last part that dominates in heap sort. The loop looks likes this:</p> <pre><code>for (i = n - 1; i &gt; 0; i--) { arr[i] = deleteMax(); } </code></pre> <p>Clearly, the loop runs O(n) times (<em>n - 1</em> to be precise, the last item is already in place). The complexity of <code>deleteMax</code> for a heap is <em>O(log n)</em>. It is typically implemented by removing the root (the largest item left in the heap) and replacing it with the last item in the heap, which is a leaf, and therefore one of the smallest items. This new root will almost certainly violate the heap property, so you have to call <code>siftDown</code> until you move it back into an acceptable position. This also has the effect of moving the next largest item up to the root. Notice that, in contrast to <code>buildHeap</code> where for most of the nodes we are calling <code>siftDown</code> from the bottom of the tree, we are now calling <code>siftDown</code> from the top of the tree on each iteration! <em>Although the tree is shrinking, it doesn't shrink fast enough</em>: The height of the tree stays constant until you have removed the first half of the nodes (when you clear out the bottom layer completely). Then for the next quarter, the height is <em>h - 1</em>. So the total work for this second stage is</p> <pre><code>h*n/2 + (h-1)*n/4 + ... + 0 * 1. </code></pre> <p>Notice the switch: now the zero work case corresponds to a single node and the <em>h</em> work case corresponds to half the nodes. This sum is <em>O(n log n)</em> just like the inefficient version of <code>buildHeap</code> that is implemented using siftUp. But in this case, we have no choice since we are trying to sort and we require the next largest item be removed next.</p> <p>In summary, the work for heap sort is the sum of the two stages: <em>O(n) time for buildHeap and <strong>O(n log n) to remove each node in order</strong>, so the complexity is O(n log n)</em>. You can prove (using some ideas from information theory) that for a comparison-based sort, <em>O(n log n)</em> is the best you could hope for anyway, so there's no reason to be disappointed by this or expect heap sort to achieve the O(n) time bound that <code>buildHeap</code> does.</p>
{ "question_id": 9755721, "question_date": "2012-03-18T03:15:59.250Z", "question_score": 779, "tags": "algorithm|big-o|heap|complexity-theory|construction", "answer_id": 18742428, "answer_date": "2013-09-11T13:22:54.310Z", "answer_score": 837 }
Please answer the following Stack Overflow question: Title: Error "The input device is not a TTY" <p>I am running the following command from my <code>Jenkinsfile</code>. However, I get the error <em>"The input device is not a TTY"</em>.</p> <pre><code>docker run -v $PWD:/foobar -it cloudfoundry/cflinuxfs2 /foobar/script.sh </code></pre> <p>Is there a way to run the script from the <code>Jenkinsfile</code> without doing interactive mode?</p> <p>I basically have a file called <code>script.sh</code> that I would like to run inside the Docker container.</p>
<p>Remove the <code>-it</code> from your cli to make it non interactive and remove the TTY. If you don't need either, e.g. running your command inside of a Jenkins or cron script, you should do this.</p> <p>Or you can change it to <code>-i</code> if you have input piped into the docker command that doesn't come from a TTY. If you have something like <code>xyz | docker ...</code> or <code>docker ... &lt;input</code> in your command line, do this.</p> <p>Or you can change it to <code>-t</code> if you want TTY support but don't have it available on the input device. Do this for apps that check for a TTY to enable color formatting of the output in your logs, or for when you later attach to the container with a proper terminal.</p> <p>Or if you need an interactive terminal and aren't running in a terminal on Linux or MacOS, use a different command line interface. PowerShell is reported to include this support on Windows.</p> <hr /> <p>What is a TTY? It's a terminal interface that supports escape sequences, moving the cursor around, etc, that comes from the old days of dumb terminals attached to mainframes. Today it is provided by the Linux command terminals and ssh interfaces. See the <a href="https://en.wikipedia.org/wiki/Terminal_emulator" rel="noreferrer">wikipedia article for more details</a>.</p> <p>To see the difference of running a container with and without a TTY, run a container without one: <code>docker run --rm -i ubuntu bash</code>. From inside that container, install vim with <code>apt-get update; apt-get install vim</code>. Note the lack of a prompt. When running vim against a file, try to move the cursor around within the file.</p>
{ "question_id": 43099116, "question_date": "2017-03-29T16:26:14.963Z", "question_score": 778, "tags": "docker|jenkins|jenkins-pipeline", "answer_id": 43099210, "answer_date": "2017-03-29T16:31:12.030Z", "answer_score": 1121 }
Please answer the following Stack Overflow question: Title: How to display line numbers in 'less' (GNU) <p>What is the command to make <a href="https://linux.die.net/man/1/less" rel="noreferrer">less</a> display line numbers in the left column?</p>
<p>From the <a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?less" rel="noreferrer">manual</a>:</p> <blockquote> <p>-N or --LINE-NUMBERS Causes a line number to be displayed at the beginning of each line in the display.</p> </blockquote> <p>You can also toggle line numbers without quitting less by typing <code>-N</code>.</p> <p>It is possible to toggle any of less's command line options in this way.</p>
{ "question_id": 831681, "question_date": "2009-05-06T20:52:09.217Z", "question_score": 778, "tags": "unix|gnu", "answer_id": 831707, "answer_date": "2009-05-06T20:56:49.473Z", "answer_score": 1114 }
Please answer the following Stack Overflow question: Title: How do I import a namespace in Razor View Page? <p>How to import a namespace in Razor View Page?</p>
<p>Finally found the answer.</p> <pre><code>@using MyNamespace </code></pre> <p>For VB.Net:</p> <pre><code>@Imports Mynamespace </code></pre> <p>Take a look at <a href="https://stackoverflow.com/a/6723046/5519709">@ravy amiry's answer</a> if you want to include a namespace across the app.</p>
{ "question_id": 3239006, "question_date": "2010-07-13T16:03:11.667Z", "question_score": 778, "tags": "asp.net|asp.net-mvc-3|razor|webmatrix", "answer_id": 3244924, "answer_date": "2010-07-14T09:38:44.643Z", "answer_score": 888 }
Please answer the following Stack Overflow question: Title: What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012? <p>The <em><a href="https://www.destroyallsoftware.com/talks/wat" rel="noreferrer">'Wat' talk for CodeMash 2012</a></em> basically points out a few bizarre quirks with Ruby and JavaScript.</p> <p>I have made a JSFiddle of the results at <a href="http://jsfiddle.net/fe479/9/" rel="noreferrer">http://jsfiddle.net/fe479/9/</a>.</p> <p>The behaviours specific to JavaScript (as I don't know Ruby) are listed below.</p> <p>I found in the JSFiddle that some of my results didn't correspond with those in the video, and I am not sure why. I am, however, curious to know how JavaScript is handling working behind the scenes in each case.</p> <pre><code>Empty Array + Empty Array [] + [] result: &lt;Empty String&gt; </code></pre> <p>I am quite curious about the <code>+</code> operator when used with arrays in JavaScript. This matches the video's result.</p> <pre><code>Empty Array + Object [] + {} result: [Object] </code></pre> <p>This matches the video's result. What's going on here? Why is this an object. What does the <code>+</code> operator do?</p> <pre><code>Object + Empty Array {} + [] result: [Object] </code></pre> <p>This doesn't match the video. The video suggests that the result is 0, whereas I get [Object].</p> <pre><code>Object + Object {} + {} result: [Object][Object] </code></pre> <p>This doesn't match the video either, and how does outputting a variable result in two objects? Maybe my JSFiddle is wrong.</p> <pre><code>Array(16).join("wat" - 1) result: NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN </code></pre> <p>Doing wat + 1 results in <code>wat1wat1wat1wat1</code>...</p> <p>I suspect this is just straightforward behaviour that trying to subtract a number from a string results in NaN.</p>
<p>Here's a list of explanations for the results you're seeing (and supposed to be seeing). The references I'm using are from the <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMA-262 standard</a>.</p> <ol> <li><h3><code>[] + []</code></h3> <p>When using the addition operator, both the left and right operands are converted to primitives first (<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.1">§11.6.1</a>). As per <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-9.1">§9.1</a>, converting an object (in this case an array) to a primitive returns its default value, which for objects with a valid <code>toString()</code> method is the result of calling <code>object.toString()</code> (<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.8">§8.12.8</a>). For arrays this is the same as calling <code>array.join()</code> (<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.2">§15.4.4.2</a>). Joining an empty array results in an empty string, so step #7 of the addition operator returns the concatenation of two empty strings, which is the empty string.</p></li> <li><h3><code>[] + {}</code></h3> <p>Similar to <code>[] + []</code>, both operands are converted to primitives first. For "Object objects" (§15.2), this is again the result of calling <code>object.toString()</code>, which for non-null, non-undefined objects is <code>"[object Object]"</code> (<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2">§15.2.4.2</a>).</p></li> <li><h3><code>{} + []</code></h3> <p>The <code>{}</code> here is not parsed as an object, but instead as an empty block (<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-12.1">§12.1</a>, at least as long as you're not forcing that statement to be an expression, but more about that later). The return value of empty blocks is empty, so the result of that statement is the same as <code>+[]</code>. The unary <code>+</code> operator (<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.4.6">§11.4.6</a>) returns <code>ToNumber(ToPrimitive(operand))</code>. As we already know, <code>ToPrimitive([])</code> is the empty string, and according to <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-9.3.1">§9.3.1</a>, <code>ToNumber("")</code> is 0.</p></li> <li><h3><code>{} + {}</code></h3> <p>Similar to the previous case, the first <code>{}</code> is parsed as a block with empty return value. Again, <code>+{}</code> is the same as <code>ToNumber(ToPrimitive({}))</code>, and <code>ToPrimitive({})</code> is <code>"[object Object]"</code> (see <code>[] + {}</code>). So to get the result of <code>+{}</code>, we have to apply <code>ToNumber</code> on the string <code>"[object Object]"</code>. When following the steps from <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-9.3.1">§9.3.1</a>, we get <code>NaN</code> as a result:</p> <blockquote> <p>If the grammar cannot interpret the String as an expansion of <em>StringNumericLiteral</em>, then the result of <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-9.3">ToNumber</a> is <strong>NaN</strong>.</p> </blockquote></li> <li><h3><code>Array(16).join("wat" - 1)</code></h3> <p>As per <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.1.1">§15.4.1.1</a> and <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.2.2">§15.4.2.2</a>, <code>Array(16)</code> creates a new array with length 16. To get the value of the argument to join, <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.2">§11.6.2</a> steps #5 and #6 show that we have to convert both operands to a number using <code>ToNumber</code>. <code>ToNumber(1)</code> is simply 1 (<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-9.3">§9.3</a>), whereas <code>ToNumber("wat")</code> again is <code>NaN</code> as per <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-9.3.1">§9.3.1</a>. Following step 7 of <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.2">§11.6.2</a>, <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.3">§11.6.3</a> dictates that </p> <blockquote> <p>If either operand is <strong>NaN</strong>, the result is <strong>NaN</strong>.</p> </blockquote> <p>So the argument to <code>Array(16).join</code> is <code>NaN</code>. Following §15.4.4.5 (<code>Array.prototype.join</code>), we have to call <code>ToString</code> on the argument, which is <code>"NaN"</code> (<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-9.8.1">§9.8.1</a>):</p> <blockquote> <p>If <em>m</em> is <strong>NaN</strong>, return the String <strong><code>"NaN"</code></strong>.</p> </blockquote> <p>Following step 10 of <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.5">§15.4.4.5</a>, we get 15 repetitions of the concatenation of <code>"NaN"</code> and the empty string, which equals the result you're seeing. When using <code>"wat" + 1</code> instead of <code>"wat" - 1</code> as argument, the addition operator converts <code>1</code> to a string instead of converting <code>"wat"</code> to a number, so it effectively calls <code>Array(16).join("wat1")</code>.</p></li> </ol> <p>As to why you're seeing different results for the <code>{} + []</code> case: When using it as a function argument, you're forcing the statement to be an <em>ExpressionStatement</em>, which makes it impossible to parse <code>{}</code> as empty block, so it's instead parsed as an empty object literal.</p>
{ "question_id": 9032856, "question_date": "2012-01-27T11:49:50.340Z", "question_score": 778, "tags": "javascript", "answer_id": 9033306, "answer_date": "2012-01-27T12:33:38.787Z", "answer_score": 1510 }
Please answer the following Stack Overflow question: Title: Sleep for milliseconds <p>I know the POSIX <code>sleep(x)</code> function makes the program sleep for x seconds. Is there a function to make the program sleep for x <em>milliseconds</em> in C++?</p>
<p>Note that there is no standard C API for milliseconds, so (on Unix) you will have to settle for <code>usleep</code>, which accepts microseconds:</p> <pre><code>#include &lt;unistd.h&gt; unsigned int microseconds; ... usleep(microseconds); </code></pre>
{ "question_id": 4184468, "question_date": "2010-11-15T12:49:51.513Z", "question_score": 777, "tags": "c++|linux|sleep", "answer_id": 4184493, "answer_date": "2010-11-15T12:52:35.607Z", "answer_score": 509 }
Please answer the following Stack Overflow question: Title: How do I display a decimal value to 2 decimal places? <p>When displaying the value of a decimal currently with <code>.ToString()</code>, it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places. </p> <p>Do I use a variation of <code>.ToString()</code> for this?</p>
<pre><code>decimalVar.ToString(&quot;#.##&quot;); // returns &quot;.5&quot; when decimalVar == 0.5m </code></pre> <p>or</p> <pre><code>decimalVar.ToString(&quot;0.##&quot;); // returns &quot;0.5&quot; when decimalVar == 0.5m </code></pre> <p>or</p> <pre><code>decimalVar.ToString(&quot;0.00&quot;); // returns &quot;0.50&quot; when decimalVar == 0.5m </code></pre>
{ "question_id": 164926, "question_date": "2008-10-02T22:41:56.833Z", "question_score": 777, "tags": "c#|.net|format|decimal", "answer_id": 164932, "answer_date": "2008-10-02T22:43:02.617Z", "answer_score": 1107 }
Please answer the following Stack Overflow question: Title: How can I match "anything up until this sequence of characters" in a regular expression? <p>Take this regular expression: <code>/^[^abc]/</code>. This will match any single character at the beginning of a string, except <em>a</em>, <em>b</em>, or *c.</p> <p>If you add a <code>*</code> after it – <code>/^[^abc]*/</code> – the regular expression will continue to add each subsequent character to the result, until it meets either an <code>a</code>, <strong>or</strong> <code>b</code>, <strong>or</strong> <code>c</code>.</p> <p>For example, with the source string <code>&quot;qwerty qwerty whatever abc hello&quot;</code>, the expression will match up to <code>&quot;qwerty qwerty wh&quot;</code>.</p> <p>But what if I wanted the matching string to be <code>&quot;qwerty qwerty whatever &quot;</code>?</p> <p>In other words, how can I match everything up to (but not including) the <em>exact sequence</em> <code>&quot;abc&quot;</code>?</p>
<p>You didn't specify which flavor of regex you're using, but this will work in any of the most popular ones that can be considered "complete".</p> <pre><code>/.+?(?=abc)/ </code></pre> <h3>How it works</h3> <p>The <code>.+?</code> part is the un-greedy version of <code>.+</code> (one or more of anything). When we use <code>.+</code>, the engine will basically match everything. Then, if there is something else in the regex it will go back in steps trying to match the following part. This is the <strong>greedy</strong> behavior, meaning <strong>as much as possible to satisfy</strong>.</p> <p>When using <code>.+?</code>, instead of matching all at once and going back for other conditions (if any), the engine will match the next characters by step until the subsequent part of the regex is matched (again if any). This is the <strong>un-greedy</strong>, meaning match <strong>the fewest possible to satisfy</strong>.</p> <pre class="lang-none prettyprint-override"><code>/.+X/ ~ "abcXabcXabcX" /.+/ ~ "abcXabcXabcX" ^^^^^^^^^^^^ ^^^^^^^^^^^^ /.+?X/ ~ "abcXabcXabcX" /.+?/ ~ "abcXabcXabcX" ^^^^ ^ </code></pre> <p>Following that we have <code>(?=</code><strong><code>{contents}</code></strong><code>)</code>, a <em>zero width assertion</em>, a <em>look around</em>. This grouped construction matches its contents, but does not count as characters matched (<strong>zero width</strong>). It only returns if it is a match or not (<strong>assertion</strong>).</p> <p>Thus, in other terms the regex <code>/.+?(?=abc)/</code> means:</p> <blockquote> <p>Match any characters as few as possible until a "abc" is found, without counting the "abc".</p> </blockquote>
{ "question_id": 7124778, "question_date": "2011-08-19T16:45:44.500Z", "question_score": 777, "tags": "regex", "answer_id": 7124976, "answer_date": "2011-08-19T17:03:11.983Z", "answer_score": 1380 }