input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: What is the difference between canonical name, simple name and class name in Java Class? <p>In Java, what is the difference between these:</p> <pre><code>Object o1 = .... o1.getClass().getSimpleName(); o1.getClass().getName(); o1.getClass().getCanonicalName(); </code></pre> <p>I have checked the Javadoc multiple times and yet this never explains it well. I also ran a test and that didn't reflect any real meaning behind the way these methods are called.</p>
<p>If you're unsure about something, try writing a test first.</p> <p>I did this:</p> <pre class="lang-java prettyprint-override"><code>class ClassNameTest { public static void main(final String... arguments) { printNamesForClass( int.class, &quot;int.class (primitive)&quot;); printNamesForClass( String.class, &quot;String.class (ordinary class)&quot;); printNamesForClass( java.util.HashMap.SimpleEntry.class, &quot;java.util.HashMap.SimpleEntry.class (nested class)&quot;); printNamesForClass( new java.io.Serializable(){}.getClass(), &quot;new java.io.Serializable(){}.getClass() (anonymous inner class)&quot;); } private static void printNamesForClass(final Class&lt;?&gt; clazz, final String label) { System.out.println(label + &quot;:&quot;); System.out.println(&quot; getName(): &quot; + clazz.getName()); System.out.println(&quot; getCanonicalName(): &quot; + clazz.getCanonicalName()); System.out.println(&quot; getSimpleName(): &quot; + clazz.getSimpleName()); System.out.println(&quot; getTypeName(): &quot; + clazz.getTypeName()); // added in Java 8 System.out.println(); } } </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code>int.class (primitive): getName(): int getCanonicalName(): int getSimpleName(): int getTypeName(): int String.class (ordinary class): getName(): java.lang.String getCanonicalName(): java.lang.String getSimpleName(): String getTypeName(): java.lang.String java.util.HashMap.SimpleEntry.class (nested class): getName(): java.util.AbstractMap$SimpleEntry getCanonicalName(): java.util.AbstractMap.SimpleEntry getSimpleName(): SimpleEntry getTypeName(): java.util.AbstractMap$SimpleEntry new java.io.Serializable(){}.getClass() (anonymous inner class): getName(): ClassNameTest$1 getCanonicalName(): null getSimpleName(): getTypeName(): ClassNameTest$1 </code></pre> <p>There's an empty entry in the last block where <code>getSimpleName</code> returns an empty string.</p> <p>The upshot looking at this is:</p> <blockquote> <ul> <li>the <strong>name</strong> is the name that you'd use to dynamically load the class with, for example, a call to <code>Class.forName</code> with the default <code>ClassLoader</code>. Within the scope of a certain <code>ClassLoader</code>, all classes have unique names.</li> <li>the <strong>canonical name</strong> is the name that would be used in an import statement. It might be useful during <code>toString</code> or logging operations. When the <code>javac</code> compiler has complete view of a classpath, it enforces uniqueness of canonical names within it by clashing fully qualified class and package names at compile time. However JVMs must accept such name clashes, and thus canonical names do not uniquely identify classes within a <code>ClassLoader</code>. (In hindsight, a better name for this getter would have been <code>getJavaName</code>; but this method dates from a time when the JVM was used solely to run Java programs.)</li> <li>the <strong>simple name</strong> loosely identifies the class, again might be useful during <code>toString</code> or logging operations but is not guaranteed to be unique.</li> <li>the <strong>type name</strong> returns &quot;an informative string for the name of this type&quot;, &quot;It's like <code>toString</code>: it's purely informative and has no contract value&quot;. (as written by sir4ur0n)</li> </ul> </blockquote> <p>Also you can commonly reference the Java Language Specification documentation for these types technical Java API details:</p> <blockquote> <ul> <li>Here's the Java 11 <strong>Specification</strong> on this subject matter: <a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-6.html#jls-6.7" rel="noreferrer">https://docs.oracle.com/javase/specs/jls/se11/html/jls-6.html#jls-6.7</a></li> </ul> <p><code>Example 6.7-2.</code> and <code>Example 6.7-2.</code> goes over <code>Fully Qualified Names</code> and <code>Fully Qualified Names v. Canonical Name</code> respectively</p> </blockquote>
{ "question_id": 15202997, "question_date": "2013-03-04T13:45:28.763Z", "question_score": 1116, "tags": "java", "answer_id": 15203417, "answer_date": "2013-03-04T14:07:27.310Z", "answer_score": 1274 }
Please answer the following Stack Overflow question: Title: Parameterize an SQL IN clause <p>How do I parameterize a query containing an <code>IN</code> clause with a variable number of arguments, like this one?</p> <pre><code>SELECT * FROM Tags WHERE Name IN ('ruby','rails','scruffy','rubyonrails') ORDER BY Count DESC </code></pre> <p>In this query, the number of arguments could be anywhere from 1 to 5.</p> <p>I would prefer not to use a dedicated stored procedure for this (or XML), but if there is some elegant way specific to <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2008" rel="noreferrer">SQL Server 2008</a>, I am open to that.</p>
<p>Here's a quick-and-dirty technique I have used:</p> <pre><code>SELECT * FROM Tags WHERE '|ruby|rails|scruffy|rubyonrails|' LIKE '%|' + Name + '|%' </code></pre> <p>So here's the C# code:</p> <pre><code>string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" }; const string cmdText = "select * from tags where '|' + @tags + '|' like '%|' + Name + '|%'"; using (SqlCommand cmd = new SqlCommand(cmdText)) { cmd.Parameters.AddWithValue("@tags", string.Join("|", tags); } </code></pre> <p>Two caveats:</p> <ul> <li>The performance is terrible. <code>LIKE "%...%"</code> queries are not indexed.</li> <li>Make sure you don't have any <code>|</code>, blank, or null tags or this won't work</li> </ul> <p>There are other ways to accomplish this that some people may consider cleaner, so please keep reading.</p>
{ "question_id": 337704, "question_date": "2008-12-03T16:16:43.187Z", "question_score": 1115, "tags": "sql|sql-server-2008|parameters", "answer_id": 337817, "answer_date": "2008-12-03T16:41:17.037Z", "answer_score": 325 }
Please answer the following Stack Overflow question: Title: How do I get the current absolute URL in Ruby on Rails? <p>How can I get the current <strong>absolute</strong> URL in my Ruby on Rails view?</p> <p>The <code>request.request_uri</code> only returns the <strong>relative</strong> URL.</p>
<h3>For Rails 3.2 or Rails 4+</h3> <p>You should use <code>request.original_url</code> to get the current URL. Source code on current repo found <a href="https://pix.realquadrant.com/original_url" rel="noreferrer">here</a>.</p> <p>This method is documented at <a href="http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-original_url" rel="noreferrer">original_url method</a>, but if you're curious, the implementation is:</p> <pre><code>def original_url base_url + original_fullpath end </code></pre> <hr /> <h3>For Rails 3:</h3> <p>You can write <code>&quot;#{request.protocol}#{request.host_with_port}#{request.fullpath}&quot;</code>, since <code>request.url</code> is now deprecated.</p> <hr /> <h3>For Rails 2:</h3> <p>You can write <code>request.url</code> instead of <code>request.request_uri</code>. This combines the protocol (usually http://) with the host, and request_uri to give you the full address.</p>
{ "question_id": 2165665, "question_date": "2010-01-29T22:32:44.613Z", "question_score": 1114, "tags": "ruby-on-rails|ruby|url", "answer_id": 2165727, "answer_date": "2010-01-29T22:44:08.553Z", "answer_score": 1494 }
Please answer the following Stack Overflow question: Title: What is a cross-platform way to get the home directory? <p>I need to get the location of the home directory of the current logged-on user. Currently, I've been using the following on Linux:</p> <pre class="lang-py prettyprint-override"><code>os.getenv(&quot;HOME&quot;) </code></pre> <p>However, this does not work on Windows. What is the correct cross-platform way to do this ?</p>
<p>You want to use <a href="http://docs.python.org/library/os.path.html?highlight=os.path#os.path.expanduser" rel="noreferrer">os.path.expanduser</a>.<br> This will ensure it works on all platforms:</p> <pre><code>from os.path import expanduser home = expanduser("~") </code></pre> <p>If you're on <strong>Python 3.5+</strong> you can use <a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.home" rel="noreferrer">pathlib.Path.home()</a>:</p> <pre><code>from pathlib import Path home = str(Path.home()) </code></pre>
{ "question_id": 4028904, "question_date": "2010-10-26T23:43:19.927Z", "question_score": 1113, "tags": "python|cross-platform|home-directory", "answer_id": 4028943, "answer_date": "2010-10-26T23:52:39.003Z", "answer_score": 1959 }
Please answer the following Stack Overflow question: Title: How do I kill the process currently using a port on localhost in Windows? <p>How can I remove the current process/application which is already assigned to a port?</p> <p>For example: <code>localhost:8080</code></p>
<p><strong>Step 1:</strong></p> <p>Open up cmd.exe (note: you <em>may</em> need to run it as an administrator, but this isn't always necessary), then run the below command:</p> <blockquote> <p><code>netstat -ano | findstr :&lt;PORT&gt;</code></p> </blockquote> <p>(Replace <code>&lt;PORT&gt;</code> with the port number you want, but keep the colon)</p> <p><img src="https://i.stack.imgur.com/lEpCZ.png" alt="" /></p> <p>The area circled in red shows the PID (process identifier). Locate the PID of the process that's using the port you want.</p> <p><strong>Step 2:</strong></p> <p>Next, run the following command:</p> <blockquote> <p><code>taskkill /PID &lt;PID&gt; /F</code></p> </blockquote> <p>(No colon this time)</p> <p><img src="https://i.stack.imgur.com/8k64x.png" alt="" /></p> <p>Lastly, you can check whether the operation succeeded or not by re-running the command in &quot;Step 1&quot;. If it was successful you shouldn't see any more search results for that port number.</p>
{ "question_id": 39632667, "question_date": "2016-09-22T07:19:51.100Z", "question_score": 1112, "tags": "windows|cmd|localhost|port|command-prompt", "answer_id": 39633428, "answer_date": "2016-09-22T07:59:14.253Z", "answer_score": 2312 }
Please answer the following Stack Overflow question: Title: How can you encode a string to Base64 in JavaScript? <p>I have a PHP script that can encode a PNG image to a Base64 string.</p> <p>I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding. I'm not used to working with binary data.</p>
<p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa" rel="noreferrer"><code>btoa()</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/atob" rel="noreferrer"><code>atob()</code></a> to convert to and from base64 encoding.</p> <p>There appears to be some confusion in the comments regarding what these functions accept/return, so…</p> <ul> <li><p><code>btoa()</code> accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.btoa#Unicode_Strings" rel="noreferrer">it will probably break</a>. This isn’t a problem <em>if</em> you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.</p> </li> <li><p><code>atob()</code> returns a “string” where each character represents an 8-bit byte – that is, its value will be between <code>0</code> and <code>0xff</code>. This does <em>not</em> mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.</p> </li> </ul> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/1095102/how-do-i-load-binary-image-data-using-javascript-and-xmlhttprequest">How do I load binary image data using Javascript and XMLHttpRequest?</a></li> </ul> <hr /> <p>Most comments here are outdated. You can probably use both <code>btoa()</code> and <code>atob()</code>, unless you support really outdated browsers.</p> <p>Check here:</p> <ul> <li><a href="https://caniuse.com/?search=atob" rel="noreferrer">https://caniuse.com/?search=atob</a></li> <li><a href="https://caniuse.com/?search=btoa" rel="noreferrer">https://caniuse.com/?search=btoa</a></li> </ul>
{ "question_id": 246801, "question_date": "2008-10-29T13:34:18.993Z", "question_score": 1112, "tags": "javascript|base64|binaryfiles", "answer_id": 247261, "answer_date": "2008-10-29T15:31:03.237Z", "answer_score": 1226 }
Please answer the following Stack Overflow question: Title: Collection was modified; enumeration operation may not execute <p>I can't get to the bottom of this error, because when the debugger is attached, it does not seem to occur.</p> <blockquote> <p>Collection was modified; enumeration operation may not execute</p> </blockquote> <p>Below is the code.</p> <p>This is a WCF server in a Windows service. The method <code>NotifySubscribers()</code> is called by the service whenever there is a data event (at random intervals, but not very often - about 800 times per day).</p> <p>When a Windows Forms client subscribes, the subscriber ID is added to the subscribers dictionary, and when the client unsubscribes, it is deleted from the dictionary. The error happens when (or after) a client unsubscribes. It appears that the next time the <code>NotifySubscribers()</code> method is called, the <code>foreach()</code> loop fails with the error in the subject line. The method writes the error into the application log as shown in the code below. When a debugger is attached and a client unsubscribes, the code executes fine.</p> <p>Do you see a problem with this code? Do I need to make the dictionary thread-safe?</p> <pre><code>[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class SubscriptionServer : ISubscriptionServer { private static IDictionary&lt;Guid, Subscriber&gt; subscribers; public SubscriptionServer() { subscribers = new Dictionary&lt;Guid, Subscriber&gt;(); } public void NotifySubscribers(DataRecord sr) { foreach(Subscriber s in subscribers.Values) { try { s.Callback.SignalData(sr); } catch (Exception e) { DCS.WriteToApplicationLog(e.Message, System.Diagnostics.EventLogEntryType.Error); UnsubscribeEvent(s.ClientId); } } } public Guid SubscribeEvent(string clientDescription) { Subscriber subscriber = new Subscriber(); subscriber.Callback = OperationContext.Current. GetCallbackChannel&lt;IDCSCallback&gt;(); subscribers.Add(subscriber.ClientId, subscriber); return subscriber.ClientId; } public void UnsubscribeEvent(Guid clientId) { try { subscribers.Remove(clientId); } catch(Exception e) { System.Diagnostics.Debug.WriteLine(&quot;Unsubscribe Error &quot; + e.Message); } } } </code></pre>
<p>What's likely happening is that <code>SignalData</code> is indirectly changing the subscribers dictionary under the hood during the loop and leading to that message. You can verify this by changing</p> <pre><code>foreach(Subscriber s in subscribers.Values) </code></pre> <p>To</p> <pre><code>foreach(Subscriber s in subscribers.Values.ToList()) </code></pre> <p>If I'm right, the problem will disappear.</p> <p>Calling <code>subscribers.Values.ToList()</code> copies the values of <code>subscribers.Values</code> to a separate list at the start of the <code>foreach</code>. Nothing else has access to this list (it doesn't even have a variable name!), so nothing can modify it inside the loop.</p>
{ "question_id": 604831, "question_date": "2009-03-03T02:01:58.987Z", "question_score": 1112, "tags": "c#|wcf|concurrency|dictionary|thread-safety", "answer_id": 604843, "answer_date": "2009-03-03T02:10:17.173Z", "answer_score": 1960 }
Please answer the following Stack Overflow question: Title: React-router URLs don't work when refreshing or writing manually <p>I'm using React-router and it works fine while I'm clicking on link buttons, but when I refresh my webpage it does not load what I want.</p> <p>For instance, I am in <code>localhost/joblist</code> and everything is fine because I arrived here pressing a link. But <em>if</em> I refresh the webpage I get:</p> <pre class="lang-none prettyprint-override"><code>Cannot GET /joblist </code></pre> <p>By default, it didn't work like this. Initially I had my URL as <code>localhost/#/</code> and <code>localhost/#/joblist</code> and they worked perfectly fine. But I don't like this kind of URL, so trying to erase that <code>#</code>, I wrote:</p> <pre><code>Router.run(routes, Router.HistoryLocation, function (Handler) { React.render(&lt;Handler/&gt;, document.body); }); </code></pre> <p>This problem does not happen with <code>localhost/</code>, this one always returns what I want.</p> <p>This app is single-page, so <code>/joblist</code> doesn't need to ask anything to any server.</p> <p>My entire router.</p> <pre><code>var routes = ( &lt;Route name=&quot;app&quot; path=&quot;/&quot; handler={App}&gt; &lt;Route name=&quot;joblist&quot; path=&quot;/joblist&quot; handler={JobList}/&gt; &lt;DefaultRoute handler={Dashboard}/&gt; &lt;NotFoundRoute handler={NotFound}/&gt; &lt;/Route&gt; ); Router.run(routes, Router.HistoryLocation, function (Handler) { React.render(&lt;Handler/&gt;, document.body); }); </code></pre>
<h3>Server-side vs Client-side</h3> <p>The first big thing to understand about this is that there are now 2 places where the URL is interpreted, whereas there used to be only 1 in 'the old days'. In the past, when life was simple, some user sent a request for <code>http://example.com/about</code> to the server, which inspected the path part of the URL, determined the user was requesting the about page, and then sent back that page.</p> <p>With client-side routing, which is what React Router provides, things are less simple. At first, the client does not have any JavaScript code loaded yet. So the very first request will always be to the server. That will then return a page that contains the needed script tags to load React and React Router, etc. Only when those scripts have loaded does phase 2 start. In phase 2, when the user clicks on the 'About us' navigation link, for example, the URL is changed <em>locally only</em> to <code>http://example.com/about</code> (made possible by the <a href="https://developer.mozilla.org/en-US/docs/Web/API/History_API" rel="noreferrer">History API</a>), but <strong>no request to the server is made</strong>. Instead, React Router does its thing on the client-side, determines which React view to render, and renders it. Assuming your about page does not need to make any <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" rel="noreferrer">REST</a> calls, it's done already. You have transitioned from <em>Home</em> to <em>About Us</em> without any server request having fired.</p> <p>So basically when you click a link, some JavaScript runs that manipulates the URL in the address bar, <em>without causing a page refresh</em>, which in turn causes React Router to perform a page transition <strong>on the client-side</strong>.</p> <p>But now consider what happens if you copy-paste the URL in the address bar and e-mail it to a friend. Your friend has not loaded your website yet. In other words, she is still in <em>phase 1</em>. No React Router is running on her machine yet. So her browser will make a <strong>server request</strong> to <code>http://example.com/about</code>.</p> <p>And this is where your trouble starts. Until now, you could get away with just placing a static HTML at the webroot of your server. But that would give <em>404</em> errors for all other URLs <em>when requested from the server</em>. Those same URLs work fine <em>on the client-side</em>, because there React Router is doing the routing for you, but they fail <em>on the server-side</em> unless you make your server understand them.</p> <h3>Combining server- and client-side routing</h3> <p>If you want the <code>http://example.com/about</code> URL to work on both the server- and the client-side, you need to set up routes for it on both the server- and the client-side. It makes sense, right?</p> <p>And this is where your choices begin. Solutions range from bypassing the problem altogether, via a catch-all route that returns the bootstrap HTML, to the full-on isomorphic approach where both the server and the client run the same JavaScript code.</p> <h2>Bypassing the problem altogether: Hash History</h2> <p>With <a href="https://github.com/jintoppy/react-training/blob/master/basic/node_modules/react-router/docs/guides/Histories.md#hashhistory" rel="noreferrer">Hash History</a>, instead of <a href="https://github.com/jintoppy/react-training/blob/master/basic/node_modules/react-router/docs/guides/Histories.md#browserhistory" rel="noreferrer">Browser History</a>, your URL for the about page would look something like this: <code>http://example.com/#/about</code></p> <p>The part after the hash (<code>#</code>) symbol is not sent to the server. So the server only sees <code>http://example.com/</code> and sends the index page as expected. React Router will pick up the <code>#/about</code> part and show the correct page.</p> <p><strong>Downsides</strong>:</p> <ul> <li>'ugly' URLs</li> <li>Server-side rendering is not possible with this approach. As far as <a href="https://en.wikipedia.org/wiki/Search_engine_optimization" rel="noreferrer">search engine optimization</a> (SEO) is concerned, your website consists of a single page with hardly any content on it.</li> </ul> <h2>Catch-all</h2> <p>With this approach, you do use the Browser History, but just set up a catch-all on the server that sends <code>/*</code> to <code>index.html</code>, effectively giving you much the same situation as with Hash History. You do have clean URLs however and you could improve upon this scheme later without having to invalidate all your user's favorites.</p> <p><strong>Downsides</strong>:</p> <ul> <li>More complex to set up</li> <li>Still no good SEO</li> </ul> <h2>Hybrid</h2> <p>In the hybrid approach, you expand upon the catch-all scenario by adding specific scripts for specific routes. You could make some simple PHP scripts to return the most important pages of your site with content included, so Googlebot can at least see what's on your page.</p> <p><strong>Downsides</strong>:</p> <ul> <li>Even more complex to set up</li> <li>Only good SEO for those routes you give the special treatment</li> <li>Duplicating code for rendering content on server and client</li> </ul> <h2>Isomorphic</h2> <p>What if we use <a href="https://en.wikipedia.org/wiki/Node.js" rel="noreferrer">Node.js</a> as our server so we can run <em>the same</em> JavaScript code on both ends? Now, we have all our routes defined in a single react-router configuration and we don't need to duplicate our rendering code. This is 'the holy grail' so to speak. The server sends the exact same markup as we would end up with if the page transition had happened on the client. This solution is optimal in terms of SEO.</p> <p><strong>Downsides</strong>:</p> <ul> <li>Server <em>must</em> (be able to) run JavaScript. I've experimented with Java in conjunction with <a href="https://en.wikipedia.org/wiki/Nashorn_(JavaScript_engine)" rel="noreferrer">Nashorn</a>, but it's not working for me. In practice, it mostly means you must use a Node.js based server.</li> <li>Many tricky environmental issues (using <code>window</code> on server-side, etc.)</li> <li>Steep learning curve</li> </ul> <h3>Which should I use?</h3> <p>Choose the one that you can get away with. Personally, I think the catch-all is simple enough to set up, so that would be my minimum. This setup allows you to improve on things over time. If you are already using Node.js as your server platform, I'd definitely investigate doing an isomorphic app. Yes, it's tough at first, but once you get the hang of it it's actually a very elegant solution to the problem.</p> <p>So basically, for me, that would be the deciding factor. If my server runs on Node.js, I'd go isomorphic; otherwise, I would go for the Catch-all solution and just expand on it (Hybrid solution) as time progresses and SEO requirements demand it.</p> <p>If you'd like to learn more about isomorphic (also called 'universal') rendering with React, there are some good tutorials on the subject:</p> <ul> <li><a href="https://www.smashingmagazine.com/2015/04/react-to-the-future-with-isomorphic-apps/" rel="noreferrer">React to the future with isomorphic apps</a></li> <li><a href="https://reactjsnews.com/isomorphic-react-in-real-life" rel="noreferrer">The Pain and the Joy of creating isomorphic apps in ReactJS</a></li> <li><a href="https://strongloop.com/strongblog/node-js-react-isomorphic-javascript-why-it-matters/" rel="noreferrer">How to Implement Node + React Isomorphic JavaScript &amp; Why it Matters</a></li> </ul> <p>Also, to get you started, I recommend looking at some starter kits. Pick one that matches your choices for the technology stack (remember, React is just the V in <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="noreferrer">MVC</a>, you need more stuff to build a full app). Start with looking at the one published by Facebook itself:</p> <ul> <li><a href="https://github.com/facebookincubator/create-react-app" rel="noreferrer">Create React App</a></li> </ul> <p>Or pick one of the many by the community. There is a nice site now that tries to index all of them:</p> <ul> <li><a href="http://andrewhfarmer.com/starter-project/" rel="noreferrer">Pick your perfect React starter project</a></li> </ul> <p>I started with these:</p> <ul> <li><a href="https://github.com/RickWong/react-isomorphic-starterkit" rel="noreferrer">React Isomorphic Starterkit</a></li> <li><a href="https://github.com/erikras/react-redux-universal-hot-example" rel="noreferrer">React Redux Universal Hot Example</a></li> </ul> <p>Currently, I am using a homebrewed version of universal rendering that was inspired by the two starter kits above, but they are out of date now.</p> <p>Good luck with your quest!</p>
{ "question_id": 27928372, "question_date": "2015-01-13T17:51:54.140Z", "question_score": 1112, "tags": "javascript|reactjs|url|react-router", "answer_id": 36623117, "answer_date": "2016-04-14T12:27:49.427Z", "answer_score": 1674 }
Please answer the following Stack Overflow question: Title: What is the difference between public, private, and protected? <p>When and why should I use <code>public</code>, <code>private</code>, and <code>protected</code> functions and variables inside a class? What is the difference between them?</p> <p>Examples:</p> <pre><code>// Public public $variable; public function doSomething() { // ... } // Private private $variable; private function doSomething() { // ... } // Protected protected $variable; protected function doSomething() { // ... } </code></pre>
<p>You use:</p> <ul> <li><p><code>public</code> scope to make that property/method available from anywhere, other classes and instances of the object.</p> </li> <li><p><code>private</code> scope when you want your property/method to be visible in its own class only.</p> </li> <li><p><code>protected</code> scope when you want to make your property/method visible in all classes that extend current class including the parent class.</p> </li> </ul> <p>If you don't use any visibility modifier, the property / method will be public.</p> <p><strong>More:</strong> (For comprehensive information)</p> <ul> <li><a href="http://php.net/manual/en/language.oop5.visibility.php" rel="noreferrer">PHP Manual - Visibility</a></li> </ul>
{ "question_id": 4361553, "question_date": "2010-12-05T22:13:14.120Z", "question_score": 1111, "tags": "php|oop|private|public|protected", "answer_id": 4361582, "answer_date": "2010-12-05T22:17:21.017Z", "answer_score": 1391 }
Please answer the following Stack Overflow question: Title: Why would a JavaScript variable start with a dollar sign? <p>I quite often see JavaScript with variables that start with a dollar sign. When/why would you choose to prefix a variable in this way?</p> <p>(I'm not asking about <code>$('p.foo')</code> syntax that you see in jQuery and others, but normal variables like <code>$name</code> and <code>$order</code>)</p>
<p>Very common use in <strong>jQuery</strong> is to distinguish <strong>jQuery</strong> objects stored in variables from other variables. </p> <p>For example, I would define:</p> <pre><code>var $email = $("#email"); // refers to the jQuery object representation of the dom object var email_field = $("#email").get(0); // refers to the dom object itself </code></pre> <p>I find this to be very helpful in writing <strong>jQuery</strong> code and makes it easy to see <strong>jQuery</strong> objects which have a different set of properties.</p>
{ "question_id": 205853, "question_date": "2008-10-15T18:26:34.923Z", "question_score": 1111, "tags": "javascript|naming-conventions", "answer_id": 553734, "answer_date": "2009-02-16T15:42:39.213Z", "answer_score": 1499 }
Please answer the following Stack Overflow question: Title: How to get the browser to navigate to URL in JavaScript <p>What is the best (correct, modern, cross-browser, safe) way to get a web browser to navigate to a URL of your choice using JavaScript?</p>
<p>This works in all browsers:</p> <pre><code>window.location.href = '...'; </code></pre> <p>If you wanted to change the page without it reflecting in the browser back history, you can do:</p> <pre><code>window.location.replace('...'); </code></pre>
{ "question_id": 1226714, "question_date": "2009-08-04T10:18:17.593Z", "question_score": 1109, "tags": "javascript|browser|navigation", "answer_id": 1226718, "answer_date": "2009-08-04T10:19:26.623Z", "answer_score": 1797 }
Please answer the following Stack Overflow question: Title: How to sort an object array by date property? <p>Say I have an array of a few objects:</p> <pre><code>var array = [{id: 1, date: Mar 12 2012 10:00:00 AM}, {id: 2, date: Mar 8 2012 08:00:00 AM}]; </code></pre> <p>How can I sort this array by the date element in order from the date closest to the current date and time down? Keep in mind that the array may have many objects, but for the sake of simplicity I used 2.</p> <p>Would I use the sort function and a custom comparator?</p>
<h2>Simplest Answer</h2> <pre><code>array.sort(function(a,b){ // Turn your strings into dates, and then subtract them // to get a value that is either negative, positive, or zero. return new Date(b.date) - new Date(a.date); }); </code></pre> <h2>More Generic Answer</h2> <pre><code>array.sort(function(o1,o2){ if (sort_o1_before_o2) return -1; else if(sort_o1_after_o2) return 1; else return 0; }); </code></pre> <p>Or more tersely:</p> <pre><code>array.sort(function(o1,o2){ return sort_o1_before_o2 ? -1 : sort_o1_after_o2 ? 1 : 0; }); </code></pre> <h2>Generic, Powerful Answer</h2> <p>Define a custom non-enumerable <code>sortBy</code> function using a <a href="http://en.wikipedia.org/wiki/Schwartzian_transform">Schwartzian transform</a> on all arrays :</p> <pre><code>(function(){ if (typeof Object.defineProperty === 'function'){ try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){} } if (!Array.prototype.sortBy) Array.prototype.sortBy = sb; function sb(f){ for (var i=this.length;i;){ var o = this[--i]; this[i] = [].concat(f.call(o,o,i),o); } this.sort(function(a,b){ for (var i=0,len=a.length;i&lt;len;++i){ if (a[i]!=b[i]) return a[i]&lt;b[i]?-1:1; } return 0; }); for (var i=this.length;i;){ this[--i]=this[i][this[i].length-1]; } return this; } })(); </code></pre> <p>Use it like so:</p> <pre><code>array.sortBy(function(o){ return o.date }); </code></pre> <p>If your date is not directly comparable, make a comparable date out of it, e.g.</p> <pre><code>array.sortBy(function(o){ return new Date( o.date ) }); </code></pre> <p>You can also use this to sort by multiple criteria if you return an array of values:</p> <pre><code>// Sort by date, then score (reversed), then name array.sortBy(function(o){ return [ o.date, -o.score, o.name ] }; </code></pre> <p><em>See <a href="http://phrogz.net/JS/Array.prototype.sortBy.js">http://phrogz.net/JS/Array.prototype.sortBy.js</a> for more details.</em></p>
{ "question_id": 10123953, "question_date": "2012-04-12T12:53:03.743Z", "question_score": 1108, "tags": "javascript|datetime", "answer_id": 10124053, "answer_date": "2012-04-12T12:58:32.493Z", "answer_score": 2021 }
Please answer the following Stack Overflow question: Title: How can I make Bootstrap columns all the same height? <p>I'm using Bootstrap. How can I make three columns all the same height?</p> <p>Here is a screenshot of the problem. I would like the blue and red columns to be the same height as the yellow column. </p> <p><img src="https://i.stack.imgur.com/PLP7h.png" alt="Three bootstrap columns with the center column longer than the other two columns"></p> <p>Here is the 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-html lang-html prettyprint-override"><code>&lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;div class="container-fluid"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-4 panel" style="background-color: red"&gt; some content &lt;/div&gt; &lt;div class="col-xs-4 panel" style="background-color: yellow"&gt; catz &lt;img width="100" height="100" src="https://lorempixel.com/100/100/cats/"&gt; &lt;/div&gt; &lt;div class="col-xs-4 panel" style="background-color: blue"&gt; some more content &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
<h1><strong>LATEST SOLUTION (2022)</strong></h1> <p><strong>Solution 4 using Bootstrap 4 or 5</strong></p> <p>Bootstrap 4 and 5 use Flexbox by default, so there is no need for extra CSS.</p> <p><a href="http://jsfiddle.net/gzm3L456/" rel="noreferrer">Demo</a></p> <pre><code>&lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;row &quot;&gt; &lt;div class=&quot;col-md-4&quot; style=&quot;background-color: red&quot;&gt; some content &lt;/div&gt; &lt;div class=&quot;col-md-4&quot; style=&quot;background-color: yellow&quot;&gt; catz &lt;img width=&quot;100&quot; height=&quot;100&quot; src=&quot;https://placekitten.com/100/100/&quot;&gt; &lt;/div&gt; &lt;div class=&quot;col-md-4&quot; style=&quot;background-color: green&quot;&gt; some more content &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>Solution 1 using negative margins (doesn't break responsiveness)</strong></p> <p><a href="http://jsfiddle.net/nV3Ua/1195/" rel="noreferrer">Demo</a></p> <pre><code>.row{ overflow: hidden; } [class*=&quot;col-&quot;]{ margin-bottom: -99999px; padding-bottom: 99999px; } </code></pre> <p><strong>Solution 2 using table</strong></p> <p><a href="http://jsfiddle.net/nV3Ua/1192/" rel="noreferrer">Demo</a></p> <pre><code>.row { display: table; } [class*=&quot;col-&quot;] { float: none; display: table-cell; vertical-align: top; } </code></pre> <p><strong>Solution 3 using flex</strong> added August 2015. Comments posted before this don't apply to this solution.</p> <p><a href="http://jsfiddle.net/nV3Ua/1821/" rel="noreferrer">Demo</a></p> <pre><code>.row { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; flex-wrap: wrap; } .row &gt; [class*='col-'] { display: flex; flex-direction: column; } </code></pre>
{ "question_id": 19695784, "question_date": "2013-10-30T23:31:37.183Z", "question_score": 1108, "tags": "css|twitter-bootstrap", "answer_id": 19695851, "answer_date": "2013-10-30T23:38:05.337Z", "answer_score": 1156 }
Please answer the following Stack Overflow question: Title: WebSockets vs. Server-Sent events/EventSource <p>Both <a href="http://dev.w3.org/html5/websockets/" rel="noreferrer">WebSockets</a> and <a href="https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events" rel="noreferrer">Server-Sent Events</a> are capable of pushing data to browsers. To me they seem to be competing technologies. What is the difference between them? When would you choose one over the other?</p>
<p>Websockets and SSE (Server Sent Events) are both capable of pushing data to browsers, however they are not competing technologies. </p> <p>Websockets connections can both send data to the browser and receive data from the browser. A good example of an application that could use websockets is a chat application.</p> <p>SSE connections can only push data to the browser. Online stock quotes, or twitters updating timeline or feed are good examples of an application that could benefit from SSE.</p> <p>In practice since everything that can be done with SSE can also be done with Websockets, Websockets is getting a lot more attention and love, and many more browsers support Websockets than SSE.</p> <p>However, it can be overkill for some types of application, and the backend could be easier to implement with a protocol such as SSE. </p> <p>Furthermore SSE can be polyfilled into older browsers that do not support it natively using just JavaScript. Some implementations of SSE polyfills can be found on the <a href="https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills" rel="noreferrer">Modernizr github page</a>.</p> <p><strong>Gotchas:</strong></p> <ul> <li>SSE suffers from a limitation to the maximum number of open connections, which can be specially painful when opening various tabs as the limit is <em>per browser</em> and set to a very low number (6). The issue has been marked as "Won't fix" in <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=275955" rel="noreferrer">Chrome</a> and <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=906896" rel="noreferrer">Firefox</a>. This limit is per browser + domain, so that means that you can open 6 SSE connections across all of the tabs to <code>www.example1.com</code> and another 6 SSE connections to <code>www.example2.com</code> (thanks Phate).</li> <li>Only WS can transmit both binary data and UTF-8, SSE is limited to UTF-8. (Thanks to Chado Nihi).</li> <li>Some enterprise firewalls with packet inspection have trouble dealing with WebSockets (Sophos XG Firewall, WatchGuard, McAfee Web Gateway).</li> </ul> <p><a href="http://www.html5rocks.com/tutorials/eventsource/basics/" rel="noreferrer">HTML5Rocks</a> has some good information on SSE. From that page:</p> <blockquote> <h1>Server-Sent Events vs. WebSockets</h1> <p>Why would you choose Server-Sent Events over WebSockets? Good question.</p> <p>One reason SSEs have been kept in the shadow is because later APIs like WebSockets provide a richer protocol to perform bi-directional, full-duplex communication. Having a two-way channel is more attractive for things like games, messaging apps, and for cases where you need near real-time updates in both directions. However, in some scenarios data doesn't need to be sent from the client. You simply need updates from some server action. A few examples would be friends' status updates, stock tickers, news feeds, or other automated data push mechanisms (e.g. updating a client-side Web SQL Database or IndexedDB object store). If you'll need to send data to a server, XMLHttpRequest is always a friend.</p> <p>SSEs are sent over traditional HTTP. That means they do not require a special protocol or server implementation to get working. WebSockets on the other hand, require full-duplex connections and new Web Socket servers to handle the protocol. In addition, Server-Sent Events have a variety of features that WebSockets lack by design such as automatic reconnection, event IDs, and the ability to send arbitrary events.</p> </blockquote> <hr> <h1>TLDR summary:</h1> <p><strong>Advantages of SSE over Websockets:</strong></p> <ul> <li>Transported over simple HTTP instead of a custom protocol</li> <li>Can be poly-filled with javascript to "backport" SSE to browsers that do not support it yet.</li> <li>Built in support for re-connection and event-id</li> <li>Simpler protocol</li> <li>No trouble with corporate firewalls doing packet inspection</li> </ul> <p><strong>Advantages of Websockets over SSE:</strong></p> <ul> <li>Real time, two directional communication.</li> <li>Native support in more browsers</li> </ul> <p><strong>Ideal use cases of SSE:</strong></p> <ul> <li>Stock ticker streaming</li> <li>twitter feed updating</li> <li>Notifications to browser</li> </ul> <p><strong>SSE gotchas:</strong></p> <ul> <li>No binary support</li> <li>Maximum open connections limit </li> </ul>
{ "question_id": 5195452, "question_date": "2011-03-04T15:07:32.160Z", "question_score": 1108, "tags": "html|browser|websocket|server-sent-events", "answer_id": 5326159, "answer_date": "2011-03-16T13:40:07.943Z", "answer_score": 1316 }
Please answer the following Stack Overflow question: Title: What is the difference between old style and new style classes in Python? <p>What is the difference between old style and new style classes in Python? When should I use one or the other?</p>
<p>From <em><a href="http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes" rel="noreferrer">New-style and classic classes</a></em>:</p> <blockquote> <p><strong>Up to Python 2.1, old-style classes were the only flavour available to the user.</strong></p> <p>The concept of (old-style) class is unrelated to the concept of type: if <code>x</code> is an instance of an old-style class, then <code>x.__class__</code> designates the class of <code>x</code>, but <code>type(x)</code> is always <code>&lt;type 'instance'&gt;</code>. </p> <p>This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance.</p> <p><strong>New-style classes were introduced in Python 2.2 to unify the concepts of class and type</strong>. A new-style class is simply a user-defined type, no more, no less.</p> <p>If x is an instance of a new-style class, then <code>type(x)</code> is typically the same as <code>x.__class__</code> (although this is not guaranteed – a new-style class instance is permitted to override the value returned for <code>x.__class__</code>).</p> <p><strong>The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model</strong>. </p> <p>It also has a number of immediate benefits, like the ability to subclass most built-in types, or the introduction of "descriptors", which enable computed properties.</p> <p><strong>For compatibility reasons, classes are still old-style by default</strong>. </p> <p>New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the "top-level type" object if no other parent is needed. </p> <p>The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type returns. </p> <p>Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are "fixes" that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance.</p> <p><strong>Python 3 only has new-style classes</strong>. </p> <p>No matter if you subclass from <code>object</code> or not, classes are new-style in Python 3.</p> </blockquote>
{ "question_id": 54867, "question_date": "2008-09-10T18:01:27.163Z", "question_score": 1108, "tags": "python|class|oop|types|new-style-class", "answer_id": 54873, "answer_date": "2008-09-10T18:02:43.743Z", "answer_score": 611 }
Please answer the following Stack Overflow question: Title: Static Classes In Java <p>Is there anything like <code>static class</code> in java?</p> <p>What is the meaning of such a class. Do all the methods of the static class need to be <code>static</code> too?</p> <p>Is it required the other way round, that if a class contains all the static methods, shall the class be static too?</p> <p>What are static classes good for?</p>
<p>Java has static <em>nested</em> classes but it sounds like you're looking for a top-level static class. Java has no way of making a top-level class static but you can simulate a static class like this:</p> <ul> <li>Declare your class <code>final</code> - Prevents extension of the class since extending a static class makes no sense</li> <li>Make the constructor <code>private</code> - Prevents instantiation by client code as it makes no sense to instantiate a static class</li> <li>Make <strong>all</strong> the members and functions of the class <code>static</code> - Since the class cannot be instantiated no instance methods can be called or instance fields accessed</li> <li>Note that the compiler will not prevent you from declaring an instance (non-static) member. The issue will only show up if you attempt to call the instance member</li> </ul> <p>Simple example per suggestions from above:</p> <pre><code>public class TestMyStaticClass { public static void main(String []args){ MyStaticClass.setMyStaticMember(5); System.out.println("Static value: " + MyStaticClass.getMyStaticMember()); System.out.println("Value squared: " + MyStaticClass.squareMyStaticMember()); // MyStaticClass x = new MyStaticClass(); // results in compile time error } } // A top-level Java class mimicking static class behavior public final class MyStaticClass { private MyStaticClass () { // private constructor myStaticMember = 1; } private static int myStaticMember; public static void setMyStaticMember(int val) { myStaticMember = val; } public static int getMyStaticMember() { return myStaticMember; } public static int squareMyStaticMember() { return myStaticMember * myStaticMember; } } </code></pre> <p><strong>What good are static classes?</strong> A good use of a static class is in defining one-off, utility and/or library classes where instantiation would not make sense. A great example is the Math class that contains some mathematical constants such as PI and E and simply provides mathematical calculations. Requiring instantiation in such a case would be unnecessary and confusing. See the <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Math.html" rel="noreferrer"><code>Math</code></a> class and <a href="http://hg.openjdk.java.net/jdk/jdk11/file/1ddf9a99e4ad/src/java.base/share/classes/java/lang/Math.java" rel="noreferrer">source code</a>. Notice that it is <code>final</code> and all of its members are <code>static</code>. If Java allowed top-level classes to be declared <code>static</code> then the Math class would indeed be static.</p>
{ "question_id": 7486012, "question_date": "2011-09-20T13:32:42.410Z", "question_score": 1107, "tags": "java|static-classes", "answer_id": 7486111, "answer_date": "2011-09-20T13:39:44.330Z", "answer_score": 976 }
Please answer the following Stack Overflow question: Title: What is the difference between angular-route and angular-ui-router? <p>I'm planning to use <strong>AngularJS</strong> in my big applications. So I'm in the process to find out the right modules to use.</p> <p>What is the difference between <strong>ngRoute (angular-route.js)</strong> and <strong>ui-router (angular-ui-router.js)</strong> modules?</p> <p>In many articles when <strong>ngRoute</strong> is used, route is configured with <strong><em>$routeProvider</em></strong>. However, when used with <em>ui-router</em>, route is configured with <strong><em>$stateProvider and $urlRouterProvider</em></strong>. </p> <blockquote> <p>Which module should I use for better manageability and extensibility?</p> </blockquote>
<p><a href="https://github.com/angular-ui/ui-router" rel="noreferrer">ui-router</a> is a 3rd-party module and is very powerful. It supports everything the normal ngRoute can do as well as many extra functions.</p> <p>Here are some common reason ui-router is chosen over ngRoute:</p> <ul> <li><p>ui-router allows for <a href="https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views" rel="noreferrer">nested views</a> and <a href="https://github.com/angular-ui/ui-router/wiki/Multiple-Named-Views" rel="noreferrer">multiple named views</a>. This is very useful with larger app where you may have pages that inherit from other sections.</p></li> <li><p>ui-router allows for you to have strong-type linking between states based on state names. Change the url in one place will update every link to that state when you build your links with <a href="http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-sref" rel="noreferrer"><code>ui-sref</code></a>. Very useful for larger projects where URLs might change.</p></li> <li><p>There is also the concept of the <a href="http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$stateProvider#methods_decorator" rel="noreferrer">decorator</a> which could be used to allow your routes to be dynamically created based on the URL that is trying to be accessed. This could mean that you will not need to specify all of your routes before hand.</p></li> <li><p><a href="https://github.com/angular-ui/ui-router/wiki#state-manager" rel="noreferrer">states</a> allow you to map and access different information about different states and you can easily pass information between states via <a href="https://github.com/angular-ui/ui-router/wiki/URL-Routing#stateparams-service" rel="noreferrer"><code>$stateParams</code></a>.</p></li> <li><p>You can easily determine if you are in a state or parent of a state to adjust UI element (highlighting the navigation of the current state) within your templates via <a href="http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state" rel="noreferrer"><code>$state</code></a> provided by ui-router which you can expose via setting it in <code>$rootScope</code> on <code>run</code>.</p></li> </ul> <p>In essence, ui-router is ngRouter with more features, under the sheets it is quite different. These additional features are very useful for larger applications.</p> <p>More Information:</p> <ul> <li>Github: <a href="https://github.com/angular-ui/ui-router" rel="noreferrer">https://github.com/angular-ui/ui-router</a></li> <li>Documentation: <ul> <li>API Reference: <a href="http://angular-ui.github.io/ui-router/site/#/api" rel="noreferrer">http://angular-ui.github.io/ui-router/site/#/api</a></li> <li>Guide: <a href="https://github.com/angular-ui/ui-router/wiki" rel="noreferrer">https://github.com/angular-ui/ui-router/wiki</a></li> </ul></li> <li>FAQs: <a href="https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions" rel="noreferrer">https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions</a></li> <li>Sample Application: <a href="http://angular-ui.github.io/ui-router/sample/#/" rel="noreferrer">http://angular-ui.github.io/ui-router/sample/#/</a> </li> </ul>
{ "question_id": 21023763, "question_date": "2014-01-09T15:03:28.493Z", "question_score": 1107, "tags": "javascript|angularjs|angularjs-routing|angular-ui-router|angularjs-module", "answer_id": 21024270, "answer_date": "2014-01-09T15:24:52.763Z", "answer_score": 1124 }
Please answer the following Stack Overflow question: Title: How to sort a list of objects based on an attribute of the objects? <p>I have a list of Python objects that I want to sort by a specific attribute of each object:</p> <pre><code>&gt;&gt;&gt; ut [Tag(name=&quot;toe&quot;, count=10), Tag(name=&quot;leg&quot;, count=2), ...] </code></pre> <p>How do I sort the list by <code>.count</code> in descending order?</p>
<pre><code># To sort the list in place... ut.sort(key=lambda x: x.count, reverse=True) # To return a new list, use the sorted() built-in function... newlist = sorted(ut, key=lambda x: x.count, reverse=True) </code></pre> <p>More on <a href="http://wiki.python.org/moin/HowTo/Sorting#Sortingbykeys" rel="noreferrer">sorting by keys</a>. </p>
{ "question_id": 403421, "question_date": "2008-12-31T16:41:32.833Z", "question_score": 1106, "tags": "python|list|sorting|count", "answer_id": 403426, "answer_date": "2008-12-31T16:42:59.820Z", "answer_score": 1755 }
Please answer the following Stack Overflow question: Title: Adding HTML entities using CSS content <p>How do you use the <strong>CSS</strong> <code>content</code> property to add <strong>HTML</strong> entities?</p> <p>Using something like this just prints <code>&amp;nbsp;</code> to the screen instead of the non-breaking space:</p> <pre class="lang-css prettyprint-override"><code>.breadcrumbs a:before { content: '&amp;nbsp;'; } </code></pre>
<p>You have to use the escaped unicode :</p> <p>Like</p> <pre class="lang-css prettyprint-override"><code>.breadcrumbs a:before { content: '\0000a0'; } </code></pre> <p>More info on : <a href="http://www.evotech.net/blog/2007/04/named-html-entities-in-numeric-order/" rel="noreferrer">http://www.evotech.net/blog/2007/04/named-html-entities-in-numeric-order/</a></p>
{ "question_id": 190396, "question_date": "2008-10-10T07:19:25.160Z", "question_score": 1106, "tags": "html|css|html-entities|css-content", "answer_id": 190412, "answer_date": "2008-10-10T07:27:52.243Z", "answer_score": 1153 }
Please answer the following Stack Overflow question: Title: :: (double colon) operator in Java 8 <p>I was exploring the <strong>Java 8</strong> source and found this particular part of code very surprising:</p> <pre><code>// Defined in IntPipeline.java @Override public final OptionalInt reduce(IntBinaryOperator op) { return evaluate(ReduceOps.makeInt(op)); } @Override public final OptionalInt max() { return reduce(Math::max); // This is the gotcha line } // Defined in Math.java public static int max(int a, int b) { return (a &gt;= b) ? a : b; } </code></pre> <p>Is <code>Math::max</code> something like a method pointer? How does a normal <code>static</code> method get converted to <code>IntBinaryOperator</code>?</p>
<p>Usually, one would call the <code>reduce</code> method using <code>Math.max(int, int)</code> as follows:</p> <pre><code>reduce(new IntBinaryOperator() { int applyAsInt(int left, int right) { return Math.max(left, right); } }); </code></pre> <p>That requires a lot of syntax for just calling <code>Math.max</code>. That's where lambda expressions come into play. Since Java 8 it is allowed to do the same thing in a much shorter way:</p> <pre><code>reduce((int left, int right) -&gt; Math.max(left, right)); </code></pre> <p>How does this work? The java compiler "detects", that you want to implement a method that accepts two <code>int</code>s and returns one <code>int</code>. This is equivalent to the formal parameters of the one and only method of interface <code>IntBinaryOperator</code> (the parameter of method <code>reduce</code> you want to call). So the compiler does the rest for you - it just assumes you want to implement <code>IntBinaryOperator</code>.</p> <p>But as <code>Math.max(int, int)</code> itself fulfills the formal requirements of <code>IntBinaryOperator</code>, it can be used directly. Because Java 7 does not have any syntax that allows a method itself to be passed as an argument (you can only pass method results, but never method references), the <code>::</code> syntax was introduced in Java 8 to reference methods:</p> <pre><code>reduce(Math::max); </code></pre> <p>Note that this will be interpreted by the compiler, not by the JVM at runtime! Although it produces different bytecodes for all three code snippets, they are semantically equal, so the last two can be considered to be short (and probably more efficient) versions of the <code>IntBinaryOperator</code> implementation above!</p> <p>(See also <a href="http://cr.openjdk.java.net/~briangoetz/lambda/lambda-translation.html" rel="noreferrer">Translation of Lambda Expressions</a>)</p>
{ "question_id": 20001427, "question_date": "2013-11-15T12:46:32.953Z", "question_score": 1106, "tags": "java|java-8", "answer_id": 20001866, "answer_date": "2013-11-15T13:08:55.673Z", "answer_score": 1132 }
Please answer the following Stack Overflow question: Title: What is a typedef enum in Objective-C? <p>I don't think I fundamentally understand what an <code>enum</code> is, and when to use it. </p> <p>For example:</p> <pre><code>typedef enum { kCircle, kRectangle, kOblateSpheroid } ShapeType; </code></pre> <p>What is really being declared here?</p>
<p>Three things are being declared here: an anonymous enumerated type is declared, <code>ShapeType</code> is being declared a typedef for that anonymous enumeration, and the three names <code>kCircle</code>, <code>kRectangle</code>, and <code>kOblateSpheroid</code> are being declared as integral constants.</p> <p>Let's break that down. In the simplest case, an enumeration can be declared as</p> <pre><code>enum tagname { ... }; </code></pre> <p>This declares an enumeration with the tag <code>tagname</code>. In C and Objective-C (but <em>not</em> C++), any references to this <em>must</em> be preceded with the <code>enum</code> keyword. For example:</p> <pre><code>enum tagname x; // declare x of type 'enum tagname' tagname x; // ERROR in C/Objective-C, OK in C++ </code></pre> <p>In order to avoid having to use the <code>enum</code> keyword everywhere, a typedef can be created:</p> <pre><code>enum tagname { ... }; typedef enum tagname tagname; // declare 'tagname' as a typedef for 'enum tagname' </code></pre> <p>This can be simplified into one line:</p> <pre><code>typedef enum tagname { ... } tagname; // declare both 'enum tagname' and 'tagname' </code></pre> <p>And finally, if we don't need to be able to use <code>enum tagname</code> with the <code>enum</code> keyword, we can make the <code>enum</code> anonymous and only declare it with the typedef name:</p> <pre><code>typedef enum { ... } tagname; </code></pre> <p>Now, in this case, we're declaring <code>ShapeType</code> to be a typedef'ed name of an anonymous enumeration. <code>ShapeType</code> is really just an integral type, and should only be used to declare variables which hold one of the values listed in the declaration (that is, one of <code>kCircle</code>, <code>kRectangle</code>, and <code>kOblateSpheroid</code>). You can assign a <code>ShapeType</code> variable another value by casting, though, so you have to be careful when reading enum values.</p> <p>Finally, <code>kCircle</code>, <code>kRectangle</code>, and <code>kOblateSpheroid</code> are declared as integral constants in the global namespace. Since no specific values were specified, they get assigned to consecutive integers starting with 0, so <code>kCircle</code> is 0, <code>kRectangle</code> is 1, and <code>kOblateSpheroid</code> is 2.</p>
{ "question_id": 707512, "question_date": "2009-04-01T21:59:43.937Z", "question_score": 1105, "tags": "objective-c|enums|typedef", "answer_id": 707572, "answer_date": "2009-04-01T22:22:20.217Z", "answer_score": 1577 }
Please answer the following Stack Overflow question: Title: What is an idempotent operation? <p>What is an idempotent operation?</p>
<p>In computing, an idempotent operation is one that has no additional effect if it is called more than once with the same input parameters. For example, removing an item from a set can be considered an idempotent operation on the set.</p> <p>In mathematics, an idempotent operation is one where <em>f(f(x)) = f(x)</em>. For example, the <code>abs()</code> function is idempotent because <code>abs(abs(x)) = abs(x)</code> for all <code>x</code>. </p> <p>These slightly different definitions can be reconciled by considering that <em>x</em> in the mathematical definition represents the state of an object, and <em>f</em> is an operation that may mutate that object. For example, consider the <a href="https://docs.python.org/2/library/stdtypes.html#set" rel="noreferrer">Python <code>set</code></a> and its <code>discard</code> method. The <code>discard</code> method removes an element from a set, and does nothing if the element does not exist. So:</p> <pre><code>my_set.discard(x) </code></pre> <p>has exactly the same effect as doing the same operation twice:</p> <pre><code>my_set.discard(x) my_set.discard(x) </code></pre> <p>Idempotent operations are often used in the design of network protocols, where a request to perform an operation is guaranteed to happen at least once, but might also happen more than once. If the operation is idempotent, then there is no harm in performing the operation two or more times.</p> <p>See the Wikipedia article on <a href="http://en.wikipedia.org/wiki/Idempotence" rel="noreferrer">idempotence</a> for more information.</p> <hr> <p><sup>The above answer previously had some incorrect and misleading examples. Comments below written before April 2014 refer to an older revision.</sup></p>
{ "question_id": 1077412, "question_date": "2009-07-03T01:06:59.927Z", "question_score": 1105, "tags": "language-agnostic|definition|idempotent", "answer_id": 1077421, "answer_date": "2009-07-03T01:10:53.897Z", "answer_score": 1240 }
Please answer the following Stack Overflow question: Title: Maximum and Minimum values for ints <p>How do I represent minimum and maximum values for integers in Python? In Java, we have <code>Integer.MIN_VALUE</code> and <code>Integer.MAX_VALUE</code>.</p>
<h3>Python 3</h3> <p>In Python 3, this question doesn't apply. The plain <code>int</code> type is unbound.</p> <p>However, you might actually be looking for information about the current interpreter's <em><a href="http://en.wikipedia.org/wiki/Word_(computer_architecture)#Table_of_word_sizes" rel="noreferrer">word size</a></em>, which will be the same as the machine's word size in most cases. That information is still available in Python 3 as <code>sys.maxsize</code>, which is the maximum value representable by a signed word. Equivalently, it's the size of the largest possible list or in-memory <a href="https://docs.python.org/3.9/library/sys.html#sys.maxsize" rel="noreferrer">sequence</a>.</p> <p>Generally, the maximum value representable by an unsigned word will be <code>sys.maxsize * 2 + 1</code>, and the number of bits in a word will be <code>math.log2(sys.maxsize * 2 + 2)</code>. See <a href="https://stackoverflow.com/a/6918334/577088">this answer</a> for more information.</p> <h3>Python 2</h3> <p>In Python 2, the maximum value for plain <code>int</code> values is available as <code>sys.maxint</code>:</p> <pre><code>&gt;&gt;&gt; sys.maxint 9223372036854775807 </code></pre> <p>You can calculate the minimum value with <code>-sys.maxint - 1</code> as shown <a href="https://docs.python.org/2/library/sys.html#sys.maxint" rel="noreferrer">here</a>.</p> <p>Python seamlessly switches from plain to long integers once you exceed this value. So most of the time, you won't need to know it.</p>
{ "question_id": 7604966, "question_date": "2011-09-30T01:01:06.630Z", "question_score": 1102, "tags": "python|integer", "answer_id": 7604981, "answer_date": "2011-09-30T01:03:49.900Z", "answer_score": 1195 }
Please answer the following Stack Overflow question: Title: Calculate distance between two latitude-longitude points? (Haversine formula) <p>How do I calculate the distance between two points specified by latitude and longitude?</p> <p>For clarification, I'd like the distance in kilometers; the points use the WGS84 system and I'd like to understand the relative accuracies of the approaches available.</p>
<p>This <a href="http://www.movable-type.co.uk/scripts/latlong.html" rel="noreferrer">link</a> might be helpful to you, as it details the use of the <a href="http://en.wikipedia.org/wiki/Haversine_formula" rel="noreferrer">Haversine formula</a> to calculate the distance.</p> <p>Excerpt:</p> <blockquote> <p>This script [in Javascript] calculates great-circle distances between the two points – that is, the shortest distance over the earth’s surface – using the ‘Haversine’ formula.</p> </blockquote> <pre class="lang-js prettyprint-override"><code>function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) { var R = 6371; // Radius of the earth in km var dLat = deg2rad(lat2-lat1); // deg2rad below var dLon = deg2rad(lon2-lon1); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon/2) * Math.sin(dLon/2) ; var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; // Distance in km return d; } function deg2rad(deg) { return deg * (Math.PI/180) } </code></pre>
{ "question_id": 27928, "question_date": "2008-08-26T12:50:45.647Z", "question_score": 1102, "tags": "algorithm|math|maps|latitude-longitude|haversine", "answer_id": 27943, "answer_date": "2008-08-26T12:55:53.030Z", "answer_score": 1319 }
Please answer the following Stack Overflow question: Title: What does 'synchronized' mean? <p>I have some questions regarding the usage and significance of the <code>synchronized</code> keyword. </p> <ul> <li>What is the significance of the <code>synchronized</code> keyword?</li> <li>When should methods be <code>synchronized</code>?</li> <li>What does it mean programmatically and logically?</li> </ul>
<p>The <code>synchronized</code> keyword is all about different threads reading and writing to the same variables, objects and resources. This is not a trivial topic in Java, but here is a quote from Sun:</p> <blockquote> <p><code>synchronized</code> methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.</p> </blockquote> <p><em>In a very, very small nutshell:</em> When you have two threads that are reading and writing to the same 'resource', say a variable named <code>foo</code>, you need to ensure that these threads access the variable in an atomic way. Without the <code>synchronized</code> keyword, your thread 1 may not see the change thread 2 made to <code>foo</code>, or worse, it may only be half changed. This would not be what you logically expect.</p> <p>Again, this is a non-trivial topic in Java. To learn more, explore topics here on SO and the Interwebs about:</p> <ul> <li><a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html" rel="noreferrer">Concurrency</a></li> <li><a href="http://en.wikipedia.org/wiki/Java_Memory_Model" rel="noreferrer">Java Memory Model</a></li> </ul> <p>Keep exploring these topics until the name <em>"Brian Goetz"</em> becomes permanently associated with the term <em>"concurrency"</em> in your brain. </p>
{ "question_id": 1085709, "question_date": "2009-07-06T06:47:23.960Z", "question_score": 1102, "tags": "java|multithreading|keyword|synchronized", "answer_id": 1085745, "answer_date": "2009-07-06T07:01:49.763Z", "answer_score": 956 }
Please answer the following Stack Overflow question: Title: How to search a Git repository by commit message? <p>I checked some source code into GIT with the commit message "Build 0051".</p> <p>However, I can't seem to find that source code any more - how do I extract this source from the GIT repository, using the command line?</p> <p><strong>Update</strong></p> <ol> <li>Checked in versions 0043, 0044, 0045 and 0046 using SmartGIT.</li> <li>Checked out 0043, and checked in versions up to 0051 on a different branch.</li> <li>Checked out 0043 again.</li> <li>Now, 0051 has disappeared.</li> </ol> <p><strong>Update</strong></p> <p>The source code is definitely there, now its a matter of checking it out:</p> <pre><code>C:\Source&gt;git log -g --grep="0052" commit 77b1f718d19e5cf46e2fab8405a9a0859c9c2889 Reflog: HEAD@{10} (unknown &lt;Mike@.(none)&gt;) Reflog message: commit: 20110819 - 1724 - GL: Intermediate version. File version: v0.5.0 build 0052. Author: unknown &lt;Mike@.(none)&gt; Date: Fri Aug 19 17:24:51 2011 +0100 20110819 - 1724 - GL: Intermediate version. File version: v0.5.0 build 0052. C:\Source&gt; </code></pre>
<p>To search the commit log (across all branches) for the given text:</p> <pre><code>git log --all --grep='Build 0051' </code></pre> <p>To search the actual content of commits through a repo's history, use:</p> <pre><code>git grep 'Build 0051' $(git rev-list --all) </code></pre> <p>to show all instances of the given text, the containing file name, and the commit sha1.</p> <p>Finally, as a last resort in case your commit is dangling and not connected to history at all, you can search the reflog itself with the <code>-g</code> flag (short for <code>--walk-reflogs</code>:</p> <pre><code>git log -g --grep='Build 0051' </code></pre> <p>EDIT: if you seem to have lost your history, check the <code>reflog</code> as your safety net. Look for Build 0051 in one of the commits listed by</p> <pre><code>git reflog </code></pre> <p>You may have simply set your <code>HEAD</code> to a part of history in which the 'Build 0051' commit is not visible, or you may have actually blown it away. The <a href="http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html" rel="noreferrer">git-ready reflog</a> article may be of help.</p> <p><strong>To recover your commit from the reflog</strong>: do a git checkout of the commit you found (and optionally make a new branch or tag of it for reference)</p> <pre><code>git checkout 77b1f718d19e5cf46e2fab8405a9a0859c9c2889 # alternative, using reflog (see git-ready link provided) # git checkout HEAD@{10} git checkout -b build_0051 # make a new branch with the build_0051 as the tip </code></pre>
{ "question_id": 7124914, "question_date": "2011-08-19T16:57:46.293Z", "question_score": 1102, "tags": "git|git-log", "answer_id": 7124949, "answer_date": "2011-08-19T17:00:59.257Z", "answer_score": 1657 }
Please answer the following Stack Overflow question: Title: Get the value in an input text box <p>What are the ways to get and render an input value using jQuery?</p> <p>Here is one: </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>$(document).ready(function() { $("#txt_name").keyup(function() { alert($(this).val()); }); })</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.3/jquery.min.js"&gt;&lt;/script&gt; &lt;input type="text" id="txt_name" /&gt;</code></pre> </div> </div> </p>
<pre><code>//Get var bla = $('#txt_name').val(); //Set $('#txt_name').val(bla); </code></pre>
{ "question_id": 4088467, "question_date": "2010-11-03T15:07:17.340Z", "question_score": 1101, "tags": "html|jquery|jquery-selectors|textinput|html-input", "answer_id": 15903284, "answer_date": "2013-04-09T13:28:33.667Z", "answer_score": 1805 }
Please answer the following Stack Overflow question: Title: How do I quickly rename a MySQL database (change schema name)? <p>The MySQL manual at <a href="http://web.archive.org/web/20160504181056/https://dev.mysql.com/doc/refman/5.1/en/rename-database.html" rel="nofollow noreferrer">MySQL</a> covers this.</p> <p>Usually I just dump the database and reimport it with a new name. This is not an option for very big databases. Apparently <code>RENAME {DATABASE | SCHEMA} db_name TO new_db_name;</code> <a href="http://web.archive.org/web/20160504181056/https://dev.mysql.com/doc/refman/5.1/en/rename-database.html" rel="nofollow noreferrer">does bad things, exists only in a handful of versions, and is a bad idea overall</a>.</p> <p>This needs to work with <a href="http://en.wikipedia.org/wiki/InnoDB" rel="nofollow noreferrer">InnoDB</a>, which stores things very differently than <a href="http://en.wikipedia.org/wiki/MyISAM" rel="nofollow noreferrer">MyISAM</a>.</p>
<p>For <strong>InnoDB</strong>, the following seems to work: create the new empty database, then rename each table in turn into the new database:</p> <pre><code>RENAME TABLE old_db.table TO new_db.table; </code></pre> <p>You will need to adjust the permissions after that.</p> <p>For scripting in a shell, you can use either of the following:</p> <pre><code>mysql -u username -ppassword old_db -sNe 'show tables' | while read table; \ do mysql -u username -ppassword -sNe "rename table old_db.$table to new_db.$table"; done </code></pre> <p>OR</p> <pre><code>for table in `mysql -u root -ppassword -s -N -e "use old_db;show tables from old_db;"`; do mysql -u root -ppassword -s -N -e "use old_db;rename table old_db.$table to new_db.$table;"; done; </code></pre> <hr> <p>Notes:</p> <ul> <li>There is no space between the option <code>-p</code> and the password. If your database has no password, remove the <code>-u username -ppassword</code> part.</li> <li><p>If some table has a trigger, it cannot be moved to another database using above method (will result <code>Trigger in wrong schema</code> error). If that is the case, use a traditional way to clone a database and then drop the old one:</p> <p><code>mysqldump old_db | mysql new_db</code></p></li> <li><p>If you have stored procedures, you can copy them afterwards:</p> <p><code>mysqldump -R old_db | mysql new_db</code></p></li> </ul>
{ "question_id": 67093, "question_date": "2008-09-15T21:22:00.090Z", "question_score": 1101, "tags": "mysql|database|innodb|rename", "answer_id": 2298602, "answer_date": "2010-02-19T18:17:41.447Z", "answer_score": 972 }
Please answer the following Stack Overflow question: Title: PHP array delete by value (not key) <p>I have a PHP array as follows:</p> <pre><code>$messages = [312, 401, 1599, 3, ...]; </code></pre> <p>I want to delete the element containing the value <code>$del_val</code> (for example, <code>$del_val=401</code>), but I don't know its key. This might help: <strong>each value can only be there once</strong>.</p> <p>I'm looking for the simplest function to perform this task, please.</p>
<p>Using <a href="http://php.net/manual/en/function.array-search.php" rel="noreferrer"><code>array_search()</code></a> and <a href="http://br2.php.net/unset" rel="noreferrer"><code>unset</code></a>, try the following:</p> <pre><code>if (($key = array_search($del_val, $messages)) !== false) { unset($messages[$key]); } </code></pre> <p><code>array_search()</code> returns the key of the element it finds, which can be used to remove that element from the original array using <code>unset()</code>. It will return <code>FALSE</code> on failure, however it can return a false-y value on success (your key may be <code>0</code> for example), which is why the strict comparison <code>!==</code> operator is used.</p> <p>The <code>if()</code> statement will check whether <code>array_search()</code> returned a value, and will only perform an action if it did.</p>
{ "question_id": 7225070, "question_date": "2011-08-29T00:44:04.337Z", "question_score": 1101, "tags": "php|arrays", "answer_id": 7225113, "answer_date": "2011-08-29T00:53:27.127Z", "answer_score": 1894 }
Please answer the following Stack Overflow question: Title: What is the difference between '@' and '=' in directive scope in AngularJS? <p>I've read the <strong>AngularJS</strong> documentation on the topic carefully, and then fiddled around with a directive. Here's the <a href="http://jsfiddle.net/iweinfuld/7g3QM/3/" rel="noreferrer">fiddle</a>.</p> <p>And here are some relevant snippets:</p> <ul> <li><p>From the <strong>HTML</strong>:</p> <pre><code>&lt;pane bi-title="title" title="{{title}}"&gt;{{text}}&lt;/pane&gt; </code></pre></li> <li><p>From the pane directive:</p> <pre><code>scope: { biTitle: '=', title: '@', bar: '=' }, </code></pre></li> </ul> <p>There are several things I don't get:</p> <ul> <li>Why do I have to use <code>"{{title}}"</code> with <code>'@'</code> and <code>"title"</code> with <code>'='</code>?</li> <li>Can I also access the parent scope directly, without decorating my element with an attribute?</li> <li>The documentation says <em>"Often it's desirable to pass data from the isolated scope via expression and to the parent scope"</em>, but that seems to work fine with bidirectional binding too. Why would the expression route be better?</li> </ul> <p>I found another fiddle that shows the expression solution too: <a href="http://jsfiddle.net/maxisam/QrCXh/" rel="noreferrer">http://jsfiddle.net/maxisam/QrCXh/</a></p>
<blockquote> <p>Why do I have to use "{{title}}" with '<strong>@</strong>' and "title" with '<strong>=</strong>'?</p> </blockquote> <p><strong>@</strong> binds a local/directive scope property to the <strong>evaluated value of the DOM attribute</strong>. If you use <code>title=title1</code> or <code>title="title1"</code>, the value of DOM attribute "title" is simply the string <code>title1</code>. If you use <code>title="{{title}}"</code>, the value of the DOM attribute "title" is the interpolated value of <code>{{title}}</code>, hence the string will be whatever parent scope property "title" is currently set to. Since attribute values are always strings, you will always end up with a string value for this property in the directive's scope when using <strong>@</strong>.</p> <p><strong>=</strong> binds a local/directive scope property to <strong>a parent scope property</strong>. So with <strong>=</strong>, you use the parent model/scope property name as the value of the DOM attribute. You can't use <code>{{}}</code>s with <strong>=</strong>.</p> <p>With @, you can do things like <code>title="{{title}} and then some"</code> -- {{title}} is interpolated, then the string "and them some" is concatenated with it. The final concatenated string is what the local/directive scope property gets. (You can't do this with <strong>=</strong>, only <strong>@</strong>.)</p> <p>With <strong>@</strong>, you will need to use <code>attr.$observe('title', function(value) { ... })</code> if you need to use the value in your link(ing) function. E.g., <code>if(scope.title == "...")</code> won't work like you expect. Note that this means you can only access this attribute <a href="https://github.com/angular/angular.js/wiki/Understanding-Directives" rel="noreferrer"><em>asynchronously</em></a>. You don't need to use $observe() if you are only using the value in a template. E.g., <code>template: '&lt;div&gt;{{title}}&lt;/div&gt;'</code>.</p> <p>With <strong>=</strong>, you don't need to use $observe.</p> <blockquote> <p>Can I also access the parent scope directly, without decorating my element with an attribute?</p> </blockquote> <p>Yes, but only if you don't use an isolate scope. Remove this line from your directive </p> <p><code>scope: { ... }</code> </p> <p>and then your directive will not create a new scope. It will use the parent scope. You can then access all of the parent scope properties directly.</p> <blockquote> <p>The documentation says "Often it's desirable to pass data from the isolated scope via an expression and to the parent scope", but that seems to work fine with bidirectional binding too. Why would the expression route be better?</p> </blockquote> <p>Yes, bidirectional binding allows the local/directive scope and the parent scope to share data. "Expression binding" allows the directive to call an expression (or function) defined by a DOM attribute -- and you can also pass data as arguments to the expression or function. So, if you don't need to share data with the parent -- you just want to call a function defined in the parent scope -- you can use the <strong>&amp;</strong> syntax.</p> <p>See also</p> <ul> <li><a href="http://onehungrymind.com/angularjs-sticky-notes-pt-2-isolated-scope/" rel="noreferrer">Lukas's isolated scope blog post</a> (covers @, =, &amp;)</li> <li><a href="https://stackoverflow.com/questions/13032621/need-some-examples-of-binding-attributes-in-custom-angularjs-tags/13033249#13033249">dnc253's explanation</a> of @ and =</li> <li><a href="https://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs/14049482#14049482">my blog-like answer</a> about scopes -- the <strong>directives</strong> section (way at the bottom, just before the Summary section) has a picture of an isolate scope and its parent scope -- the directive scope uses @ for one property and = for another</li> <li><a href="https://stackoverflow.com/questions/14908133/what-is-the-difference-between-vs-and-in-angularjs">What is the difference between &amp; vs @ and = in angularJS</a></li> </ul>
{ "question_id": 14050195, "question_date": "2012-12-27T06:10:29.370Z", "question_score": 1101, "tags": "angularjs|angularjs-directive|angularjs-scope|isolated-scope", "answer_id": 14063373, "answer_date": "2012-12-28T01:15:27.413Z", "answer_score": 1168 }
Please answer the following Stack Overflow question: Title: MySQL error code: 1175 during UPDATE in MySQL Workbench <p>I'm trying to update the column <code>visited</code> to give it the value 1. I use MySQL workbench, and I'm writing the statement in the SQL editor from inside the workbench. I'm writing the following command:</p> <pre><code>UPDATE tablename SET columnname=1; </code></pre> <p>It gives me the following error:</p> <blockquote> <p>You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option ....</p> </blockquote> <p>I followed the instructions, and I unchecked the <code>safe update</code> option from the <code>Edit</code> menu then <code>Preferences</code> then <code>SQL Editor</code>. The same error still appear &amp; I'm not able to update this value. Please, tell me what is wrong?</p>
<p>I found the answer. The problem was that I have to precede the table name with the schema name. i.e, the command should be:</p> <pre><code>UPDATE schemaname.tablename SET columnname=1; </code></pre> <p>Thanks all.</p>
{ "question_id": 11448068, "question_date": "2012-07-12T08:44:39.407Z", "question_score": 1100, "tags": "mysql|sql-update|mysql-workbench", "answer_id": 11448213, "answer_date": "2012-07-12T08:52:58.017Z", "answer_score": 17 }
Please answer the following Stack Overflow question: Title: Git push results in "Authentication Failed" <p>I have been using GitHub for a little while, and I have been fine with <code>git add</code>, <code>git commit</code>, and <code>git push</code>, so far without any problems. Suddenly I am having an error that says:</p> <blockquote> <p>fatal: Authentication Failed</p> </blockquote> <p>In the terminal I cloned a repository, worked on a file and then I used <code>git add</code> to add the file to the commit log and when I did <code>git commit</code>, it worked fine. Finally, <code>git push</code> asks for username and password. I put those in correctly and every time I do this, it says the same error.</p> <p>What is the cause of this problem and how can I fix it?</p> <p>The contents of <code>.git/config</code> are:</p> <pre><code>[core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true [remote &quot;origin&quot;] url = http://www.github.com/######/Random-Python-Tests fetch = +refs/heads/*:refs/remotes/origin/* [branch &quot;master&quot;] remote = origin merge = refs/heads/master [user] name = ##### email = ############ </code></pre>
<blockquote> <p>If you enabled two-factor authentication in your GitHub account you won't be able to push via HTTPS using your accounts password. Instead you need to generate a personal access token. This can be done in the application settings of your GitHub account. Using this token as your password should allow you to push to your remote repository via HTTPS. Use your username as usual.</p> </blockquote> <p><em><a href="https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/" rel="noreferrer">Creating a personal access token</a></em></p> <p>You may also need to update the origin for your repository if it is set to HTTPS. Do this to switch to SSH:</p> <pre><code>git remote -v git remote set-url origin [email protected]:USERNAME/REPONAME.git </code></pre>
{ "question_id": 17659206, "question_date": "2013-07-15T16:34:04.587Z", "question_score": 1100, "tags": "git|authentication|github|visual-studio-code", "answer_id": 21027728, "answer_date": "2014-01-09T17:59:19.980Z", "answer_score": 1665 }
Please answer the following Stack Overflow question: Title: How do I call Objective-C code from Swift? <p>In Swift, how does one call Objective-C code?</p> <p>Apple mentioned that they could co-exist in one application, but does this mean that one could technically re-use old classes made in Objective-C whilst building new classes in Swift?</p>
<h1>Using Objective-C Classes in Swift</h1> <blockquote> <p>If you have an existing class that you'd like to use, perform <strong>Step 2</strong> and then skip to <strong>Step 5</strong>. (For some cases, I had to add an explicit <code>#import &lt;Foundation/Foundation.h</code> to an older Objective-C File.)</p> </blockquote> <h3>Step 1: Add Objective-C Implementation -- .m</h3> <p>Add a <code>.m</code> file to your class, and name it <code>CustomObject.m</code>.</p> <h3>Step 2: Add Bridging Header</h3> <p>When adding your <code>.m</code> file, you'll likely be hit with a prompt that looks like this:</p> <p><img src="https://i.stack.imgur.com/nakLZ.png" alt="A macOS sheet-style dialog from Xcode asking if you would &quot;like to configure an Objective-C bridging header&quot;"></p> <p>Click <strong>Yes</strong>! </p> <p>If you did not see the prompt, or accidentally deleted your bridging header, add a new <code>.h</code> file to your project and name it <code>&lt;#YourProjectName#&gt;-Bridging-Header.h</code>.</p> <p>In some situations, particularly when working with Objective-C frameworks, you don't add an Objective-C class explicitly and Xcode can't find the linker. In this case, create your <code>.h</code> file named as mentioned above, then make sure you link its path in your target's project settings like so:</p> <p><img src="https://i.stack.imgur.com/8LiwF.gif" alt="An animation demonstrating the above paragraph"></p> <p><strong>Note:</strong></p> <p>It's best practice to link your project using the <code>$(SRCROOT)</code> macro so that if you move your project, or work on it with others using a remote repository, it will still work. <code>$(SRCROOT)</code> can be thought of as the directory that contains your .xcodeproj file. It might look like this:</p> <pre><code>$(SRCROOT)/Folder/Folder/&lt;#YourProjectName#&gt;-Bridging-Header.h </code></pre> <h3>Step 3: Add Objective-C Header -- .h</h3> <p>Add another <code>.h</code> file and name it <code>CustomObject.h</code>.</p> <h3>Step 4: Build your Objective-C Class</h3> <p>In <code>CustomObject.h</code></p> <pre class="lang-c prettyprint-override"><code>#import &lt;Foundation/Foundation.h&gt; @interface CustomObject : NSObject @property (strong, nonatomic) id someProperty; - (void) someMethod; @end </code></pre> <p>In <code>CustomObject.m</code></p> <pre class="lang-c prettyprint-override"><code>#import "CustomObject.h" @implementation CustomObject - (void) someMethod { NSLog(@"SomeMethod Ran"); } @end </code></pre> <h3>Step 5: Add Class to Bridging-Header</h3> <p>In <code>YourProject-Bridging-Header.h</code>:</p> <pre class="lang-c prettyprint-override"><code>#import "CustomObject.h" </code></pre> <h3>Step 6: Use your Object</h3> <p>In <code>SomeSwiftFile.swift</code>:</p> <pre class="lang-swift prettyprint-override"><code>var instanceOfCustomObject = CustomObject() instanceOfCustomObject.someProperty = "Hello World" print(instanceOfCustomObject.someProperty) instanceOfCustomObject.someMethod() </code></pre> <p>There is no need to import explicitly; that's what the bridging header is for. </p> <h1>Using Swift Classes in Objective-C</h1> <h3>Step 1: Create New Swift Class</h3> <p>Add a <code>.swift</code> file to your project, and name it <code>MySwiftObject.swift</code>.</p> <p>In <code>MySwiftObject.swift</code>:</p> <pre class="lang-swift prettyprint-override"><code>import Foundation @objc(MySwiftObject) class MySwiftObject : NSObject { @objc var someProperty: AnyObject = "Some Initializer Val" as NSString init() {} @objc func someFunction(someArg: Any) -&gt; NSString { return "You sent me \(someArg)" } } </code></pre> <h3>Step 2: Import Swift Files to ObjC Class</h3> <p>In <code>SomeRandomClass.m</code>:</p> <pre class="lang-c prettyprint-override"><code>#import "&lt;#YourProjectName#&gt;-Swift.h" </code></pre> <p>The file:<code>&lt;#YourProjectName#&gt;-Swift.h</code> should already be created automatically in your project, even if you can not see it.</p> <h3>Step 3: Use your class</h3> <pre class="lang-c prettyprint-override"><code>MySwiftObject * myOb = [MySwiftObject new]; NSLog(@"MyOb.someProperty: %@", myOb.someProperty); myOb.someProperty = @"Hello World"; NSLog(@"MyOb.someProperty: %@", myOb.someProperty); NSString * retString = [myOb someFunctionWithSomeArg:@"Arg"]; NSLog(@"RetString: %@", retString); </code></pre> <h2>Notes:</h2> <ol> <li><p>If Code Completion isn't behaving as you expect, try running a quick build with <kbd>⌘</kbd><kbd>⇧</kbd><kbd>R</kbd> to help Xcode find some of the Objective-C code from a Swift context and vice versa. </p></li> <li><p>If you add a <code>.swift</code> file to an older project and get the error <code>dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib</code>, try completely <a href="https://stackoverflow.com/q/24002836/2611971">restarting Xcode</a>.</p></li> <li><p>While it was originally possible to use pure Swift classes (Not descendents of <code>NSObject</code>) which are visible to Objective-C by using the <code>@objc</code> prefix, this is no longer possible. Now, to be visible in Objective-C, the Swift object must either be a class conforming to <code>NSObjectProtocol</code> (easiest way to do this is to inherit from <code>NSObject</code>), or to be an <code>enum</code> marked <code>@objc</code> with a raw value of some integer type like <code>Int</code>. <a href="https://stackoverflow.com/revisions/24005242/11">You may view the edit history for an example of Swift 1.x code using <code>@objc</code> without these restrictions.</a></p></li> </ol>
{ "question_id": 24002369, "question_date": "2014-06-02T20:05:42.603Z", "question_score": 1100, "tags": "objective-c|swift", "answer_id": 24005242, "answer_date": "2014-06-03T00:12:17.480Z", "answer_score": 1523 }
Please answer the following Stack Overflow question: Title: Use of PUT vs PATCH methods in REST API real life scenarios <p>First of all, some definitions:</p> <p>PUT is defined in <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6" rel="noreferrer">Section 9.6 RFC 2616</a>:</p> <blockquote> <p>The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity <strong>SHOULD be considered as a modified version of the one residing on the origin server</strong>. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI.</p> </blockquote> <p>PATCH is defined in <a href="https://www.rfc-editor.org/rfc/rfc5789" rel="noreferrer">RFC 5789</a>:</p> <blockquote> <p>The PATCH method requests that <strong>a set of changes</strong> described in the request entity be applied to the resource identified by the Request- URI.</p> </blockquote> <p>Also according to <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2" rel="noreferrer">RFC 2616 Section 9.1.2</a> PUT is Idempotent while PATCH is not.</p> <p>Now let us take a look at a real example. When I do POST to <code>/users</code> with the data <code>{username: 'skwee357', email: '[email protected]'}</code> and the server is capable of creating a resource, it will respond with 201 and resource location (lets assume <code>/users/1</code>) and any next call to GET <code>/users/1</code> will return <code>{id: 1, username: 'skwee357', email: '[email protected]'}</code>.</p> <p>Now let us say I want to modify my email. Email modification is considered &quot;a set of changes&quot; and therefore I should PATCH <code>/users/1</code> with &quot;<a href="https://www.rfc-editor.org/rfc/rfc5789#section-2" rel="noreferrer">patch document</a>&quot;. In my case it would be the JSON document: <code>{email: '[email protected]'}</code>. The server then returns 200 (assuming permission are ok). This brings me to first question:</p> <ul> <li>PATCH is NOT idempotent. It said so in RFC 2616 and RFC 5789. However if I issue the same PATCH request (with my new email), I will get the same resource state (with my email being modified to the requested value). Why is PATCH not then idempotent?</li> </ul> <p>PATCH is a relatively new verb (RFC introduced in March 2010), and it comes to solve the problem of &quot;patching&quot; or modifying a set of fields. Before PATCH was introduced, everybody used PUT to update resources. But after PATCH was introduced, it leaves me confused about what PUT is used for. And this brings me to my second (and the main) question:</p> <ul> <li>What is the real difference between PUT and PATCH? I have read somewhere that PUT might be used to <strong>replace</strong> entire entity under specific resource, so one should send the full entity (instead of set of attributes as with PATCH). What is the real practical usage for such case? When would you like to replace / overwrite an entity at a specific resource URI and why is such an operation not considered updating / patching the entity? The only practical use case I see for PUT is issuing a PUT on a collection, i.e. <code>/users</code> to replace the entire collection. Issuing PUT on a specific entity makes no sense after PATCH was introduced. Am I wrong?</li> </ul>
<p><strong>NOTE</strong>: When I first spent time reading about REST, idempotence was a confusing concept to try to get right. I still didn't get it quite right in my original answer, as further comments (and <a href="https://stackoverflow.com/a/39338329/2449905">Jason Hoetger's answer</a>) have shown. For a while, I have resisted updating this answer extensively, to avoid effectively plagiarizing Jason, but I'm editing it now because, well, I was asked to (in the comments).</p> <p>After reading my answer, I suggest you also read <a href="https://stackoverflow.com/a/39338329/2449905">Jason Hoetger's excellent answer</a> to this question, and I will try to make my answer better without simply stealing from Jason.</p> <h2>Why is PUT idempotent?</h2> <p>As you noted in your RFC 2616 citation, PUT is considered idempotent. When you PUT a resource, these two assumptions are in play:</p> <ol> <li><p>You are referring to an entity, not to a collection.</p> </li> <li><p>The entity you are supplying is complete (the <em>entire</em> entity).</p> </li> </ol> <p>Let's look at one of your examples.</p> <pre class="lang-json prettyprint-override"><code>{ &quot;username&quot;: &quot;skwee357&quot;, &quot;email&quot;: &quot;[email protected]&quot; } </code></pre> <p>If you POST this document to <code>/users</code>, as you suggest, then you might get back an entity such as</p> <pre class="lang-json prettyprint-override"><code>## /users/1 { &quot;username&quot;: &quot;skwee357&quot;, &quot;email&quot;: &quot;[email protected]&quot; } </code></pre> <p>If you want to modify this entity later, you choose between PUT and PATCH. A PUT might look like this:</p> <pre class="lang-json prettyprint-override"><code>PUT /users/1 { &quot;username&quot;: &quot;skwee357&quot;, &quot;email&quot;: &quot;[email protected]&quot; // new email address } </code></pre> <p>You can accomplish the same using PATCH. That might look like this:</p> <pre class="lang-json prettyprint-override"><code>PATCH /users/1 { &quot;email&quot;: &quot;[email protected]&quot; // new email address } </code></pre> <p>You'll notice a difference right away between these two. The PUT included all of the parameters on this user, but PATCH only included the one that was being modified (<code>email</code>).</p> <p>When using PUT, it is assumed that you are sending the complete entity, and that complete entity <em>replaces</em> any existing entity at that URI. In the above example, the PUT and PATCH accomplish the same goal: they both change this user's email address. But PUT handles it by replacing the entire entity, while PATCH only updates the fields that were supplied, leaving the others alone.</p> <p>Since PUT requests include the entire entity, if you issue the same request repeatedly, it should always have the same outcome (the data you sent is now the entire data of the entity). Therefore PUT is idempotent.</p> <h2>Using PUT wrong</h2> <p>What happens if you use the above PATCH data in a PUT request?</p> <pre class="lang-json prettyprint-override"><code>GET /users/1 { &quot;username&quot;: &quot;skwee357&quot;, &quot;email&quot;: &quot;[email protected]&quot; } PUT /users/1 { &quot;email&quot;: &quot;[email protected]&quot; // new email address } GET /users/1 { &quot;email&quot;: &quot;[email protected]&quot; // new email address... and nothing else! } </code></pre> <p>(I'm assuming for the purposes of this question that the server doesn't have any specific required fields, and would allow this to happen... that may not be the case in reality.)</p> <p>Since we used PUT, but only supplied <code>email</code>, now that's the only thing in this entity. This has resulted in data loss.</p> <p>This example is here for illustrative purposes -- don't ever actually do this (unless your intent is to drop the omitted fields, of course... then you are using PUT as it should be used). This PUT request is technically idempotent, but that doesn't mean it isn't a terrible, broken idea.</p> <h2>How can PATCH be idempotent?</h2> <p>In the above example, PATCH <em>was</em> idempotent. You made a change, but if you made the same change again and again, it would always give back the same result: you changed the email address to the new value.</p> <pre class="lang-json prettyprint-override"><code>GET /users/1 { &quot;username&quot;: &quot;skwee357&quot;, &quot;email&quot;: &quot;[email protected]&quot; } PATCH /users/1 { &quot;email&quot;: &quot;[email protected]&quot; // new email address } GET /users/1 { &quot;username&quot;: &quot;skwee357&quot;, &quot;email&quot;: &quot;[email protected]&quot; // email address was changed } PATCH /users/1 { &quot;email&quot;: &quot;[email protected]&quot; // new email address... again } GET /users/1 { &quot;username&quot;: &quot;skwee357&quot;, &quot;email&quot;: &quot;[email protected]&quot; // nothing changed since last GET } </code></pre> <h2>My original example, fixed for accuracy</h2> <p>I originally had examples that I thought were showing non-idempotency, but they were misleading / incorrect. I am going to keep the examples, but use them to illustrate a different thing: that multiple PATCH documents against the same entity, modifying different attributes, do not make the PATCHes non-idempotent.</p> <p>Let's say that at some past time, a user was added. This is the state that you are starting from.</p> <pre class="lang-json prettyprint-override"><code>{ &quot;id&quot;: 1, &quot;name&quot;: &quot;Sam Kwee&quot;, &quot;email&quot;: &quot;[email protected]&quot;, &quot;address&quot;: &quot;123 Mockingbird Lane&quot;, &quot;city&quot;: &quot;New York&quot;, &quot;state&quot;: &quot;NY&quot;, &quot;zip&quot;: &quot;10001&quot; } </code></pre> <p>After a PATCH, you have a modified entity:</p> <pre class="lang-json prettyprint-override"><code>PATCH /users/1 {&quot;email&quot;: &quot;[email protected]&quot;} { &quot;id&quot;: 1, &quot;name&quot;: &quot;Sam Kwee&quot;, &quot;email&quot;: &quot;[email protected]&quot;, // the email changed, yay! &quot;address&quot;: &quot;123 Mockingbird Lane&quot;, &quot;city&quot;: &quot;New York&quot;, &quot;state&quot;: &quot;NY&quot;, &quot;zip&quot;: &quot;10001&quot; } </code></pre> <p>If you then repeatedly apply your PATCH, you will continue to get the same result: the email was changed to the new value. A goes in, A comes out, therefore this is idempotent.</p> <p>An hour later, after you have gone to make some coffee and take a break, someone else comes along with their own PATCH. It seems the Post Office has been making some changes.</p> <pre class="lang-json prettyprint-override"><code>PATCH /users/1 {&quot;zip&quot;: &quot;12345&quot;} { &quot;id&quot;: 1, &quot;name&quot;: &quot;Sam Kwee&quot;, &quot;email&quot;: &quot;[email protected]&quot;, // still the new email you set &quot;address&quot;: &quot;123 Mockingbird Lane&quot;, &quot;city&quot;: &quot;New York&quot;, &quot;state&quot;: &quot;NY&quot;, &quot;zip&quot;: &quot;12345&quot; // and this change as well } </code></pre> <p>Since this PATCH from the post office doesn't concern itself with email, only zip code, if it is repeatedly applied, it will also get the same result: the zip code is set to the new value. A goes in, A comes out, therefore this is <em>also</em> idempotent.</p> <p>The next day, you decide to send your PATCH again.</p> <pre class="lang-json prettyprint-override"><code>PATCH /users/1 {&quot;email&quot;: &quot;[email protected]&quot;} { &quot;id&quot;: 1, &quot;name&quot;: &quot;Sam Kwee&quot;, &quot;email&quot;: &quot;[email protected]&quot;, &quot;address&quot;: &quot;123 Mockingbird Lane&quot;, &quot;city&quot;: &quot;New York&quot;, &quot;state&quot;: &quot;NY&quot;, &quot;zip&quot;: &quot;12345&quot; } </code></pre> <p>Your patch has the same effect it had yesterday: it set the email address. A went in, A came out, therefore this is idempotent as well.</p> <h2>What I got wrong in my original answer</h2> <p>I want to draw an important distinction (something I got wrong in my original answer). Many servers will respond to your REST requests by sending back the new entity state, with your modifications (if any). So, when you get this <em>response</em> back, it is different <em>from the one you got back yesterday</em>, because the zip code is not the one you received last time. However, your request was not concerned with the zip code, only with the email. So your PATCH document is still idempotent - the email you sent in PATCH is now the email address on the entity.</p> <h2>So when is PATCH not idempotent, then?</h2> <p>For a full treatment of this question, I again refer you to <a href="https://stackoverflow.com/a/39338329/2449905">Jason Hoetger's answer</a> which already fully answers that.</p>
{ "question_id": 28459418, "question_date": "2015-02-11T16:30:01.457Z", "question_score": 1099, "tags": "json|rest|http|put|http-method", "answer_id": 34400076, "answer_date": "2015-12-21T16:20:35.623Z", "answer_score": 1417 }
Please answer the following Stack Overflow question: Title: How do I use PHP to get the current year? <p>I want to put a copyright notice in the footer of a web site, but I think it's incredibly tacky for the year to be outdated.</p> <p>How would I make the year update automatically with <a href="http://en.wikipedia.org/wiki/PHP#History" rel="noreferrer">PHP 4</a> or <a href="http://en.wikipedia.org/wiki/PHP#History" rel="noreferrer">PHP 5</a>?</p>
<p>You can use either <a href="http://php.net/manual/en/function.date.php" rel="noreferrer">date</a> or <a href="http://php.net/manual/en/function.strftime.php" rel="noreferrer">strftime</a>. In this case I'd say it doesn't matter as a year is a year, no matter what (unless there's a locale that formats the year differently?)</p> <p>For example:</p> <pre><code>&lt;?php echo date("Y"); ?&gt; </code></pre> <p>On a side note, when formatting dates in PHP it matters when you want to format your date in a different locale than your default. If so, you have to use setlocale and strftime. According to the <a href="http://php.net/manual/en/function.date.php" rel="noreferrer">php manual</a> on date:</p> <blockquote> <p>To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().</p> </blockquote> <p>From this point of view, I think it would be best to use strftime as much as possible, if you even have a remote possibility of having to localize your application. If that's not an issue, pick the one you like best.</p>
{ "question_id": 64003, "question_date": "2008-09-15T15:34:54.977Z", "question_score": 1098, "tags": "php|date|php-5.3|php-5.4|php4", "answer_id": 64097, "answer_date": "2008-09-15T15:45:50.990Z", "answer_score": 1368 }
Please answer the following Stack Overflow question: Title: How to iterate over arguments in a Bash script <p>I have a complex command that I'd like to make a shell/bash script of. I can write it in terms of <code>$1</code> easily:</p> <pre><code>foo $1 args -o $1.ext </code></pre> <p>I want to be able to pass multiple input names to the script. What's the right way to do it? </p> <p>And, of course, I want to handle filenames with spaces in them.</p>
<p>Use <code>"$@"</code> to represent all the arguments:</p> <pre><code>for var in "$@" do echo "$var" done </code></pre> <p>This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them:</p> <pre><code>sh test.sh 1 2 '3 4' 1 2 3 4 </code></pre>
{ "question_id": 255898, "question_date": "2008-11-01T18:14:21.607Z", "question_score": 1098, "tags": "bash|command-line", "answer_id": 255913, "answer_date": "2008-11-01T18:25:27.233Z", "answer_score": 1808 }
Please answer the following Stack Overflow question: Title: Return multiple values in JavaScript? <p>I am trying to return two values in <strong>JavaScript</strong>. Is this possible? </p> <pre><code>var newCodes = function() { var dCodes = fg.codecsCodes.rs; var dCodes2 = fg.codecsCodes2.rs; return dCodes, dCodes2; }; </code></pre>
<p>No, but you could return an array containing your values:</p> <pre><code>function getValues() { return [getFirstValue(), getSecondValue()]; } </code></pre> <p>Then you can access them like so:</p> <pre><code>var values = getValues(); var first = values[0]; var second = values[1]; </code></pre> <p>With the latest <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" rel="noreferrer">ECMAScript 6 syntax</a>*, you can also destructure the return value more intuitively:</p> <pre><code>const [first, second] = getValues(); </code></pre> <p>If you want to put &quot;labels&quot; on each of the returned values (easier to maintain), you can return an object:</p> <pre><code>function getValues() { return { first: getFirstValue(), second: getSecondValue(), }; } </code></pre> <p>And to access them:</p> <pre><code>var values = getValues(); var first = values.first; var second = values.second; </code></pre> <p>Or with ES6 syntax:</p> <pre><code>const {first, second} = getValues(); </code></pre> <p><sup>* See <a href="https://kangax.github.io/compat-table/es6/" rel="noreferrer">this table</a> for browser compatibility. Basically, all modern browsers aside from IE support this syntax, but you can compile ES6 code down to IE-compatible JavaScript at build time with tools like <a href="https://babeljs.io/" rel="noreferrer">Babel</a>.</sup></p>
{ "question_id": 2917175, "question_date": "2010-05-26T22:06:55.067Z", "question_score": 1096, "tags": "javascript|return|multiple-variable-return", "answer_id": 2917186, "answer_date": "2010-05-26T22:09:39.163Z", "answer_score": 1691 }
Please answer the following Stack Overflow question: Title: Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery) <p>Is there any way to select/manipulate CSS pseudo-elements such as <code>::before</code> and <code>::after</code> (and the old version with one semi-colon) using jQuery?</p> <p>For example, my stylesheet has the following rule:</p> <pre class="lang-css prettyprint-override"><code>.span::after{ content:'foo' } </code></pre> <p>How can I change 'foo' to 'bar' using vanilla JS or jQuery?</p>
<p>You could also pass the content to the pseudo element with a data attribute and then use jQuery to manipulate that:</p> <p>In HTML:</p> <pre><code>&lt;span&gt;foo&lt;/span&gt; </code></pre> <p>In jQuery:</p> <pre><code>$('span').hover(function(){ $(this).attr('data-content','bar'); }); </code></pre> <p>In CSS: </p> <pre class="lang-css prettyprint-override"><code>span:after { content: attr(data-content) ' any other text you may want'; } </code></pre> <p>If you want to prevent the 'other text' from showing up, you could combine this with seucolega's solution like this:</p> <p>In HTML:</p> <pre><code>&lt;span&gt;foo&lt;/span&gt; </code></pre> <p>In jQuery:</p> <pre><code>$('span').hover(function(){ $(this).addClass('change').attr('data-content','bar'); }); </code></pre> <p>In CSS: </p> <pre class="lang-css prettyprint-override"><code>span.change:after { content: attr(data-content) ' any other text you may want'; } </code></pre>
{ "question_id": 5041494, "question_date": "2011-02-18T12:53:10.700Z", "question_score": 1096, "tags": "javascript|jquery|css|jquery-selectors|pseudo-element", "answer_id": 5734583, "answer_date": "2011-04-20T17:59:04.550Z", "answer_score": 768 }
Please answer the following Stack Overflow question: Title: How can I trigger the same function from multiple events with jQuery? <p>Is there a way to have <code>keyup</code>, <code>keypress</code>, <code>blur</code>, and <code>change</code> events call the same function in one line or do I have to do them separately?</p> <p>The problem I have is that I need to validate some data with a db lookup and would like to make sure validation is not missed in any case, whether it is typed or pasted into the box.</p>
<p>You can use <code>.on()</code> to bind a function to multiple events:</p> <pre><code>$('#element').on('keyup keypress blur change', function(e) { // e.type is the type of event fired }); </code></pre> <p>Or just pass the function as the parameter to normal event functions:</p> <pre><code>var myFunction = function() { ... } $('#element') .keyup(myFunction) .keypress(myFunction) .blur(myFunction) .change(myFunction) </code></pre>
{ "question_id": 2534089, "question_date": "2010-03-28T18:53:57.243Z", "question_score": 1096, "tags": "jquery|events|jquery-events", "answer_id": 2534107, "answer_date": "2010-03-28T18:56:20.207Z", "answer_score": 2013 }
Please answer the following Stack Overflow question: Title: Show git diff on file in staging area <p>Is there a way I can see the changes that were made to a <code>file</code> after I have done <code>git add file</code>?</p> <p>That is, when I do: </p> <pre><code>git add file git diff file </code></pre> <p>no diff is shown. I guess there's a way to see the differences since the last commit but I don't know what that is.</p>
<p>You can show changes that have been staged with the <code>--cached</code> flag:</p> <pre><code>$ git diff --cached </code></pre> <p>In more recent versions of git, you can also use the <code>--staged</code> flag (<code>--staged</code> is a synonym for <code>--cached</code>):</p> <pre><code>$ git diff --staged </code></pre>
{ "question_id": 3527856, "question_date": "2010-08-20T02:52:21.103Z", "question_score": 1096, "tags": "git|git-diff|git-stage", "answer_id": 3527985, "answer_date": "2010-08-20T03:27:17.193Z", "answer_score": 1760 }
Please answer the following Stack Overflow question: Title: What is the difference between ++i and i++? <p>In C, what is the difference between using <code>++i</code> and <code>i++</code>, and which should be used in the incrementation block of a <code>for</code> loop?</p>
<ul> <li><p><code>++i</code> will increment the value of <code>i</code>, and then return the incremented value.</p> <pre><code> i = 1; j = ++i; (i is 2, j is 2) </code></pre></li> <li><p><code>i++</code> will increment the value of <code>i</code>, but return the original value that <code>i</code> held before being incremented.</p> <pre><code> i = 1; j = i++; (i is 2, j is 1) </code></pre></li> </ul> <p>For a <code>for</code> loop, either works. <code>++i</code> seems more common, perhaps because that is what is used in <a href="https://en.wikipedia.org/wiki/The_C_Programming_Language" rel="noreferrer">K&amp;R</a>.</p> <p>In any case, follow the guideline "prefer <code>++i</code> over <code>i++</code>" and you won't go wrong.</p> <p>There's a couple of comments regarding the efficiency of <code>++i</code> and <code>i++</code>. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.</p> <p>The efficiency question is interesting... here's my attempt at an answer: <a href="https://stackoverflow.com/questions/24886/is-there-a-performance-difference-between-i-and-i">Is there a performance difference between i++ and ++i in C?</a></p> <p>As <a href="https://stackoverflow.com/users/2150/on-freund">@OnFreund</a> notes, it's different for a C++ object, since <code>operator++()</code> is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value.</p>
{ "question_id": 24853, "question_date": "2008-08-24T05:19:19.713Z", "question_score": 1095, "tags": "c|for-loop|post-increment|pre-increment", "answer_id": 24858, "answer_date": "2008-08-24T05:23:18.487Z", "answer_score": 1347 }
Please answer the following Stack Overflow question: Title: How to convert UTF-8 byte[] to string <p>I have a <code>byte[]</code> array that is loaded from a file that I happen to known contains <a href="http://en.wikipedia.org/wiki/UTF-8" rel="noreferrer">UTF-8</a>.</p> <p>In some debugging code, I need to convert it to a string. Is there a one-liner that will do this?</p> <p>Under the covers it should be just an allocation and a <em>memcopy</em>, so even if it is not implemented, it should be possible.</p>
<pre><code>string result = System.Text.Encoding.UTF8.GetString(byteArray); </code></pre>
{ "question_id": 1003275, "question_date": "2009-06-16T18:47:00.180Z", "question_score": 1095, "tags": "c#|.net|arrays|string|type-conversion", "answer_id": 1003289, "answer_date": "2009-06-16T18:49:15.713Z", "answer_score": 1687 }
Please answer the following Stack Overflow question: Title: How do I retrieve an HTML element's actual width and height? <p>Suppose that I have a <code>&lt;div&gt;</code> that I wish to center in the browser's display (viewport). To do so, I need to calculate the width and height of the <code>&lt;div&gt;</code> element. </p> <p>What should I use? Please include information on browser compatibility.</p>
<p>You should use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth" rel="noreferrer"><code>.offsetWidth</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight" rel="noreferrer"><code>.offsetHeight</code></a> properties. Note they belong to the element, not <code>.style</code>.</p> <pre class="lang-js prettyprint-override"><code>var width = document.getElementById('foo').offsetWidth; </code></pre> <p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect" rel="noreferrer"><code>.getBoundingClientRect()</code></a> function returns the dimensions and location of the element as floating-point numbers after performing CSS transforms.</p> <pre class="lang-js prettyprint-override"><code>&gt; console.log(document.getElementById('foo').getBoundingClientRect()) DOMRect { bottom: 177, height: 54.7, left: 278.5,​ right: 909.5, top: 122.3, width: 631, x: 278.5, y: 122.3, } </code></pre>
{ "question_id": 294250, "question_date": "2008-11-16T19:15:24.577Z", "question_score": 1095, "tags": "javascript|html|dhtml", "answer_id": 294273, "answer_date": "2008-11-16T19:35:11.697Z", "answer_score": 1569 }
Please answer the following Stack Overflow question: Title: How can I get the application's path in a .NET console application? <p>How do I find the application's path in a console application?</p> <p>In <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a>, I can use <code>Application.StartupPath</code> to find the current path, but this doesn't seem to be available in a console application.</p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.getexecutingassembly" rel="noreferrer"><code>System.Reflection.Assembly.GetExecutingAssembly()</code></a>.<a href="https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.location" rel="noreferrer"><code>Location</code></a><sup>1</sup></p> <p>Combine that with <a href="https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getdirectoryname" rel="noreferrer"><code>System.IO.Path.GetDirectoryName</code></a> if all you want is the directory.</p> <blockquote> <p><sup>1</sup><em>As per Mr.Mindor's comment:</em><br> <code>System.Reflection.Assembly.GetExecutingAssembly().Location</code> returns where the executing assembly is currently located, which may or may not be where the assembly is located when not executing. In the case of shadow copying assemblies, you will get a path in a temp directory. <a href="https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.codebase" rel="noreferrer"><code>System.Reflection.Assembly.GetExecutingAssembly().CodeBase</code></a> will return the 'permanent' path of the assembly.</p> </blockquote>
{ "question_id": 837488, "question_date": "2009-05-07T23:05:09.640Z", "question_score": 1095, "tags": "c#|.net|console|console-application", "answer_id": 837501, "answer_date": "2009-05-07T23:09:06.277Z", "answer_score": 1318 }
Please answer the following Stack Overflow question: Title: Error message "No exports were found that match the constraint contract name" <p>This morning I faced a problem while opening my Visual Studio solution, and when I tried to run it, it said:</p> <blockquote> <p>No exports were found that match the constraint contract name</p> </blockquote> <p>How can I fix this problem?</p>
<p>I solved this problem by clearing Visual Studio Component Model Cache.</p> <p>Just delete or rename this folder: </p> <pre><code>%LocalAppData%\Microsoft\VisualStudio\11.0\ComponentModelCache </code></pre> <p>or</p> <pre><code>%LocalAppData%\Microsoft\VPDExpress\11.0\ComponentModelCache </code></pre> <p>and restart Visual Studio.</p> <p>The version of Visual Studio you have is specified by the number e.g.</p> <p>Visual Studio 2012 is <code>11.0</code> (as shown above)</p> <p>Visual Studio 2013 is <code>12.0</code></p> <p>Visual Studio 2015 is <code>14.0</code></p> <p>Visual Studio 2017 is <code>15.0</code></p> <p>Visual Studio 2019 is <code>16.0</code></p> <p>For those that don't know: <code>%LocalAppData%\</code> is the same as <code>C:\Users\{yourUsername}\AppData\Local</code></p> <p>For those who have multiple versions of Visual Studio installed, e.g. 2012 and 2013, it might help to remove the ComponentModelCache for both versions before restarting Visual Studio, e.g. 11.0 and 12.0.</p>
{ "question_id": 17596543, "question_date": "2013-07-11T14:47:24.073Z", "question_score": 1095, "tags": "visual-studio", "answer_id": 17604007, "answer_date": "2013-07-11T21:41:22.950Z", "answer_score": 2194 }
Please answer the following Stack Overflow question: Title: List all environment variables from the command line <p>Is it possible to list <em>all</em> environment variables from a Windows' command prompt?</p> <p>Something equivalent to PowerShell's <code>gci env:</code> (or <code>ls env:</code> or <code>dir env:</code>).</p>
<p>Just do:</p> <pre><code>SET </code></pre> <p>You can also do <code>SET prefix</code> to see all variables with names starting with <code>prefix</code>.</p> <p>For example, if you want to read only derbydb from the environment variables, do the following: </p> <pre><code>set derby </code></pre> <p>...and you will get the following: </p> <pre><code>DERBY_HOME=c:\Users\amro-a\Desktop\db-derby-10.10.1.1-bin\db-derby-10.10.1.1-bin </code></pre>
{ "question_id": 5327495, "question_date": "2011-03-16T15:22:24.770Z", "question_score": 1094, "tags": "windows|command-line|environment-variables|prompt", "answer_id": 5327531, "answer_date": "2011-03-16T15:24:41.933Z", "answer_score": 1559 }
Please answer the following Stack Overflow question: Title: Why does the C preprocessor interpret the word "linux" as the constant "1"? <p>Why does the <strong>C</strong> preprocessor in <strong>GCC</strong> interpret the word <code>linux</code> (small letters) as the constant <code>1</code>?</p> <p><strong>test.c:</strong></p> <pre><code>#include &lt;stdio.h&gt; int main(void) { int linux = 5; return 0; } </code></pre> <p>Result of <code>$ gcc -E test.c</code> (stop after the preprocessing stage):</p> <pre><code>.... int main(void) { int 1 = 5; return 0; } </code></pre> <p>Which of course yields an error.</p> <p>(BTW: There is no <code>#define linux</code> in the <code>stdio.h</code> file.)</p>
<p>In the Old Days (pre-ANSI), predefining symbols such as <code>unix</code> and <code>vax</code> was a way to allow code to detect at compile time what system it was being compiled for. There was no official language standard back then (beyond the reference material at the back of the first edition of K&amp;R), and C code of any complexity was typically a complex maze of <code>#ifdef</code>s to allow for differences between systems. These macro definitions were generally set by the compiler itself, not defined in a library header file. Since there were no real rules about which identifiers could be used by the implementation and which were reserved for programmers, compiler writers felt free to use simple names like <code>unix</code> and assumed that programmers would simply avoid using those names for their own purposes.</p> <p>The 1989 ANSI C standard introduced rules restricting what symbols an implementation could legally predefine. A macro predefined by the compiler could only have a name starting with two underscores, or with an underscore followed by an uppercase letter, leaving programmers free to use identifiers not matching that pattern and not used in the standard library.</p> <p>As a result, any compiler that predefines <code>unix</code> or <code>linux</code> is non-conforming, since it will fail to compile perfectly legal code that uses something like <code>int linux = 5;</code>.</p> <p>As it happens, gcc is non-conforming by default -- but it can be made to conform (reasonably well) with the right command-line options:</p> <pre><code>gcc -std=c90 -pedantic ... # or -std=c89 or -ansi gcc -std=c99 -pedantic gcc -std=c11 -pedantic </code></pre> <p>See <a href="http://gcc.gnu.org/onlinedocs/gcc-4.8.1/gcc/Standards.html" rel="noreferrer">the gcc manual</a> for more details.</p> <p>gcc will be phasing out these definitions in future releases, so you shouldn't write code that depends on them. If your program needs to know whether it's being compiled for a Linux target or not it can check whether <code>__linux__</code> is defined (assuming you're using gcc or a compiler that's compatible with it). See <a href="https://gcc.gnu.org/onlinedocs/cpp/System-specific-Predefined-Macros.html" rel="noreferrer">the GNU C preprocessor manual</a> for more information.</p> <p>A largely irrelevant aside: the "Best One Liner" winner of the 1987 <a href="http://www.ioccc.org/" rel="noreferrer">International Obfuscated C Code Contest</a>, by David Korn (yes, the author of the Korn Shell) took advantage of the predefined <code>unix</code> macro:</p> <pre><code>main() { printf(&amp;unix["\021%six\012\0"],(unix)["have"]+"fun"-0x60);} </code></pre> <p>It prints <code>"unix"</code>, but for reasons that have absolutely nothing to do with the spelling of the macro name.</p>
{ "question_id": 19210935, "question_date": "2013-10-06T16:09:48.263Z", "question_score": 1094, "tags": "c|linux|gcc|c-preprocessor", "answer_id": 19214007, "answer_date": "2013-10-06T21:11:27.147Z", "answer_score": 1013 }
Please answer the following Stack Overflow question: Title: Converting from a string to boolean in Python <p>How do I convert a string into a boolean in Python? This attempt returns <code>True</code>:</p> <pre><code>&gt;&gt;&gt; bool(&quot;False&quot;) True </code></pre>
<p>Really, you just compare the string to whatever you expect to accept as representing true, so you can do this:</p> <pre><code>s == 'True' </code></pre> <p>Or to checks against a whole bunch of values:</p> <pre><code>s.lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh'] </code></pre> <p>Be cautious when using the following:</p> <pre><code>&gt;&gt;&gt; bool("foo") True &gt;&gt;&gt; bool("") False </code></pre> <p>Empty strings evaluate to <code>False</code>, but everything else evaluates to <code>True</code>. So this should not be used for any kind of parsing purposes.</p>
{ "question_id": 715417, "question_date": "2009-04-03T19:44:20.353Z", "question_score": 1092, "tags": "python|string|boolean", "answer_id": 715455, "answer_date": "2009-04-03T19:52:56.183Z", "answer_score": 1147 }
Please answer the following Stack Overflow question: Title: Why would you use Expression<Func<T>> rather than Func<T>? <p>I understand lambdas and the <code>Func</code> and <code>Action</code> delegates. But expressions stump me. </p> <p>In what circumstances would you use an <code>Expression&lt;Func&lt;T&gt;&gt;</code> rather than a plain old <code>Func&lt;T&gt;</code>?</p>
<p>When you want to treat lambda expressions as expression trees and look inside them instead of executing them. For example, LINQ to SQL gets the expression and converts it to the equivalent SQL statement and submits it to server (rather than executing the lambda).</p> <p>Conceptually, <code>Expression&lt;Func&lt;T&gt;&gt;</code> is <em>completely different</em> from <code>Func&lt;T&gt;</code>. <code>Func&lt;T&gt;</code> denotes a <code>delegate</code> which is pretty much a pointer to a method and <code>Expression&lt;Func&lt;T&gt;&gt;</code> denotes a <em>tree data structure</em> for a lambda expression. This tree structure <strong>describes what a lambda expression does</strong> rather than doing the actual thing. It basically holds data about the composition of expressions, variables, method calls, ... (for example it holds information such as this lambda is some constant + some parameter). You can use this description to convert it to an actual method (with <code>Expression.Compile</code>) or do other stuff (like the LINQ to SQL example) with it. The act of treating lambdas as anonymous methods and expression trees is purely a compile time thing.</p> <pre><code>Func&lt;int&gt; myFunc = () =&gt; 10; // similar to: int myAnonMethod() { return 10; } </code></pre> <p>will effectively compile to an IL method that gets nothing and returns 10.</p> <pre><code>Expression&lt;Func&lt;int&gt;&gt; myExpression = () =&gt; 10; </code></pre> <p>will be converted to a data structure that describes an expression that gets no parameters and returns the value 10:</p> <p><a href="https://i.stack.imgur.com/gwU0E.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/gwU0E.jpg" alt="Expression vs Func"> <em>larger image</em></a></p> <p>While they both look the same at compile time, what the compiler generates is <strong>totally different</strong>.</p>
{ "question_id": 793571, "question_date": "2009-04-27T13:50:14.503Z", "question_score": 1092, "tags": "c#|delegates|lambda|expression-trees", "answer_id": 793584, "answer_date": "2009-04-27T13:52:31.423Z", "answer_score": 1270 }
Please answer the following Stack Overflow question: Title: How to change the name of an iOS app? <p>I began an iPhone project the other day with a silly development code name, and now I want to change the name of the project since it's nearly finished. </p> <p>But I'm not sure how to do this with Xcode, trying the obvious of changing the application's name in the info.plist file, causes the signing process to go wrong (I think...) and my app won't launch giving me a Launcher error.</p> <p>I guess I could make a new project and copy paste everything over, but it seems so primitive that I'm hoping for a more civilized solution.</p>
<ol> <li>Go to <code>Targets</code> in <code>Xcode</code>.</li> <li><code>Build Settings</code> on your project's target (your current development name).</li> <li>Search for <code>Product Name</code> under <code>Packaging</code>. Change its value to what you want your new project name to be.</li> </ol>
{ "question_id": 238980, "question_date": "2008-10-27T03:07:03.177Z", "question_score": 1091, "tags": "ios|xcode", "answer_id": 239006, "answer_date": "2008-10-27T03:30:28.107Z", "answer_score": 1082 }
Please answer the following Stack Overflow question: Title: Is there a float input type in HTML5? <p>According to <a href="http://simon.html5.org/html-elements" rel="noreferrer">html5.org</a>, the "number" input type's "value attribute, if specified and not empty, must have a value that is a valid floating point number."</p> <p>Yet it is simply (in the latest version of Chrome, anyway), an "updown" control with integers, not floats:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="number" id="totalAmt"&gt;&lt;/input&gt;</code></pre> </div> </div> </p> <p>Is there a floating point input element native to HTML5, or a way to make the number input type work with floats, not ints? Or must I resort to a jQuery UI plugin?</p>
<p>The <code>number</code> type has a <code>step</code> value controlling which numbers are valid (along with <code>max</code> and <code>min</code>), which defaults to <code>1</code>. This value is also used by implementations for the stepper buttons (i.e. pressing up increases by <code>step</code>).</p> <p>Simply change this value to whatever is appropriate. For money, two decimal places are probably expected:</p> <pre><code>&lt;label for=&quot;totalAmt&quot;&gt;Total Amount&lt;/label&gt; &lt;input type=&quot;number&quot; step=&quot;0.01&quot; id=&quot;totalAmt&quot;&gt; </code></pre> <p>(I'd also set <code>min=0</code> if it can only be positive)</p> <p>If you'd prefer to allow any number of decimal places, you can use <code>step=&quot;any&quot;</code> (though for currencies, I'd recommend sticking to <code>0.01</code>). In Chrome &amp; Firefox, the stepper buttons will increment / decrement by 1 when using <code>any</code>. (thanks to Michal Stefanow's answer for pointing out <code>any</code>, and <a href="http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-attributes.html#attr-input-step" rel="noreferrer">see the relevant spec here</a>)</p> <p>Here's a playground showing how various steps affect various input types:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form&gt; &lt;input type=number step=1 /&gt; Step 1 (default)&lt;br /&gt; &lt;input type=number step=0.01 /&gt; Step 0.01&lt;br /&gt; &lt;input type=number step=any /&gt; Step any&lt;br /&gt; &lt;input type=range step=20 /&gt; Step 20&lt;br /&gt; &lt;input type=datetime-local step=60 /&gt; Step 60 (default)&lt;br /&gt; &lt;input type=datetime-local step=1 /&gt; Step 1&lt;br /&gt; &lt;input type=datetime-local step=any /&gt; Step any&lt;br /&gt; &lt;input type=datetime-local step=0.001 /&gt; Step 0.001&lt;br /&gt; &lt;input type=datetime-local step=3600 /&gt; Step 3600 (1 hour)&lt;br /&gt; &lt;input type=datetime-local step=86400 /&gt; Step 86400 (1 day)&lt;br /&gt; &lt;input type=datetime-local step=70 /&gt; Step 70 (1 min, 10 sec)&lt;br /&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <hr /> <p>As usual, I'll add a quick note: remember that client-side validation is just a convenience to the user. You must also validate on the server-side!</p>
{ "question_id": 19011861, "question_date": "2013-09-25T17:51:41.123Z", "question_score": 1089, "tags": "html|input|floating-point", "answer_id": 19012837, "answer_date": "2013-09-25T18:48:21.250Z", "answer_score": 2228 }
Please answer the following Stack Overflow question: Title: jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found) <p>I'm seeing error messages about a file, <code>min.map</code>, being not found:</p> <blockquote> <p>GET jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)</p> </blockquote> <hr /> <h3>Screenshot</h3> <p><img src="https://i.stack.imgur.com/M6CMw.png" alt="enter image description here" /></p> <p>Where is this coming from?</p>
<p>If Chrome DevTools is reporting a 404 for a .map file (maybe <code>jquery-1.10.2.min.map</code>, <code>jquery.min.map</code> or <code>jquery-2.0.3.min.map</code>, but can happen with anything) first thing to know is this is only requested when using the DevTools. <strong>Your users will not be hitting this 404.</strong></p> <p>Now you can fix this or disable the sourcemap functionality. </p> <h2>Fix: get the files</h2> <p>Next, it's an easy fix. Head to <a href="http://jquery.com/download/">http://jquery.com/download/</a> and click the <strong>Download the map file</strong> link for your version, and you'll want the uncompressed file downloaded as well.</p> <p><img src="https://i.stack.imgur.com/lfwrB.png" alt="enter image description here"></p> <p>Having the map file in place allows you do debug your minified jQuery via the original sources, which will save a lot of time and frustration if you don't like dealing with variable names like <code>a</code> and <code>c</code>. </p> <p>More about sourcemaps here: <a href="http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/">An Introduction to JavaScript Source Maps</a></p> <h2>Dodge: disable sourcemaps</h2> <p>Instead of getting the files, you can alternatively disable JavaScript source maps completely for now, in your settings. This is a fine choice if you never plan on debugging JavaScript on this page. Use the cog icon in the bottom right of the DevTools, to open settings, then: <img src="https://i.stack.imgur.com/Ezwue.png" alt="enter image description here"></p>
{ "question_id": 18365315, "question_date": "2013-08-21T18:46:31.020Z", "question_score": 1089, "tags": "javascript|jquery|google-chrome-devtools", "answer_id": 18365316, "answer_date": "2013-08-21T18:46:31.020Z", "answer_score": 1282 }
Please answer the following Stack Overflow question: Title: Do the parentheses after the type name make a difference with new? <p>If 'Test' is an ordinary class, is there any difference between:</p> <pre><code>Test* test = new Test; </code></pre> <p>and</p> <pre><code>Test* test = new Test(); </code></pre>
<p>Let's get pedantic, because there are differences that can actually affect your code's behavior. Much of the following is taken from comments made to an <a href="https://devblogs.microsoft.com/oldnewthing/20061214-02/?p=28713" rel="noreferrer">"Old New Thing" article</a>.</p> <p>Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a <a href="https://stackoverflow.com/questions/146452/what-are-pod-types-in-c">POD (plain old data)</a>, or if it's a class that contains POD members and is using a compiler-generated default constructor.</p> <ul> <li>In C++1998 there are 2 types of initialization: zero and default</li> <li>In C++2003 a 3rd type of initialization, value initialization was added.</li> </ul> <p>Assume:</p> <pre><code>struct A { int m; }; // POD struct B { ~B(); int m; }; // non-POD, compiler generated default ctor struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m </code></pre> <p>In a C++98 compiler, the following should occur:</p> <ul> <li><code>new A</code> - indeterminate value</li> <li><p><code>new A()</code> - zero-initialize</p></li> <li><p><code>new B</code> - default construct (B::m is uninitialized)</p></li> <li><p><code>new B()</code> - default construct (B::m is uninitialized)</p></li> <li><p><code>new C</code> - default construct (C::m is zero-initialized)</p></li> <li><code>new C()</code> - default construct (C::m is zero-initialized)</li> </ul> <p>In a C++03 conformant compiler, things should work like so:</p> <ul> <li><code>new A</code> - indeterminate value</li> <li><p><code>new A()</code> - value-initialize A, which is zero-initialization since it's a POD.</p></li> <li><p><code>new B</code> - default-initializes (leaves B::m uninitialized)</p></li> <li><p><code>new B()</code> - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.</p></li> <li><p><code>new C</code> - default-initializes C, which calls the default ctor.</p></li> <li><code>new C()</code> - value-initializes C, which calls the default ctor.</li> </ul> <p>So in all versions of C++ there's a difference between <code>new A</code> and <code>new A()</code> because A is a POD.</p> <p>And there's a difference in behavior between C++98 and C++03 for the case <code>new B()</code>.</p> <p>This is one of the dusty corners of C++ that can drive you crazy. When constructing an object, sometimes you want/need the parens, sometimes you absolutely cannot have them, and sometimes it doesn't matter.</p>
{ "question_id": 620137, "question_date": "2009-03-06T19:39:12.697Z", "question_score": 1089, "tags": "c++|constructor|initialization|new-operator|c++-faq", "answer_id": 620402, "answer_date": "2009-03-06T21:01:23.543Z", "answer_score": 1013 }
Please answer the following Stack Overflow question: Title: How can I access and process nested objects, arrays, or JSON? <p>I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or keys)?</p> <p>For example:</p> <pre><code>var data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }; </code></pre> <p>How could I access the <code>name</code> of the second item in <code>items</code>?</p>
<h2>Preliminaries</h2> <p>JavaScript has only one data type which can contain multiple values: <strong>Object</strong>. An <strong>Array</strong> is a special form of object.</p> <p>(Plain) Objects have the form</p> <pre><code>{key: value, key: value, ...} </code></pre> <p>Arrays have the form</p> <pre><code>[value, value, ...] </code></pre> <p>Both arrays and objects expose a <code>key -&gt; value</code> structure. Keys in an array must be numeric, whereas any string can be used as key in objects. The key-value pairs are also called the <strong>"properties"</strong>.</p> <p>Properties can be accessed either using <strong>dot notation</strong></p> <pre><code>const value = obj.someProperty; </code></pre> <p>or <strong>bracket notation</strong>, if the property name would not be a valid JavaScript <a href="http://es5.github.com/#x7.6" rel="noreferrer">identifier name <em><sup>[spec]</sup></em></a>, or the name is the value of a variable:</p> <pre><code>// the space is not a valid character in identifier names const value = obj["some Property"]; // property name as variable const name = "some Property"; const value = obj[name]; </code></pre> <p>For that reason, array elements can only be accessed using bracket notation:</p> <pre><code>const value = arr[5]; // arr.5 would be a syntax error // property name / index as variable const x = 5; const value = arr[x]; </code></pre> <h3>Wait... what about JSON?</h3> <p>JSON is a textual representation of data, just like XML, YAML, CSV, and others. To work with such data, it first has to be converted to JavaScript data types, i.e. arrays and objects (and how to work with those was just explained). How to parse JSON is explained in the question <a href="https://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript">Parse JSON in JavaScript?</a> .</p> <h3>Further reading material</h3> <p>How to access arrays and objects is fundamental JavaScript knowledge and therefore it is advisable to read the <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Guide" rel="noreferrer">MDN JavaScript Guide</a>, especially the sections</p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects" rel="noreferrer">Working with Objects</a></li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Array_object" rel="noreferrer">Arrays</a></li> <li><a href="http://eloquentjavascript.net/04_data.html" rel="noreferrer">Eloquent JavaScript - Data Structures</a></li> </ul> <hr> <hr> <h2>Accessing nested data structures</h2> <p>A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. </p> <p>Here is an example:</p> <pre><code>const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }; </code></pre> <p>Let's assume we want to access the <code>name</code> of the second item. </p> <p>Here is how we can do it step-by-step:</p> <p>As we can see <code>data</code> is an object, hence we can access its properties using dot notation. The <code>items</code> property is accessed as follows:</p> <pre><code>data.items </code></pre> <p>The value is an array, to access its second element, we have to use bracket notation:</p> <pre><code>data.items[1] </code></pre> <p>This value is an object and we use dot notation again to access the <code>name</code> property. So we eventually get:</p> <pre><code>const item_name = data.items[1].name; </code></pre> <p>Alternatively, we could have used bracket notation for any of the properties, especially if the name contained characters that would have made it invalid for dot notation usage:</p> <pre><code>const item_name = data['items'][1]['name']; </code></pre> <hr> <h3>I'm trying to access a property but I get only <code>undefined</code> back?</h3> <p>Most of the time when you are getting <code>undefined</code>, the object/array simply doesn't have a property with that name.</p> <pre><code>const foo = {bar: {baz: 42}}; console.log(foo.baz); // undefined </code></pre> <p>Use <a href="https://developer.mozilla.org/en-US/docs/DOM/console.log" rel="noreferrer"><code>console.log</code></a> or <a href="https://developer.mozilla.org/en-US/docs/DOM/console.dir" rel="noreferrer"><code>console.dir</code></a> and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.</p> <pre><code>console.log(foo.bar.baz); // 42 </code></pre> <hr> <h3>What if the property names are dynamic and I don't know them beforehand?</h3> <p>If the property names are unknown or we want to access all properties of an object / elements of an array, we can use the <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...in" rel="noreferrer"><code>for...in</code> <em><sup>[MDN]</sup></em></a> loop for objects and the <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for" rel="noreferrer"><code>for</code> <em><sup>[MDN]</sup></em></a> loop for arrays to iterate over all properties / elements.</p> <p><strong>Objects</strong></p> <p>To iterate over all properties of <code>data</code>, we can iterate over the <strong>object</strong> like so:</p> <pre><code>for (const prop in data) { // `prop` contains the name of each property, i.e. `'code'` or `'items'` // consequently, `data[prop]` refers to the value of each property, i.e. // either `42` or the array } </code></pre> <p>Depending on where the object comes from (and what you want to do), you might have to test in each iteration whether the property is really a property of the object, or it is an inherited property. You can do this with <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty" rel="noreferrer"><code>Object#hasOwnProperty</code> <em><sup>[MDN]</sup></em></a>.</p> <p>As alternative to <code>for...in</code> with <code>hasOwnProperty</code>, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys" rel="noreferrer"><code>Object.keys</code> <em><sup>[MDN]</sup></em></a> to get an <em>array of property names</em>:</p> <pre><code>Object.keys(data).forEach(function(prop) { // `prop` is the property name // `data[prop]` is the property value }); </code></pre> <p><strong>Arrays</strong></p> <p>To iterate over all elements of the <code>data.items</code> <strong>array</strong>, we use a <code>for</code> loop:</p> <pre><code>for(let i = 0, l = data.items.length; i &lt; l; i++) { // `i` will take on the values `0`, `1`, `2`,..., i.e. in each iteration // we can access the next element in the array with `data.items[i]`, example: // // var obj = data.items[i]; // // Since each element is an object (in our example), // we can now access the objects properties with `obj.id` and `obj.name`. // We could also use `data.items[i].id`. } </code></pre> <p>One could also use <code>for...in</code> to iterate over arrays, but there are reasons why this should be avoided: <a href="https://stackoverflow.com/questions/2265167/why-is-forvar-item-in-list-with-arrays-considered-bad-practice-in-javascript">Why is &#39;for(var item in list)&#39; with arrays considered bad practice in JavaScript?</a>.</p> <p>With the increasing browser support of ECMAScript 5, the array method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach" rel="noreferrer"><code>forEach</code> <em><sup>[MDN]</sup></em></a> becomes an interesting alternative as well:</p> <pre><code>data.items.forEach(function(value, index, array) { // The callback is executed for each element in the array. // `value` is the element itself (equivalent to `array[index]`) // `index` will be the index of the element in the array // `array` is a reference to the array itself (i.e. `data.items` in this case) }); </code></pre> <p>In environments supporting ES2015 (ES6), you can also use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of" rel="noreferrer"><em><code>for...of</code></em> <em><sup>[MDN]</sup></em></a> loop, which not only works for arrays, but for any <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable" rel="noreferrer"><em>iterable</em></a>:</p> <pre><code>for (const item of data.items) { // `item` is the array element, **not** the index } </code></pre> <p>In each iteration, <code>for...of</code> directly gives us the next element of the iterable, there is no "index" to access or use.</p> <hr> <h3>What if the "depth" of the data structure is unknown to me?</h3> <p>In addition to unknown keys, the "depth" of the data structure (i.e. how many nested objects) it has, might be unknown as well. How to access deeply nested properties usually depends on the exact data structure.</p> <p>But if the data structure contains repeating patterns, e.g. the representation of a binary tree, the solution typically includes to <a href="https://en.wikipedia.org/wiki/Recursion_%28computer_science%29" rel="noreferrer"><strong>recursively</strong> <em><sup>[Wikipedia]</sup></em></a> access each level of the data structure.</p> <p>Here is an example to get the first leaf node of a binary tree:</p> <pre><code>function getLeaf(node) { if (node.leftChild) { return getLeaf(node.leftChild); // &lt;- recursive call } else if (node.rightChild) { return getLeaf(node.rightChild); // &lt;- recursive call } else { // node must be a leaf node return node; } } const first_leaf = getLeaf(root); </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const root = { leftChild: { leftChild: { leftChild: null, rightChild: null, data: 42 }, rightChild: { leftChild: null, rightChild: null, data: 5 } }, rightChild: { leftChild: { leftChild: null, rightChild: null, data: 6 }, rightChild: { leftChild: null, rightChild: null, data: 7 } } }; function getLeaf(node) { if (node.leftChild) { return getLeaf(node.leftChild); } else if (node.rightChild) { return getLeaf(node.rightChild); } else { // node must be a leaf node return node; } } console.log(getLeaf(root).data);</code></pre> </div> </div> </p> <p>A more generic way to access a nested data structure with unknown keys and depth is to test the type of the value and act accordingly.</p> <p>Here is an example which adds all primitive values inside a nested data structure into an array (assuming it does not contain any functions). If we encounter an object (or array) we simply call <code>toArray</code> again on that value (recursive call).</p> <pre><code>function toArray(obj) { const result = []; for (const prop in obj) { const value = obj[prop]; if (typeof value === 'object') { result.push(toArray(value)); // &lt;- recursive call } else { result.push(value); } } return result; } </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }; function toArray(obj) { const result = []; for (const prop in obj) { const value = obj[prop]; if (typeof value === 'object') { result.push(toArray(value)); } else { result.push(value); } } return result; } console.log(toArray(data));</code></pre> </div> </div> </p> <hr> <hr> <h2>Helpers</h2> <p>Since the structure of a complex object or array is not necessarily obvious, we can inspect the value at each step to decide how to move further. <a href="https://developer.mozilla.org/en-US/docs/DOM/console.log" rel="noreferrer"><code>console.log</code> <em><sup>[MDN]</sup></em></a> and <a href="https://developer.mozilla.org/en-US/docs/DOM/console.dir" rel="noreferrer"><code>console.dir</code> <em><sup>[MDN]</sup></em></a> help us doing this. For example (output of the Chrome console):</p> <pre><code>&gt; console.log(data.items) [ Object, Object ] </code></pre> <p>Here we see that that <code>data.items</code> is an array with two elements which are both objects. In Chrome console the objects can even be expanded and inspected immediately.</p> <pre><code>&gt; console.log(data.items[1]) Object id: 2 name: "bar" __proto__: Object </code></pre> <p>This tells us that <code>data.items[1]</code> is an object, and after expanding it we see that it has three properties, <code>id</code>, <code>name</code> and <code>__proto__</code>. The latter is an internal property used for the prototype chain of the object. The prototype chain and inheritance is out of scope for this answer, though.</p>
{ "question_id": 11922383, "question_date": "2012-08-12T13:02:12.127Z", "question_score": 1088, "tags": "javascript|arrays|object|nested|data-manipulation", "answer_id": 11922384, "answer_date": "2012-08-12T13:02:12.127Z", "answer_score": 1420 }
Please answer the following Stack Overflow question: Title: How to manage startActivityForResult on Android <p>In my activity, I'm calling a second activity from the main activity by <code>startActivityForResult</code>. In my second activity, there are some methods that finish this activity (maybe without a result), however, just one of them returns a result.</p> <p>For example, from the main activity, I call a second one. In this activity, I'm checking some features of a handset, such as does it have a camera. If it doesn't have then I'll close this activity. Also, during the preparation of <code>MediaRecorder</code> or <code>MediaPlayer</code> if a problem happens then I'll close this activity.</p> <p>If its device has a camera and recording is done completely, then after recording a video if a user clicks on the done button then I'll send the result (address of the recorded video) back to the main activity.</p> <p>How do I check the result from the main activity?</p>
<p>From your <code>FirstActivity</code>, call the <code>SecondActivity</code> using the <code>startActivityForResult()</code> method.</p> <p>For example:</p> <pre><code>int LAUNCH_SECOND_ACTIVITY = 1 Intent i = new Intent(this, SecondActivity.class); startActivityForResult(i, LAUNCH_SECOND_ACTIVITY); </code></pre> <p>In your <code>SecondActivity</code>, set the data which you want to return back to <code>FirstActivity</code>. If you don't want to return back, don't set any.</p> <p>For example: In <code>SecondActivity</code> if you want to send back data:</p> <pre><code>Intent returnIntent = new Intent(); returnIntent.putExtra(&quot;result&quot;,result); setResult(Activity.RESULT_OK,returnIntent); finish(); </code></pre> <p>If you don't want to return data:</p> <pre><code>Intent returnIntent = new Intent(); setResult(Activity.RESULT_CANCELED, returnIntent); finish(); </code></pre> <p>Now in your <code>FirstActivity</code> class, write the following code for the <code>onActivityResult()</code> method.</p> <pre><code>@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == LAUNCH_SECOND_ACTIVITY) { if(resultCode == Activity.RESULT_OK){ String result=data.getStringExtra(&quot;result&quot;); } if (resultCode == Activity.RESULT_CANCELED) { // Write your code if there's no result } } } //onActivityResult </code></pre> <p>To implement passing data between two activities in a much better way in Kotlin, please go through <em>'<a href="https://proandroiddev.com/is-onactivityresult-deprecated-in-activity-results-api-lets-deep-dive-into-it-302d5cf6edd" rel="noreferrer">A better way to pass data between Activities</a>'</em>.</p>
{ "question_id": 10407159, "question_date": "2012-05-02T03:03:00.523Z", "question_score": 1086, "tags": "android|android-intent|android-activity|startactivityforresult", "answer_id": 10407371, "answer_date": "2012-05-02T03:36:38.790Z", "answer_score": 2621 }
Please answer the following Stack Overflow question: Title: What is the difference between g++ and gcc? <p>What is the difference between g++ and gcc? Which one of them should be used for general c++ development?</p>
<p><code>gcc</code> and <code>g++</code> are compiler-drivers of the GNU Compiler <em>Collection</em> (which was once upon a time just the GNU <em>C Compiler</em>).</p> <p>Even though they automatically determine which backends (<code>cc1</code> <code>cc1plus</code> ...) to call depending on the file-type, unless overridden with <code>-x language</code>, they have some differences.</p> <p>The probably most important difference in their defaults is which libraries they link against automatically.</p> <p>According to GCC's online documentation <a href="https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html" rel="noreferrer">link options</a> and <a href="https://gcc.gnu.org/onlinedocs/gcc/Invoking-G_002b_002b.html" rel="noreferrer">how g++ is invoked</a>, <code>g++</code> is equivalent to <code>gcc -xc++ -lstdc++ -shared-libgcc</code> (the 1st is a compiler option, the 2nd two are linker options). This can be checked by running both with the <code>-v</code> option (it displays the backend toolchain commands being run).</p>
{ "question_id": 172587, "question_date": "2008-10-05T20:25:13.563Z", "question_score": 1086, "tags": "c++|gcc|g++", "answer_id": 172592, "answer_date": "2008-10-05T20:26:59.520Z", "answer_score": 880 }
Please answer the following Stack Overflow question: Title: Error: Can't set headers after they are sent to the client <p>I'm fairly new to Node.js and I am having some issues.</p> <p>I am using Node.js 4.10 and Express 2.4.3.</p> <p>When I try to access <a href="http://127.0.0.1:8888/auth/facebook" rel="noreferrer">http://127.0.0.1:8888/auth/facebook</a>, i'll be redirected to <a href="http://127.0.0.1:8888/auth/facebook_callback" rel="noreferrer">http://127.0.0.1:8888/auth/facebook_callback</a>.</p> <p>I then received the following error:</p> <pre><code>Error: Can't render headers after they are sent to the client. at ServerResponse.&lt;anonymous&gt; (http.js:573:11) at ServerResponse._renderHeaders (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:64:25) at ServerResponse.writeHead (http.js:813:20) at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/auth.strategies/facebook.js:28:15 at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:113:13 at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/strategyExecutor.js:45:39) at [object Object].pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:32:3) at [object Object].halt (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:29:8) at [object Object].redirect (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:16:8) at [object Object].&lt;anonymous&gt; (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/auth.strategies/facebook.js:77:15) Error: Can't set headers after they are sent. at ServerResponse.&lt;anonymous&gt; (http.js:527:11) at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:195:11) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23) at param (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:189:13) at pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:191:10) at Object.router [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:197:6) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15) at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7) Error: Can't set headers after they are sent. at ServerResponse.&lt;anonymous&gt; (http.js:527:11) at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23) at param (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:189:13) at pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:191:10) at Object.router [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:197:6) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15) at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7) Error: Can't set headers after they are sent. at ServerResponse.&lt;anonymous&gt; (http.js:527:11) at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9) at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15) at HTTPServer.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:211:3) at Object.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:105:14) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15) Error: Can't set headers after they are sent. at ServerResponse.&lt;anonymous&gt; (http.js:527:11) at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9) at HTTPServer.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:211:3) at Object.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:105:14) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15) at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:323:9 at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:338:9 node.js:134 throw e; // process.nextTick error, or 'error' event on first tick ^ Error: Can't set headers after they are sent. at ServerResponse.&lt;anonymous&gt; (http.js:527:11) at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13) at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9) at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:323:9 at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:338:9 at Array.&lt;anonymous&gt; (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session/memory.js:57:7) at EventEmitter._tickCallback (node.js:126:26) </code></pre> <p>The following is my code:</p> <pre><code>var fbId= "XXX"; var fbSecret= "XXXXXX"; var fbCallbackAddress= "http://127.0.0.1:8888/auth/facebook_callback" var cookieSecret = "node"; // enter a random hash for security var express= require('express'); var auth = require('connect-auth') var app = express.createServer(); app.configure(function(){ app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(express.session({secret: cookieSecret})); app.use(auth([ auth.Facebook({ appId : fbId, appSecret: fbSecret, callback: fbCallbackAddress, scope: 'offline_access,email,user_about_me,user_activities,manage_pages,publish_stream', failedUri: '/noauth' }) ])); app.use(app.router); }); app.get('/auth/facebook', function(req, res) { req.authenticate("facebook", function(error, authenticated) { if (authenticated) { res.redirect("/great"); console.log("ok cool."); console.log(res['req']['session']); } }); }); app.get('/noauth', function(req, res) { console.log('Authentication Failed'); res.send('Authentication Failed'); }); app.get('/great', function( req, res) { res.send('Supercoolstuff'); }); app.listen(8888); </code></pre> <p>May I know what is wrong with my code?</p>
<p>The <code>res</code> object in Express is a subclass of <a href="https://nodejs.org/docs/latest/api/http.html#http_class_http_serverresponse" rel="noreferrer">Node.js's <code>http.ServerResponse</code></a> (<a href="https://github.com/nodejs/node-v0.x-archive/blob/master/lib/http.js" rel="noreferrer">read the http.js source</a>). You are allowed to call <code>res.setHeader(name, value)</code> as often as you want until you call <code>res.writeHead(statusCode)</code>. After <code>writeHead</code>, the headers are baked in and you can only call <code>res.write(data)</code>, and finally <code>res.end(data)</code>.</p> <p>The error &quot;Error: Can't set headers after they are sent.&quot; means that you're already in the Body or Finished state, but some function tried to set a header or statusCode. When you see this error, try to look for anything that tries to send a header after some of the body has already been written. For example, look for callbacks that are accidentally called twice, or any error that happens after the body is sent.</p> <p>In your case, you called <code>res.redirect()</code>, which caused the response to become Finished. Then your code threw an error (<code>res.req</code> is <code>null</code>). and since the error happened within your actual <code>function(req, res, next)</code> (not within a callback), Connect was able to catch it and then tried to send a 500 error page. But since the headers were already sent, Node.js's <code>setHeader</code> threw the error that you saw.</p> <h1>Comprehensive list of Node.js/Express response methods and when they must be called:</h1> <p>Response must be in <strong>Head</strong> and remains in <strong>Head</strong>:</p> <ol> <li><a href="https://nodejs.org/docs/latest/api/http.html#http_response_writecontinue" rel="noreferrer"><code>res.writeContinue()</code></a></li> <li><a href="https://nodejs.org/docs/latest/api/http.html#http_response_statuscode" rel="noreferrer"><code>res.statusCode = 404</code></a></li> <li><a href="https://nodejs.org/docs/latest/api/http.html#http_request_setheader_name_value" rel="noreferrer"><code>res.setHeader(name, value)</code></a></li> <li><a href="https://nodejs.org/docs/latest/api/http.html#http_request_getheader_name" rel="noreferrer"><code>res.getHeader(name)</code></a></li> <li><a href="https://nodejs.org/docs/latest/api/http.html#http_request_removeheader_name" rel="noreferrer"><code>res.removeHeader(name)</code></a></li> <li><a href="https://expressjs.com/en/api.html#setHeaders" rel="noreferrer"><code>res.header(key[, val])</code></a> (Express only)</li> <li><code>res.charset = 'utf-8'</code> (Express only; only affects Express-specific methods)</li> <li><a href="https://expressjs.com/en/api.html#req.is" rel="noreferrer"><code>res.contentType(type)</code></a> (Express only)</li> </ol> <p>Response must be in <strong>Head</strong> and becomes <strong>Body</strong>:</p> <ol> <li><a href="https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers" rel="noreferrer"><code>res.writeHead(statusCode, [reasonPhrase], [headers])</code></a></li> </ol> <p>Response can be in either <strong>Head/Body</strong> and remains in <strong>Body</strong>:</p> <ol> <li><a href="https://nodejs.org/docs/latest/api/http.html#http_request_write_chunk_encoding_callback" rel="noreferrer"><code>res.write(chunk, encoding='utf8')</code></a></li> </ol> <p>Response can be in either <strong>Head/Body</strong> and becomes <strong>Finished</strong>:</p> <ol> <li><a href="https://nodejs.org/docs/latest/api/http.html#http_response_end_data_encoding_callback" rel="noreferrer"><code>res.end([data], [encoding])</code></a></li> </ol> <p>Response can be in either <strong>Head/Body</strong> and remains in its current state:</p> <ol> <li><a href="https://nodejs.org/docs/latest/api/http.html#http_response_addtrailers_headers" rel="noreferrer"><code>res.addTrailers(headers)</code></a></li> </ol> <p>Response must be in <strong>Head</strong> and becomes <strong>Finished</strong>:</p> <ol> <li><code>return next([err])</code> (Connect/Express only)</li> <li>Any exceptions within middleware <code>function(req, res, next)</code> (Connect/Express only)</li> <li><a href="https://expressjs.com/en/api.html#res.attachment" rel="noreferrer"><code>res.send(body|status[, headers|status[, status]])</code></a> (Express only)</li> <li><a href="https://expressjs.com/en/api.html#res.attachment" rel="noreferrer"><code>res.attachment(filename)</code></a> (Express only)</li> <li><a href="https://expressjs.com/en/api.html#res.attachment" rel="noreferrer"><code>res.sendfile(path[, options[, callback]])</code></a> (Express only)</li> <li><a href="https://expressjs.com/en/api.html#res.attachment" rel="noreferrer"><code>res.json(obj[, headers|status[, status]])</code></a> (Express only)</li> <li><a href="https://expressjs.com/en/api.html#res.redirect" rel="noreferrer"><code>res.redirect(url[, status])</code></a> (Express only)</li> <li><a href="https://expressjs.com/en/api.html#res.cookie" rel="noreferrer"><code>res.cookie(name, val[, options])</code></a> (Express only)</li> <li><a href="https://expressjs.com/en/api.html#res.clearCookie" rel="noreferrer"><code>res.clearCookie(name[, options])</code></a> (Express only)</li> <li><a href="https://expressjs.com/en/api.html#res.clearCookie" rel="noreferrer"><code>res.render(view[, options[, fn]])</code></a> (Express only)</li> <li><a href="http://expressjs.com/2x/guide.html#res.partial()" rel="noreferrer"><code>res.partial(view[, options])</code></a> (Express only)</li> </ol>
{ "question_id": 7042340, "question_date": "2011-08-12T15:21:00.207Z", "question_score": 1085, "tags": "javascript|node.js|express", "answer_id": 7086621, "answer_date": "2011-08-17T00:11:24.840Z", "answer_score": 1502 }
Please answer the following Stack Overflow question: Title: When should I use CROSS APPLY over INNER JOIN? <p>What is the main purpose of using <a href="http://technet.microsoft.com/en-us/library/ms175156.aspx" rel="noreferrer">CROSS APPLY</a>?</p> <p>I have read (vaguely, through posts on the Internet) that <code>cross apply</code> can be more efficient when selecting over large data sets if you are partitioning. (Paging comes to mind)</p> <p>I also know that <code>CROSS APPLY</code> doesn't require a UDF as the right-table.</p> <p>In most <code>INNER JOIN</code> queries (one-to-many relationships), I could rewrite them to use <code>CROSS APPLY</code>, but they always give me equivalent execution plans. </p> <p>Can anyone give me a good example of when <code>CROSS APPLY</code> makes a difference in those cases where <code>INNER JOIN</code> will work as well?</p> <hr> <p><strong>Edit:</strong></p> <p>Here's a trivial example, where the execution plans are exactly the same. (Show me one where they differ and where <code>cross apply</code> is faster/more efficient)</p> <pre><code>create table Company ( companyId int identity(1,1) , companyName varchar(100) , zipcode varchar(10) , constraint PK_Company primary key (companyId) ) GO create table Person ( personId int identity(1,1) , personName varchar(100) , companyId int , constraint FK_Person_CompanyId foreign key (companyId) references dbo.Company(companyId) , constraint PK_Person primary key (personId) ) GO insert Company select 'ABC Company', '19808' union select 'XYZ Company', '08534' union select '123 Company', '10016' insert Person select 'Alan', 1 union select 'Bobby', 1 union select 'Chris', 1 union select 'Xavier', 2 union select 'Yoshi', 2 union select 'Zambrano', 2 union select 'Player 1', 3 union select 'Player 2', 3 union select 'Player 3', 3 /* using CROSS APPLY */ select * from Person p cross apply ( select * from Company c where p.companyid = c.companyId ) Czip /* the equivalent query using INNER JOIN */ select * from Person p inner join Company c on p.companyid = c.companyId </code></pre>
<blockquote> <p>Can anyone give me a good example of when CROSS APPLY makes a difference in those cases where INNER JOIN will work as well?</p> </blockquote> <p>See the article in my blog for detailed performance comparison:</p> <ul> <li><a href="http://explainextended.com/2009/07/16/inner-join-vs-cross-apply/" rel="noreferrer"><strong><code>INNER JOIN</code> vs. <code>CROSS APPLY</code></strong></a></li> </ul> <p><code>CROSS APPLY</code> works better on things that have no simple <code>JOIN</code> condition.</p> <p>This one selects <code>3</code> last records from <code>t2</code> for each record from <code>t1</code>:</p> <pre><code>SELECT t1.*, t2o.* FROM t1 CROSS APPLY ( SELECT TOP 3 * FROM t2 WHERE t2.t1_id = t1.id ORDER BY t2.rank DESC ) t2o </code></pre> <p>It cannot be easily formulated with an <code>INNER JOIN</code> condition.</p> <p>You could probably do something like that using <code>CTE</code>'s and window function:</p> <pre><code>WITH t2o AS ( SELECT t2.*, ROW_NUMBER() OVER (PARTITION BY t1_id ORDER BY rank) AS rn FROM t2 ) SELECT t1.*, t2o.* FROM t1 INNER JOIN t2o ON t2o.t1_id = t1.id AND t2o.rn &lt;= 3 </code></pre> <p>, but this is less readable and probably less efficient.</p> <p><strong>Update:</strong></p> <p>Just checked.</p> <p><code>master</code> is a table of about <code>20,000,000</code> records with a <code>PRIMARY KEY</code> on <code>id</code>.</p> <p>This query:</p> <pre><code>WITH q AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS rn FROM master ), t AS ( SELECT 1 AS id UNION ALL SELECT 2 ) SELECT * FROM t JOIN q ON q.rn &lt;= t.id </code></pre> <p>runs for almost <code>30</code> seconds, while this one:</p> <pre><code>WITH t AS ( SELECT 1 AS id UNION ALL SELECT 2 ) SELECT * FROM t CROSS APPLY ( SELECT TOP (t.id) m.* FROM master m ORDER BY id ) q </code></pre> <p>is instant.</p>
{ "question_id": 1139160, "question_date": "2009-07-16T17:42:21.513Z", "question_score": 1085, "tags": "sql|sql-server|performance|tsql|cross-apply", "answer_id": 1139231, "answer_date": "2009-07-16T17:52:56.203Z", "answer_score": 774 }
Please answer the following Stack Overflow question: Title: How can I move a tag on a git branch to a different commit? <p>I created a tag on the master branch called <code>v0.1</code> like this:</p> <pre><code>git tag -a v0.1 </code></pre> <p>But then I realized there were still some changes I needed to merge into master for release 0.1, so I did that. But now my <code>v0.1</code> tag is stuck on (to invoke the post-it note analogy) the wrong commit. I want it to be stuck on the most recent commit on master, but instead it is stuck on the second most recent commit on master.</p> <p>How can I move it to the most recent commit on master?</p>
<p>Use the <code>-f</code> option to <a href="https://git-scm.com/docs/git-tag" rel="noreferrer"><code>git tag</code></a>:</p> <pre><code>-f --force Replace an existing tag with the given name (instead of failing) </code></pre> <p>You probably want to use <code>-f</code> in conjunction with <code>-a</code> to force-create an annotated tag instead of a non-annotated one.</p> <h2>Example</h2> <ol> <li><p>Delete the tag on any remote before you push</p> <pre><code>git push origin :refs/tags/&lt;tagname&gt; </code></pre> </li> <li><p>Replace the tag to reference the most recent commit</p> <pre><code>git tag -fa &lt;tagname&gt; </code></pre> </li> <li><p>Push the tag to the remote origin</p> <pre><code>git push origin master --tags </code></pre> </li> </ol>
{ "question_id": 8044583, "question_date": "2011-11-08T00:32:07.097Z", "question_score": 1085, "tags": "git|git-tag", "answer_id": 8044605, "answer_date": "2011-11-08T00:34:45.427Z", "answer_score": 1466 }
Please answer the following Stack Overflow question: Title: How is an HTTP POST request made in node.js? <p>How can I make an outbound HTTP POST request, with data, in node.js?</p>
<p>Here's an example of using node.js to make a POST request to the Google Compiler API:</p> <pre><code>// We need this to build our post string var querystring = require('querystring'); var http = require('http'); var fs = require('fs'); function PostCode(codestring) { // Build the post string from an object var post_data = querystring.stringify({ 'compilation_level' : 'ADVANCED_OPTIMIZATIONS', 'output_format': 'json', 'output_info': 'compiled_code', 'warning_level' : 'QUIET', 'js_code' : codestring }); // An object of options to indicate where to post to var post_options = { host: 'closure-compiler.appspot.com', port: '80', path: '/compile', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(post_data) } }; // Set up the request var post_req = http.request(post_options, function(res) { res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('Response: ' + chunk); }); }); // post the data post_req.write(post_data); post_req.end(); } // This is an async file read fs.readFile('LinkedList.js', 'utf-8', function (err, data) { if (err) { // If this were just a small part of the application, you would // want to handle this differently, maybe throwing an exception // for the caller to handle. Since the file is absolutely essential // to the program's functionality, we're going to exit with a fatal // error instead. console.log("FATAL An error occurred trying to read in the file: " + err); process.exit(-2); } // Make sure there's data before we post it if(data) { PostCode(data); } else { console.log("No data to post"); process.exit(-1); } }); </code></pre> <p>I've updated the code to show how to post data from a file, instead of the hardcoded string. It uses the async <code>fs.readFile</code> command to achieve this, posting the actual code after a successful read. If there's an error, it is thrown, and if there's no data the process exits with a negative value to indicate failure.</p>
{ "question_id": 6158933, "question_date": "2011-05-28T00:44:10.283Z", "question_score": 1084, "tags": "node.js|http|post|httprequest", "answer_id": 6158966, "answer_date": "2011-05-28T00:50:32.063Z", "answer_score": 929 }
Please answer the following Stack Overflow question: Title: Can I call a constructor from another constructor (do constructor chaining) in C++? <p>As a <a href="http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29" rel="noreferrer">C#</a> developer I'm used to running through constructors:</p> <pre class="lang-cs prettyprint-override"><code>class Test { public Test() { DoSomething(); } public Test(int count) : this() { DoSomethingWithCount(count); } public Test(int count, string name) : this(count) { DoSomethingWithName(name); } } </code></pre> <p>Is there a way to do this in C++?</p> <p>I tried calling the Class name and using the 'this' keyword, but both fail.</p>
<p><strong>C++11: Yes!</strong></p> <p>C++11 and onwards has this same feature (called <a href="https://secure.wikimedia.org/wikipedia/en/wiki/C++11#Object_construction_improvement" rel="noreferrer">delegating constructors</a>). </p> <p>The syntax is slightly different from C#:</p> <pre><code>class Foo { public: Foo(char x, int y) {} Foo(int y) : Foo('a', y) {} }; </code></pre> <p><strong>C++03: No</strong></p> <p>Unfortunately, there's no way to do this in C++03, but there are two ways of simulating this:</p> <ol> <li><p>You can combine two (or more) constructors via default parameters:</p> <pre><code>class Foo { public: Foo(char x, int y=0); // combines two constructors (char) and (char, int) // ... }; </code></pre></li> <li><p>Use an init method to share common code:</p> <pre><code>class Foo { public: Foo(char x); Foo(char x, int y); // ... private: void init(char x, int y); }; Foo::Foo(char x) { init(x, int(x) + 7); // ... } Foo::Foo(char x, int y) { init(x, y); // ... } void Foo::init(char x, int y) { // ... } </code></pre></li> </ol> <p>See <a href="https://isocpp.org/wiki/faq/ctors#init-methods" rel="noreferrer">the C++FAQ entry</a> for reference.</p>
{ "question_id": 308276, "question_date": "2008-11-21T09:43:08.520Z", "question_score": 1084, "tags": "c++|constructor", "answer_id": 308318, "answer_date": "2008-11-21T10:04:17.963Z", "answer_score": 1436 }
Please answer the following Stack Overflow question: Title: What's the difference between HEAD^ and HEAD~ in Git? <p>When I specify an ancestor commit object in Git, I'm confused between <code>HEAD^</code> and <code>HEAD~</code>.</p> <p>Both have a "numbered" version like <code>HEAD^3</code> and <code>HEAD~2</code>.</p> <p>They seem very similar or the same to me, but are there any differences between the tilde and the caret?</p>
<h2>Rules of thumb</h2> <ul> <li>Use <code>~</code> most of the time — to go back a number of generations, usually what you want</li> <li>Use <code>^</code> on merge commits — because they have two or more (immediate) parents</li> </ul> <p>Mnemonics:</p> <ul> <li>Tilde <code>~</code> is almost linear in appearance and wants to go backward in a straight line</li> <li>Caret <code>^</code> suggests an interesting segment of a tree or a fork in the road</li> </ul> <h2>Tilde</h2> <p>The <a href="https://git-scm.com/docs/git-rev-parse#Documentation/git-rev-parse.txt-emltrevgtltngtemegemmaster3em" rel="noreferrer">“Specifying Revisions” section of the <code>git rev-parse</code> documentation</a> defines <code>~</code> as</p> <blockquote> <p><strong><code>&lt;rev&gt;~&lt;n&gt;</code>, e.g. <code>master~3</code></strong><br /> A suffix <code>~&lt;n&gt;</code> to a revision parameter means the commit object that is the <em>n</em><sup>th</sup> generation ancestor of the named commit object, following only the first parents. For example, <code>&lt;rev&gt;~3</code> is equivalent to <code>&lt;rev&gt;^^^</code> which is equivalent to <code>&lt;rev&gt;^1^1^1</code> …</p> </blockquote> <p>You can get to parents of any commit, not just <code>HEAD</code>. You can also move back through generations: for example, <code>master~2</code> means the grandparent of the tip of the master branch, favoring the first parent on merge commits.</p> <h2>Caret</h2> <p>Git history is nonlinear: a directed acyclic graph (DAG) or tree. For a commit with only one parent, <code>rev~</code> and <code>rev^</code> mean the same thing. The caret selector becomes useful with merge commits because each one is the child of two or more parents — and strains language borrowed from biology.</p> <p><code>HEAD^</code> means the first <em>immediate</em> parent of the tip of the current branch. <code>HEAD^</code> is short for <code>HEAD^1</code>, and you can also address <code>HEAD^2</code> and so on as appropriate. The <a href="https://git-scm.com/docs/git-rev-parse#Documentation/git-rev-parse.txt-emltrevgtemegemHEADv1510em" rel="noreferrer">same section of the <code>git rev-parse</code> documentation</a> defines it as</p> <blockquote> <p><strong><code>&lt;rev&gt;^</code>, <em>e.g.</em> <code>HEAD^</code>, <code>v1.5.1^0</code></strong><br /> A suffix <code>^</code> to a revision parameter means the first parent of that commit object. <code>^&lt;n&gt;</code> means the <em>n</em><sup>th</sup> parent ([<em>e.g.</em>] <code>&lt;rev&gt;^</code> is equivalent to <code>&lt;rev&gt;^1</code>). As a special rule, <code>&lt;rev&gt;^0</code> means the commit itself and is used when <code>&lt;rev&gt;</code> is the object name of a tag object that refers to a commit object.</p> </blockquote> <h2>Examples</h2> <p>These specifiers or selectors can be chained arbitrarily, <em>e.g.</em>, <code>topic~3^2</code> in English is the second parent of the merge commit that is the great-grandparent (three generations back) of the current tip of the branch <code>topic</code>.</p> <p>The <a href="https://git-scm.com/docs/git-rev-parse#_specifying_revisions" rel="noreferrer">aforementioned section of the <code>git rev-parse</code> documentation</a> traces many paths through a notional git history. Time flows generally downward. Commits D, F, B, and A are merge commits.</p> <blockquote> <p>Here is an illustration, by Jon Loeliger. Both commit nodes B and C are parents of commit node A. Parent commits are ordered left-to-right. (N.B. The <code>git log --graph</code> command displays history in the opposite order.)</p> <pre><code>G H I J \ / \ / D E F \ | / \ \ | / | \|/ | B C \ / \ / A A = = A^0 B = A^ = A^1 = A~1 C = A^2 D = A^^ = A^1^1 = A~2 E = B^2 = A^^2 F = B^3 = A^^3 G = A^^^ = A^1^1^1 = A~3 H = D^2 = B^^2 = A^^^2 = A~2^2 I = F^ = B^3^ = A^^3^ J = F^2 = B^3^2 = A^^3^2 </code></pre> </blockquote> <p>Run the code below to create a git repository whose history matches the quoted illustration.</p> <pre class="lang-perl prettyprint-override"><code>#! /usr/bin/env perl use strict; use warnings; use subs qw/ postorder /; use File::Temp qw/ mkdtemp /; my %sha1; my %parents = ( A =&gt; [ qw/ B C / ], B =&gt; [ qw/ D E F / ], C =&gt; [ qw/ F / ], D =&gt; [ qw/ G H / ], F =&gt; [ qw/ I J / ], ); sub postorder { my($root,$hash) = @_; my @parents = @{ $parents{$root} || [] }; postorder($_, $hash) for @parents; return if $sha1{$root}; @parents = map &quot;-p $sha1{$_}&quot;, @parents; chomp($sha1{$root} = `git commit-tree @parents -m &quot;$root&quot; $hash`); die &quot;$0: git commit-tree failed&quot; if $?; system(&quot;git tag -a -m '$sha1{$root}' '$root' '$sha1{$root}'&quot;) == 0 or die &quot;$0: git tag failed&quot;; } $0 =~ s!^.*/!!; # / fix Stack Overflow highlighting my $repo = mkdtemp &quot;repoXXXXXXXX&quot;; chdir $repo or die &quot;$0: chdir: $!&quot;; system(&quot;git init&quot;) == 0 or die &quot;$0: git init failed&quot;; chomp(my $tree = `git write-tree`); die &quot;$0: git write-tree failed&quot; if $?; postorder 'A', $tree; system &quot;git update-ref HEAD $sha1{A}&quot;; die &quot;$0: git update-ref failed&quot; if $?; system &quot;git update-ref master $sha1{A}&quot;; die &quot;$0: git update-ref failed&quot; if $?; # for browsing history - http://blog.kfish.org/2010/04/git-lola.html system &quot;git config alias.lol 'log --graph --decorate --pretty=oneline --abbrev-commit'&quot;; system &quot;git config alias.lola 'log --graph --decorate --pretty=oneline --abbrev-commit --all'&quot;; </code></pre> <p>It adds aliases in the new throwaway repo only for <a href="http://blog.kfish.org/2010/04/git-lola.html" rel="noreferrer"><code>git lol</code> and <code>git lola</code></a> so you can view history as in</p> <pre><code>$ git lol * 29392c8 (HEAD -&gt; master, tag: A) A |\ | * a1ef6fd (tag: C) C | | | \ *-. \ 8ae20e9 (tag: B) B |\ \ \ | | |/ | | * 03160db (tag: F) F | | |\ | | | * 9df28cb (tag: J) J | | * 2afd329 (tag: I) I | * a77cb1f (tag: E) E * cd75703 (tag: D) D |\ | * 3043d25 (tag: H) H * 4ab0473 (tag: G) G </code></pre> <p>Note that on your machine the SHA-1 object names will differ from those above, but the tags allow you to address commits by name and check your understanding.</p> <pre><code>$ git log -1 --format=%f $(git rev-parse A^) B $ git log -1 --format=%f $(git rev-parse A~^3~) I $ git log -1 --format=%f $(git rev-parse A^2~) F </code></pre> <p>The <a href="https://git-scm.com/docs/git-rev-parse#_specifying_revisions" rel="noreferrer">“Specifying Revisions” in the <code>git rev-parse</code> documentation</a> is full of great information and is worth an in-depth read. See also <a href="https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection" rel="noreferrer">Git Tools - Revision Selection</a> from the book <a href="https://git-scm.com/book/en/v2/" rel="noreferrer"><em>Pro Git</em></a>.</p> <h2>Order of Parent Commits</h2> <p>The commit <a href="https://github.com/git/git/commit/89e4fcb0dd01b42e82b8f27f9a575111a26844df" rel="noreferrer">89e4fcb0dd</a> from git’s own history is a merge commit, as <code>git show 89e4fcb0dd</code> indicates with the Merge header line that displays the immediate ancestors’ object names.</p> <blockquote> <pre><code>commit 89e4fcb0dd01b42e82b8f27f9a575111a26844df Merge: c670b1f876 649bf3a42f b67d40adbb Author: Junio C Hamano &lt;[email protected]&gt; Date: Mon Oct 29 10:15:31 2018 +0900 Merge branches 'bp/reset-quiet' and 'js/mingw-http-ssl' into nd/config-split […] </code></pre> </blockquote> <p>We can confirm the ordering by asking <code>git rev-parse</code> to show 89e4fcb0dd’s immediate parents in sequence.</p> <pre><code>$ git rev-parse 89e4fcb0dd^1 89e4fcb0dd^2 89e4fcb0dd^3 c670b1f876521c9f7cd40184bf7ed05aad843433 649bf3a42f344e71b1b5a7f562576f911a1f7423 b67d40adbbaf4f5c4898001bf062a9fd67e43368 </code></pre> <p>Querying the non-existent fourth parent results in an error.</p> <pre><code>$ git rev-parse 89e4fcb0dd^4 89e4fcb0dd^4 fatal: ambiguous argument '89e4fcb0dd^4': unknown revision or path not in the working tree. Use '--' to separate paths from revisions, like this: 'git &lt;command&gt; [&lt;revision&gt;...] -- [&lt;file&gt;...]' </code></pre> <p>If you want to extract the parents only, use <a href="https://git-scm.com/docs/git-log#_pretty_formats" rel="noreferrer">pretty format</a> <code>%P</code> for the full hashes</p> <pre><code>$ git log -1 --pretty=%P 89e4fcb0dd c670b1f876521c9f7cd40184bf7ed05aad843433 649bf3a42f344e71b1b5a7f562576f911a1f7423 b67d40adbbaf4f5c4898001bf062a9fd67e43368 </code></pre> <p>or <code>%p</code> for abbreviated parents.</p> <pre><code>$ git log -1 --pretty=%p 89e4fcb0dd c670b1f876 649bf3a42f b67d40adbb </code></pre>
{ "question_id": 2221658, "question_date": "2010-02-08T12:56:42.440Z", "question_score": 1083, "tags": "git", "answer_id": 2222920, "answer_date": "2010-02-08T16:06:54.960Z", "answer_score": 1177 }
Please answer the following Stack Overflow question: Title: How do you auto format code in Visual Studio? <p>I know Visual Studio can auto format to make my methods and loops indented properly, but I cannot find the setting.</p>
<p>To format a selection: <kbd>Ctrl</kbd>+<kbd>K</kbd>, <kbd>Ctrl</kbd>+<kbd>F</kbd></p> <p>To format a document: <kbd>Ctrl</kbd>+<kbd>K</kbd>, <kbd>Ctrl</kbd>+<kbd>D</kbd></p> <p>See the <a href="https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/da5kh0wa(v=vs.100)" rel="noreferrer">pre-defined keyboard shortcuts</a>. (These two are <code>Edit.FormatSelection</code> and <code>Edit.FormatDocument</code>.)</p> <h3>Note for macOS</h3> <p>On macOS, use the <kbd>CMD ⌘</kbd> key instead of <kbd>Ctrl</kbd>:</p> <ul> <li>To format a selection: <kbd>CMD ⌘</kbd>+<kbd>K</kbd>, <kbd>CMD ⌘</kbd>+<kbd>F</kbd></li> <li>To format a document: <kbd>CMD ⌘</kbd>+<kbd>K</kbd>, <kbd>CMD ⌘</kbd>+<kbd>D</kbd></li> </ul>
{ "question_id": 5755942, "question_date": "2011-04-22T13:33:54.733Z", "question_score": 1082, "tags": "visual-studio|indentation", "answer_id": 5755979, "answer_date": "2011-04-22T13:37:35.027Z", "answer_score": 1652 }
Please answer the following Stack Overflow question: Title: Returning JSON from a PHP Script <p>I want to return JSON from a PHP script.</p> <p>Do I just echo the result? Do I have to set the <code>Content-Type</code> header?</p>
<p>While you're usually fine without it, you can and should set the <code>Content-Type</code> header:</p> <pre><code>&lt;?php $data = /** whatever you're serializing **/; header('Content-Type: application/json; charset=utf-8'); echo json_encode($data); </code></pre> <p>If I'm not using a particular framework, I usually allow some request params to modify the output behavior. It can be useful, generally for quick troubleshooting, to not send a header, or sometimes <code>print_r</code> the data payload to eyeball it (though in most cases, it shouldn't be necessary).</p>
{ "question_id": 4064444, "question_date": "2010-10-31T18:23:54.783Z", "question_score": 1082, "tags": "php|json|header", "answer_id": 4064468, "answer_date": "2010-10-31T18:27:30.790Z", "answer_score": 1951 }
Please answer the following Stack Overflow question: Title: How can the default node version be set using NVM? <p>I have installed nvm (ubuntu with zsh shell) with two node version: <code>v6.11.5</code> and <code>v9.0.0</code> and the default version in nvm is the <code>v9.0.0</code></p> <p>Every time I need to change the node version</p> <pre><code>$ nvm list v6.11.5 -&gt; v9.0.0 system default -&gt; node (-&gt; v9.0.0) node -&gt; stable (-&gt; v9.0.0) (default) stable -&gt; 9.0 (-&gt; v9.0.0) (default) $ nvm v6 </code></pre> <p>How could I change the nvm version default to define <code>v6.11.5</code>?</p>
<p>(nvm maintainer here)</p> <p><code>nvm alias default 6.11.5</code> if you want it pegged to that specific version.</p> <p>You can also do <code>nvm alias default 16</code>.</p> <p>Either way, you'll want to upgrade to the latest version of <code>nvm</code> (v0.33.11 as of this writing)</p> <pre class="lang-sh prettyprint-override"><code>$ nvm alias default 16.14.2 # nvm set default node.js version 16.14.2 $ node -v # v16.14.2 </code></pre>
{ "question_id": 47190861, "question_date": "2017-11-08T22:34:07.757Z", "question_score": 1082, "tags": "node.js|version|nvm", "answer_id": 47787025, "answer_date": "2017-12-13T06:42:15.520Z", "answer_score": 2224 }
Please answer the following Stack Overflow question: Title: How can I get the current stack trace in Java? <p>How do I get the current <a href="http://en.wikipedia.org/wiki/Stack_trace" rel="noreferrer">stack trace</a> in Java, like how in .NET you can do <a href="http://msdn.microsoft.com/en-us/library/system.environment.stacktrace.aspx?ppud=4" rel="noreferrer"><code>Environment.StackTrace</code></a>?</p> <p>I found <code>Thread.dumpStack()</code> but it is not what I want - I want to get the stack trace back, not print it out.</p>
<p>You can use <code><a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#getStackTrace()" rel="noreferrer">Thread.currentThread().getStackTrace()</a></code>.</p> <p>That returns an array of <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/StackTraceElement.html" rel="noreferrer"><code>StackTraceElement</code></a>s that represent the current stack trace of a program.</p>
{ "question_id": 1069066, "question_date": "2009-07-01T13:13:01.657Z", "question_score": 1081, "tags": "stack-trace|java", "answer_id": 1069074, "answer_date": "2009-07-01T13:15:41.947Z", "answer_score": 1250 }
Please answer the following Stack Overflow question: Title: Why can't variables be declared in a switch statement? <p>I've always wondered this - why can't you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring them close to first use is obviously a good thing) but the following still won't work:</p> <pre><code>switch (val) { case VAL: // This won't work int newVal = 42; break; case ANOTHER_VAL: ... break; } </code></pre> <p>The above gives me the following error (MSC):</p> <blockquote> <p>initialization of 'newVal' is skipped by 'case' label</p> </blockquote> <p>This seems to be a limitation in other languages too. Why is this such a problem?</p>
<p><code>Case</code> statements are only <strong>labels</strong>. This means the compiler will interpret this as a jump directly to the label. In C++, the problem here is one of scope. Your curly brackets define the scope as everything inside the <code>switch</code> statement. This means that you are left with a scope where a jump will be performed further into the code skipping the initialization. </p> <p>The correct way to handle this is to define a scope specific to that <code>case</code> statement and define your variable within it:</p> <pre><code>switch (val) { case VAL: { // This will work int newVal = 42; break; } case ANOTHER_VAL: ... break; } </code></pre>
{ "question_id": 92396, "question_date": "2008-09-18T13:11:55.467Z", "question_score": 1081, "tags": "c++|switch-statement", "answer_id": 92439, "answer_date": "2008-09-18T13:17:14.533Z", "answer_score": 1290 }
Please answer the following Stack Overflow question: Title: angular.service vs angular.factory <p>I have seen both <a href="http://docs.angularjs.org/guide/dev_guide.services.creating_services" rel="noreferrer">angular.factory()</a> and <a href="http://briantford.com/blog/huuuuuge-angular-apps.html" rel="noreferrer">angular.service()</a> used to declare services; however, I <a href="http://briantford.com/blog/huuuuuge-angular-apps.html" rel="noreferrer">cannot find</a> <code>angular.service</code> anywhere in official documentation.</p> <p>What is the difference between the two methods?<br> Which should be used for what (assuming they do different things)?</p>
<pre><code> angular.service('myService', myServiceFunction); angular.factory('myFactory', myFactoryFunction); </code></pre> <hr /> <p>I had trouble wrapping my head around this concept until I put it to myself this way:</p> <p><strong>Service</strong>: the <em>function</em> that you write will be <strong>new</strong>-ed:</p> <pre><code> myInjectedService &lt;---- new myServiceFunction() </code></pre> <p><strong>Factory</strong>: the <em>function</em> (constructor) that you write will be <strong>invoked</strong>:</p> <pre><code> myInjectedFactory &lt;--- myFactoryFunction() </code></pre> <p>What you do with that is up to you, but there are some useful patterns...</p> <h3>Such as writing a <em>service</em> function to expose a public API:</h3> <pre><code>function myServiceFunction() { this.awesomeApi = function(optional) { // calculate some stuff return awesomeListOfValues; } } --------------------------------------------------------------------------------- // Injected in your controller $scope.awesome = myInjectedService.awesomeApi(); </code></pre> <h3>Or using a <em>factory</em> function to expose a public API:</h3> <pre><code>function myFactoryFunction() { var aPrivateVariable = &quot;yay&quot;; function hello() { return &quot;hello mars &quot; + aPrivateVariable; } // expose a public API return { hello: hello }; } --------------------------------------------------------------------------------- // Injected in your controller $scope.hello = myInjectedFactory.hello(); </code></pre> <h3>Or using a <em>factory</em> function to return a constructor:</h3> <pre><code>function myFactoryFunction() { return function() { var a = 2; this.a2 = function() { return a*2; }; }; } --------------------------------------------------------------------------------- // Injected in your controller var myShinyNewObject = new myInjectedFactory(); $scope.four = myShinyNewObject.a2(); </code></pre> <hr /> <h3>Which one to use?...</h3> <p>You can accomplish the same thing with both. However, in some cases the <em>factory</em> gives you a little bit more flexibility to create an injectable with a simpler syntax. That's because while myInjectedService must always be an object, myInjectedFactory can be an object, a function reference, or any value at all. For example, if you wrote a service to create a constructor (as in the last example above), it would have to be instantiated like so:</p> <pre><code>var myShinyNewObject = new myInjectedService.myFunction() </code></pre> <p>which is arguably less desirable than this:</p> <pre><code>var myShinyNewObject = new myInjectedFactory(); </code></pre> <p>(But you should be wary about using this type of pattern in the first place because <em>new</em>-ing objects in your controllers creates hard-to-track dependencies that are difficult to mock for testing. Better to have a service manage a collection of objects for you than use <code>new()</code> wily-nilly.)</p> <hr /> <h3>One more thing, they are all Singletons...</h3> <p>Also keep in mind that in both cases, angular is helping you manage a singleton. Regardless of where or how many times you inject your service or function, you will get the same reference to the same object or function. (With the exception of when a factory simply returns a value like a number or string. In that case, you will always get the same value, but not a reference.)</p>
{ "question_id": 14324451, "question_date": "2013-01-14T18:36:41.180Z", "question_score": 1080, "tags": "angularjs|angular-services", "answer_id": 21900284, "answer_date": "2014-02-20T06:46:54.690Z", "answer_score": 1278 }
Please answer the following Stack Overflow question: Title: How to make --no-ri --no-rdoc the default for gem install? <p>I don't use the RI or RDoc output from the gems I install in my machine or in the servers I handle (I use other means of documentation).</p> <p>Every gem I install installs RI and RDoc documentation by default, because I forget to set <code>--no-ri --no-rdoc</code>.</p> <p>Is there a way to make those two flags the default?</p>
<p>You just add the following line to your local <code>~/.gemrc</code> file (it is in your <em>home</em> folder):</p> <pre><code>gem: --no-document </code></pre> <p>by</p> <pre><code>echo 'gem: --no-document' &gt;&gt; ~/.gemrc </code></pre> <p>or you can add this line to the global <code>gemrc</code> config file.</p> <p>Here is how to find it (in Linux):</p> <pre><code>strace gem source 2&gt;&amp;1 | grep gemrc </code></pre> <p>The <code>--no-document</code> option is documented in <a href="https://guides.rubygems.org/command-reference/#installupdate-options" rel="noreferrer">the RubyGems CLI Reference</a>.</p>
{ "question_id": 1381725, "question_date": "2009-09-04T21:48:59.303Z", "question_score": 1080, "tags": "ruby|rubygems", "answer_id": 1386014, "answer_date": "2009-09-06T16:10:23.333Z", "answer_score": 1282 }
Please answer the following Stack Overflow question: Title: Insert into a MySQL table or update if exists <p>I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.</p> <p>For example:</p> <pre class="lang-sql prettyprint-override"><code>INSERT INTO table_name (ID, NAME, AGE) VALUES(1, &quot;A&quot;, 19); </code></pre> <p>Let’s say the unique key is <code>ID</code>, and in my <strong>Database</strong>, there is a row with <code>ID = 1</code>. In that case, I want to update that row with these values. Normally this gives an error.<br /> If I use <code>INSERT IGNORE</code> it will ignore the error, but it still won’t update.</p>
<p>Use <a href="https://dev.mysql.com/doc/en/insert-on-duplicate.html" rel="noreferrer"><code>INSERT ... ON DUPLICATE KEY UPDATE</code></a></p> <p><strong>QUERY:</strong></p> <pre><code>INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE name="A", age=19 </code></pre>
{ "question_id": 4205181, "question_date": "2010-11-17T14:08:52.573Z", "question_score": 1079, "tags": "mysql|sql|insert-update|upsert", "answer_id": 4205207, "answer_date": "2010-11-17T14:12:56.693Z", "answer_score": 1950 }
Please answer the following Stack Overflow question: Title: Using ls to list directories and their total sizes <p>Is it possible to use <code>ls</code> in Unix to list the total size of a sub-directory and all its contents as opposed to the usual <code>4K</code> that (I assume) is just the directory file itself?</p> <pre><code>total 12K drwxrwxr-x 6 *** *** 4.0K 2009-06-19 10:10 branches drwxrwxr-x 13 *** *** 4.0K 2009-06-19 10:52 tags drwxrwxr-x 16 *** *** 4.0K 2009-06-19 10:02 trunk </code></pre> <p>After scouring the man pages I'm coming up empty.</p>
<p>Try something like:</p> <pre><code>du -sh * </code></pre> <p>short version of:</p> <pre><code>du --summarize --human-readable * </code></pre> <h3>Explanation:</h3> <p><code>du</code>: <strong>D</strong>isk <strong>U</strong>sage</p> <p><code>-s</code>: Display a summary for each specified file. (Equivalent to <code>-d 0</code>)</p> <p><code>-h</code>: "Human-readable" output. Use unit suffixes: <strong>B</strong>yte, <strong>K</strong>ibibyte (KiB), <strong>M</strong>ebibyte (MiB), <strong>G</strong>ibibyte (GiB), <strong>T</strong>ebibyte (TiB) and <strong>P</strong>ebibyte (PiB). (BASE2)</p>
{ "question_id": 1019116, "question_date": "2009-06-19T17:29:00.347Z", "question_score": 1079, "tags": "linux|unix", "answer_id": 1019124, "answer_date": "2009-06-19T17:30:36.117Z", "answer_score": 1940 }
Please answer the following Stack Overflow question: Title: How to get the sizes of the tables of a MySQL database? <p>I can run this query to get the sizes of all tables in a MySQL database:</p> <pre><code>show table status from myDatabaseName; </code></pre> <p>I would like some help in understanding the results. I am looking for tables with the largest sizes. </p> <p>Which column should I look at?</p>
<p>You can use this query to show the size of a table (although you need to substitute the variables first):</p> <pre><code>SELECT table_name AS `Table`, round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB` FROM information_schema.TABLES WHERE table_schema = "$DB_NAME" AND table_name = "$TABLE_NAME"; </code></pre> <p>or this query to list the size of every table in every database, largest first:</p> <pre><code>SELECT table_schema as `Database`, table_name AS `Table`, round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB` FROM information_schema.TABLES ORDER BY (data_length + index_length) DESC; </code></pre>
{ "question_id": 9620198, "question_date": "2012-03-08T15:30:31.937Z", "question_score": 1079, "tags": "mysql", "answer_id": 9620273, "answer_date": "2012-03-08T15:34:46.537Z", "answer_score": 2249 }
Please answer the following Stack Overflow question: Title: Checking whether a variable is an integer or not <p>How do I check whether a variable is an integer?</p>
<p>If you need to do this, do</p> <pre><code>isinstance(&lt;var&gt;, int) </code></pre> <p>unless you are in Python 2.x in which case you want</p> <pre><code>isinstance(&lt;var&gt;, (int, long)) </code></pre> <p>Do not use <code>type</code>. It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism. For instance, if you subclass <code>int</code>, your new class should register as an <code>int</code>, which <code>type</code> will not do:</p> <pre><code>class Spam(int): pass x = Spam(0) type(x) == int # False isinstance(x, int) # True </code></pre> <p>This adheres to Python's strong polymorphism: you should allow any object that behaves like an <code>int</code>, instead of mandating that it be one.</p> <h1>BUT</h1> <p>The classical Python mentality, though, is that it's <em>easier to ask forgiveness than permission</em>. In other words, don't check whether <code>x</code> is an integer; assume that it is and catch the exception results if it isn't:</p> <pre><code>try: x += 1 except TypeError: ... </code></pre> <p>This mentality is slowly being overtaken by the use of <a href="http://docs.python.org/library/abc.html" rel="noreferrer">abstract base classes</a>, which let you register exactly what properties your object should have (adding? multiplying? doubling?) by making it inherit from a specially-constructed class. That would be the best solution, since it will permit <em>exactly</em> those objects with the necessary and sufficient attributes, but you will have to read the docs on how to use it.</p>
{ "question_id": 3501382, "question_date": "2010-08-17T10:15:08.270Z", "question_score": 1078, "tags": "python|integer", "answer_id": 3501408, "answer_date": "2010-08-17T10:18:16.010Z", "answer_score": 1313 }
Please answer the following Stack Overflow question: Title: Best way to use multiple SSH private keys on one client <p>I want to use multiple private keys to connect to different servers or different portions of the same server (my uses are system administration of server, administration of Git, and normal Git usage within the same server). I tried simply stacking the keys in the <code>id_rsa</code> files to no avail.</p> <p>Apparently a straightforward way to do this is to use the command </p> <pre><code>ssh -i &lt;key location&gt; [email protected] </code></pre> <p>That is quite cumbersome.</p> <p>Any suggestions as to how to go about doing this a bit easier?</p>
<p>From my <code>.ssh/config</code>:</p> <pre><code>Host myshortname realname.example.com HostName realname.example.com IdentityFile ~/.ssh/realname_rsa # private key for realname User remoteusername Host myother realname2.example.org HostName realname2.example.org IdentityFile ~/.ssh/realname2_rsa # different private key for realname2 User remoteusername </code></pre> <p>Then you can use the following to connect:</p> <p><code>ssh myshortname</code></p> <p><code>ssh myother</code></p> <p>And so on.</p>
{ "question_id": 2419566, "question_date": "2010-03-10T18:40:58.140Z", "question_score": 1078, "tags": "ssh|ssh-keys|openssh", "answer_id": 2419609, "answer_date": "2010-03-10T18:46:39.323Z", "answer_score": 1504 }
Please answer the following Stack Overflow question: Title: How can I generate an MD5 hash in Java? <p>Is there any method to generate MD5 hash of a string in Java?</p>
<p>You need <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/security/MessageDigest.html" rel="noreferrer"><code>java.security.MessageDigest</code></a>.</p> <p>Call <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/security/MessageDigest.html#getInstance(java.lang.String)" rel="noreferrer"><code>MessageDigest.getInstance("MD5")</code></a> to get a MD5 instance of <code>MessageDigest</code> you can use.</p> <p>The compute the hash by doing one of:</p> <ul> <li>Feed the entire input as a <code>byte[]</code> and calculate the hash in one operation with <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/security/MessageDigest.html#digest(byte%5B%5D)" rel="noreferrer"><code>md.digest(bytes)</code></a>.</li> <li>Feed the <code>MessageDigest</code> one <code>byte[]</code> chunk at a time by calling <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/security/MessageDigest.html#update(byte%5B%5D)" rel="noreferrer"><code>md.update(bytes)</code></a>. When you're done adding input bytes, calculate the hash with <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/security/MessageDigest.html#digest()" rel="noreferrer"><code>md.digest()</code></a>.</li> </ul> <p>The <code>byte[]</code> returned by <code>md.digest()</code> is the MD5 hash.</p>
{ "question_id": 415953, "question_date": "2009-01-06T09:45:12.130Z", "question_score": 1076, "tags": "java|hash|md5|hashcode", "answer_id": 415956, "answer_date": "2009-01-06T09:47:52.173Z", "answer_score": 640 }
Please answer the following Stack Overflow question: Title: Should I use 'has_key()' or 'in' on Python dicts? <p>Given:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': 2} </code></pre> <p>Which of the following is the best way to check if <code>'a'</code> is in <code>d</code>?</p> <pre><code>&gt;&gt;&gt; 'a' in d True </code></pre> <pre><code>&gt;&gt;&gt; d.has_key('a') True </code></pre>
<p><code>in</code> is definitely more pythonic.</p> <p>In fact <a href="http://docs.python.org/3.1/whatsnew/3.0.html#builtins" rel="noreferrer"><code>has_key()</code> was removed in Python 3.x</a>.</p>
{ "question_id": 1323410, "question_date": "2009-08-24T16:30:15.820Z", "question_score": 1076, "tags": "python|dictionary", "answer_id": 1323426, "answer_date": "2009-08-24T16:33:18.873Z", "answer_score": 1559 }
Please answer the following Stack Overflow question: Title: How do you explicitly set a new property on `window` in TypeScript? <p>I setup global namespaces for my objects by explicitly setting a property on <code>window</code>.</p> <pre><code>window.MyNamespace = window.MyNamespace || {}; </code></pre> <p>TypeScript underlines <code>MyNamespace</code> and complains that:</p> <blockquote> <p>The property 'MyNamespace' does not exist on value of type 'window' any"</p> </blockquote> <p>I can make the code work by declaring <code>MyNamespace</code> as an ambient variable and dropping the <code>window</code> explicitness but I don't want to do that.</p> <pre><code>declare var MyNamespace: any; MyNamespace = MyNamespace || {}; </code></pre> <p>How can I keep <code>window</code> in there and make TypeScript happy?</p> <p>As a side note I find it especially funny that TypeScript complains since it tells me that <code>window</code> is of type <code>any</code> which by definitely can contain anything.</p>
<p>I just found the answer to this in <a href="https://stackoverflow.com/a/12703866/31308">another Stack Overflow question's answer</a>.</p> <pre><code>declare global { interface Window { MyNamespace: any; } } window.MyNamespace = window.MyNamespace || {}; </code></pre> <p>Basically, you need to extend the existing <code>window</code> interface to tell it about your new property.</p>
{ "question_id": 12709074, "question_date": "2012-10-03T13:01:15.793Z", "question_score": 1076, "tags": "typescript", "answer_id": 12709880, "answer_date": "2012-10-03T13:46:44.400Z", "answer_score": 1256 }
Please answer the following Stack Overflow question: Title: Static way to get 'Context' in Android? <p>Is there a way to get the current <code>Context</code> instance inside a static method? </p> <p>I'm looking for that way because I hate saving the 'Context' instance each time it changes.</p>
<p>Do this:</p> <p>In the Android Manifest file, declare the following.</p> <pre><code>&lt;application android:name="com.xyz.MyApplication"&gt; &lt;/application&gt; </code></pre> <p>Then write the class:</p> <pre><code>public class MyApplication extends Application { private static Context context; public void onCreate() { super.onCreate(); MyApplication.context = getApplicationContext(); } public static Context getAppContext() { return MyApplication.context; } } </code></pre> <p>Now everywhere call <code>MyApplication.getAppContext()</code> to get your application context statically.</p>
{ "question_id": 2002288, "question_date": "2010-01-04T21:15:00.603Z", "question_score": 1075, "tags": "android|android-context", "answer_id": 5114361, "answer_date": "2011-02-25T06:37:00.513Z", "answer_score": 1397 }
Please answer the following Stack Overflow question: Title: Is there any difference between a GUID and a UUID? <p>I see these two acronyms being thrown around and I was wondering if there are any differences between a GUID and a UUID?</p>
<p><strike>The <strong>simple answer</strong> is: **no difference, they are the same thing.</strike></p> <p><strong>2020-08-20 Update</strong>: While GUIDs (as used by Microsoft) and UUIDs (as defined by RFC4122) look similar and serve similar purposes, there are subtle-but-occasionally-important differences. Specifically, <a href="https://docs.microsoft.com/en-us/windows/win32/msi/guid" rel="noreferrer">some Microsoft GUID docs</a> allow GUIDs to contain any hex digit in any position, while RFC4122 requires certain values for the <code>version</code> and <code>variant</code> fields. Also, [per that same link], GUIDs should be all-upper case, whereas UUIDs <a href="https://www.rfc-editor.org/rfc/rfc4122#section-3" rel="noreferrer">should be</a> &quot;output as lower case characters and are case insensitive on input&quot;. This can lead to incompatibilities between code libraries (<a href="https://github.com/uuidjs/uuid/issues/511" rel="noreferrer">such as this</a>).</p> <p>(Original answer follows)</p> <hr /> <p>Treat them as a 16 byte (128 bits) value that is used as a unique value. In Microsoft-speak they are called GUIDs, but call them UUIDs when not using Microsoft-speak.</p> <p>Even the authors of the UUID specification and Microsoft claim they are synonyms:</p> <ul> <li><p>From the introduction to IETF <a href="https://datatracker.ietf.org/doc/html/rfc4122" rel="noreferrer">RFC 4122</a> &quot;<em>A Universally Unique IDentifier (UUID) URN Namespace</em>&quot;: &quot;a Uniform Resource Name namespace for UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier).&quot;</p> </li> <li><p>From the <a href="http://www.itu.int/ITU-T/studygroups/com17/oid.html" rel="noreferrer">ITU-T Recommendation X.667, ISO/IEC 9834-8:2004 International Standard</a>: &quot;UUIDs are also known as Globally Unique Identifiers (GUIDs), but this term is not used in this Recommendation.&quot;</p> </li> <li><p>And Microsoft even <a href="http://msdn.microsoft.com/en-us/library/cc246025%28v=PROT.13%29.aspx" rel="noreferrer">claims</a> a GUID is specified by the UUID RFC: &quot;In Microsoft Windows programming and in Windows operating systems, a globally unique identifier (GUID), as specified in [RFC4122], is ... The term universally unique identifier (UUID) is sometimes used in Windows protocol specifications as a synonym for GUID.&quot;</p> </li> </ul> <p>But the <strong>correct answer</strong> depends on what the question means when it says &quot;UUID&quot;...</p> <p>The first part depends on what the asker is thinking when they are saying &quot;UUID&quot;.</p> <p>Microsoft's claim implies that all UUIDs are GUIDs. But are all GUIDs real UUIDs? That is, is the set of all UUIDs just a proper subset of the set of all GUIDs, or is it the exact same set?</p> <p>Looking at the details of the RFC 4122, there are four different &quot;variants&quot; of UUIDs. This is mostly because such 16 byte identifiers were in use before those specifications were brought together in the creation of a UUID specification. From section 4.1.1 of <a href="https://datatracker.ietf.org/doc/html/rfc4122" rel="noreferrer">RFC 4122</a>, the four <em>variants</em> of UUID are:</p> <ol> <li>Reserved, Network Computing System backward compatibility</li> <li>The <em>variant</em> specified in RFC 4122 (of which there are five sub-variants, which are called &quot;versions&quot;)</li> <li>Reserved, Microsoft Corporation backward compatibility</li> <li>Reserved for future definition.</li> </ol> <p>According to RFC 4122, all UUID <em>variants</em> are &quot;real UUIDs&quot;, then all GUIDs are real UUIDs. To the literal question &quot;is there any difference between GUID and UUID&quot; the answer is definitely no for RFC 4122 UUIDs: <strong>no difference</strong> (but subject to the second part below).</p> <p>But not all GUIDs are <em>variant</em> 2 UUIDs (e.g. Microsoft COM has GUIDs which are variant 3 UUIDs). If the question was &quot;is there any difference between GUID and variant 2 UUIDs&quot;, then the answer would be yes -- they can be different. Someone asking the question probably doesn't know about <em>variants</em> and they might be only thinking of <em>variant</em> 2 UUIDs when they say the word &quot;UUID&quot; (e.g. they vaguely know of the MAC address+time and the random number algorithms forms of UUID, which are both <em>versions</em> of <em>variant</em> 2). In which case, the answer is <strong>yes different</strong>.</p> <p>So the answer, in part, depends on what the person asking is thinking when they say the word &quot;UUID&quot;. Do they mean variant 2 UUID (because that is the only variant they are aware of) or all UUIDs?</p> <p>The second part depends on which specification being used as the definition of UUID.</p> <p>If you think that was confusing, read the <a href="http://www.itu.int/ITU-T/studygroups/com17/oid.html" rel="noreferrer">ITU-T X.667 ISO/IEC 9834-8:2004</a> which is supposed to be aligned and fully technically compatible with <a href="https://datatracker.ietf.org/doc/html/rfc4122" rel="noreferrer">RFC 4122</a>. It has an extra sentence in Clause 11.2 that says, &quot;All UUIDs conforming to this Recommendation | International Standard shall have variant bits with bit 7 of octet 7 set to 1 and bit 6 of octet 7 set to 0&quot;. Which means that only <em>variant</em> 2 UUID conform to that Standard (those two bit values mean <em>variant</em> 2). If that is true, then not all GUIDs are conforming ITU-T/ISO/IEC UUIDs, because conformant ITU-T/ISO/IEC UUIDs can only be <em>variant</em> 2 values.</p> <p>Therefore, the real answer also depends on which specification of UUID the question is asking about. Assuming we are clearly talking about all UUIDs and not just variant 2 UUIDs: there is <strong>no difference</strong> between GUID and IETF's UUIDs, but <strong>yes difference</strong> between GUID and <em>conforming</em> ITU-T/ISO/IEC's UUIDs!</p> <p><strong>Binary encodings could differ</strong></p> <p>When encoded in binary (as opposed to the human-readable text format), the GUID <a href="http://en.wikipedia.org/wiki/Globally_unique_identifier" rel="noreferrer">may be stored</a> in a structure with four different fields as follows. This format differs from the [UUID standard] <a href="https://www.rfc-editor.org/rfc/rfc4122" rel="noreferrer">8</a> only in the byte order of the first 3 fields.</p> <pre><code>Bits Bytes Name Endianness Endianness (GUID) RFC 4122 32 4 Data1 Native Big 16 2 Data2 Native Big 16 2 Data3 Native Big 64 8 Data4 Big Big </code></pre>
{ "question_id": 246930, "question_date": "2008-10-29T14:09:08.830Z", "question_score": 1074, "tags": "guid|uuid", "answer_id": 6953207, "answer_date": "2011-08-05T08:01:48.497Z", "answer_score": 1020 }
Please answer the following Stack Overflow question: Title: Getting the ID of the element that fired an event <p>Is there any way to get the ID of the element that fires an event?</p> <p>I'm thinking something like:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() { $("a").click(function() { var test = caller.id; alert(test.val()); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script type="text/javascript" src="starterkit/jquery.js"&gt;&lt;/script&gt; &lt;form class="item" id="aaa"&gt; &lt;input class="title"&gt;&lt;/input&gt; &lt;/form&gt; &lt;form class="item" id="bbb"&gt; &lt;input class="title"&gt;&lt;/input&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>Except of course that the var <code>test</code> should contain the id <code>"aaa"</code>, if the event is fired from the first form, and <code>"bbb"</code>, if the event is fired from the second form.</p>
<p>In jQuery <code>event.target</code> always refers to the element that triggered the event, where <code>event</code> is the parameter passed to the function. <a href="http://api.jquery.com/category/events/event-object/" rel="noreferrer">http://api.jquery.com/category/events/event-object/</a></p> <pre><code>$(document).ready(function() { $("a").click(function(event) { alert(event.target.id); }); }); </code></pre> <p>Note also that <code>this</code> will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as <code>$(this)</code>, e.g.:</p> <pre><code>$(document).ready(function() { $("a").click(function(event) { // this.append wouldn't work $(this).append(" Clicked"); }); }); </code></pre>
{ "question_id": 48239, "question_date": "2008-09-07T08:09:38.610Z", "question_score": 1073, "tags": "javascript|jquery|dom-events", "answer_id": 48684, "answer_date": "2008-09-07T19:02:37.010Z", "answer_score": 1390 }
Please answer the following Stack Overflow question: Title: How do I clear/delete the current line in terminal? <p>If I'm using terminal and typing in a line of text for a command, is there a hotkey or any way to clear/delete that line?</p> <p>For example, if my current line/command is something really long like:</p> <pre><code>&gt; git log --graph --all --blah..uh oh i want to cancel and clear this line &lt;cursor is here now&gt; </code></pre> <p>Is there a hotkey or command to go from the above to:</p> <pre><code>&gt; </code></pre> <p>?</p> <p>Usually I will press the <kbd>&#8595;</kbd> key, and if my current line is a brand new one on the history, that will clear it. But if I'm going through my command history via the <kbd>&#8593;</kbd> key and start editing or using those commands, <kbd>&#8595;</kbd> will only change the prompt to the next newest command in history, so it doesn't work here unless I press <kbd>&#8595;</kbd> multiple times.</p>
<p>You can use <kbd>Ctrl</kbd>+<kbd>U</kbd> to clear up to the beginning.</p> <p>You can use <kbd>Ctrl</kbd>+<kbd>W</kbd> to delete just a word.</p> <p>You can also use <kbd>Ctrl</kbd>+<kbd>C</kbd> to cancel.</p> <p>If you want to keep the history, you can use <kbd>Alt</kbd>+<kbd>Shift</kbd>+<kbd>#</kbd> to make it a comment.</p> <hr> <p><sub><a href="http://www.catonmat.net/blog/bash-emacs-editing-mode-cheat-sheet/" rel="noreferrer">Bash Emacs Editing Mode Cheat Sheet</a></sub></p>
{ "question_id": 9679776, "question_date": "2012-03-13T07:17:30.700Z", "question_score": 1073, "tags": "bash|terminal", "answer_id": 9679852, "answer_date": "2012-03-13T07:23:57.937Z", "answer_score": 2001 }
Please answer the following Stack Overflow question: Title: Pretty-print an entire Pandas Series / DataFrame <p>I work with Series and DataFrames on the terminal a lot. The default <code>__repr__</code> for a Series returns a reduced sample, with some head and tail values, but the rest missing.</p> <p>Is there a builtin way to pretty-print the entire Series / DataFrame? Ideally, it would support proper alignment, perhaps borders between columns, and maybe even color-coding for the different columns.</p>
<p>You can also use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.option_context.html" rel="noreferrer"><code>option_context</code></a>, with one or more options:</p> <pre><code>with pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified also print(df) </code></pre> <p>This will automatically return the options to their previous values.</p> <p>If you are working on jupyter-notebook, using <code>display(df)</code> instead of <code>print(df)</code> will use jupyter rich display logic <a href="https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.display" rel="noreferrer">(like so)</a>.</p>
{ "question_id": 19124601, "question_date": "2013-10-01T19:46:07.170Z", "question_score": 1072, "tags": "python|pandas|dataframe", "answer_id": 30691921, "answer_date": "2015-06-07T09:22:15.250Z", "answer_score": 1366 }
Please answer the following Stack Overflow question: Title: Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction <p>In ASP.NET MVC, what is the difference between:</p> <ul> <li><code>Html.Partial</code> and <code>Html.RenderPartial</code></li> <li><code>Html.Action</code> and <code>Html.RenderAction</code></li> </ul>
<p><code>Html.Partial</code> returns a String. <code>Html.RenderPartial</code> calls <code>Write</code> internally and returns <code>void</code>.</p> <p>The basic usage is:</p> <pre><code>// Razor syntax @Html.Partial("ViewName") @{ Html.RenderPartial("ViewName"); } // WebView syntax &lt;%: Html.Partial("ViewName") %&gt; &lt;% Html.RenderPartial("ViewName"); %&gt; </code></pre> <p>In the snippet above, both calls will yield the same result.</p> <p>While one can store the output of <code>Html.Partial</code> in a variable or return it from a method, one <em>cannot</em> do this with <code>Html.RenderPartial</code>. </p> <p>The result will be written to the <code>Response</code> stream during execution/evaluation.</p> <p>This also applies to <code>Html.Action</code> and <code>Html.RenderAction</code>.</p>
{ "question_id": 5248183, "question_date": "2011-03-09T15:41:24.550Z", "question_score": 1072, "tags": ".net|asp.net-mvc|partial-views|renderpartial|renderaction", "answer_id": 5248218, "answer_date": "2011-03-09T15:44:04.490Z", "answer_score": 1269 }
Please answer the following Stack Overflow question: Title: Git: Find the most recent common ancestor of two branches <p>How to find the most recent common ancestor of two Git branches?</p>
<p>You are looking for <a href="https://www.kernel.org/pub/software/scm/git/docs/git-merge-base.html" rel="noreferrer"><code>git merge-base</code></a>. Usage:</p> <pre><code>$ git merge-base branch2 branch3 050dc022f3a65bdc78d97e2b1ac9b595a924c3f2 </code></pre>
{ "question_id": 1549146, "question_date": "2009-10-10T21:43:09.257Z", "question_score": 1072, "tags": "git|git-branch", "answer_id": 1549155, "answer_date": "2009-10-10T21:47:38.127Z", "answer_score": 1324 }
Please answer the following Stack Overflow question: Title: INNER JOIN ON vs WHERE clause <p>For simplicity, assume all relevant fields are <code>NOT NULL</code>.</p> <p>You can do:</p> <pre><code>SELECT table1.this, table2.that, table2.somethingelse FROM table1, table2 WHERE table1.foreignkey = table2.primarykey AND (some other conditions) </code></pre> <p>Or else:</p> <pre><code>SELECT table1.this, table2.that, table2.somethingelse FROM table1 INNER JOIN table2 ON table1.foreignkey = table2.primarykey WHERE (some other conditions) </code></pre> <p>Do these two work on the same way in <code>MySQL</code>?</p>
<p><code>INNER JOIN</code> is ANSI syntax that you should use.</p> <p>It is generally considered more readable, especially when you join lots of tables.</p> <p>It can also be easily replaced with an <code>OUTER JOIN</code> whenever a need arises.</p> <p>The <code>WHERE</code> syntax is more relational model oriented.</p> <p>A result of two tables <code>JOIN</code>ed is a cartesian product of the tables to which a filter is applied which selects only those rows with joining columns matching.</p> <p>It's easier to see this with the <code>WHERE</code> syntax.</p> <p>As for your example, in MySQL (and in SQL generally) these two queries are synonyms.</p> <p>Also, note that MySQL also has a <code>STRAIGHT_JOIN</code> clause.</p> <p>Using this clause, you can control the <code>JOIN</code> order: which table is scanned in the outer loop and which one is in the inner loop.</p> <p>You cannot control this in MySQL using <code>WHERE</code> syntax.</p>
{ "question_id": 1018822, "question_date": "2009-06-19T16:16:24.347Z", "question_score": 1071, "tags": "sql|mysql|join|inner-join", "answer_id": 1018825, "answer_date": "2009-06-19T16:17:28.200Z", "answer_score": 770 }
Please answer the following Stack Overflow question: Title: How to change Status Bar text color in iOS <p>My application has a dark background, but in iOS 7 the status bar became transparent. So I can't see anything there, only the green battery indicator in the corner. How can I change the status bar text color to white like it is on the home screen?</p>
<ol> <li><p>Set the <code>UIViewControllerBasedStatusBarAppearance</code> to <code>YES</code> in the .plist file. </p></li> <li><p>In the <code>viewDidLoad</code> do a <code>[self setNeedsStatusBarAppearanceUpdate];</code> </p></li> <li><p>Add the following method:</p> <pre><code>- (UIStatusBarStyle)preferredStatusBarStyle { return UIStatusBarStyleLightContent; } </code></pre></li> </ol> <p><strong>Note</strong>: This does not work for controllers inside <code>UINavigationController</code>, please see <a href="https://stackoverflow.com/questions/17678881/how-to-change-status-bar-text-color-in-ios-7#comment28947732_17768797">Tyson's comment below</a> :) </p> <p><strong>Swift 3</strong> - This will work controllers inside <code>UINavigationController</code>. Add this code inside your controller.</p> <pre><code>// Preferred status bar style lightContent to use on dark background. // Swift 3 override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } </code></pre> <p><strong>Swift 5 and SwiftUI</strong></p> <p>For SwiftUI create a new swift file called <code>HostingController.swift</code></p> <pre><code>import Foundation import UIKit import SwiftUI class HostingController: UIHostingController&lt;ContentView&gt; { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } </code></pre> <p>Then change the following lines of code in the <code>SceneDelegate.swift</code></p> <pre><code>window.rootViewController = UIHostingController(rootView: ContentView()) </code></pre> <p>to</p> <pre><code>window.rootViewController = HostingController(rootView: ContentView()) </code></pre>
{ "question_id": 17678881, "question_date": "2013-07-16T14:11:22.137Z", "question_score": 1071, "tags": "ios|swift|ios7|statusbar|uistatusbar", "answer_id": 17768797, "answer_date": "2013-07-21T03:36:11.823Z", "answer_score": 1456 }
Please answer the following Stack Overflow question: Title: Can you force Visual Studio to always run as an Administrator in Windows 8? <p>In Windows 7, you could go into a programs compatibility settings and check off to always run as an Administrator. Is there a similar option in Windows 8? </p> <p>I've always disabled UAC on my machines, and did the same after my Windows 8 upgrade, or so I thought. It turns out there is no <code>off</code> option, only turning off the notifications. </p> <p>This means nothing is run as an Administrator despite being in the Administrator group. I need to keep closing and reopening my consoles\Visual Studio when I try to debug (attach to process, not <kbd>F5</kbd>), which is very frustrating. </p> <p>It's really annoying that I need to either remember to take extra steps to open it as an Administrator or tell it to close and re-open when I go to debug for the first time.</p>
<p>In Windows 8, Windows 10, and Windows 11, you have to right-click <code>devenv.exe</code> and select &quot;Troubleshoot compatibility&quot;.</p> <ol> <li>Select &quot;Troubleshoot program&quot;</li> <li>Check &quot;The program requires additional permissions&quot;</li> <li>Click &quot;Next&quot;</li> <li>Click &quot;Test the program...&quot;</li> <li>Wait for the program to launch</li> <li>Click &quot;Next&quot;</li> <li>Select &quot;Yes, save these settings for this program&quot;</li> <li>Click &quot;Close&quot;</li> </ol> <p>If, when you open Visual Studio it asks to save changes to devenv.sln, see this answer to disable it:</p> <p><a href="https://stackoverflow.com/questions/13595999/disable-visual-studio-devenv-solution-save-dialog">Disable Visual Studio devenv solution save dialog</a></p> <hr /> <p>If you change your mind and wish to undo the &quot;Run As Administrator&quot; Compatibility setting, see the answer here: <a href="https://stackoverflow.com/a/41602199/741136">How to Fix Unrecognized Guid format in Visual Studio 2015 </a></p>
{ "question_id": 12257110, "question_date": "2012-09-04T05:07:37.353Z", "question_score": 1071, "tags": "visual-studio|windows-8|uac", "answer_id": 12859334, "answer_date": "2012-10-12T12:42:04.550Z", "answer_score": 2117 }
Please answer the following Stack Overflow question: Title: jQuery AJAX submit form <p>I have a form with name <code>orderproductForm</code> and an undefined number of inputs.</p> <p>I want to do some kind of jQuery.get or ajax or anything like that that would call a page through Ajax, and send along all the inputs of the form <code>orderproductForm</code>.</p> <p>I suppose one way would be to do something like</p> <pre><code>jQuery.get("myurl", {action : document.orderproductForm.action.value, cartproductid : document.orderproductForm.cartproductid.value, productid : document.orderproductForm.productid.value, ... </code></pre> <p>However I do not know exactly all the form inputs. Is there a feature, function or something that would just send ALL the form inputs?</p>
<p>You can use the ajaxForm/ajaxSubmit functions from <a href="https://jquery-form.github.io/form/" rel="noreferrer">Ajax Form Plugin</a> or the jQuery serialize function.</p> <p><strong>AjaxForm</strong>:</p> <pre><code>$("#theForm").ajaxForm({url: 'server.php', type: 'post'}) </code></pre> <p>or</p> <pre><code>$("#theForm").ajaxSubmit({url: 'server.php', type: 'post'}) </code></pre> <p>ajaxForm will send when the submit button is pressed. ajaxSubmit sends immediately.</p> <p><strong>Serialize</strong>:</p> <pre><code>$.get('server.php?' + $('#theForm').serialize()) $.post('server.php', $('#theForm').serialize()) </code></pre> <p><a href="http://docs.jquery.com/Ajax/serialize" rel="noreferrer">AJAX serialization documentation is here</a>.</p>
{ "question_id": 1960240, "question_date": "2009-12-25T01:31:48.877Z", "question_score": 1070, "tags": "javascript|jquery|ajax|submit|forms", "answer_id": 1960245, "answer_date": "2009-12-25T01:36:52.757Z", "answer_score": 864 }
Please answer the following Stack Overflow question: Title: Save PL/pgSQL output from PostgreSQL to a CSV file <p>What is the easiest way to save PL/pgSQL output from a PostgreSQL database to a CSV file? </p> <p>I'm using PostgreSQL 8.4 with pgAdmin III and PSQL plugin where I run queries from.</p>
<p>Do you want the resulting file on the server, or on the client?</p> <h1>Server side</h1> <p>If you want something easy to re-use or automate, you can use Postgresql's built in <a href="http://www.postgresql.org/docs/current/interactive/sql-copy.html" rel="noreferrer">COPY</a> command. e.g.</p> <pre><code>Copy (Select * From foo) To '/tmp/test.csv' With CSV DELIMITER ',' HEADER; </code></pre> <p><strong>This approach runs entirely on the remote server</strong> - it can't write to your local PC. It also needs to be run as a Postgres &quot;superuser&quot; (normally called &quot;root&quot;) because Postgres can't stop it doing nasty things with that machine's local filesystem.</p> <p>That doesn't actually mean you have to be connected as a superuser (automating that would be a security risk of a different kind), because you can use <a href="http://www.postgresql.org/docs/current/interactive/sql-createfunction.html" rel="noreferrer">the <code>SECURITY DEFINER</code> option to <code>CREATE FUNCTION</code></a> to make a function which <em>runs as though you were a superuser</em>.</p> <p>The crucial part is that your function is there to perform additional checks, not just by-pass the security - so you could write a function which exports the exact data you need, or you could write something which can accept various options as long as they meet a strict whitelist. You need to check two things:</p> <ol> <li>Which <strong>files</strong> should the user be allowed to read/write on disk? This might be a particular directory, for instance, and the filename might have to have a suitable prefix or extension.</li> <li>Which <strong>tables</strong> should the user be able to read/write in the database? This would normally be defined by <code>GRANT</code>s in the database, but the function is now running as a superuser, so tables which would normally be &quot;out of bounds&quot; will be fully accessible. You probably don’t want to let someone invoke your function and add rows on the end of your “users” table…</li> </ol> <p>I've written <a href="http://rwec.co.uk/q/pg-copy" rel="noreferrer">a blog post expanding on this approach</a>, including some examples of functions that export (or import) files and tables meeting strict conditions.</p> <hr /> <h1>Client side</h1> <p>The other approach is to <strong>do the file handling on the client side</strong>, i.e. in your application or script. The Postgres server doesn't need to know what file you're copying to, it just spits out the data and the client puts it somewhere.</p> <p>The underlying syntax for this is the <code>COPY TO STDOUT</code> command, and graphical tools like pgAdmin will wrap it for you in a nice dialog.</p> <p>The <strong><code>psql</code> command-line client</strong> has a special &quot;meta-command&quot; called <strong><code>\copy</code></strong>, which takes all the same options as the &quot;real&quot; <code>COPY</code>, but is run inside the client:</p> <pre><code>\copy (Select * From foo) To '/tmp/test.csv' With CSV DELIMITER ',' HEADER </code></pre> <p>Note that there is no terminating <code>;</code>, because meta-commands are terminated by newline, unlike SQL commands.</p> <p>From <a href="http://www.postgresql.org/docs/current/interactive/app-psql.html#APP-PSQL-META-COMMANDS-COPY" rel="noreferrer">the docs</a>:</p> <blockquote> <p>Do not confuse COPY with the psql instruction \copy. \copy invokes COPY FROM STDIN or COPY TO STDOUT, and then fetches/stores the data in a file accessible to the psql client. Thus, file accessibility and access rights depend on the client rather than the server when \copy is used.</p> </blockquote> <p>Your application programming language <em>may</em> also have support for pushing or fetching the data, but you cannot generally use <code>COPY FROM STDIN</code>/<code>TO STDOUT</code> within a standard SQL statement, because there is no way of connecting the input/output stream. PHP's PostgreSQL handler (<em>not</em> PDO) includes very basic <a href="http://www.php.net/manual/en/function.pg-copy-from.php" rel="noreferrer"><code>pg_copy_from</code></a> and <a href="http://www.php.net/manual/en/function.pg-copy-to.php" rel="noreferrer"><code>pg_copy_to</code></a> functions which copy to/from a PHP array, which may not be efficient for large data sets.</p>
{ "question_id": 1517635, "question_date": "2009-10-04T22:58:51.100Z", "question_score": 1069, "tags": "sql|postgresql|csv|postgresql-copy", "answer_id": 1517692, "answer_date": "2009-10-04T23:18:19.780Z", "answer_score": 1556 }
Please answer the following Stack Overflow question: Title: Android Studio: Add jar as library? <p>I'm trying to use the new Android Studio but I can't seem to get it working correctly.</p> <p>I'm using the <strong>Gson</strong> library to serialize/deserialize JSON-objects. But the library somehow isn't included in the build.</p> <p>I had created a new project with just a <strong>MainActivity</strong>. Copied <strong>gson-2.2.3.jar</strong> in the /libs folder and added it as a library dependancy(right click->Add as library). This includes the jar in android studio so it can be referenced from the source files.</p> <p>When I try to run the project it cannot compile so I added:</p> <pre><code>compile files('libs/gson-2.2.3.jar') </code></pre> <p>to the dependencies in de .gradle file. After that it compiles correctly but when running the application I get a <code>ClassDefNotFoundException</code>.</p> <p>Does anyone know what I'm doing wrong?</p>
<p>I've been struggling with the same thing for many hours, trying to get the Gson jar to work no less. I finally cracked it – here are the steps I took:</p> <ol> <li>Put the Gson jar (in my case, <code>gson-2.2.4.jar</code>) into the <code>libs</code> folder</li> <li>Right click it and hit 'Add as library'</li> <li><p>Ensure that <code>compile files('libs/gson-2.2.4.jar')</code> is in your <code>build.gradle</code> file (or <code>compile fileTree(dir: 'libs', include: '*.jar')</code> if you are using many jar files) </p> <p>Edit : Use <code>implementation files('libs/gson-2.2.4.jar')</code> (or <code>implementation fileTree(dir: 'libs', include: '*.jar')</code>) in Android Studio 3.0+</p></li> <li><p>Do a clean build (you can probably do this fine in Android Studio, but to make sure I navigated in a terminal to the root folder of my app and typed <code>gradlew clean</code>. I'm on Mac OS X, the command might be different on your system</p></li> </ol> <p>After I did the above four, it started working fine. I think the 'Add as library' step was the one I'd previously missed, and it didn't work until I cleaned it either.</p> <p>[Edit - added the <code>build.gradle</code> step which is also necessary as others have pointed out]</p>
{ "question_id": 16608135, "question_date": "2013-05-17T11:41:59.930Z", "question_score": 1068, "tags": "android|gradle|android-gradle-plugin|build.gradle|dependency-management", "answer_id": 16628496, "answer_date": "2013-05-18T20:08:54.180Z", "answer_score": 1552 }
Please answer the following Stack Overflow question: Title: push_back vs emplace_back <p>I'm a bit confused regarding the difference between <code>push_back</code> and <code>emplace_back</code>.</p> <pre><code>void emplace_back(Type&amp;&amp; _Val); void push_back(const Type&amp; _Val); void push_back(Type&amp;&amp; _Val); </code></pre> <p>As there is a <code>push_back</code> overload taking a rvalue reference I don't quite see what the purpose of <code>emplace_back</code> becomes?</p>
<p>In addition to what visitor said :</p> <p>The function <code>void emplace_back(Type&amp;&amp; _Val)</code> provided by MSCV10 is non conforming and redundant, because as you noted it is strictly equivalent to <code>push_back(Type&amp;&amp; _Val)</code>.</p> <p>But the real C++0x form of <code>emplace_back</code> is really useful: <a href="https://en.cppreference.com/w/cpp/container/vector/emplace_back" rel="noreferrer"><code>void emplace_back(Args&amp;&amp;...)</code></a>;</p> <p>Instead of taking a <code>value_type</code> it takes a variadic list of arguments, so that means that you can now perfectly forward the arguments and construct directly an object into a container without a temporary at all. </p> <p>That's useful because no matter how much cleverness RVO and move semantic bring to the table there is still complicated cases where a push_back is likely to make unnecessary copies (or move). For example, with the traditional <code>insert()</code> function of a <code>std::map</code>, you have to create a temporary, which will then be copied into a <code>std::pair&lt;Key, Value&gt;</code>, which will then be copied into the map : </p> <pre><code>std::map&lt;int, Complicated&gt; m; int anInt = 4; double aDouble = 5.0; std::string aString = "C++"; // cross your finger so that the optimizer is really good m.insert(std::make_pair(4, Complicated(anInt, aDouble, aString))); // should be easier for the optimizer m.emplace(4, anInt, aDouble, aString); </code></pre> <p>So why didn't they implement the right version of emplace_back in MSVC? Actually, it bugged me too a while ago, so I asked the same question on the <a href="https://docs.microsoft.com/archive/blogs/vcblog/visual-studio-2010-beta-2-is-now-available-for-download" rel="noreferrer">Visual C++ blog</a>. Here is the answer from Stephan T Lavavej, the official maintainer of the Visual C++ standard library implementation at Microsoft.</p> <blockquote> <p>Q: Are beta 2 emplace functions just some kind of placeholder right now?</p> <p>A: As you may know, variadic templates aren't implemented in VC10. We simulate them with preprocessor machinery for things like <code>make_shared&lt;T&gt;()</code>, tuple, and the new things in <code>&lt;functional&gt;</code>. This preprocessor machinery is relatively difficult to use and maintain. Also, it significantly affects compilation speed, as we have to repeatedly include subheaders. Due to a combination of our time constraints and compilation speed concerns, we haven't simulated variadic templates in our emplace functions.</p> <p>When variadic templates are implemented in the compiler, you can expect that we'll take advantage of them in the libraries, including in our emplace functions. We take conformance very seriously, but unfortunately, we can't do everything all at once.</p> </blockquote> <p>It's an understandable decision. Everyone who tried just once to emulate variadic template with preprocessor horrible tricks knows how disgusting this stuff gets. </p>
{ "question_id": 4303513, "question_date": "2010-11-29T12:04:09.360Z", "question_score": 1068, "tags": "c++|visual-studio-2010|stl|c++11|move-semantics", "answer_id": 4306581, "answer_date": "2010-11-29T18:00:28.900Z", "answer_score": 749 }
Please answer the following Stack Overflow question: Title: Detecting request type in PHP (GET, POST, PUT or DELETE) <p>How can I detect which request type was used (GET, POST, PUT or DELETE) in PHP?</p>
<p>By using</p> <pre><code>$_SERVER['REQUEST_METHOD'] </code></pre> <h3>Example</h3> <pre><code>if ($_SERVER['REQUEST_METHOD'] === 'POST') { // The request is using the POST method } </code></pre> <p>For more details please see the <a href="http://php.net/manual/en/reserved.variables.server.php" rel="noreferrer">documentation for the $_SERVER variable</a>.</p>
{ "question_id": 359047, "question_date": "2008-12-11T11:31:27.170Z", "question_score": 1068, "tags": "php|http|request", "answer_id": 359050, "answer_date": "2008-12-11T11:32:18.277Z", "answer_score": 1502 }
Please answer the following Stack Overflow question: Title: StringBuilder vs String concatenation in toString() in Java <p>Given the 2 <code>toString()</code> implementations below, which one is preferred:</p> <pre><code>public String toString(){ return "{a:"+ a + ", b:" + b + ", c: " + c +"}"; } </code></pre> <p>or</p> <pre><code>public String toString(){ StringBuilder sb = new StringBuilder(100); return sb.append("{a:").append(a) .append(", b:").append(b) .append(", c:").append(c) .append("}") .toString(); } </code></pre> <p>?</p> <p>More importantly, given we have only 3 properties it might not make a difference, but at what point would you switch from <code>+</code> concat to <code>StringBuilder</code>?</p>
<p>Version 1 is preferable because it is shorter and <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18.1" rel="noreferrer">the compiler will in fact turn it into version 2</a> - no performance difference whatsoever.</p> <blockquote> <p>More importantly given we have only 3 properties it might not make a difference, but at what point do you switch from concat to builder?</p> </blockquote> <p>At the point where you're concatenating in a loop - that's usually when the compiler can't substitute <code>StringBuilder</code> by itself.</p>
{ "question_id": 1532461, "question_date": "2009-10-07T15:44:08.690Z", "question_score": 1068, "tags": "java|performance|string|concatenation|stringbuilder", "answer_id": 1532499, "answer_date": "2009-10-07T15:51:05.743Z", "answer_score": 1094 }
Please answer the following Stack Overflow question: Title: Update Git submodule to latest commit on origin <p>I have a project with a Git submodule. It is from an ssh://... URL, and is on commit A. Commit B has been pushed to that URL, and I want the submodule to retrieve the commit, and change to it.</p> <p>Now, my understanding is that <code>git submodule update</code> should do this, but it doesn't. It doesn't do anything (no output, success exit code). Here's an example:</p> <pre><code>$ mkdir foo $ cd foo $ git init . Initialized empty Git repository in /.../foo/.git/ $ git submodule add ssh://user@host/git/mod mod Cloning into mod... user@host's password: hunter2 remote: Counting objects: 131, done. remote: Compressing objects: 100% (115/115), done. remote: Total 131 (delta 54), reused 0 (delta 0) Receiving objects: 100% (131/131), 16.16 KiB, done. Resolving deltas: 100% (54/54), done. $ git commit -m "Hello world." [master (root-commit) 565b235] Hello world. 2 files changed, 4 insertions(+), 0 deletions(-) create mode 100644 .gitmodules create mode 160000 mod # At this point, ssh://user@host/git/mod changes; submodule needs to change too. $ git submodule init Submodule 'mod' (ssh://user@host/git/mod) registered for path 'mod' $ git submodule update $ git submodule sync Synchronizing submodule url for 'mod' $ git submodule update $ man git-submodule $ git submodule update --rebase $ git submodule update $ echo $? 0 $ git status # On branch master nothing to commit (working directory clean) $ git submodule update mod $ ... </code></pre> <p>I've also tried <code>git fetch mod</code>, which appears to do a fetch (but can't possibly, because it's not prompting for a password!), but <code>git log</code> and <code>git show</code> deny the existence of new commits. Thus far I've just been <code>rm</code>-ing the module and re-adding it, but this is both wrong in principle and tedious in practice.</p>
<p>The <a href="http://git-scm.com/docs/git-submodule" rel="noreferrer"><code>git submodule update</code></a> command actually tells Git that you want your submodules to each check out the commit already specified in the index of the superproject. If you want to <em>update</em> your submodules to the latest commit available from their remote, you will need to do this directly in the submodules.</p> <p>So in summary:</p> <pre class="lang-sh prettyprint-override"><code># Get the submodule initially git submodule add ssh://bla submodule_dir git submodule init # Time passes, submodule upstream is updated # and you now want to update # Change to the submodule directory cd submodule_dir # Checkout desired branch git checkout master # Update git pull # Get back to your project root cd .. # Now the submodules are in the state you want, so git commit -am &quot;Pulled down update to submodule_dir&quot; </code></pre> <p>Or, if you're a busy person:</p> <pre><code>git submodule foreach git pull origin master </code></pre>
{ "question_id": 5828324, "question_date": "2011-04-29T05:41:46.727Z", "question_score": 1067, "tags": "git|git-submodules|git-pull", "answer_id": 5828396, "answer_date": "2011-04-29T05:50:56.800Z", "answer_score": 1788 }
Please answer the following Stack Overflow question: Title: Git: How do I list only local branches? <p><code>git branch -a</code> shows both remote and local branches.</p> <p><code>git branch -r</code> shows remote branches.</p> <p>Is there a way to list just the local branches?</p>
<p>Just <code>git branch</code> without options.</p> <p>From the <a href="http://manpages.ubuntu.com/manpages/precise/en/man1/git-branch.1.html" rel="noreferrer">manpage</a>:</p> <blockquote> <p>With no arguments, existing branches are listed and the current branch will be highlighted with an asterisk.</p> </blockquote>
{ "question_id": 12370714, "question_date": "2012-09-11T13:21:19.417Z", "question_score": 1067, "tags": "git|git-branch", "answer_id": 12370765, "answer_date": "2012-09-11T13:23:39.667Z", "answer_score": 1592 }
Please answer the following Stack Overflow question: Title: How to subtract a day from a date? <p>I have a Python <a href="https://docs.python.org/library/datetime.html#datetime-objects" rel="noreferrer"><code>datetime.datetime</code></a> object. What is the best way to subtract one day?</p>
<p>You can use a <a href="http://docs.python.org/library/datetime.html#timedelta-objects" rel="noreferrer"><code>timedelta</code></a> object:</p> <pre><code>from datetime import datetime, timedelta d = datetime.today() - timedelta(days=days_to_subtract) </code></pre>
{ "question_id": 441147, "question_date": "2009-01-13T22:39:36.473Z", "question_score": 1066, "tags": "python|datetime|date", "answer_id": 441152, "answer_date": "2009-01-13T22:41:39.213Z", "answer_score": 1803 }
Please answer the following Stack Overflow question: Title: What is JavaScript's highest integer value that a number can go to without losing precision? <p>Is this defined by the language? Is there a defined maximum? Is it different in different browsers?</p>
<p>JavaScript has two number types: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number" rel="noreferrer"><code>Number</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Glossary/BigInt" rel="noreferrer"><code>BigInt</code></a>. </p> <p>The most frequently-used number type, <code>Number</code>, is a 64-bit floating point <a href="https://en.wikipedia.org/wiki/IEEE_754" rel="noreferrer">IEEE 754</a> number. </p> <p>The largest exact integral value of this type is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER" rel="noreferrer"><code>Number.MAX_SAFE_INTEGER</code></a>, which is:</p> <ul> <li>2<sup>53</sup>-1, or </li> <li>+/- 9,007,199,254,740,991, or</li> <li>nine quadrillion seven trillion one hundred ninety-nine billion two hundred fifty-four million seven hundred forty thousand nine hundred ninety-one </li> </ul> <p>To put this in perspective: one quadrillion bytes is a petabyte (or one thousand terabytes).</p> <p>"Safe" in this context refers to the ability to represent integers exactly and to correctly compare them.</p> <p><a href="https://www.ecma-international.org/ecma-262/10.0/index.html#sec-ecmascript-language-types-number-type" rel="noreferrer">From the spec:</a></p> <blockquote> <p>Note that all the positive and negative integers whose magnitude is no greater than 2<sup>53</sup> are representable in the <code>Number</code> type (indeed, the integer 0 has two representations, +0 and -0).</p> </blockquote> <p>To safely use integers larger than this, you need to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" rel="noreferrer"><code>BigInt</code></a>, which has no upper bound. </p> <p>Note that the bitwise operators and shift operators operate on 32-bit integers, so in that case, the max safe integer is 2<sup>31</sup>-1, or 2,147,483,647. </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 log = console.log var x = 9007199254740992 var y = -x log(x == x + 1) // true ! log(y == y - 1) // also true ! // Arithmetic operators work, but bitwise/shifts only operate on int32: log(x / 2) // 4503599627370496 log(x &gt;&gt; 1) // 0 log(x | 1) // 1</code></pre> </div> </div> </p> <hr> <p>Technical note on the subject of the number 9,007,199,254,740,992: There is an exact IEEE-754 representation of this value, and you can assign and read this value from a variable, so for <em>very carefully</em> chosen applications in the domain of integers less than or equal to this value, you could treat this as a maximum value.</p> <p>In the general case, you must treat this IEEE-754 value as inexact, because it is ambiguous whether it is encoding the logical value 9,007,199,254,740,992 or 9,007,199,254,740,993. </p>
{ "question_id": 307179, "question_date": "2008-11-20T22:47:54.100Z", "question_score": 1065, "tags": "javascript|math|browser|cross-browser", "answer_id": 307200, "answer_date": "2008-11-20T22:53:40.780Z", "answer_score": 955 }
Please answer the following Stack Overflow question: Title: How to replace local branch with remote branch entirely in Git? <p>I have two branches:</p> <ol> <li>local branch (the one which I work with)</li> <li>remote branch (public, only well-tested commits go there)</li> </ol> <p>Recently I seriously messed up my local branch.</p> <p>How would I replace the local branch entirely with the remote one, so I can continue my work from where the remote branch is now?</p> <p>I have already searched SO and checking out to the remote branch locally does not have any effect.</p>
<ol> <li>Make sure you've checked out the branch you're replacing (from Zoltán's <a href="https://stackoverflow.com/questions/9210446/replace-local-branch-with-remote-branch-entirely#comment64191505_9210705">comment</a>).</li> <li><p>Assuming that master is the local branch you're replacing, and that "origin/master" is the remote branch you want to reset to:</p> <pre><code>git reset --hard origin/master </code></pre></li> </ol> <p>This updates your local HEAD branch to be the same revision as origin/master, and <code>--hard</code> will sync this change into the index and workspace as well.</p>
{ "question_id": 9210446, "question_date": "2012-02-09T11:59:28.320Z", "question_score": 1065, "tags": "git", "answer_id": 9210705, "answer_date": "2012-02-09T12:19:20.483Z", "answer_score": 1730 }
Please answer the following Stack Overflow question: Title: How to "comment-out" (add comment) in a batch/cmd? <p>I have a batch file that runs several python scripts that do table modifications. </p> <ol> <li><p>I want to have users comment out the 1-2 python scripts that they don't want to run, rather than removing them from the batch file (so the next user knows these scripts exist as options!)</p></li> <li><p>I also want to add comments to bring to their attention specifically the variables they need to update in the Batch file before they run it. I see that I can use <code>REM</code>. But it looks like that's more for updating the user with progress after they've run it. </p></li> </ol> <p>Is there a syntax for more appropriately adding a comment?</p>
<p>The <code>rem</code> command is indeed for comments. It doesn't inherently update anyone after running the script. Some script authors might use it that way instead of <code>echo</code>, though, because by default the batch interpreter will <em>print out</em> each command before it's processed. Since <code>rem</code> commands don't do anything, it's safe to print them without side effects. To avoid printing a command, prefix it with <code>@</code>, or, to apply that setting throughout the program, run <code>@echo off</code>. (It's <code>echo off</code> to avoid printing further commands; the <code>@</code> is to avoid printing <em>that</em> command prior to the echo setting taking effect.)</p> <p>So, in your batch file, you might use this:</p> <pre><code>@echo off REM To skip the following Python commands, put "REM" before them: python foo.py python bar.py </code></pre>
{ "question_id": 11269338, "question_date": "2012-06-29T21:40:58.793Z", "question_score": 1064, "tags": "batch-file|cmd|comments|comment-conventions", "answer_id": 11269427, "answer_date": "2012-06-29T21:49:47.633Z", "answer_score": 977 }
Please answer the following Stack Overflow question: Title: Switch statement for multiple cases in JavaScript <p>I need multiple cases in switch statement in JavaScript, Something like:</p> <pre><code>switch (varName) { case &quot;afshin&quot;, &quot;saeed&quot;, &quot;larry&quot;: alert('Hey'); break; default: alert('Default case'); break; } </code></pre> <p>How can I do that? If there's no way to do something like that in JavaScript, I want to know an alternative solution that also follows the <a href="http://c2.com/cgi/wiki?DontRepeatYourself" rel="noreferrer">DRY concept</a>.</p>
<p>Use the fall-through feature of the <code>switch</code> statement. A matched case will run until a <code>break</code> (or the end of the <code>switch</code> statement) is found, so you could write it like:</p> <pre><code>switch (varName) { case &quot;afshin&quot;: case &quot;saeed&quot;: case &quot;larry&quot;: alert('Hey'); break; default: alert('Default case'); } </code></pre>
{ "question_id": 13207927, "question_date": "2012-11-03T09:43:09.950Z", "question_score": 1064, "tags": "javascript|switch-statement", "answer_id": 13207939, "answer_date": "2012-11-03T09:44:45.347Z", "answer_score": 2163 }