input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Java abstract interface <p>Consider an example (which compiles in java)</p> <pre><code>public abstract interface Interface { public void interfacing(); public abstract boolean interfacing(boolean really); } </code></pre> <p>Why is it necessary for an interface to be "declared" abstract? Is there other rules that applies with an abstract interface?</p> <hr> <p>Finally: If <code>abstract</code> is obsolete, why is it included in Java? Is there a history for abstract interface?</p>
<blockquote> <p>Why is it necessary for an interface to be "declared" abstract?</p> </blockquote> <p>It's not.</p> <pre><code>public abstract interface Interface { \___.__/ | '----&gt; Neither this... public void interfacing(); public abstract boolean interfacing(boolean really); \___.__/ | '----&gt; nor this, are necessary. } </code></pre> <p>Interfaces and their methods are implicitly <code>abstract</code> and adding that modifier makes no difference.</p> <blockquote> <p>Is there other rules that applies with an abstract interface?</p> </blockquote> <p>No, same rules apply. The method must be implemented by any (concrete) implementing class.</p> <blockquote> <p>If abstract is obsolete, why is it included in Java? Is there a history for abstract interface?</p> </blockquote> <p>Interesting question. I dug up the <em>first</em> edition of JLS, and even there it says <a href="http://web.archive.org/web/20091123225637/http://java.sun.com/docs/books/jls/first_edition/html/9.doc.html#30820" rel="noreferrer"><em>"This modifier is obsolete and should not be used in new Java programs"</em></a>.</p> <p>Okay, <strong>digging even further</strong>... After hitting numerous broken links, I managed to find a copy of the original <a href="http://en.wikipedia.org/wiki/Oak_%28programming_language%29" rel="noreferrer">Oak 0.2</a> <a href="http://aioo.be/mirrored/OakSpec0.2.pdf" rel="noreferrer">Specification</a> (or "manual"). Quite interesting read I must say, and only 38 pages in total! :-)</p> <p>Under Section 5, Interfaces, it provides the following example:</p> <pre><code>public interface Storing { void freezeDry(Stream s) = 0; void reconstitute(Stream s) = 0; } </code></pre> <p>And in the margin it says</p> <blockquote> <p><em>In the future, the " =0" part of declaring methods in interfaces may go away.</em></p> </blockquote> <p>Assuming <code>=0</code> got replaced by the <code>abstract</code> keyword, I suspect that <code>abstract</code> was at some point mandatory for interface methods!</p> <hr> <p>Related article: <a href="http://programming.guide/java/abstract-interface.html" rel="noreferrer">Java: Abstract interfaces and abstract interface methods</a></p>
{ "question_id": 7202616, "question_date": "2011-08-26T09:23:38.517Z", "question_score": 214, "tags": "java|interface|abstract", "answer_id": 7202659, "answer_date": "2011-08-26T09:26:58.847Z", "answer_score": 469 }
Please answer the following Stack Overflow question: Title: How do I uninstall a Service Worker? <p>After deleting <code>/serviceworker.js</code> from my root directory, Chrome still runs the service worker that I removed from my webroot. How do I uninstall the service worker from my website and Chrome so I can log back into my website?</p> <p>I've tracked the issue down to Service Work's cache mechanism and I just want to remove for now until I have time to debug it. The login script that I'm using redirects to Google's servers for them to login to their Google account. But all I get from the login.php page is an <code>ERR_FAILED</code> message. </p>
<h1>Removing Service Workers Programmatically</h1> <p>You can remove service workers programmatically like this:</p> <pre><code>navigator.serviceWorker.getRegistrations().then(function(registrations) { for(let registration of registrations) { registration.unregister() } }) </code></pre> <p>Docs: <a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/getRegistrations" rel="noreferrer">getRegistrations</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/unregister" rel="noreferrer">unregister</a></p> <h1>Removing Service Workers Through The User Interface</h1> <p>You can also remove service workers under the Application tab in Chrome Devtools.</p>
{ "question_id": 33704791, "question_date": "2015-11-14T03:28:31.127Z", "question_score": 214, "tags": "html|google-chrome|service-worker", "answer_id": 33705250, "answer_date": "2015-11-14T04:55:02.340Z", "answer_score": 412 }
Please answer the following Stack Overflow question: Title: What does it mean to squash commits in git? <p>What does Squashing commits in git mean. How do I squash commits in Github?</p> <p>I'm new to Git and I requested to be assigned to a newcomer bug in coala-analyzer. I fixed the bug, and now I was asked to squash my commits. How do I do it? </p>
<p>You can think of Git as an advanced database of snapshots of your working directory(ies). </p> <p>One very nice feature of Git is the ability to rewrite the history of commits.<br> The principal reason for doing this is that a lot of such history is relevant only for the developer who generated it, so it must be simplified, or made more nice, before submitting it to a shared repository.</p> <p><strong>Squashing a commit</strong> means, from an idiomatic point of view, to move the changes introduced in said commit into its parent so that you end up with one commit instead of two (or more).<br> If you repeat this process multiple times, you can reduce <em>n</em> commit to a single one. </p> <p>Visually, if you started your work at the commit tagged <em>Start</em>, you want this</p> <p><a href="https://i.stack.imgur.com/sShta.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sShta.png" alt="Git commits squashing"></a></p> <p>You may notice that the new commit has a slightly darker shade of blue. This is intentional.</p> <p>In Git squashing is achieved with a <em>Rebase</em>, of a special form called <em>Interactive Rebase</em>.<br> Simplifying when you rebase a set of commits into a branch <em>B</em>, you apply all the changes introduced by those commits as they were done, starting from <em>B</em> instead of their original ancestor.</p> <p>A visual clue</p> <p><a href="https://i.stack.imgur.com/CAHMp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CAHMp.png" alt="enter image description here"></a> </p> <p>Note again the different shades of blue.</p> <p>An interactive rebase let you choose how commits should be rebased. If you run this command:</p> <pre><code> git rebase -i branch </code></pre> <p>You would end up with a file that lists the commits that will be rebased</p> <pre><code> pick ae3... pick ef6... pick 1e0... pick 341... </code></pre> <p>I didn't name the commits, but these four ones are intended to be the commits from <em>Start</em> to <em>Head</em></p> <p>The nice thing about this list is that <strong>it is editable</strong>.<br> You can omit commits, or you can <strong>squash them</strong>.<br> All you have to do is to change the first word to <em>squash</em>.</p> <pre><code> pick ae3... squash ef6... squash 1e0... squash 341... </code></pre> <p>If you close the editor and no merge conflicts are found, you end up with this history:</p> <p><a href="https://i.stack.imgur.com/2LiYf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2LiYf.png" alt="enter image description here"></a></p> <p>In your case, you don't want to rebase into another branch, but rather into a previous commit.<br> In order to transform the history as shown in the very first example, you have to run something like</p> <pre><code>git rebase -i HEAD~4 </code></pre> <p>change the "commands" to <em>squash</em> for all the commits apart from the first one, and then close your editor.</p> <hr> <p><strong>Note about altering history</strong></p> <p>In Git, commits are never edited. They can be pruned, made not reachable, cloned but not changed.<br> When you rebase, you are actually creating new commits.<br> The old ones are not longer reachable by any refs, so are not shown in the history but they are still there! </p> <p>This is what you actually get for a rebase:</p> <p><a href="https://i.stack.imgur.com/fszS3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fszS3.png" alt="enter image description here"></a></p> <p>If you have already pushed them somewhere, rewriting the history will actually make a branch!</p>
{ "question_id": 35703556, "question_date": "2016-02-29T15:40:26.780Z", "question_score": 214, "tags": "git|github", "answer_id": 35704829, "answer_date": "2016-02-29T16:42:38.877Z", "answer_score": 321 }
Please answer the following Stack Overflow question: Title: How to escape curly-brackets in f-strings? <p>I have a string in which I would like curly-brackets, but also take advantage of the f-strings feature. Is there some syntax that works for this?</p> <p>Here are two ways it does not work. I would like to include the literal text <code>{bar}</code> as part of the string.</p> <pre><code>foo = &quot;test&quot; fstring = f&quot;{foo} {bar}&quot; </code></pre> <p><code>NameError: name 'bar' is not defined</code></p> <pre><code>fstring = f&quot;{foo} \{bar\}&quot; </code></pre> <p><code>SyntaxError: f-string expression part cannot include a backslash</code></p> <p>Desired result:</p> <pre><code>'test {bar}' </code></pre> <p>Edit: Looks like this question has the same answer as <a href="https://stackoverflow.com/questions/5466451/how-can-i-print-literal-curly-brace-characters-in-python-string-and-also-use-fo">How can I print literal curly-brace characters in a string and also use .format on it?</a>, but you can only know that if you know that <code>str.format</code> uses the same rules as the f-string. So hopefully this question has value in tying f-string searchers to this answer.</p>
<p>Although there is a custom syntax error from the parser, the <a href="https://stackoverflow.com/q/5466451/674039">same trick</a> works as for calling <code>.format</code> on regular strings. </p> <p>Use double curlies:</p> <pre><code>&gt;&gt;&gt; foo = 'test' &gt;&gt;&gt; f'{foo} {{bar}}' 'test {bar}' </code></pre> <p>It's mentioned in the spec <a href="https://www.python.org/dev/peps/pep-0498/#specification" rel="noreferrer">here</a> and the docs <a href="https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals" rel="noreferrer">here</a>.</p>
{ "question_id": 42521230, "question_date": "2017-03-01T00:35:10.363Z", "question_score": 214, "tags": "python|python-3.x|curly-braces|f-string", "answer_id": 42521252, "answer_date": "2017-03-01T00:37:00.887Z", "answer_score": 328 }
Please answer the following Stack Overflow question: Title: An expression tree may not contain a call or invocation that uses optional arguments <blockquote> <p>An expression tree may not contain a call or invocation that uses optional arguments</p> </blockquote> <pre><code>return this.RedirectToAction&lt;MerchantController&gt;(x =&gt; x.Edit(merchantId)); </code></pre> <p>Where edit had a second, nullable argument.</p> <p>Why is this?</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.call.aspx" rel="noreferrer">underlying expression tree API</a> does not support optional arguments.</p> <p>For IL-compiled code the C# compiler inserts the default values at compile time (hard-coded), because the CLR does not support calling methods with optional arguments either when the arguments are not provided explicitly.</p>
{ "question_id": 12413583, "question_date": "2012-09-13T19:39:19.910Z", "question_score": 214, "tags": "c#|asp.net-mvc-3", "answer_id": 12413809, "answer_date": "2012-09-13T19:55:02.190Z", "answer_score": 141 }
Please answer the following Stack Overflow question: Title: GraphViz - How to connect subgraphs? <p>In the <code>DOT</code> language for <code>GraphViz</code>, I'm trying to represent a dependency diagram. I need to be able to have nodes inside a container and to be able to make nodes and/or containers dependent on other nodes and/or containers.</p> <p>I'm using <code>subgraph</code> to represent my containers. Node linking works just fine, but I can't figure out how to connect subgraphs.</p> <p>Given the program below, I need to be able to connect <code>cluster_1</code> and <code>cluster_2</code> with an arrow, but anything I've tried creates new nodes instead of connecting the clusters:</p> <pre><code>digraph G { graph [fontsize=10 fontname="Verdana"]; node [shape=record fontsize=10 fontname="Verdana"]; subgraph cluster_0 { node [style=filled]; "Item 1" "Item 2"; label = "Container A"; color=blue; } subgraph cluster_1 { node [style=filled]; "Item 3" "Item 4"; label = "Container B"; color=blue; } subgraph cluster_2 { node [style=filled]; "Item 5" "Item 6"; label = "Container C"; color=blue; } // Renders fine "Item 1" -&gt; "Item 2"; "Item 2" -&gt; "Item 3"; // Both of these create new nodes cluster_1 -&gt; cluster_2; "Container A" -&gt; "Container C"; } </code></pre> <p><img src="https://i.stack.imgur.com/TvSPM.png" alt="enter image description here"></p>
<p>The DOT user manual gives the following example of a graph with clusters with edges between clusters:</p> <blockquote> <p>IMPORTANT: The initial <code>compound=true</code> statement is required.</p> </blockquote> <pre><code>digraph G { compound=true; subgraph cluster0 { a -&gt; b; a -&gt; c; b -&gt; d; c -&gt; d; } subgraph cluster1 { e -&gt; g; e -&gt; f; } b -&gt; f [lhead=cluster1]; d -&gt; e; c -&gt; g [ltail=cluster0,lhead=cluster1]; c -&gt; e [ltail=cluster0]; d -&gt; h; } </code></pre> <p>... and edges between nodes and clusters:</p> <p><img src="https://i.stack.imgur.com/Ka0t2.png" alt="enter image description here"></p>
{ "question_id": 2012036, "question_date": "2010-01-06T09:45:42.123Z", "question_score": 214, "tags": "graphics|graphviz|dot|directed-graph|subgraph", "answer_id": 2012106, "answer_date": "2010-01-06T10:03:29.590Z", "answer_score": 250 }
Please answer the following Stack Overflow question: Title: Why is the <center> tag deprecated in HTML? <p>I am just curious as to why the <code>&lt;center&gt;</code> tag in HTML was deprecated.</p> <p>The <code>&lt;center&gt;</code> was a simple way of quickly center-aligning blocks of text and images by encapsulating the container in a <code>&lt;center&gt;</code> tag, and I really cannot find any simpler way on how to do it now.</p> <p>Anyone know of any simple way on how to center "stuff" (not the <code>margin-left:auto; margin-right:auto;</code> and width thing), something that replaces <code>&lt;center&gt;</code> ? And also, why was it deprecated?</p>
<p>The <code>&lt;center&gt;</code> element was deprecated because it defines the <em>presentation</em> of its contents — it does not describe its contents.</p> <p>One method of centering is to set the <code>margin-left</code> and <code>margin-right</code> properties of the element to <code>auto</code>, and then set the parent element’s <code>text-align</code> property to <code>center</code>. This guarantees that the element will be centered in all modern browsers.</p>
{ "question_id": 1798817, "question_date": "2009-11-25T18:00:48.530Z", "question_score": 214, "tags": "html|tags|center|deprecated", "answer_id": 1798853, "answer_date": "2009-11-25T18:06:21.993Z", "answer_score": 246 }
Please answer the following Stack Overflow question: Title: How to check if NSString begins with a certain character <p>How do you check if an NSString begins with a certain character (the character *).</p> <p>The * is an indicator for the type of the cell, so I need the contents of this NSString without the *, but need to know if the * exists.</p>
<p>You can use the <code>-hasPrefix:</code> method of <code>NSString</code>:</p> <p><strong>Objective-C:</strong></p> <pre class="lang-c prettyprint-override"><code>NSString* output = nil; if([string hasPrefix:@"*"]) { output = [string substringFromIndex:1]; } </code></pre> <p><strong>Swift:</strong></p> <pre><code>var output:String? if string.hasPrefix("*") { output = string.substringFromIndex(string.startIndex.advancedBy(1)) } </code></pre>
{ "question_id": 2503436, "question_date": "2010-03-23T20:39:59.260Z", "question_score": 214, "tags": "objective-c|nsstring", "answer_id": 2503754, "answer_date": "2010-03-23T21:26:11.420Z", "answer_score": 468 }
Please answer the following Stack Overflow question: Title: How to test a merge without actually merging first <p>Is there any way of simulating a <code>git merge</code> between two branches, the current working branch and the master, but without making any changes?</p> <p>I often have conflicts when I have to make a <code>git merge</code>. Is there any way of simulating the merge first?</p>
<p>I don't think there is a way of simulating what will happen until you try the merge. However, if you make sure that the output of <code>git status</code> is empty before you do the merge, it is quite safe to just go ahead and try it. If you get conflicts, you can immediately get back to the state you were at before with:</p> <pre><code>git reset --merge </code></pre> <p>Since git 1.7.4, you can also abort the merge by doing:</p> <pre><code>git merge --abort </code></pre> <p>(As <a href="https://github.com/git/git/commit/35d2fffdb8">the commit message that added that option explains</a>, this was added for consistency with <code>git rebase --abort</code> and so on.)</p>
{ "question_id": 7484199, "question_date": "2011-09-20T11:12:46.303Z", "question_score": 214, "tags": "git|merge", "answer_id": 7484246, "answer_date": "2011-09-20T11:16:44.777Z", "answer_score": 171 }
Please answer the following Stack Overflow question: Title: "No such module" when using @testable in Xcode Unit tests <p>I recently updated to Xcode 7 beta 5. I tried adding a unit test to an earlier project, but I am getting the error message "No such module [myModuleName]" on the <code>@testable import myModuleName</code> line.</p> <p><a href="https://i.stack.imgur.com/6jloe.png"><img src="https://i.stack.imgur.com/6jloe.png" alt="enter image description here"></a></p> <p>I tried</p> <ul> <li>cleaning the project with <kbd>Option</kbd> Clean Build Folder</li> <li>checking that "Enable Testability" (debug) was set to Yes in the Build Options</li> <li>deleting the tests target and then re-adding the iOS Unit testing bundle </li> </ul> <p>None of this worked for this project (but I have gotten testing to work in another project). Has anyone else had this problem and solved it?</p>
<p><strong>The answer that worked for me</strong></p> <p>The answer was that I had some errors in my project that was making the build fail. (It was just your standard every day bug in the code.) After I fixed the errors and did another clean and build, it worked.</p> <p>Note that these errors didn't show up at first. To get them to show up:</p> <ul> <li>Comment out your entire Test file that is giving you the "No such module" error.</li> <li>Try to run your project again.</li> </ul> <p>If there are other errors, they should show up now. Fix them and then uncomment your Test file code. The "No such module" error was gone for me.</p> <hr> <p>In case this doesn't solve the problem for other people, you can also try the following:</p> <p><strong>Clean the build folder</strong></p> <p>Open the Product menu, hold down <kbd>Option</kbd>, and click "Clean Build Folder..." </p> <p><a href="https://i.stack.imgur.com/BQQ2G.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BQQ2G.png" alt="enter image description here"></a></p> <p><strong>Make sure that Enable Testability is set to Yes</strong></p> <p>In the Project Navigator click your project name. Select Build Settings and scroll down to Build Options. Make sure that Enable Testability is Yes (for debug).</p> <p><a href="https://i.stack.imgur.com/bS26k.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bS26k.png" alt="enter image description here"></a></p> <p><strong>Delete and re-add your Tests target</strong></p> <p>If you have done the other things my guess is that you probably don't need to do this. But if you do, <strong><a href="https://stackoverflow.com/questions/32008403/no-such-module-when-using-testable-in-xcode-unit-tests/32009368#comment53906865_32009368">remember to save any Unit Tests that you have already written.</a></strong></p> <p>Click your project name in the Project Navigator. Then select your Tests target. Click the minus (-) button at the bottom to delete it.</p> <p><a href="https://i.stack.imgur.com/pW3x5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pW3x5.png" alt="enter image description here"></a></p> <p>Then click the plus (+) button and choose iOS Unit Testing Bundle to add it back again. As you can see, you can also add a UI Testing Bundle in the same way.</p> <p><strong>A few other ideas</strong></p> <ul> <li>Make sure that all required classes are members of your test target.</li> <li>Make sure that you have added all the required libraries.</li> <li>Make sure that the module name is written correctly (see <a href="https://stackoverflow.com/a/32844977/3681880">this answer</a>).</li> </ul> <p><strong>Or...</strong></p> <p>Leave a comment or answer below if you found something else that worked.</p> <p><strong>Related</strong></p> <ul> <li><a href="https://stackoverflow.com/a/31570612/3681880">How to do a Unit Test in Xcode</a></li> <li><a href="https://stackoverflow.com/questions/31600777/xcode-ui-test-example">Xcode UI Test example</a></li> </ul>
{ "question_id": 32008403, "question_date": "2015-08-14T10:56:30.837Z", "question_score": 214, "tags": "xcode|unit-testing|xctest", "answer_id": 32009368, "answer_date": "2015-08-14T11:49:11.303Z", "answer_score": 132 }
Please answer the following Stack Overflow question: Title: is it possible to select EXISTS directly as a bit? <p>I was wondering if it's possible to do something like this (which doesn't work): </p> <p><code>select cast( (exists(select * from theTable where theColumn like 'theValue%') as bit)</code></p> <p>Seems like it should be doable, but lots of things that should work in SQL don't ;) I've seen workarounds for this (SELECT 1 where... Exists...) but it seems like I should be able to just cast the result of the exists function as a bit and be done with it.</p>
<p>No, you'll have to use a workaround. </p> <p>If you must return a conditional bit 0/1 another way is to:</p> <pre><code>SELECT CAST( CASE WHEN EXISTS(SELECT * FROM theTable where theColumn like 'theValue%') THEN 1 ELSE 0 END AS BIT) </code></pre> <p>Or without the cast:</p> <pre><code>SELECT CASE WHEN EXISTS( SELECT 1 FROM theTable WHERE theColumn LIKE 'theValue%' ) THEN 1 ELSE 0 END </code></pre>
{ "question_id": 2759756, "question_date": "2010-05-03T17:03:40.040Z", "question_score": 214, "tags": "sql|sql-server|tsql", "answer_id": 2760065, "answer_date": "2010-05-03T17:53:56.560Z", "answer_score": 306 }
Please answer the following Stack Overflow question: Title: What is the Swift equivalent of respondsToSelector? <p>I've googled but not been able to find out what the swift equivalent to <code>respondsToSelector:</code> is.</p> <p>This is the only thing I could find (<a href="https://stackoverflow.com/questions/24142906/swift-alternative-to-respondstoselector">Swift alternative to respondsToSelector:</a>) but isn't too relevant in my case as its checking the existence of the delegate, I don't have a delegate I just want to check if a new API exists or not when running on the device and if not fall back to a previous version of the api.</p>
<p>As mentioned, in Swift <strong>most of the time you can achieve what you need with the <code>?</code> optional unwrapper operator</strong>. This allows you to call a method on an object if and only if the object exists (not <code>nil</code>) and the method is implemented.</p> <p>In the case where you still need <code>respondsToSelector:</code>, it is still there as part of the <code>NSObject</code> protocol.</p> <p>If you are calling <code>respondsToSelector:</code> on an Obj-C type in Swift, then it works the same as you would expect. If you are using it on your own Swift class, you will need to ensure your class derives from <code>NSObject</code>.</p> <p>Here's an example of a Swift class that you can check if it responds to a selector:</p> <pre><code>class Worker : NSObject { func work() { } func eat(food: AnyObject) { } func sleep(hours: Int, minutes: Int) { } } let worker = Worker() let canWork = worker.respondsToSelector(Selector("work")) // true let canEat = worker.respondsToSelector(Selector("eat:")) // true let canSleep = worker.respondsToSelector(Selector("sleep:minutes:")) // true let canQuit = worker.respondsToSelector(Selector("quit")) // false </code></pre> <p>It is important that you do not leave out the parameter names. In this example, <code>Selector("sleep::")</code> is <strong>not</strong> the same as <code>Selector("sleep:minutes:")</code>.</p>
{ "question_id": 24167791, "question_date": "2014-06-11T16:16:13.533Z", "question_score": 214, "tags": "objective-c|swift|selector", "answer_id": 24168825, "answer_date": "2014-06-11T17:16:54.783Z", "answer_score": 181 }
Please answer the following Stack Overflow question: Title: What is Domain Driven Design? <p>Can somebody please explain (in succinct terms) what exactly is domain driven design? I see the term quite a lot but really don't understand what it is or what it looks like. How does it differ from non-domain driven design?</p> <p>Also, can somebody explain what a Domain Object is? How does domain differ from normal objects?</p>
<p>EDIT:</p> <p>As this seem to be a top result on Google and my answer below is not, please refer to this much better answer:</p> <p><a href="https://stackoverflow.com/a/1222488/1240557">https://stackoverflow.com/a/1222488/1240557</a></p> <p>OLD ANSWER (not so complete :))</p> <blockquote> <p>In order to create good software, you have to know what that software is all about. You cannot create a banking software system unless you have a good understanding of what banking is all about, one must understand the domain of banking.</p> </blockquote> <p>From: Domain Driven Design by Eric Evans.</p> <p>This book does a pretty good job of describing DDD.</p> <p><a href="http://www.infoq.com/minibooks/domain-driven-design-quickly" rel="noreferrer">Register to download a summary of the book</a>, or <a href="http://ddd-cqrs-base-project.googlecode.com/files/DomainDrivenDesignQuicklyOnline.pdf" rel="noreferrer">download the summary directly</a>.</p>
{ "question_id": 5325836, "question_date": "2011-03-16T13:15:44.463Z", "question_score": 214, "tags": "domain-driven-design", "answer_id": 5325943, "answer_date": "2011-03-16T13:24:30.843Z", "answer_score": 117 }
Please answer the following Stack Overflow question: Title: Algorithm to implement a word cloud like Wordle <h2>Context</h2> <ul> <li>Take a look at Wordle: <a href="http://www.wordle.net/" rel="noreferrer">http://www.wordle.net/</a></li> <li>It's much better looking than any other word cloud generators I've seen</li> <li>Note: the source is not available - read the FAQ: <a href="http://www.wordle.net/faq#code" rel="noreferrer">http://www.wordle.net/faq#code</a></li> </ul> <h2>My Questions</h2> <ul> <li>Is there an algorithm available that does what Wordle does?</li> <li>If no, what are some alternatives that produces similar kinds of output?</li> </ul> <h2>Why I'm asking</h2> <ul> <li>just curious</li> <li>want to learn</li> </ul>
<p>I'm the creator of Wordle. Here's how Wordle actually works:</p> <p>Count the words, throw away boring words, and sort by the count, descending. Keep the top N words for some N. Assign each word a font size proportional to its count. Generate a Java2D Shape for each word, using the Java2D API.</p> <p>Each word "wants" to be somewhere, such as "at some random x position in the vertical center". In decreasing order of frequency, do this for each word:</p> <pre><code>place the word where it wants to be while it intersects any of the previously placed words move it one step along an ever-increasing spiral </code></pre> <p>That's it. The <strong>hard</strong> part is in doing the intersection-testing efficiently, for which I use last-hit caching, hierarchical bounding boxes, and a quadtree spatial index (all of which are things you can learn more about with some diligent googling).</p> <p>Edit: As Reto Aebersold pointed out, there's now a book chapter, freely available, that covers this same territory: <a href="http://static.mrfeinberg.com/bv_ch03.pdf" rel="noreferrer">Beautiful Visualization, Chapter 3: Wordle</a></p>
{ "question_id": 342687, "question_date": "2008-12-05T01:50:23.573Z", "question_score": 214, "tags": "layout|fonts|typography|tag-cloud|wordle-word-cloud", "answer_id": 1478314, "answer_date": "2009-09-25T16:33:41.170Z", "answer_score": 508 }
Please answer the following Stack Overflow question: Title: Android: allow portrait and landscape for tablets, but force portrait on phone? <p>I would like tablets to be able to display in portrait and landscape (sw600dp or greater), but phones to be restricted to portrait only. I can't find any way to conditionally choose an orientation. Any suggestions?</p>
<p>Here's a good way using <a href="http://developer.android.com/guide/topics/resources/more-resources.html#Bool" rel="noreferrer">resources</a> and <a href="http://developer.android.com/guide/practices/screens_support.html#NewQualifiers" rel="noreferrer">size qualifiers</a>.</p> <p>Put this bool resource in res/values as bools.xml or whatever (file names don't matter here):</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;bool name="portrait_only"&gt;true&lt;/bool&gt; &lt;/resources&gt; </code></pre> <p>Put this one in res/values-sw600dp and res/values-xlarge:</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;bool name="portrait_only"&gt;false&lt;/bool&gt; &lt;/resources&gt; </code></pre> <p>See <a href="https://stackoverflow.com/a/39302787">this supplemental answer</a> for help adding these directories and files in Android Studio.</p> <p>Then, in the onCreate method of your Activities you can do this:</p> <pre><code> if(getResources().getBoolean(R.bool.portrait_only)){ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } </code></pre> <p>Devices that are more than 600 dp in the smallest width direction, or x-large on pre-Android 3.2 devices (tablets, basically) will behave like normal, <a href="http://developer.android.com/reference/android/R.attr.html#screenOrientation" rel="noreferrer">based on sensor and user-locked rotation, etc</a>. Everything else (phones, pretty much) will be portrait only.</p>
{ "question_id": 9627774, "question_date": "2012-03-09T01:34:16.510Z", "question_score": 214, "tags": "android|tablet|screen-orientation", "answer_id": 14793611, "answer_date": "2013-02-10T01:20:43.277Z", "answer_score": 478 }
Please answer the following Stack Overflow question: Title: disable the swipe gesture that opens the navigation drawer in android <p>I've been following <a href="http://developer.android.com/training/implementing-navigation/nav-drawer.html">the navigation drawer guide by Google</a> and I'd like to add it to an Activity with tabs and gestures.</p> <p>I'd like to disable the gesture to open the navigation drawer, does anyone have any idea how to do this? </p>
<p>You should use:</p> <pre><code>mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); </code></pre> <p>It worked for me, the swipe to open the drawer was disabled.</p> <p>If it still won't work, check out the answer provided <a href="https://stackoverflow.com/a/18413276/1708390">here</a>.</p>
{ "question_id": 17051104, "question_date": "2013-06-11T18:25:03.953Z", "question_score": 214, "tags": "android|tabs|navigation|gesture|drawer", "answer_id": 17165256, "answer_date": "2013-06-18T09:27:15.867Z", "answer_score": 489 }
Please answer the following Stack Overflow question: Title: In HTML5, is the localStorage object isolated per page/domain? <p>Is the HTML5 localStorage object isolated per page/domain? I am wondering because of how I would name localStorage keys. Do I need a separate prefix? Or can I name them whatever I want?</p>
<p>It's per domain and port (the same segregation rules as the <a href="http://en.wikipedia.org/wiki/Same-origin_policy#Origin_determination_rules" rel="noreferrer">same origin policy</a>), to make it per-page you'd have to use a key based on the <code>location</code>, or some other approach. </p> <p>You don't <em>need</em> a prefix, use one if you need it though. Also, yes, you can name them whatever you want.</p>
{ "question_id": 4201239, "question_date": "2010-11-17T03:33:57.003Z", "question_score": 214, "tags": "javascript|html|local-storage", "answer_id": 4201249, "answer_date": "2010-11-17T03:36:08.750Z", "answer_score": 243 }
Please answer the following Stack Overflow question: Title: What is the difference between Spring's GA, RC and M2 releases? <p>Spring's 3.0 version is now <strong>GA</strong> release, before that they have launched 3.0 <strong>RC1</strong>, <strong>RC2</strong> version Also, there was Spring 3.0 <strong>M2</strong> version. What's the difference between GA, RC, M versions?</p>
<p>GA = General availability (a release); should be very stable and feature complete</p> <p>RC = Release candidate; probably feature complete and should be pretty stable - problems should be relatively rare and minor, but worth reporting to try to get them fixed for release.</p> <p>M = Milestone build - probably not feature complete; should be vaguely stable (i.e. it's more than just a nightly snapshot) but may still have problems.</p> <p>SR = Service Release (subsequent maintenance releases that come after major <code>-RELEASE</code>).</p>
{ "question_id": 2107484, "question_date": "2010-01-21T07:10:27.507Z", "question_score": 214, "tags": "spring|release-cycle", "answer_id": 2107490, "answer_date": "2010-01-21T07:12:27.177Z", "answer_score": 391 }
Please answer the following Stack Overflow question: Title: Not recommended to use "use strict" in ES6? <p>I'm not familiar with ECMAScript 6 yet. I've just cloned the React Starter Kit repo, which uses ES6 for application code. I was surprised to see that the linter is <a href="https://github.com/kriasoft/react-starter-kit/blob/master/.eslintrc" rel="noreferrer">configured</a> to forbid occurences of the <code>use strict</code> directive, which I thought was recommended in pre-ES6 JavaScript. So what's the point?</p>
<p>ES6 modules are always in strict mode. To quote the relevant part of <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-strict-mode-code">the spec</a>:</p> <blockquote> <h2>10.2.1 Strict Mode Code</h2> <p>An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:</p> <ul> <li>Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).</li> <li><strong>Module code is always strict mode code.</strong></li> <li>All parts of a ClassDeclaration or a ClassExpression are strict mode code.</li> <li>Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.</li> <li>Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.</li> <li>Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.</li> </ul> </blockquote>
{ "question_id": 31685262, "question_date": "2015-07-28T19:18:54.160Z", "question_score": 214, "tags": "javascript|ecmascript-6|strict|es6-modules", "answer_id": 31685340, "answer_date": "2015-07-28T19:23:12.513Z", "answer_score": 273 }
Please answer the following Stack Overflow question: Title: difference between foldLeft and reduceLeft in Scala <p>I have learned the basic difference between <code>foldLeft</code> and <code>reduceLeft</code></p> <p><strong>foldLeft:</strong></p> <ul> <li>initial value has to be passed</li> </ul> <p><strong>reduceLeft:</strong></p> <ul> <li>takes first element of the collection as initial value</li> <li>throws exception if collection is empty</li> </ul> <p>Is there any other difference ?</p> <p>Any specific reason to have two methods with similar functionality?</p>
<p>Few things to mention here, before giving the actual answer:</p> <ul> <li>Your question doesn't have anything to do with <code>left</code>, it's rather about the difference between reducing and folding</li> <li>The difference is not the implementation at all, just look at the signatures.</li> <li>The question doesn't have anything to do with Scala in particular, it's rather about the two concepts of functional programming.</li> </ul> <p><strong>Back to your question:</strong></p> <p>Here is the signature of <code>foldLeft</code> (could also have been <code>foldRight</code> for the point I'm going to make):</p> <pre><code>def foldLeft [B] (z: B)(f: (B, A) =&gt; B): B </code></pre> <p>And here is the signature of <code>reduceLeft</code> (again the direction doesn't matter here)</p> <pre><code>def reduceLeft [B &gt;: A] (f: (B, A) =&gt; B): B </code></pre> <p>These two look very similar and thus caused the confusion. <code>reduceLeft</code> is a special case of <code>foldLeft</code> (which by the way means that you <strong>sometimes</strong> can express the same thing by using either of them).</p> <p>When you call <code>reduceLeft</code> say on a <code>List[Int]</code> it will literally reduce the whole list of integers into a single value, which is going to be of type <code>Int</code> (or a supertype of <code>Int</code>, hence <code>[B &gt;: A]</code>).</p> <p>When you call <code>foldLeft</code> say on a <code>List[Int]</code> it will fold the whole list (imagine rolling a piece of paper) into a single value, but this value doesn't have to be even related to <code>Int</code> (hence <code>[B]</code>).</p> <p>Here is an example:</p> <pre><code>def listWithSum(numbers: List[Int]) = numbers.foldLeft((List.empty[Int], 0)) { (resultingTuple, currentInteger) =&gt; (currentInteger :: resultingTuple._1, currentInteger + resultingTuple._2) } </code></pre> <p>This method takes a <code>List[Int]</code> and returns a <code>Tuple2[List[Int], Int]</code> or <code>(List[Int], Int)</code>. It calculates the sum and returns a tuple with a list of integers and it's sum. By the way the list is returned backwards, because we used <code>foldLeft</code> instead of <code>foldRight</code>.</p> <p>Watch <a href="https://youtu.be/xMhZUSEGtt0" rel="noreferrer">One Fold to rule them all</a> for a more in depth explanation.</p>
{ "question_id": 7764197, "question_date": "2011-10-14T07:08:44.753Z", "question_score": 214, "tags": "scala|functional-programming|fold|higher-order-functions", "answer_id": 7764889, "answer_date": "2011-10-14T08:19:25.770Z", "answer_score": 326 }
Please answer the following Stack Overflow question: Title: How to serialize a TimeSpan to XML <p>I am trying to serialize a .NET <code>TimeSpan</code> object to XML and it is not working. A quick google has suggested that while <code>TimeSpan</code> is serializable, the <code>XmlCustomFormatter</code> does not provide methods to convert <code>TimeSpan</code> objects to and from XML.</p> <p>One suggested approach was to ignore the <code>TimeSpan</code> for serialization, and instead serialize the result of <code>TimeSpan.Ticks</code> (and use <code>new TimeSpan(ticks)</code> for deserialization). An example of this follows:</p> <pre><code>[Serializable] public class MyClass { // Local Variable private TimeSpan m_TimeSinceLastEvent; // Public Property - XmlIgnore as it doesn't serialize anyway [XmlIgnore] public TimeSpan TimeSinceLastEvent { get { return m_TimeSinceLastEvent; } set { m_TimeSinceLastEvent = value; } } // Pretend property for serialization [XmlElement("TimeSinceLastEvent")] public long TimeSinceLastEventTicks { get { return m_TimeSinceLastEvent.Ticks; } set { m_TimeSinceLastEvent = new TimeSpan(value); } } } </code></pre> <p>While this appears to work in my brief testing - is this the best way to achieve this?</p> <p>Is there a better way to serialize a TimeSpan to and from XML?</p>
<p>The way you've already posted is probably the cleanest. If you don't like the extra property, you could implement <code>IXmlSerializable</code>, but then you have to do <strong>everything</strong>, which largely defeats the point. I'd happily use the approach you've posted; it is (for example) efficient (no complex parsing etc), culture independent, unambiguous, and timestamp-type numbers are easily and commonly understood.</p> <p>As an aside, I often add:</p> <pre><code>[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] </code></pre> <p>This just hides it in the UI and in referencing dlls, to avoid confusion.</p>
{ "question_id": 637933, "question_date": "2009-03-12T09:55:13.423Z", "question_score": 214, "tags": "c#|serialization|timespan", "answer_id": 637968, "answer_date": "2009-03-12T10:08:54.357Z", "answer_score": 72 }
Please answer the following Stack Overflow question: Title: Why do I need underscores in swift? <p><a href="https://www.weheartswift.com/tuples-enums/" rel="noreferrer">Here</a> it says, "Note: the <code>_</code> means “I don’t care about that value”", but coming from JavaScript, I don't understand what that means.</p> <p>The only way I can get these functions to print was by using the underscores before the parameters:</p> <pre><code>func divmod(_ a: Int, _ b:Int) -&gt; (Int, Int) { return (a / b, a % b) } print(divmod(7, 3)) print(divmod(5, 2)) print(divmod(12,4)) </code></pre> <p>Without the underscores I have to write it like this to avoid any errors:</p> <pre><code>func divmod(a: Int, b:Int) -&gt; (Int, Int) { return (a / b, a % b) } print(divmod(a: 7, b: 3)) print(divmod(a: 5, b: 2)) print(divmod(a: 12,b: 4)) </code></pre> <p>I don't understand this underscore usage. When, how and why do I use these underscores? </p>
<p>There are a few nuances to different use cases, but generally an underscore means "ignore this".</p> <hr> <p>When declaring a new function, an underscore tells Swift that the parameter should have no label when called — that's the case you're seeing. A fuller function declaration looks like this:</p> <pre><code>func myFunc(label name: Int) // call it like myFunc(label: 3) </code></pre> <p>"label" is an argument label, and must be present when you call the function. (And since Swift 3, labels are required for all arguments by default.) "name" is the variable name for that argument that you use inside the function. A shorter form looks like this:</p> <pre><code>func myFunc(name: Int) // call it like myFunc(name: 3) </code></pre> <p>This is a shortcut that lets you use the same word for both external argument label and internal parameter name. It's equivalent to <code>func myFunc(name name: Int)</code>.</p> <p>If you want your function to be callable without parameter labels, you use the underscore <code>_</code> to make the label be nothing/ignored. (In that case you have to provide an internal name if you want to be able to use the parameter.)</p> <pre><code>func myFunc(_ name: Int) // call it like myFunc(3) </code></pre> <hr> <p>In an assignment statement, an underscore means "don't assign to anything". You can use this if you want to call a function that returns a result but don't care about the returned value.</p> <pre><code>_ = someFunction() </code></pre> <p>Or, like in the article you linked to, to ignore one element of a returned tuple:</p> <pre><code>let (x, _) = someFunctionThatReturnsXandY() </code></pre> <hr> <p>When you write a closure that implements some defined function type, you can use the underscore to ignore certain parameters.</p> <pre><code>PHPhotoLibrary.performChanges( { /* some changes */ }, completionHandler: { success, _ in // don't care about error if success { print("yay") } }) </code></pre> <p>Similarly, when declaring a function that adopts a protocol or overrides a superclass method, you can use <code>_</code> for parameter <em>names</em> to ignore parameters. Since the protocol/superclass might also define that the parameter has no label, you can even end up with two underscores in a row.</p> <pre><code>class MyView: NSView { override func mouseDown(with _: NSEvent) { // don't care about event, do same thing for every mouse down } override func draw(_ _: NSRect) { // don't care about dirty rect, always redraw the whole view } } </code></pre> <hr> <p>Somewhat related to the last two styles: when using a flow control construct that binds a local variable/constant, you can use <code>_</code> to ignore it. For example, if you want to iterate a sequence without needing access to its members:</p> <pre><code>for _ in 1...20 { // or 0..&lt;20 // do something 20 times } </code></pre> <hr> <p>If you're binding tuple cases in a switch statement, the underscore can work as a wildcard, as in this example (shortened from one in <a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-ID120" rel="noreferrer"><em>The Swift Programming Language</em></a>):</p> <pre><code>switch somePoint { // somePoint is an (Int, Int) tuple case (0, 0): print("(0, 0) is at the origin") case (_, 0): print("(\(somePoint.0), 0) is on the x-axis") case (0, _): print("(0, \(somePoint.1)) is on the y-axis") default: print("(\(somePoint.0), \(somePoint.1)) isn't on an axis") } </code></pre> <hr> <p>One last thing that's not quite related, but which I'll include since (as noted by comments) it seems to lead people here: An underscore <em>in</em> an identifier — e.g. <code>var _foo</code>, <code>func do_the_thing()</code>, <code>struct Stuff_</code> — means nothing in particular to Swift, but has a few uses among programmers. </p> <p>Underscores within a name are a style choice, but not preferred in the Swift community, which has strong conventions about using UpperCamelCase for types and lowerCamelCase for all other symbols.</p> <p>Prefixing or suffixing a symbol name with underscore is a style convention, historically used to distinguish private/internal-use-only symbols from exported API. However, Swift has access modifiers for that, so this convention generally is seen as non-idiomatic in Swift.</p> <p>A few symbols with double-underscore prefixes (<code>func __foo()</code>) lurk in the depths of Apple's SDKs: These are (Obj)C symbols imported into Swift using the <code>NS_REFINED_FOR_SWIFT</code> attribute. Apple uses that when they want to make a "more Swifty" version of an (Obj)C API — for example, <a href="https://github.com/apple/swift/blob/master/stdlib/public/SDK/Photos/PHChange.swift" rel="noreferrer">to make a type-agnostic method into a generic method</a>. They need to use the imported API to make the refined Swift version work, so they use the <code>__</code> to keep it available while hiding it from most tools and documentation.</p>
{ "question_id": 39627106, "question_date": "2016-09-21T21:48:52.163Z", "question_score": 214, "tags": "swift", "answer_id": 39627305, "answer_date": "2016-09-21T22:07:43.387Z", "answer_score": 452 }
Please answer the following Stack Overflow question: Title: What does the filter parameter to createScaledBitmap do? <p>The declaration of <code>android.graphics.Bitmap.createScaledBitmap</code> is</p> <pre><code>public static Bitmap createScaledBitmap (Bitmap src, int dstWidth, int dstHeight, boolean filter) </code></pre> <p>However, the documentation doesn't explain any of the parameters. All of them are pretty obvious except for <code>boolean filter</code>. Does anyone know what it does?</p>
<p>A quick dig through the SKIA source-code indicates that (at least by default) the FILTER flag causes it to do a straightforward bilinear interpolation. Check Wikipedia or your favorite graphics reference to see what the expected consequences are. Traditionally, you want to do bilinear or bicubic interpolation when upsizing images, and area averaging when downsizing images. I get the impression (though I'm glad to be corrected) that Android/Skia does simple subsampling when downsizing without filtering, so you are likely to get better results from filtering even when downsizing. (There's an alternate method for getting high quality downsizing with interpolation, involving doing a series of 50% scale reductions. See <a href="http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html" rel="noreferrer">http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html</a> for details.)</p>
{ "question_id": 2895065, "question_date": "2010-05-24T06:05:38.747Z", "question_score": 214, "tags": "android|scaling", "answer_id": 3897597, "answer_date": "2010-10-09T19:45:47.900Z", "answer_score": 88 }
Please answer the following Stack Overflow question: Title: What is the reason behind cbegin/cend? <p>I wonder why <code>cbegin</code> and <code>cend</code> were introduced in C++11? </p> <p>What are cases when calling these methods makes a difference from const overloads of <code>begin</code> and <code>end</code>?</p>
<p>It's quite simple. Say I have a vector:</p> <pre><code>std::vector&lt;int&gt; vec; </code></pre> <p>I fill it with some data. Then I want to get some iterators to it. Maybe pass them around. Maybe to <code>std::for_each</code>:</p> <pre><code>std::for_each(vec.begin(), vec.end(), SomeFunctor()); </code></pre> <p>In C++03, <code>SomeFunctor</code> was free to be able to <em>modify</em> the parameter it gets. Sure, <code>SomeFunctor</code> could take its parameter by value or by <code>const&amp;</code>, but there's no way to <em>ensure</em> that it does. Not without doing something silly like this:</p> <pre><code>const std::vector&lt;int&gt; &amp;vec_ref = vec; std::for_each(vec_ref.begin(), vec_ref.end(), SomeFunctor()); </code></pre> <p>Now, we introduce <code>cbegin/cend</code>:</p> <pre><code>std::for_each(vec.cbegin(), vec.cend(), SomeFunctor()); </code></pre> <p>Now, we have syntactic assurances that <code>SomeFunctor</code> cannot modify the elements of the vector (without a const-cast, of course). We explicitly get <code>const_iterator</code>s, and therefore <code>SomeFunctor::operator()</code> will be called with <code>const int &amp;</code>. If it takes it's parameters as <code>int &amp;</code>, C++ will issue a compiler error.</p> <hr> <p>C++17 has a more elegant solution to this problem: <a href="http://en.cppreference.com/w/cpp/utility/as_const" rel="noreferrer"><code>std::as_const</code></a>. Well, at least it's elegant when using range-based <code>for</code>:</p> <pre><code>for(auto &amp;item : std::as_const(vec)) </code></pre> <p>This simply returns a <code>const&amp;</code> to the object it is provided. </p>
{ "question_id": 12001410, "question_date": "2012-08-17T07:16:32.720Z", "question_score": 214, "tags": "c++|c++11|iterator|const-correctness|const-iterator", "answer_id": 12001519, "answer_date": "2012-08-17T07:24:36.390Z", "answer_score": 247 }
Please answer the following Stack Overflow question: Title: Are +0 and -0 the same? <p>Reading through the <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-8.5">ECMAScript 5.1 specification</a>, <code>+0</code> and <code>-0</code> are distinguished.</p> <p>Why then does <code>+0 === -0</code> evaluate to <code>true</code>?</p>
<p>JavaScript uses <a href="http://en.wikipedia.org/wiki/IEEE_754" rel="noreferrer">IEEE 754 standard</a> to represent numbers. From <a href="http://en.wikipedia.org/wiki/Negative_zero" rel="noreferrer">Wikipedia</a>:</p> <blockquote> <p><strong>Signed zero</strong> is zero with an associated sign. In ordinary arithmetic, −0 = +0 = 0. However, in computing, some number representations allow for the existence of two zeros, often denoted by <strong>−0 (negative zero)</strong> and <strong>+0 (positive zero)</strong>. This occurs in some signed number representations for integers, and in most floating point number representations. The number 0 is usually encoded as +0, but can be represented by either +0 or −0.</p> <p>The IEEE 754 standard for floating point arithmetic (presently used by most computers and programming languages that support floating point numbers) requires both +0 and −0. The zeroes can be considered as a variant of the extended real number line such that 1/−0 = −∞ and 1/+0 = +∞, division by zero is only undefined for ±0/±0 and ±∞/±∞.</p> </blockquote> <p>The article contains further information about the different representations.</p> <p>So this is the reason why, technically, both zeros have to be distinguished. </p> <blockquote> <p>However, <code>+0 === -0</code> evaluates to true. Why is that (...) ?</p> </blockquote> <p>This behaviour is explicitly defined in <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-strict-equality-comparison" rel="noreferrer">section 11.9.6</a>, the <em>Strict Equality Comparison Algorithm</em> (emphasis partly mine):</p> <blockquote> <p>The comparison <code>x === y</code>, where <code>x</code> and <code>y</code> are values, produces <strong>true</strong> or <strong>false</strong>. Such a comparison is performed as follows: </p> <p>(...)</p> <ul> <li><p>If Type(x) is Number, then</p> <ol> <li>If x is NaN, return false.</li> <li>If y is NaN, return false.</li> <li>If x is the same Number value as y, return true.</li> <li><strong>If x is +0 and y is −0, return true.</strong></li> <li><strong>If x is −0 and y is +0, return true.</strong></li> <li>Return false.</li> </ol></li> </ul> <p>(...)</p> </blockquote> <p><em>(The same holds for <code>+0 == -0</code> btw.)</em></p> <p>It seems logically to treat <code>+0</code> and <code>-0</code> as equal. Otherwise we would have to take this into account in our code and I, personally, don't want to do that ;)</p> <hr> <p><strong>Note:</strong></p> <p>ES2015 introduces a new comparison method, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is" rel="noreferrer"><code>Object.is</code></a>. <code>Object.is</code> explicitly distinguishes between <code>-0</code> and <code>+0</code>:</p> <pre><code>Object.is(-0, +0); // false </code></pre>
{ "question_id": 7223359, "question_date": "2011-08-28T19:31:29.193Z", "question_score": 214, "tags": "javascript", "answer_id": 7223395, "answer_date": "2011-08-28T19:37:50.493Z", "answer_score": 229 }
Please answer the following Stack Overflow question: Title: what is the function of webpages:Enabled in MVC 3 web.config <p>I just started a new MVC 3 project. Can anyone tell me what </p> <pre><code>&lt;add key="webpages:Enabled" value="false" /&gt; </code></pre> <p>in my web.config file does?</p>
<p><code>webPages:enabled</code> with value <code>false</code> prevents <code>.cshtml</code> or <code>.vbhtml</code> files in the <code>Views</code> folder from being directly accessible from a web browser.</p>
{ "question_id": 4886095, "question_date": "2011-02-03T12:24:08.327Z", "question_score": 214, "tags": "asp.net-mvc-3", "answer_id": 4886130, "answer_date": "2011-02-03T12:27:47.350Z", "answer_score": 253 }
Please answer the following Stack Overflow question: Title: Django - How to rename a model field using South? <p>I would like to change a name of specific fields in a model:</p> <pre><code>class Foo(models.Model): name = models.CharField() rel = models.ForeignKey(Bar) </code></pre> <p>should change to:</p> <pre><code>class Foo(models.Model): full_name = models.CharField() odd_relation = models.ForeignKey(Bar) </code></pre> <p>What's the easiest way to do this using South?</p>
<p>You can use the <a href="http://south.readthedocs.org/en/latest/databaseapi.html#db-rename-column" rel="noreferrer"><code>db.rename_column</code></a> function.</p> <pre><code>class Migration: def forwards(self, orm): # Rename 'name' field to 'full_name' db.rename_column('app_foo', 'name', 'full_name') def backwards(self, orm): # Rename 'full_name' field to 'name' db.rename_column('app_foo', 'full_name', 'name') </code></pre> <p>The first argument of <code>db.rename_column</code> is the table name, so it's important to remember how <a href="https://docs.djangoproject.com/en/stable/ref/models/options/#table-names" rel="noreferrer">Django creates table names</a>:</p> <blockquote> <p>Django automatically derives the name of the database table from the name of your model class and the app that contains it. A model's database table name is constructed by joining the model's "app label" -- the name you used in manage.py startapp -- to the model's class name, with an underscore between them.</p> </blockquote> <p>In the case where you have a multi-worded, camel-cased model name, such as ProjectItem, the table name will be <code>app_projectitem</code> (i.e., an underscore will not be inserted between <code>project</code> and <code>item</code> even though they are camel-cased).</p>
{ "question_id": 3235995, "question_date": "2010-07-13T09:53:02.320Z", "question_score": 214, "tags": "python|django|django-models|django-south", "answer_id": 3236197, "answer_date": "2010-07-13T10:26:56.057Z", "answer_score": 232 }
Please answer the following Stack Overflow question: Title: Return type of '?:' (ternary conditional operator) <p>Why does the first return a reference?</p> <pre><code>int x = 1; int y = 2; (x &gt; y ? x : y) = 100; </code></pre> <p>While the second does not?</p> <pre><code>int x = 1; long y = 2; (x &gt; y ? x : y) = 100; </code></pre> <p>Actually, the second did not compile at all - "not lvalue left of assignment".</p>
<p>Expressions don't have return types, they have a type and - as it's known in the latest C++ standard - a value category.</p> <p>A conditional expression can be an <em>lvalue</em> or an <em>rvalue</em>. This is its value category. (This is somewhat of a simplification, in <code>C++11</code> we have lvalues, xvalues and prvalues.)</p> <p>In very broad and simple terms, an <em>lvalue</em> refers to an object in memory and an <em>rvalue</em> is just a value that may not necessarily be attached to an object in memory.</p> <p>An assignment expression assigns a value to an object so the thing being assigned to must be an <em>lvalue</em>.</p> <p>For a conditional expression (<code>?:</code>) to be an <em>lvalue</em> (again, in broad and simple terms), <strong>the second and third operands must be <em>lvalues</em> of the same type</strong>. This is because the type and value category of a conditional expression is determined at compile time and must be appropriate whether or not the condition is true. If one of the operands must be converted to a different type to match the other then the conditional expression cannot be an <em>lvalue</em> as the result of this conversion would not be an <em>lvalue</em>.</p> <blockquote> <p>ISO/IEC 14882:2011 references:</p> <p>3.10 [basic.lval] Lvalues and rvalues (about value categories)</p> <p>5.15 [expr.cond] Conditional operator (rules for what type and value category a conditional expression has)</p> <p>5.17 [expr.ass] Assignment and compound assignment operators (requirement that the l.h.s. of an assignment must be a modifiable lvalue)</p> </blockquote>
{ "question_id": 8535226, "question_date": "2011-12-16T13:57:39.373Z", "question_score": 214, "tags": "c++|types|reference|conditional-operator|lvalue", "answer_id": 8535301, "answer_date": "2011-12-16T14:05:08.010Z", "answer_score": 177 }
Please answer the following Stack Overflow question: Title: What is the difference between * and *|* in CSS? <p>In CSS, <code>*</code> will match any element.</p> <p>Frequently, <code>*|*</code> is used instead of <code>*</code> to match all elements. This is generally used for testing purposes.</p> <p>What is the difference between <code>*</code> and <code>*|*</code> in CSS?</p>
<p>As per <a href="http://www.w3.org/TR/css3-selectors/#univnmsp" rel="noreferrer">W3C Selector Spec</a>:</p> <blockquote> <p>The universal selector allows an optional namespace component. It is used as follows:</p> <p><code>ns|*</code><br /> all elements in namespace ns</p> <p><code>*|*</code><br /> all elements</p> <p><code>|*</code><br /> all elements without a namespace</p> <p><code>*</code><br /> if no default namespace has been specified, this is equivalent to *|*. Otherwise it is equivalent to ns|* where ns is the default namespace.</p> </blockquote> <p>So, no <code>*</code> and <code>*|*</code> are not always the same. If a default name space is provided then <code>*</code> selects only elements that are part of that namespace.</p> <hr /> <p>You can visually see the differences using the below two snippets. In the first, a default namespace is defined and so the <code>*</code> selector applies the beige colored background only to the element which is part of that namsepace whereas the <code>*|*</code> applies the border to all elements. <div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>@namespace "http://www.w3.org/2000/svg"; * { background: beige; } *|* { border: 1px solid; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;a href="#"&gt;This is some link&lt;/a&gt; &lt;svg xmlns="http://www.w3.org/2000/svg"&gt; &lt;a xlink:href="#"&gt; &lt;text x="20" y="20"&gt;This is some link&lt;/text&gt; &lt;/a&gt; &lt;/svg&gt;</code></pre> </div> </div> </p> <p>In the below snippet no default namespace is defined and so both <code>*</code> and <code>*|*</code> applies to all elements and so all of them get both the beige background and the black border. In other words, they work the same way when no default namespace is specified.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { background: beige; } *|* { border: 1px solid; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;a href="#"&gt;This is some link&lt;/a&gt; &lt;svg xmlns="http://www.w3.org/2000/svg"&gt; &lt;a xlink:href="#"&gt; &lt;text x="20" y="20"&gt;This is some link&lt;/text&gt; &lt;/a&gt; &lt;/svg&gt;</code></pre> </div> </div> </p> <hr /> <p>As BoltClock points out in comments (<a href="https://stackoverflow.com/questions/34987370/what-is-the-difference-between-and-in-css/34987469#comment57763935_34987469">1</a>,<a href="https://stackoverflow.com/questions/34987370/what-is-the-difference-between-and-in-css/34987469#comment57827474_34987469">2</a>), initially namespaces applied only to XML based languages such as XHTML, SVG etc but as per latest specs, all HTML elements (that is, elements in the HTML namespace) are namespaced to <code>http://www.w3.org/1999/xhtml</code>. Firefox follows this behavior and it is consistent across all HTML5 user agents. You can find more information in <a href="https://stackoverflow.com/questions/3608819/what-does-this-mean-in-css/12979656#12979656">this answer</a>.</p>
{ "question_id": 34987370, "question_date": "2016-01-25T07:40:11.630Z", "question_score": 214, "tags": "css|css-selectors|namespaces", "answer_id": 34987469, "answer_date": "2016-01-25T07:47:10.097Z", "answer_score": 219 }
Please answer the following Stack Overflow question: Title: Generating a Random Number between 1 and 10 Java <p>I want to generate a number between 1 and 10 in Java.</p> <p>Here is what I tried:</p> <pre><code>Random rn = new Random(); int answer = rn.nextInt(10) + 1; </code></pre> <p>Is there a way to tell what to put in the parenthesis <code>()</code> when calling the nextInt method and what to add? </p>
<p>As <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Random.html" rel="noreferrer">the documentation</a> says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.</p> <p>Generally speaking, if you need to generate numbers from <code>min</code> to <code>max</code> (including both), you write</p> <pre><code>random.nextInt(max - min + 1) + min </code></pre>
{ "question_id": 20389890, "question_date": "2013-12-05T01:51:05.503Z", "question_score": 213, "tags": "java|random", "answer_id": 20389923, "answer_date": "2013-12-05T01:54:40.530Z", "answer_score": 301 }
Please answer the following Stack Overflow question: Title: How to initialize a vector in C++ <p>I want to initialize a vector like we do in case of an array.</p> <p>Example</p> <pre><code>int vv[2] = {12, 43}; </code></pre> <p>But when I do it like this,</p> <pre><code>vector&lt;int&gt; v(2) = {34, 23}; </code></pre> <p>OR</p> <pre><code>vector&lt;int&gt; v(2); v = {0, 9}; </code></pre> <p>it gives an error:</p> <blockquote> <p>expected primary-expression before ‘{’ token</p> </blockquote> <p>AND</p> <blockquote> <p>error: expected ‘,’ or ‘;’ before ‘=’ token</p> </blockquote> <p>respectively.</p>
<p>With the new C++ standard (may need special flags to be enabled on your compiler) you can simply do:</p> <pre><code>std::vector&lt;int&gt; v { 34,23 }; // or // std::vector&lt;int&gt; v = { 34,23 }; </code></pre> <p>Or even:</p> <pre><code>std::vector&lt;int&gt; v(2); v = { 34,23 }; </code></pre> <p>On compilers that don't support this feature (initializer lists) yet you can emulate this with an array:</p> <pre><code>int vv[2] = { 12,43 }; std::vector&lt;int&gt; v(&amp;vv[0], &amp;vv[0]+2); </code></pre> <p>Or, for the case of assignment to an existing vector:</p> <pre><code>int vv[2] = { 12,43 }; v.assign(&amp;vv[0], &amp;vv[0]+2); </code></pre> <p>Like James Kanze suggested, it's more robust to have functions that give you the beginning and end of an array:</p> <pre><code>template &lt;typename T, size_t N&gt; T* begin(T(&amp;arr)[N]) { return &amp;arr[0]; } template &lt;typename T, size_t N&gt; T* end(T(&amp;arr)[N]) { return &amp;arr[0]+N; } </code></pre> <p>And then you can do this without having to repeat the size all over:</p> <pre><code>int vv[] = { 12,43 }; std::vector&lt;int&gt; v(begin(vv), end(vv)); </code></pre>
{ "question_id": 8906545, "question_date": "2012-01-18T07:22:46.203Z", "question_score": 213, "tags": "c++|arrays|vector|declaration", "answer_id": 8906577, "answer_date": "2012-01-18T07:24:59.560Z", "answer_score": 286 }
Please answer the following Stack Overflow question: Title: Datetime equal or greater than today in MySQL <p>What's the best way to do following:</p> <pre><code>SELECT * FROM users WHERE created &gt;= today; </code></pre> <p>Note: created is a datetime field.</p>
<pre><code>SELECT * FROM users WHERE created &gt;= CURDATE(); </code></pre> <p>But I think you mean <code>created &lt; today</code></p> <p>You can compare datetime with date, for example: <code>SELECT NOW() &lt; CURDATE()</code> gives <code>0</code>, <code>SELECT NOW() = CURDATE()</code> gives <code>1</code>.</p>
{ "question_id": 5182275, "question_date": "2011-03-03T14:49:50.883Z", "question_score": 213, "tags": "mysql|sql|datetime", "answer_id": 5182309, "answer_date": "2011-03-03T14:52:26.020Z", "answer_score": 394 }
Please answer the following Stack Overflow question: Title: Override body style for content in an iframe <p>How can I control the background image and colour of a body element within an <code>iframe</code>? Note, the embedded body element has a class, and the <code>iframe</code> is of a page that is part of my site. </p> <p>The reason I need this is that my site has a black background assigned to the body, and then a white background assigned to divs that contain text. A WYSIWYG editor uses an <code>iframe</code> to embed content when editing, but it doesn't include the div, so the text is very hard to read. </p> <p>The body of the <code>iframe</code> when in the editor has a class that isn't used anywhere else, so I'm assuming this was put there so problems like this could be solved. However, when I apply styles to <code>class.body</code> they don't override the styles applied to body. The weird thing is that the styles do appear in Firebug, so I've no idea what's going on! </p> <p>Thanks </p> <p>UPDATE - I've tried @mikeq's solution of adding a style to the class that is the body's class. This doesn't work when added to the main page's stylesheet, but it does work when added with Firebug. I'm assuming this is because Firebug is applied to all elements on the page whereas the CSS is not applied within iframes. Does this mean that adding the css after window load with JavaScript would work? </p>
<p>An iframe is a 'hole' in your page that displays another web page inside of it. The contents of the iframe is not in any shape or form part of your parent page.</p> <p>As others have stated, your options are:</p> <ul> <li>give the file that is being loaded in the iframe the necessary CSS </li> <li>if the file in the iframe is from the same domain as your parent, then you can access the DOM of the document in the iframe from the parent.</li> </ul>
{ "question_id": 6494721, "question_date": "2011-06-27T14:49:29.537Z", "question_score": 213, "tags": "css|iframe|styles|overriding", "answer_id": 6495816, "answer_date": "2011-06-27T16:18:15.977Z", "answer_score": 131 }
Please answer the following Stack Overflow question: Title: 'str' object does not support item assignment <p>I would like to read some characters from a string <code>s1</code> and put it into another string <code>s2</code>.</p> <p>However, assigning to <code>s2[j]</code> gives an error:</p> <pre class="lang-py prettyprint-override"><code>s2[j] = s1[i] # TypeError: 'str' object does not support item assignment </code></pre> <hr /> <p>In C, this works:</p> <pre class="lang-cpp prettyprint-override"><code>int i = j = 0; while (s1[i] != '\0') s2[j++] = s1[i++]; </code></pre> <p>My attempt in Python:</p> <pre class="lang-py prettyprint-override"><code>s1 = &quot;Hello World&quot; s2 = &quot;&quot; j = 0 for i in range(len(s1)): s2[j] = s1[i] j = j + 1 </code></pre>
<p>In Python, strings are immutable, so you can't change their characters in-place.</p> <p>You can, however, do the following:</p> <pre><code>for c in s1: s2 += c </code></pre> <p>The reasons this works is that it's a shortcut for:</p> <pre><code>for c in s1: s2 = s2 + c </code></pre> <p>The above <em>creates a new string</em> with each iteration, and stores the reference to that new string in <code>s2</code>.</p>
{ "question_id": 10631473, "question_date": "2012-05-17T07:18:41.070Z", "question_score": 213, "tags": "python|string", "answer_id": 10631478, "answer_date": "2012-05-17T07:19:38.530Z", "answer_score": 141 }
Please answer the following Stack Overflow question: Title: Where can I find the Java SDK in Linux after installing it? <p>I installed JDK using apt-get install but I don't know where my jdk folder is. I need to set the path for that. Does any one have a clue on the location?</p>
<p>This depends a bit from your package system ... if the <code>java</code> command works, you can type <code>readlink -f $(which java)</code> to find the location of the java command. On the OpenSUSE system I'm on now it returns <code>/usr/lib64/jvm/java-1.6.0-openjdk-1.6.0/jre/bin/java</code> (but this is not a system which uses <code>apt-get</code>).</p> <hr> <p>On Ubuntu, it <a href="http://packages.ubuntu.com/openjdk-6-jdk/filelist">looks like it is in</a> <code>/usr/lib/jvm/java-6-openjdk/</code> for OpenJDK, and in some other subdirectory of <code>/usr/lib/jvm/</code> for Suns JDK (and other implementations as well, I think).</p> <p><a href="http://packages.debian.org/wheezy/i386/openjdk-6-jre/filelist">Debian is the same.</a></p> <hr> <p>For any given package you can determine what files it installs and where it installs them by querying dpkg. For example for the package 'openjdk-6-jdk': <code>dpkg -L openjdk-6-jdk</code></p>
{ "question_id": 5251323, "question_date": "2011-03-09T19:48:49.127Z", "question_score": 213, "tags": "linux|java", "answer_id": 5251365, "answer_date": "2011-03-09T19:53:13.330Z", "answer_score": 430 }
Please answer the following Stack Overflow question: Title: How to stop C++ console application from exiting immediately? <p>Lately, I've been trying to learn C++ from <a href="http://www.cplusplus.com/doc/tutorial/" rel="noreferrer">this website</a>. Unfortunately whenever I try to run one of the code samples, I see that program open for about a half second and then immediately close. Is there a way to stop the program from closing immediately so that I can see the fruits of my effort?</p>
<p><strong>Edit:</strong> As Charles Bailey rightly points out in a comment below, this won't work if there are characters buffered in <code>stdin</code>, and there's really no good way to work around that. If you're running with a debugger attached, <a href="https://stackoverflow.com/questions/2529617/how-to-stop-c-console-application-from-exiting-immediately/2529936#2529936">John Dibling's suggested solution</a> is probably the cleanest solution to your problem.</p> <p>That said, I'll leave this here and maybe someone else will find it useful. I've used it a lot as a quick hack of sorts when writing tests during development.</p> <hr> <p>At the end of your <code>main</code> function, you can call <a href="http://en.cppreference.com/w/cpp/io/c/getchar" rel="noreferrer"><code>std::getchar();</code></a></p> <p>This will get a single character from <code>stdin</code>, thus giving you the "press any key to continue" sort of behavior (if you actually want a "press any key" message, you'll have to print one yourself).</p> <p>You need to <code>#include &lt;cstdio&gt;</code> for <code>getchar</code>.</p>
{ "question_id": 2529617, "question_date": "2010-03-27T14:29:41.627Z", "question_score": 213, "tags": "c++|console|exit|terminate|c++-faq", "answer_id": 2529625, "answer_date": "2010-03-27T14:31:35.787Z", "answer_score": 135 }
Please answer the following Stack Overflow question: Title: How to check date of last change in stored procedure or function in SQL server <p>I need to check when function was changed last time. I know how to check creation date (it is in function properties window in SQL Server Management Studio).<br> I found that in SQL Server 2000 it wasn't possible to check modify date ( look at this post: <a href="https://stackoverflow.com/questions/163957/is-it-possible-to-determine-when-a-stored-procedure-was-last-modified-in-sql-serv">Is it possible to determine when a stored procedure was last modified in SQL Server 2000?</a>)</p> <p>Is it possible to check it in SQL Server 2008? Does MS add some new feature in system tables that allow to check it?</p>
<pre><code>SELECT name, create_date, modify_date FROM sys.objects WHERE type = 'P' ORDER BY modify_date DESC </code></pre> <p>The <code>type</code> for a function is <code>FN</code> rather than <code>P</code> for procedure. Or you can filter on the name column.</p>
{ "question_id": 5579223, "question_date": "2011-04-07T09:56:33.803Z", "question_score": 213, "tags": "sql-server-2008|stored-procedures|sql-server-2008-r2|sql-function", "answer_id": 5579265, "answer_date": "2011-04-07T10:00:17.723Z", "answer_score": 441 }
Please answer the following Stack Overflow question: Title: How to kill zombie process <p>I launched my program in the foreground (a daemon program), and then I killed it with <code>kill -9</code>, but I get a zombie remaining and I m not able to kill it with <code>kill -9</code>. How to kill a zombie process?</p> <p>If the zombie is a dead process (already killed), how I remove it from the output of <code>ps aux</code>?</p> <pre><code>root@OpenWrt:~# anyprogramd &amp; root@OpenWrt:~# ps aux | grep anyprogram 1163 root 2552 S anyprogramd 1167 root 2552 S anyprogramd 1169 root 2552 S anyprogramd 1170 root 2552 S anyprogramd 10101 root 944 S grep anyprogram root@OpenWrt:~# pidof anyprogramd 1170 1169 1167 1163 root@OpenWrt:~# kill -9 1170 1169 1167 1163 root@OpenWrt:~# ps aux |grep anyprogram 1163 root 0 Z [anyprogramd] root@OpenWrt:~# kill -9 1163 root@OpenWrt:~# ps aux |grep anyprogram 1163 root 0 Z [anyprogramd] </code></pre>
<p>A zombie is already dead, so you cannot kill it. To clean up a zombie, it must be waited on by its parent, so killing the parent should work to eliminate the zombie. (After the parent dies, the zombie will be inherited by pid 1, which will wait on it and clear its entry in the process table.) If your daemon is spawning children that become zombies, you have a bug. Your daemon should notice when its children die and <code>wait</code> on them to determine their exit status.</p> <p>An example of how you might send a signal to every process that is the parent of a zombie (note that this is extremely crude and might kill processes that you do not intend. I do not recommend using this sort of sledge hammer):</p> <pre><code># Don't do this. Incredibly risky sledge hammer! kill $(ps -A -ostat,ppid | awk '/[zZ]/ &amp;&amp; !a[$2]++ {print $2}') </code></pre>
{ "question_id": 16944886, "question_date": "2013-06-05T16:14:46.970Z", "question_score": 213, "tags": "linux|shell|ubuntu|debian|zombie-process", "answer_id": 16944931, "answer_date": "2013-06-05T16:17:00.830Z", "answer_score": 288 }
Please answer the following Stack Overflow question: Title: How do I get the current time only in JavaScript <p>How can I get the current time in JavaScript and use it in a timepicker?</p> <p>I tried <code>var x = Date()</code> and got: </p> <blockquote> <p>Tue May 15 2012 05:45:40 GMT-0500</p> </blockquote> <p>But I need only current time, for example, <code>05:45</code></p> <p>How can I assign this to a variable?</p>
<pre><code>var d = new Date("2011-04-20T09:30:51.01"); d.getHours(); // =&gt; 9 d.getMinutes(); // =&gt; 30 d.getSeconds(); // =&gt; 51 </code></pre> <p>or</p> <pre><code>var d = new Date(); // for now d.getHours(); // =&gt; 9 d.getMinutes(); // =&gt; 30 d.getSeconds(); // =&gt; 51 </code></pre>
{ "question_id": 10599148, "question_date": "2012-05-15T10:48:57.003Z", "question_score": 213, "tags": "javascript|datetime", "answer_id": 10599188, "answer_date": "2012-05-15T10:51:15.193Z", "answer_score": 282 }
Please answer the following Stack Overflow question: Title: How to terminate the script in JavaScript? <p>How can I exit the JavaScript script much like PHP's <code>exit</code> or <code>die</code>? I know it's not the best programming practice but I need to.</p>
<p><a href="https://github.com/kvz/phpjs/blob/master/experimental/misc/die.js" rel="noreferrer">JavaScript equivalent for PHP's <code>die</code></a>. BTW it just calls <a href="https://github.com/kvz/phpjs/blob/master/experimental/misc/exit.js" rel="noreferrer"><code>exit()</code></a> (thanks splattne):</p> <pre><code>function exit( status ) { // http://kevin.vanzonneveld.net // + original by: Brett Zamir (http://brettz9.blogspot.com) // + input by: Paul // + bugfixed by: Hyam Singer (http://www.impact-computing.com/) // + improved by: Philip Peterson // + bugfixed by: Brett Zamir (http://brettz9.blogspot.com) // % note 1: Should be considered expirimental. Please comment on this function. // * example 1: exit(); // * returns 1: null var i; if (typeof status === 'string') { alert(status); } window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false); var handlers = [ 'copy', 'cut', 'paste', 'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll', 'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput', 'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload' ]; function stopPropagation (e) { e.stopPropagation(); // e.preventDefault(); // Stop for the form controls, etc., too? } for (i=0; i &lt; handlers.length; i++) { window.addEventListener(handlers[i], function (e) {stopPropagation(e);}, true); } if (window.stop) { window.stop(); } throw ''; } </code></pre>
{ "question_id": 550574, "question_date": "2009-02-15T09:14:49.903Z", "question_score": 213, "tags": "javascript|exit|die", "answer_id": 550583, "answer_date": "2009-02-15T09:17:34.157Z", "answer_score": 89 }
Please answer the following Stack Overflow question: Title: How to make remote REST call inside Node.js? any CURL? <p>In <strong>Node.js</strong>, other than using child process to make <strong>CURL</strong> call, is there a way to make CURL call to remote server <strong>REST</strong> API and get the return data?</p> <p>I also need to set up the request header to the remote <strong>REST</strong> call, and also query string as well in GET (or POST). </p> <p>I find this one: <a href="http://blog.nodejitsu.com/jsdom-jquery-in-5-lines-on-nodejs" rel="noreferrer">http://blog.nodejitsu.com/jsdom-jquery-in-5-lines-on-nodejs</a></p> <p>but it doesn't show any way to POST query string. </p>
<p>Look at <a href="https://nodejs.org/api/http.html#http_http_request_options_callback"><code>http.request</code></a></p> <pre><code>var options = { host: url, port: 80, path: '/resource?id=foo&amp;bar=baz', method: 'POST' }; http.request(options, function(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }).end(); </code></pre>
{ "question_id": 5643321, "question_date": "2011-04-13T01:01:53.577Z", "question_score": 213, "tags": "rest|curl|node.js", "answer_id": 5643366, "answer_date": "2011-04-13T01:11:09.783Z", "answer_score": 235 }
Please answer the following Stack Overflow question: Title: Remove Primary Key in MySQL <p>I have the following table schema which maps user_customers to permissions on a live MySQL database:</p> <pre><code>mysql&gt; describe user_customer_permission; +------------------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+---------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | user_customer_id | int(11) | NO | PRI | NULL | | | permission_id | int(11) | NO | PRI | NULL | | +------------------+---------+------+-----+---------+----------------+ 3 rows in set (0.00 sec) </code></pre> <p>I would like to remove the primary keys for user_customer_id and permission_id and retain the primary key for id.</p> <p>When I run the command:</p> <pre><code>alter table user_customer_permission drop primary key; </code></pre> <p>I get the following error:</p> <pre><code>ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key </code></pre> <p>How can I drop a column's primary key?</p>
<p>Without an index, maintaining an autoincrement column becomes too expensive, that's why <code>MySQL</code> requires an autoincrement column to be a leftmost part of an index.</p> <p>You should remove the autoincrement property before dropping the key:</p> <pre><code>ALTER TABLE user_customer_permission MODIFY id INT NOT NULL; ALTER TABLE user_customer_permission DROP PRIMARY KEY; </code></pre> <p>Note that you have a composite <code>PRIMARY KEY</code> which covers all three columns and <code>id</code> is not guaranteed to be unique.</p> <p>If it happens to be unique, you can make it to be a <code>PRIMARY KEY</code> and <code>AUTO_INCREMENT</code> again:</p> <pre><code>ALTER TABLE user_customer_permission MODIFY id INT NOT NULL PRIMARY KEY AUTO_INCREMENT; </code></pre>
{ "question_id": 2111291, "question_date": "2010-01-21T17:20:38.860Z", "question_score": 213, "tags": "mysql|sql|database-design|primary-key|mysql-error-1075", "answer_id": 2111324, "answer_date": "2010-01-21T17:23:31.390Z", "answer_score": 339 }
Please answer the following Stack Overflow question: Title: hexadecimal string to byte array in python <p>I have a long Hex string that represents a series of values of different types. I wish to convert this Hex String into a byte array so that I can shift each value out and convert it into its proper data type. </p>
<p>Suppose your hex string is something like</p> <pre><code>&gt;&gt;&gt; hex_string = &quot;deadbeef&quot; </code></pre> <h3>Convert it to a bytearray (Python 3 and 2.7):</h3> <pre><code>&gt;&gt;&gt; bytearray.fromhex(hex_string) bytearray(b'\xde\xad\xbe\xef') </code></pre> <h3>Convert it to a bytes object (Python 3):</h3> <pre><code>&gt;&gt;&gt; bytes.fromhex(hex_string) b'\xde\xad\xbe\xef' </code></pre> <p>Note that <code>bytes</code> is an immutable version of <code>bytearray</code>.</p> <h3>Convert it to a string (Python ≤ 2.7):</h3> <pre><code>&gt;&gt;&gt; hex_data = hex_string.decode(&quot;hex&quot;) &gt;&gt;&gt; hex_data &quot;\xde\xad\xbe\xef&quot; </code></pre>
{ "question_id": 5649407, "question_date": "2011-04-13T12:43:58.007Z", "question_score": 213, "tags": "python|bytearray", "answer_id": 5682984, "answer_date": "2011-04-15T22:32:21.317Z", "answer_score": 345 }
Please answer the following Stack Overflow question: Title: Converting Stream to String and back...what are we missing? <p>I want to serialize objects to strings, and back.</p> <p>We use protobuf-net to turn an object into a Stream and back, successfully.</p> <p>However, Stream to string and back... not so successful. After going through <code>StreamToString</code> and <code>StringToStream</code>, the new <code>Stream</code>isn't deserialized by protobuf-net; it raises an <code>Arithmetic Operation resulted in an Overflow</code> exception. If we deserialize the original stream, it works.</p> <p>Our methods:</p> <pre><code>public static string StreamToString(Stream stream) { stream.Position = 0; using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { return reader.ReadToEnd(); } } public static Stream StringToStream(string src) { byte[] byteArray = Encoding.UTF8.GetBytes(src); return new MemoryStream(byteArray); } </code></pre> <p>Our example code using these two:</p> <pre><code>MemoryStream stream = new MemoryStream(); Serializer.Serialize&lt;SuperExample&gt;(stream, test); stream.Position = 0; string strout = StreamToString(stream); MemoryStream result = (MemoryStream)StringToStream(strout); var other = Serializer.Deserialize&lt;SuperExample&gt;(result); </code></pre>
<p>This is so common but so profoundly wrong. Protobuf data is not string data. It certainly isn't ASCII. You are using the encoding <strong>backwards</strong>. A text encoding transfers:</p> <ul> <li>an arbitrary string to formatted bytes</li> <li>formatted bytes to the original string</li> </ul> <p>You do not have "formatted bytes". You have <em>arbitrary bytes</em>. You need to use something like a base-n (commonly: base-64) encode. This transfers</p> <ul> <li>arbitrary bytes to a formatted string</li> <li>a formatted string to the original bytes</li> </ul> <p>look at Convert.ToBase64String and Convert. FromBase64String</p>
{ "question_id": 17801761, "question_date": "2013-07-23T04:55:57.853Z", "question_score": 213, "tags": "c#|.net|serialization|deserialization|protobuf-net", "answer_id": 17830185, "answer_date": "2013-07-24T09:32:29.483Z", "answer_score": 63 }
Please answer the following Stack Overflow question: Title: Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on <p>I want to send temperature value from a microcontroller using UART to C# interface and Display temperature on <code>Label.Content</code>. Here is my microcontroller code:</p> <pre><code>while(1) { key_scan(); // get value of temp if (Usart_Data_Ready()) { while(temperature[i]!=0) { if(temperature[i]!=' ') { Usart_Write(temperature[i]); Delay_ms(1000); } i = i + 1; } i =0; Delay_ms(2000); } } </code></pre> <p>and my C# code is:</p> <pre><code>private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { txt += serialPort1.ReadExisting().ToString(); textBox1.Text = txt.ToString(); } </code></pre> <p>but exception arises there "<strong>Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on</strong>" Please tell me how to get temperature string from my microcontroller and remove this Error!</p>
<p>The data received in your <code>serialPort1_DataReceived</code> method is coming from another thread context than the UI thread, and that's the reason you see this error.<br /> To remedy this, you will have to use a dispatcher as descibed in the MSDN article:<br /> <a href="https://docs.microsoft.com/dotnet/framework/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls" rel="noreferrer">How to: Make Thread-Safe Calls to Windows Forms Controls</a></p> <p>So instead of setting the text property directly in the <code>serialport1_DataReceived</code> method, use this pattern:</p> <pre><code>delegate void SetTextCallback(string text); private void SetText(string text) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (this.textBox1.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.textBox1.Text = text; } } </code></pre> <p>So in your case:</p> <pre><code>private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { txt += serialPort1.ReadExisting().ToString(); SetText(txt.ToString()); } </code></pre>
{ "question_id": 10775367, "question_date": "2012-05-27T16:05:48.677Z", "question_score": 213, "tags": "c#|multithreading|invoke|uart", "answer_id": 10775421, "answer_date": "2012-05-27T16:15:14.590Z", "answer_score": 358 }
Please answer the following Stack Overflow question: Title: How to bind 'touchstart' and 'click' events but not respond to both? <p>I'm working on a mobile web site that has to work on a variety of devices. The ones giving me a headache at the moment are BlackBerry.</p> <p>We need to support both keyboard clicks as well as touch events.</p> <p>Ideally I'd just use:</p> <pre><code>$thing.click(function(){...}) </code></pre> <p>but the issue we're running into is that some of these blackberry devices have a very annoying delay from the time of the touch to it triggering a click.</p> <p>The remedy is to instead use touchstart:</p> <pre><code>$thing.bind('touchstart', function(event){...}) </code></pre> <p>But how do I go about binding both events, but only firing one? I still need the click event for keyboard devices, but of course, don't want the click event firing if I'm using a touch device.</p> <p>A bonus question: Is there anyway to do this and additionally accommodate browsers that don't even have a touchstart event? In researching this, it looks like BlackBerry OS5 doesn't support touchstart so will also need to rely on click events for that browser.</p> <p>ADDENDUM:</p> <p>Perhaps a more comprehensive question is:</p> <p>With jQuery, is it possible/recommended to handle both touch interactions and mouse interactions with the same bindings?</p> <p>Ideally, the answer is yes. If not, I do have some options:</p> <ol> <li><p>We use WURFL to get device info so could create our own matrix of devices. Depending on the device, we'll use touchstart OR click.</p> </li> <li><p>Detect for touch support in the browser via JS (I need to do some more research on that, but it seems like that is doable).</p> </li> </ol> <p>However, that still leaves one issue: what about devices that support BOTH. Some of the phones we support (namely the Nokias and BlackBerries) have both touch screens <em>and</em> keyboards. So that kind of takes me full circle back to the original question...is there a way to allow for both at once somehow?</p>
<p><strong>Update</strong>: Check out the jQuery <a href="https://github.com/jquery/PEP">Pointer Events Polyfill</a> project which allows you to bind to "pointer" events instead of choosing between mouse &amp; touch.</p> <hr> <p>Bind to both, but make a flag so the function only fires once per 100ms or so.</p> <pre><code>var flag = false; $thing.bind('touchstart click', function(){ if (!flag) { flag = true; setTimeout(function(){ flag = false; }, 100); // do something } return false }); </code></pre>
{ "question_id": 7018919, "question_date": "2011-08-10T22:56:04.520Z", "question_score": 213, "tags": "jquery|click|touchstart", "answer_id": 7019461, "answer_date": "2011-08-11T00:14:42.350Z", "answer_score": 144 }
Please answer the following Stack Overflow question: Title: jQuery posting JSON <p>update: I would like to pass the <code>var value</code> to the server</p> <p>hello, same old, same old ... :)</p> <p>I have a form called <code>&lt;form id="testForm" action="javascript:test()"&gt;</code> and a code area called <code>&lt;code id="testArea"&gt;&lt;/code&gt;</code></p> <p>I am using this code to stringify and display the data in the code area:</p> <pre><code>var formData = form2object('testForm'); document.getElementById('testArea').innerHTML = JSON.stringify(formData, null, '\t'); var value = JSON.stringify(formData, null, '\t'); </code></pre> <p>What I want is to send this data to a JSON file. I've been working on this project : <a href="http://ridegrab.com/profile_old/" rel="noreferrer">http://ridegrab.com/profile_old/</a> and if you press <code>Submit Query</code> button you will see the head of the page populate.</p> <p>Also I want use this piece of script to send data:</p> <pre><code> function authenticate(userName, password) { $.ajax ({ type: "POST", //the url where you want to sent the userName and password to url: 'username:password@link to the server/update', dataType: 'json', async: false, //json object to sent to the authentication url data: '{"userName": "' + userName + '", "password" : "' + password + '"}', success: function () { alert("Thanks!"); } }) } </code></pre> <p>Again, all I want is to be able to send that JSON data to the server. My server is set up to <code>update or POST</code> the data in the right place.</p>
<p>'data' should be a stringified JavaScript object:</p> <pre><code>data: JSON.stringify({ &quot;userName&quot;: userName, &quot;password&quot; : password }) </code></pre> <p>To send your <code>formData</code>, pass it to <code>stringify</code>:</p> <pre><code>data: JSON.stringify(formData) </code></pre> <p>Some servers also require the <code>application/json</code> content type header:</p> <pre><code>contentType: 'application/json' </code></pre> <p>There's also a more detailed answer to a similar question here: <a href="https://stackoverflow.com/questions/6323338/jquery-ajax-posting-json-to-webservice">Jquery Ajax Posting JSON to webservice</a></p>
{ "question_id": 5570747, "question_date": "2011-04-06T17:49:01.347Z", "question_score": 213, "tags": "jquery|json|post", "answer_id": 5571112, "answer_date": "2011-04-06T18:19:08.463Z", "answer_score": 243 }
Please answer the following Stack Overflow question: Title: JavaScript foreach loop on an associative array object <p>Why is my for for-each loop not iterating over my JavaScript associative array object?</p> <pre><code>// Defining an array var array = []; // Assigning values to corresponding keys array[&quot;Main&quot;] = &quot;Main page&quot;; array[&quot;Guide&quot;] = &quot;Guide page&quot;; array[&quot;Articles&quot;] = &quot;Articles page&quot;; array[&quot;Forum&quot;] = &quot;Forum board&quot;; // Expected: loop over every item, // yet it logs only &quot;last&quot; assigned value - &quot;Forum&quot; for (var i = 0; i &lt; array.length; i++) { console.log(array[i]); } </code></pre> <p>jQuery <code>each()</code> could be helpful: <a href="https://api.jquery.com/jQuery.each/" rel="noreferrer">https://api.jquery.com/jQuery.each/</a></p>
<p>The <code>.length</code> property only tracks properties with numeric indexes (keys). You're using strings for keys.</p> <p>You can do this:</p> <pre><code>var arr_jq_TabContents = {}; // no need for an array arr_jq_TabContents["Main"] = jq_TabContents_Main; arr_jq_TabContents["Guide"] = jq_TabContents_Guide; arr_jq_TabContents["Articles"] = jq_TabContents_Articles; arr_jq_TabContents["Forum"] = jq_TabContents_Forum; for (var key in arr_jq_TabContents) { console.log(arr_jq_TabContents[key]); } </code></pre> <p>To be safe, it's a good idea in loops like that to make sure that none of the properties are unexpected results of inheritance:</p> <pre><code>for (var key in arr_jq_TabContents) { if (arr_jq_TabContents.hasOwnProperty(key)) console.log(arr_jq_TabContents[key]); } </code></pre> <p><em>edit</em> &mdash; it's probably a good idea now to note that the <code>Object.keys()</code> function is available on modern browsers and in Node etc. That function returns the "own" keys of an object, as an array:</p> <pre><code>Object.keys(arr_jq_TabContents).forEach(function(key, index) { console.log(this[key]); }, arr_jq_TabContents); </code></pre> <p>The callback function passed to <code>.forEach()</code> is called with each key and the key's index in the array returned by <code>Object.keys()</code>. It's also passed the array through which the function is iterating, but that array is not really useful to us; we need the original <em>object</em>. That can be accessed directly by name, but (in my opinion) it's a little nicer to pass it explicitly, which is done by passing a second argument to <code>.forEach()</code> &mdash; the original object &mdash; which will be bound as <code>this</code> inside the callback. (Just saw that this was noted in a comment below.)</p>
{ "question_id": 18804592, "question_date": "2013-09-14T17:42:15.980Z", "question_score": 213, "tags": "javascript|arrays|foreach", "answer_id": 18804596, "answer_date": "2013-09-14T17:42:52.860Z", "answer_score": 355 }
Please answer the following Stack Overflow question: Title: Issue with virtualenv - cannot activate <p>I created a virtualenv around my project, but when I try to activate it I cannot. It might just be syntax or folder location, but I am stumped right now.</p> <p>You can see below, I create the virtualenv and call it venv. Everything looks good, then I try to activate it by running <code>source venv/bin/activate</code></p> <p>I'm thinking it might just have to do with my system path, but not sure what to point it to (I do know how to edit the path). I'm on python 7 / windows os, virtual env 2.2.x</p> <pre> Processing dependencies for virtualenv Finished processing dependencies for virtualenv c:\testdjangoproj\mysite>virtualenv --no-site-packages venv The --no-site-packages flag is deprecated; it is now the default behavior. Using real prefix 'C:\\Program Files (x86)\\Python' New python executable in venv\Scripts\python.exe File venv\Lib\distutils\distutils.cfg exists with different content; not overwri ting Installing setuptools.................done. Installing pip...................done. c:\testdjangoproj\mysite>source venv/bin/activate 'source' is not recognized as an internal or external command, operable program or batch file. c:\testdjangoproj\mysite>source venv/bin/activate 'source' is not recognized as an internal or external command, operable program or batch file. c:\testdjangoproj\mysite>source mysite/bin/activate 'source' is not recognized as an internal or external command, operable program or batch file. c:\testdjangoproj\mysite> </pre>
<p><code>source</code> is a shell command designed for users running on Linux (or any Posix, but whatever, not Windows).</p> <p>On Windows, virtualenv creates a .bat/.ps1 file, so you should run <code>venv\Scripts\activate</code> instead (per the virtualenv <a href="https://virtualenv.pypa.io/en/legacy/userguide.html#activate-script" rel="noreferrer">documentation on the activate script</a>).</p> <p>Just run <code>activate</code>, without an extension, so the right file will get used regardless of whether you're using cmd.exe or PowerShell.</p>
{ "question_id": 8921188, "question_date": "2012-01-19T04:54:37.953Z", "question_score": 213, "tags": "python|virtualenv", "answer_id": 8921211, "answer_date": "2012-01-19T04:57:50.810Z", "answer_score": 498 }
Please answer the following Stack Overflow question: Title: Remote Debugging for Chrome iOS (and Safari) <p>With the recent release of Chrome for iOS, I was wondering how do you enable remote debugging for Chrome iOS?</p> <p>Update: With the release of iOS 6, remote debugging can now be done with <strong><em>Safari</em></strong>.</p>
<p><strong>Update:</strong></p> <p>This is <strong>not</strong> the best answer anymore, please follow <a href="https://stackoverflow.com/questions/11262236/ios-remote-debugging/22047495#22047495">gregers</a>' advice.</p> <p><strong>New answer:</strong></p> <p>Use <a href="https://stackoverflow.com/questions/11262236/ios-remote-debugging/22047495#22047495">Weinre</a>.</p> <p><strong>Old answer:</strong></p> <p>You can now use Safari for remote debugging. But it requires iOS 6.</p> <p>Here is a quick translation of <a href="http://html5-mobile.de/blog/ios6-remote-debugging-web-inspector" rel="noreferrer">http://html5-mobile.de/blog/ios6-remote-debugging-web-inspector</a></p> <ol> <li>Connect your iDevice via USB with your Mac</li> <li>Open Safari on your Mac and activate the dev tools</li> <li>On your iDevice: go to settings > safari > advanced and activate the web inspector</li> <li>Go to any website with your iDevice</li> <li>On your Mac: Open the developer menu and chose the site from your iDevice (its at the top Safari Menu)</li> </ol> <p>As pointed out by <a href="https://stackoverflow.com/a/15428492/981933">Simons answer</a> one need to turn off private browsing to make remote debugging work.</p> <p>Settings > Safari > Private Browsing > OFF</p>
{ "question_id": 11262236, "question_date": "2012-06-29T12:58:10.157Z", "question_score": 213, "tags": "google-chrome|google-chrome-devtools|chrome-for-ios", "answer_id": 12607124, "answer_date": "2012-09-26T17:23:37.043Z", "answer_score": 120 }
Please answer the following Stack Overflow question: Title: Bootstrap 3 Navbar Collapse <p>Is there any way to increase the point at which the bootstrap 3 navbar collapses (i.e. so that it collapses into a drop down on portrait tablets)?</p> <p>These two were applicable to bootstrap 2 but not now!</p> <p><a href="https://stackoverflow.com/questions/9405610/how-to-change-navbar-collapse-threshold-using-twitter-bootstrap-responsive">How to change navbar collapse threshold using Twitter bootstrap-responsive?</a></p> <p><a href="https://stackoverflow.com/questions/12486051/bootstrap-change-the-default-responsive-navbar-breakpoint">Change the default responsive navbar breakpoint</a></p>
<p>I had the same problem today.</p> <p><strong>Bootstrap 4</strong></p> <p>It's a native functionality: <a href="https://getbootstrap.com/docs/4.0/components/navbar/#responsive-behaviors" rel="noreferrer">https://getbootstrap.com/docs/4.0/components/navbar/#responsive-behaviors</a></p> <p>You have to use <code>.navbar-expand{-sm|-md|-lg|-xl}</code> classes:</p> <pre><code>&lt;nav class="navbar navbar-expand-md navbar-light bg-light"&gt; </code></pre> <p><strong>Bootstrap 3</strong></p> <pre class="lang-css prettyprint-override"><code>@media (max-width: 991px) { .navbar-header { float: none; } .navbar-toggle { display: block; } .navbar-collapse { border-top: 1px solid transparent; box-shadow: inset 0 1px 0 rgba(255,255,255,0.1); } .navbar-collapse.collapse { display: none!important; } .navbar-nav { float: none!important; margin: 7.5px -15px; } .navbar-nav&gt;li { float: none; } .navbar-nav&gt;li&gt;a { padding-top: 10px; padding-bottom: 10px; } .navbar-text { float: none; margin: 15px 0; } /* since 3.1.0 */ .navbar-collapse.collapse.in { display: block!important; } .collapsing { overflow: hidden!important; } } </code></pre> <p>Just change <code>991px</code> by <code>1199px</code> for <code>md</code> sizes.</p> <p><a href="http://www.bootply.com/Wf53bcAyl8" rel="noreferrer">Demo</a></p>
{ "question_id": 18192082, "question_date": "2013-08-12T16:29:22.477Z", "question_score": 213, "tags": "twitter-bootstrap|twitter-bootstrap-3|navbar", "answer_id": 20249415, "answer_date": "2013-11-27T17:42:00.727Z", "answer_score": 346 }
Please answer the following Stack Overflow question: Title: Setting a system environment variable from a Windows batch file? <p>Is it possible to set a environment variable at the system level from a command prompt in Windows 7 (or even XP for that matter). I am running from an elevated command prompt.</p> <p>When I use the <code>set</code> command (<code>set name=value</code>), the environment variable seems to be only valid for the session of the command prompt.</p>
<p>The XP Support Tools (which can be installed from your XP CD) come with a program called <code>setx.exe</code>:</p> <pre><code>C:\Program Files\Support Tools&gt;setx /? SETX: This program is used to set values in the environment of the machine or currently logged on user using one of three modes. 1) Command Line Mode: setx variable value [-m] Optional Switches: -m Set value in the Machine environment. Default is User. ... For more information and example use: SETX -i </code></pre> <p>I think Windows 7 actually comes with <code>setx</code> as part of a standard install.</p>
{ "question_id": 3803581, "question_date": "2010-09-27T12:07:27.660Z", "question_score": 213, "tags": "windows|batch-file|cmd|environment-variables", "answer_id": 3804979, "answer_date": "2010-09-27T14:49:07.547Z", "answer_score": 188 }
Please answer the following Stack Overflow question: Title: How to connect to remote Redis server? <p>I have URL and PORT of remote Redis server. I am able to write into Redis from Scala. However I want to connect to remote Redis via terminal using <code>redis-server</code> or something similar in order to make several call of <code>hget</code>, <code>get</code>, etc. (I can do it with my locally installed Redis without any problem).</p>
<pre><code>redis-cli -h XXX.XXX.XXX.XXX -p YYYY </code></pre> <p><code>xxx.xxx.xxx.xxx</code> is the IP address and <code>yyyy</code> is the port</p> <p>EXAMPLE from my dev environment</p> <pre><code>redis-cli -h 10.144.62.3 -p 30000 </code></pre> <p><a href="http://redis.io/topics/rediscli" rel="noreferrer">REDIS CLI COMMANDS</a></p> <blockquote> <p>Host, port, password and database By default redis-cli connects to the server at 127.0.0.1 port 6379. As you can guess, you can easily change this using command line options. To specify a different host name or an IP address, use -h. In order to set a different port, use -p.</p> <p>redis-cli -h redis15.localnet.org -p 6390 ping</p> </blockquote>
{ "question_id": 40678865, "question_date": "2016-11-18T13:54:57.337Z", "question_score": 213, "tags": "redis", "answer_id": 40678950, "answer_date": "2016-11-18T13:59:03.230Z", "answer_score": 382 }
Please answer the following Stack Overflow question: Title: Error to use a section registered as allowDefinition='MachineToApplication' beyond application level <blockquote> <p>It is an error to use a section registered as <code>allowDefinition='MachineToApplication'</code> beyond application level.</p> </blockquote> <p>The top line in all of my aspx pages in my <code>/portal/</code> directory has this error message, and I know it's a common one. I have googled this error message to no end, and I see a lot of posts telling me to configure the <code>/portal/</code> folder as an application in IIS (which I have), and more posts telling me I have nested <code>web.config</code>s (but none of the postings offer guidance toward a solution).</p> <p>My setup is that I have a <code>web.config</code> in my root directory, and then I'm trying to make a company portal, in the <code>/portal/</code> directory. The <code>/portal/</code> directory has its own (necessary) <code>web.config</code>.</p> <p>My web.config line 50 is like this:</p> <pre><code>&lt;customErrors mode=&quot;Off&quot; defaultRedirect=&quot;customerrorpage.aspx&quot;/&gt; &lt;anonymousIdentification enabled=&quot;true&quot;/&gt; &lt;authentication mode=&quot;Forms&quot;/&gt; &lt;membership defaultProvider=&quot;MyProvider&quot;&gt; </code></pre> <p>So I have <code>domain.example/web.config</code> and <code>domain.example/portal/web.config</code> ... so my <code>domain.example/portal/default.aspx</code> page will not load.</p> <p>What is the real solution to this? Do I somehow find a way to merge my root <code>web.config</code> with my <code>/portal/</code> directory <code>web.config</code>, or am I way off base here?</p>
<p>Just for background information; Configuration information for an ASP.NET website is defined in one or more Web.config files. The configuration settings are applied in a hierarchical manner. There's a “global” Web.config file that spells out the baseline configuration information for all websites on the web server; this file lives in the <code>%WINDIR%\Microsoft.Net\Framework\version\CONFIG</code> folder. You can also have a Web.config file in the root folder of your website. This Web.config file can override settings defined in the “global” Web.config file, or add new ones. Additionally, you may have Web.config files in the subfolders of your website, which define new configuration settings or override configuration settings defined in Web.config files higher up in the hierarchy.</p> <p>Certain configuration elements in Web.config cannot be defined beyond the application level, meaning that they must be defined in the “global” Web.config file or in the Web.config file in the website's root folder. The <code>&lt;authentication&gt;</code> element is one such example. The above error message indicates that there is a Web.config file in one of the website's subfolders that has one of these configuration elements that cannot be defined beyond the application level.</p> <p>Source: <a href="http://scottonwriting.net/sowblog/archive/2010/02/17/163375.aspx" rel="noreferrer">http://scottonwriting.net/sowblog/archive/2010/02/17/163375.aspx</a></p> <p>You have correctly identified the 2 possible approaches. </p> <p>1 - Depending on the contents of your second web.config and if your setup would allow (i.e same authentication method) - add the <code>&lt;authentication&gt;</code> settings and any other elements that should be define globally into the top web.config</p> <p>2 - If you cannot merge then web.config contents then you should be able to turn the sub-folder into a web application in IIS by following the steps contained in this link archived link below. The original link is no longer working. (see <a href="https://web.archive.org/web/20140811021651/http://www.tamilcodes.com/asp-net/converting-virtual-directory-into-an-application-to-run-asp-net-in-iis/" rel="noreferrer">archived</a>) Hope this helps.</p>
{ "question_id": 9300927, "question_date": "2012-02-15T20:36:42.490Z", "question_score": 213, "tags": "asp.net|web-config", "answer_id": 9301369, "answer_date": "2012-02-15T21:05:10.127Z", "answer_score": 228 }
Please answer the following Stack Overflow question: Title: JavaScript DOM remove element <p>I'm trying to test if a DOM element exists, and if it does exist delete it, and if it doesn't exist create it.</p> <pre><code>var duskdawnkey = localStorage["duskdawnkey"]; var iframe = document.createElement("iframe"); var whereto = document.getElementById("debug"); var frameid = document.getElementById("injected_frame"); iframe.setAttribute("id", "injected_frame"); iframe.setAttribute("src", 'http://google.com'); iframe.setAttribute("width", "100%"); iframe.setAttribute("height", "400"); if (frameid) // check and see if iframe is already on page { //yes? Remove iframe iframe.removeChild(frameid.childNodes[0]); } else // no? Inject iframe { whereto.appendChild(iframe); // add the newly created element and it's content into the DOM my_div = document.getElementById("debug"); document.body.insertBefore(iframe, my_div); } </code></pre> <p>Checking if it exists works, creating the element works, but deleting the element doesn't. Basically all this code does is inject an iframe into a webpage by clicking a button. What I would like to happen is if the iframe is already there to delete it. But for some reason I am failing.</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Node.removeChild" rel="noreferrer"><code>removeChild</code></a> should be invoked on the parent, i.e.:</p> <pre><code>parent.removeChild(child); </code></pre> <p>In your example, you should be doing something like:</p> <pre><code>if (frameid) { frameid.parentNode.removeChild(frameid); } </code></pre>
{ "question_id": 8830839, "question_date": "2012-01-12T06:06:29.197Z", "question_score": 213, "tags": "javascript|dom", "answer_id": 8830882, "answer_date": "2012-01-12T06:11:59.513Z", "answer_score": 351 }
Please answer the following Stack Overflow question: Title: Converting XML to JSON using Python? <p>I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.</p> <p>So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.</p> <p>This public <a href="http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&amp;cm_cat=rss&amp;par=LWO_rss" rel="noreferrer">weather.com RSS feed</a> is a good example of what we'd be parsing (<em>our actual weather.com feed contains additional information because of a partnership w/them</em>).</p> <p>In a nutshell, how should we convert XML to JSON using Python?</p>
<p>There is no "one-to-one" mapping between XML and JSON, so converting one to the other necessarily requires some understanding of what you want to <em>do</em> with the results.</p> <p>That being said, Python's standard library has <a href="http://docs.python.org/2/library/xml.html" rel="noreferrer">several modules for parsing XML</a> (including DOM, SAX, and ElementTree). As of Python 2.6, support for converting Python data structures to and from JSON is included in the <a href="http://docs.python.org/2/library/json.html" rel="noreferrer"><code>json</code> module</a>.</p> <p>So the infrastructure is there.</p>
{ "question_id": 191536, "question_date": "2008-10-10T14:19:44.207Z", "question_score": 213, "tags": "python|json|xml|converter", "answer_id": 191617, "answer_date": "2008-10-10T14:34:55.580Z", "answer_score": 70 }
Please answer the following Stack Overflow question: Title: How do I calculate the date in JavaScript three months prior to today? <p>I Am trying to form a date which is 3 months before the current date. I get the current month by the below code</p> <pre><code>var currentDate = new Date(); var currentMonth = currentDate.getMonth()+1; </code></pre> <p>Can you guys provide me the logic to calculate and form a date (an object of the <code>Date</code> data type) considering that when the month is January (1), 3 months before date would be OCtober (10)?</p>
<pre><code>var d = new Date(); d.setMonth(d.getMonth() - 3); </code></pre> <p>This works for January. Run this snippet:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var d = new Date("January 14, 2012"); console.log(d.toLocaleDateString()); d.setMonth(d.getMonth() - 3); console.log(d.toLocaleDateString());</code></pre> </div> </div> </p> <hr> <p><strong>There are some caveats...</strong></p> <p>A month is a curious thing. How do you define 1 month? 30 days? Most people will say that one month ago means the same day of the month on the previous month <sup><a href="https://xkcd.com/285/" rel="noreferrer">citation needed</a></sup>. But more than half the time, that is 31 days ago, not 30. And if today is the 31st of the month (and it isn't August or Decemeber), that day of the month doesn't exist in the previous month.</p> <p>Interestingly, Google agrees with JavaScript if you ask it <a href="https://www.google.com/search?q=one+month+before+March+31+1995" rel="noreferrer">what day is one month before another day</a>:</p> <p><img src="https://i.stack.imgur.com/hLBZE.png" alt="Google search result for &#39;one month before March 31st&#39; shows &#39;March 3rd&#39;"></p> <p>It also says that <a href="https://www.google.com/search?q=one+month+in+days" rel="noreferrer">one month is 30.4167 days long</a>: <img src="https://i.stack.imgur.com/Heouk.png" alt="Google search result for &#39;one month in days&#39; shows &#39;30.4167&#39;"></p> <p>So, is one month before March 31st the same day as one month before March 28th, 3 days earlier? This all depends on what you mean by "one month before". Go have a conversation with your product owner.</p> <p>If you want to do like momentjs does, and correct these last day of the month errors by moving to the last day of the month, you can do something like this:</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 d = new Date("March 31, 2019"); console.log(d.toLocaleDateString()); const month = d.getMonth(); d.setMonth(d.getMonth() - 1); while (d.getMonth() === month) { d.setDate(d.getDate() - 1); } console.log(d.toLocaleDateString());</code></pre> </div> </div> </p> <p>If your requirements are more complicated than that, use some math and write some code. You are a developer! You don't have to install a library! You don't have to copy and paste from stackoverflow! You can develop the code yourself to do precisely what you need!</p>
{ "question_id": 7937233, "question_date": "2011-10-29T05:44:21.933Z", "question_score": 213, "tags": "javascript|date", "answer_id": 7937257, "answer_date": "2011-10-29T05:53:37.133Z", "answer_score": 451 }
Please answer the following Stack Overflow question: Title: How to set a default value with Html.TextBoxFor? <p>Simple question, if you use the Html Helper from ASP.NET MVC Framework 1 it is easy to set a default value on a textbox because there is an overload <code>Html.TextBox(string name, object value)</code>. When I tried using the <em>Html.TextBoxFor</em> method, my first guess was to try the following which did not work:</p> <pre><code>&lt;%: Html.TextBoxFor(x =&gt; x.Age, new { value = "0"}) %&gt; </code></pre> <p>Should I just stick with Html.TextBox(string, object) for now?</p>
<p>It turns out that if you don't specify the Model to the View method within your controller, it doesn't create a object for you with the default values.</p> <pre><code>[AcceptVerbs(HttpVerbs.Get)] public ViewResult Create() { // Loads default values Instructor i = new Instructor(); return View("Create", i); } [AcceptVerbs(HttpVerbs.Get)] public ViewResult Create() { // Does not load default values from instructor return View("Create"); } </code></pre>
{ "question_id": 3034986, "question_date": "2010-06-14T04:41:43.687Z", "question_score": 213, "tags": "c#|asp.net-mvc-2|html-helper", "answer_id": 3038589, "answer_date": "2010-06-14T15:41:37.267Z", "answer_score": 31 }
Please answer the following Stack Overflow question: Title: Most efficient T-SQL way to pad a varchar on the left to a certain length? <p>As compared to say:</p> <pre><code>REPLICATE(@padchar, @len - LEN(@str)) + @str </code></pre>
<p>This is simply an inefficient use of SQL, no matter how you do it. </p> <p>perhaps something like </p> <pre><code>right('XXXXXXXXXXXX'+ rtrim(@str), @n) </code></pre> <p>where X is your padding character and @n is the number of characters in the resulting string (assuming you need the padding because you are dealing with a fixed length). </p> <p>But as I said you should really avoid doing this in your database.</p>
{ "question_id": 121864, "question_date": "2008-09-23T15:46:39.147Z", "question_score": 213, "tags": "sql|sql-server|tsql", "answer_id": 121890, "answer_date": "2008-09-23T15:50:14.240Z", "answer_score": 333 }
Please answer the following Stack Overflow question: Title: Put content in HttpResponseMessage object? <p>Several months ago, Microsoft decided to change up the HttpResponseMessage class. Before, you could simply pass a data type into the constructor, and then return the message with that data, but not anymore.</p> <p>Now, you need to use the Content property to set the content of the message. The problem is that it is of type HttpContent, and I can't seem to find a way to convert a string, for example, to HttpContent.</p> <p>Does anyone know how to deal with this issue? Thanks a lot.</p>
<p>Apparently the new way to do it is detailed here:</p> <p><a href="http://aspnetwebstack.codeplex.com/discussions/350492" rel="noreferrer">http://aspnetwebstack.codeplex.com/discussions/350492</a></p> <p>To quote Henrik,</p> <pre class="lang-cs prettyprint-override"><code>HttpResponseMessage response = new HttpResponseMessage(); response.Content = new ObjectContent&lt;T&gt;(T, myFormatter, "application/some-format"); </code></pre> <p>So basically, one has to create a ObjectContent type, which apparently can be returned as an HttpContent object. </p>
{ "question_id": 12240713, "question_date": "2012-09-03T00:02:05.517Z", "question_score": 213, "tags": "c#|asp.net-mvc|asp.net-web-api", "answer_id": 12240738, "answer_date": "2012-09-03T00:09:50.490Z", "answer_score": 74 }
Please answer the following Stack Overflow question: Title: How to load a tsv file into a Pandas DataFrame? <p>I'm new to python and pandas. I'm trying to get a <code>tsv</code> file loaded into a pandas <code>DataFrame</code>. </p> <p>This is what I'm trying and the error I'm getting:</p> <pre><code>&gt;&gt;&gt; df1 = DataFrame(csv.reader(open('c:/~/trainSetRel3.txt'), delimiter='\t')) Traceback (most recent call last): File "&lt;pyshell#28&gt;", line 1, in &lt;module&gt; df1 = DataFrame(csv.reader(open('c:/~/trainSetRel3.txt'), delimiter='\t')) File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 318, in __init__ raise PandasError('DataFrame constructor not properly called!') PandasError: DataFrame constructor not properly called! </code></pre>
<p>The <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="noreferrer">.read_csv</a> function does what you want:</p> <pre><code>pd.read_csv('c:/~/trainSetRel3.txt', sep='\t') </code></pre> <p>If you have a header, you can pass <code>header=0</code>.</p> <pre><code>pd.read_csv('c:/~/trainSetRel3.txt', sep='\t', header=0) </code></pre> <p><strong>Note</strong>: Prior 17.0, <code>pd.DataFrame.from_csv</code> was used (it is now deprecated and <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.from_csv.html" rel="noreferrer">the <code>.from_csv</code> documentation link</a> redirects to the page for <code>pd.read_csv</code>).</p>
{ "question_id": 9652832, "question_date": "2012-03-11T06:00:56.347Z", "question_score": 213, "tags": "python|pandas|csv", "answer_id": 9652858, "answer_date": "2012-03-11T06:06:56.443Z", "answer_score": 240 }
Please answer the following Stack Overflow question: Title: PHP PDO: charset, set names? <p>I had this previously in my normal mysql_* connection:</p> <pre><code>mysql_set_charset("utf8",$link); mysql_query("SET NAMES 'UTF8'"); </code></pre> <p>Do I need it for the PDO? And where should I have it?</p> <pre><code>$connect = new PDO("mysql:host=$host;dbname=$db", $user, $pass, array(PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION)); </code></pre>
<p>You'll have it in your connection string like:</p> <pre><code>&quot;mysql:host=$host;dbname=$db;charset=utf8mb4&quot; </code></pre> <p>HOWEVER, prior to PHP 5.3.6, the charset option was ignored. If you're running an older version of PHP, you must do it like this:</p> <pre><code>$dbh = new PDO(&quot;mysql:host=$host;dbname=$db&quot;, $user, $password); $dbh-&gt;exec(&quot;set names utf8mb4&quot;); </code></pre>
{ "question_id": 4361459, "question_date": "2010-12-05T21:54:00.873Z", "question_score": 213, "tags": "php|mysql|pdo", "answer_id": 4361485, "answer_date": "2010-12-05T21:58:22.877Z", "answer_score": 519 }
Please answer the following Stack Overflow question: Title: Do checkbox inputs only post data if they're checked? <p>Is it standard behaviour for browsers to only send the checkbox input value data if it is checked upon form submission?</p> <p>And if no value data is supplied, is the default value always "on"?</p> <p>Assuming the above is correct, is this consistent behaviour across all browsers?</p>
<p>Yes, standard behaviour is the value is only sent if the checkbox is checked. This typically means you need to have a way of remembering what checkboxes you are expecting on the server side since not all the data comes back from the form.</p> <p>The default value is always "on", this should be consistent across browsers. </p> <p>This is covered in the <a href="http://www.w3.org/TR/html401/interact/forms.html">W3C HTML 4 recommendation</a>:</p> <blockquote> <p>Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.</p> </blockquote>
{ "question_id": 11424037, "question_date": "2012-07-11T00:48:49.150Z", "question_score": 213, "tags": "html|input|checkbox", "answer_id": 11424089, "answer_date": "2012-07-11T00:55:54.127Z", "answer_score": 215 }
Please answer the following Stack Overflow question: Title: Convert String to Type in C# <p>If I receive a string that contains the name of a class and I want to convert this string to a real type (the one in the string), how can I do this?</p> <p>I tried</p> <pre><code>Type.GetType("System.Int32") </code></pre> <p>for example, it appears to work.</p> <p>But when I try with my own object, it always returns null ...</p> <p>I have no idea what will be in the string in advance so it's my only source for converting it to its real type.</p> <pre><code>Type.GetType("NameSpace.MyClasse"); </code></pre> <p>Any idea?</p>
<p>You can only use <em>just</em> the name of the type (with its namespace, of course) if the type is in <code>mscorlib</code> or the calling assembly. Otherwise, you've got to include the assembly name as well:</p> <pre><code>Type type = Type.GetType("Namespace.MyClass, MyAssembly"); </code></pre> <p>If the assembly is strongly named, you've got to include all that information too. See the documentation for <a href="http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx" rel="noreferrer"><code>Type.GetType(string)</code></a> for more information.</p> <p>Alternatively, if you have a reference to the assembly already (e.g. through a well-known type) you can use <a href="http://msdn.microsoft.com/en-us/library/y0cd10tb.aspx" rel="noreferrer"><code>Assembly.GetType</code></a>:</p> <pre><code>Assembly asm = typeof(SomeKnownType).Assembly; Type type = asm.GetType(namespaceQualifiedTypeName); </code></pre>
{ "question_id": 11107536, "question_date": "2012-06-19T18:55:47.743Z", "question_score": 213, "tags": "c#|.net|string|types", "answer_id": 11107562, "answer_date": "2012-06-19T18:57:40.303Z", "answer_score": 446 }
Please answer the following Stack Overflow question: Title: How to configure postgresql for the first time? <p>I have just installed postgresql and I specified password x during installation. When I try to do <code>createdb</code> and specify any password I get the message:</p> <blockquote> <p>createdb: could not connect to database postgres: FATAL: password authentication failed for user</p> </blockquote> <p>Same for <code>createuser</code>.</p> <p>How should I start? Can I add myself as a user to the database?</p>
<p>The other answers were not completely satisfying to me. Here's what worked for postgresql-9.1 on Xubuntu 12.04.1 LTS.</p> <ol> <li><p>Connect to the default database with user postgres:</p> <blockquote> <p>sudo -u postgres psql template1</p> </blockquote></li> <li><p>Set the password for user postgres, then exit psql (Ctrl-D):</p> <blockquote> <p>ALTER USER postgres with encrypted password 'xxxxxxx';</p> </blockquote></li> <li><p>Edit the <code>pg_hba.conf</code> file:</p> <blockquote> <p>sudo vim /etc/postgresql/9.1/main/pg_hba.conf</p> </blockquote> <p>and change "peer" to "md5" on the line concerning postgres:</p> <blockquote> <p>local&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;all&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>postgres</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strike>peer</strike> md5</p> </blockquote> <p>To know what version of postgresql you are running, look for the version folder under <code>/etc/postgresql</code>. Also, you can use Nano or other editor instead of VIM.</p></li> <li><p>Restart the database :</p> <blockquote> <p>sudo /etc/init.d/postgresql restart</p> </blockquote> <p>(Here you can check if it worked with <code>psql -U postgres</code>).</p></li> <li><p>Create a user having the same name as you (to find it, you can type <code>whoami</code>):</p> <blockquote> <p>sudo createuser -U postgres -d -e -E -l -P -r -s <code>&lt;my_name&gt;</code></p> </blockquote> <p>The options tell postgresql to create a user that can login, create databases, create new roles, is a superuser, and will have an encrypted password. The really important ones are -P -E, so that you're asked to type the password that will be encrypted, and -d so that you can do a <code>createdb</code>.</p> <p><strong>Beware of passwords</strong>: it will first ask you twice the new password (for the new user), repeated, and then once the postgres password (the one specified on step 2).</p></li> <li><p>Again, edit the <code>pg_hba.conf</code> file (see step 3 above), and change "peer" to "md5" on the line concerning "all" other users:</p> <blockquote> <p>local&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;all&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>all</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strike>peer</strike> md5</p> </blockquote></li> <li><p>Restart (like in step 4), and check that you can login without -U postgres:</p> <blockquote> <p>psql template1</p> </blockquote> <p>Note that if you do a mere <code>psql</code>, it will fail since it will try to connect you to a default database having the same name as you (i.e. <code>whoami</code>). template1 is the admin database that is here from the start.</p></li> <li><p>Now <code>createdb &lt;dbname&gt;</code> should work.</p></li> </ol>
{ "question_id": 1471571, "question_date": "2009-09-24T13:06:18.187Z", "question_score": 213, "tags": "linux|database|postgresql|configuration", "answer_id": 12670521, "answer_date": "2012-10-01T09:20:46.177Z", "answer_score": 347 }
Please answer the following Stack Overflow question: Title: /** and /* in Java Comments <p>What's the difference between </p> <pre><code>/** * comment * * */ </code></pre> <p>and </p> <pre><code>/* * * comment * */ </code></pre> <p>in Java? When should I use them?</p>
<p>The first form is called <a href="http://en.wikipedia.org/wiki/Javadoc">Javadoc</a>. You use this when you're writing formal APIs for your code, which are generated by the <code>javadoc</code> tool. For an example, <a href="http://docs.oracle.com/javase/7/docs/api/">the Java 7 API page</a> uses Javadoc and was generated by that tool.</p> <p>Some common elements you'd see in Javadoc include:</p> <ul> <li><p><code>@param</code>: this is used to indicate what parameters are being passed to a method, and what value they're expected to have</p></li> <li><p><code>@return</code>: this is used to indicate what result the method is going to give back</p></li> <li><p><code>@throws</code>: this is used to indicate that a method throws an exception or error in case of certain input</p></li> <li><p><code>@since</code>: this is used to indicate the earliest Java version this class or function was available in</p></li> </ul> <p>As an example, here's Javadoc for the <code>compare</code> method of <code>Integer</code>:</p> <pre><code>/** * Compares two {@code int} values numerically. * The value returned is identical to what would be returned by: * &lt;pre&gt; * Integer.valueOf(x).compareTo(Integer.valueOf(y)) * &lt;/pre&gt; * * @param x the first {@code int} to compare * @param y the second {@code int} to compare * @return the value {@code 0} if {@code x == y}; * a value less than {@code 0} if {@code x &lt; y}; and * a value greater than {@code 0} if {@code x &gt; y} * @since 1.7 */ public static int compare(int x, int y) { return (x &lt; y) ? -1 : ((x == y) ? 0 : 1); } </code></pre> <p>The second form is a block (multi-line) comment. You use this if you want to have multiple lines in a comment.</p> <p>I will say that you'd only want to use the latter form <em>sparingly</em>; that is, you don't want to overburden your code with block comments that don't describe what behaviors the method/complex function is supposed to have.</p> <p>Since Javadoc is the more descriptive of the two, and you can generate actual documentation as a result of using it, using Javadoc would be more preferable to simple block comments.</p>
{ "question_id": 29815636, "question_date": "2015-04-23T06:42:55.060Z", "question_score": 213, "tags": "java|comments|javadoc", "answer_id": 29815698, "answer_date": "2015-04-23T06:45:46.877Z", "answer_score": 255 }
Please answer the following Stack Overflow question: Title: How can I remove all text after a character in bash? <p>How can I remove all text after a character, in this case a colon (":"), in bash? Can I remove the colon, too? I have no idea how to. </p>
<p>An example might have been useful, but if I understood you correctly, this would work:</p> <pre><code>echo &quot;Hello: world&quot; | cut -f1 -d&quot;:&quot; </code></pre> <p>This will convert <code>Hello: world</code> into <code>Hello</code>.</p>
{ "question_id": 4168371, "question_date": "2010-11-12T19:34:29.180Z", "question_score": 213, "tags": "bash", "answer_id": 4168417, "answer_date": "2010-11-12T19:41:28.867Z", "answer_score": 198 }
Please answer the following Stack Overflow question: Title: Get hostname of current request in node.js Express <p>So, I may be missing something simple here, but I can't seem to find a way to get the hostname that a request object I'm sending a response to was requested from.</p> <p>Is it possible to figure out what hostname the user is currently visiting from node.js?</p>
<p>If you're talking about an HTTP request, you can find the request host in:</p> <pre><code>request.headers.host </code></pre> <p>But that relies on an incoming request.</p> <p>More at <a href="http://nodejs.org/docs/v0.4.12/api/http.html#http.ServerRequest" rel="noreferrer">http://nodejs.org/docs/v0.4.12/api/http.html#http.ServerRequest</a></p> <p>If you're looking for machine/native information, try the process object.</p>
{ "question_id": 7507015, "question_date": "2011-09-21T21:40:57.103Z", "question_score": 213, "tags": "node.js|express|hostname", "answer_id": 7507507, "answer_date": "2011-09-21T22:31:36.090Z", "answer_score": 249 }
Please answer the following Stack Overflow question: Title: Serializing an object to JSON <p>How can I serialize an object to JSON in JavaScript?</p>
<p>You're looking for <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify" rel="noreferrer"><code>JSON.stringify()</code></a>.</p>
{ "question_id": 558518, "question_date": "2009-02-17T20:13:15.933Z", "question_score": 213, "tags": "javascript|json", "answer_id": 558534, "answer_date": "2009-02-17T20:16:50.577Z", "answer_score": 297 }
Please answer the following Stack Overflow question: Title: How do I determine the correct "max-old-space-size" for node.js? <p>I'm having some trouble to understand how Node.js acts based on the parameter <code>max-old-space-size</code>.</p> <p>In my case, for example, I'm running two <code>t2.small</code> AWS instances (2GB of RAM).</p> <p>Not sure why, but I did set <code>max-old-space-size=4096</code> (4GB). What does node do in this case? Could this configuration lead to a possible memory allocation failure?</p> <p>How do I determine the correct value of <code>max-old-space-size</code> based on the server resources?</p> <p>My application is constantly growing the memory usage and I'm trying to understand everything about node internals.</p>
<p>"Old space" is the biggest and most configurable section of V8's managed (aka garbage-collected) heap (i.e. where the JavaScript objects live), and the <code>--max-old-space-size</code> flag controls its maximum size. As memory consumption approaches the limit, V8 will spend more time on garbage collection in an effort to free unused memory.</p> <p>If heap memory consumption (i.e. live objects that the GC cannot free) exceeds the limit, V8 will crash your process (for lack of alternative), so you don't want to set it too low. Of course, if you set it too high, then the additional heap usage that V8 will allow might cause your overall system to run out of memory (and either swap or kill random processes, for lack of alternative).</p> <p>In summary, on a machine with 2GB of memory I would probably set <code>--max-old-space-size</code> to about 1.5GB to leave some memory for other uses and avoid swapping.</p>
{ "question_id": 48387040, "question_date": "2018-01-22T17:24:35.127Z", "question_score": 213, "tags": "node.js|memory|v8", "answer_id": 48392705, "answer_date": "2018-01-23T01:10:16.320Z", "answer_score": 265 }
Please answer the following Stack Overflow question: Title: Check if instance is of a type <p>Using this to check if <code>c</code> is an instance of <code>TForm</code>. </p> <pre><code>c.GetType().Name.CompareTo("TForm") == 0 </code></pre> <p>Is there a more type safe way to do it besides using a <code>string</code> as a param to <code>CompareTo()</code>? </p>
<p>The different answers here have two different meanings.</p> <p>If you want to check whether an instance is of <em>an exact type</em> then</p> <pre><code>if (c.GetType() == typeof(TForm)) </code></pre> <p>is the way to go.</p> <p>If you want to know whether <code>c</code> is an instance of <code>TForm</code> <em>or a subclass</em> then use <code>is</code>/<code>as</code>:</p> <pre><code>if (c is TForm) </code></pre> <p>or</p> <pre><code>TForm form = c as TForm; if (form != null) </code></pre> <p>It's worth being clear in your mind about which of these behaviour you actually want.</p>
{ "question_id": 3561202, "question_date": "2010-08-24T21:31:36.477Z", "question_score": 213, "tags": "c#|.net", "answer_id": 3561320, "answer_date": "2010-08-24T21:47:37.757Z", "answer_score": 472 }
Please answer the following Stack Overflow question: Title: Accessing Object Memory Address <p>When you call the <code>object.__repr__()</code> method in Python you get something like this back: </p> <blockquote> <pre><code>&lt;__main__.Test object at 0x2aba1c0cf890&gt; </code></pre> </blockquote> <p>Is there any way to get a hold of the memory address if you overload <code>__repr__()</code>, other then calling <code>super(Class, obj).__repr__()</code> and regexing it out? </p>
<p>The <a href="https://docs.python.org/2/library/functions.html#id" rel="noreferrer">Python manual</a> has this to say about <code>id()</code>:</p> <blockquote> <p>Return the "identity'' of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. (Implementation note: this is the address of the object.)</p> </blockquote> <p>So in CPython, this will be the address of the object. No such guarantee for any other Python interpreter, though.</p> <p>Note that if you're writing a C extension, you have full access to the internals of the Python interpreter, including access to the addresses of objects directly.</p>
{ "question_id": 121396, "question_date": "2008-09-23T14:35:00.443Z", "question_score": 213, "tags": "python|object|memory-address|repr", "answer_id": 121452, "answer_date": "2008-09-23T14:41:30.270Z", "answer_score": 250 }
Please answer the following Stack Overflow question: Title: How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime <p>My component has styles that depend on current datetime. In my component I've got the following function.</p> <pre><code> private fontColor( dto : Dto ) : string { // date d'exécution du dto let dtoDate : Date = new Date( dto.LastExecution ); (...) let color = "hsl( " + hue + ", 80%, " + (maxLigness - lightnessAmp) + "%)"; return color; } </code></pre> <p><code>lightnessAmp</code> is calculated from the current datetime. The color changes if <code>dtoDate</code> is in the last 24 hours.</p> <p>The exact error is the following:</p> <blockquote> <p>Expression has changed after it was checked. Previous value: 'hsl( 123, 80%, 49%)'. Current value: 'hsl( 123, 80%, 48%)'</p> </blockquote> <p>I know the exception appear in development mode only at the moment the value is checked. If the checked value is different of the updated value, the exception is thrown.</p> <p>So I tried to update the current datetime at each lifecycle in the following hook method to prevent the exception:</p> <pre><code> ngAfterViewChecked() { console.log( "! changement de la date du composant !" ); this.dateNow = new Date(); } </code></pre> <p>...but without success.</p>
<p>Run change detection explicitly after the change:</p> <pre><code>import { ChangeDetectorRef } from '@angular/core'; constructor(private cdRef:ChangeDetectorRef) {} ngAfterViewChecked() { console.log( "! changement de la date du composant !" ); this.dateNow = new Date(); this.cdRef.detectChanges(); } </code></pre>
{ "question_id": 39787038, "question_date": "2016-09-30T08:31:52.573Z", "question_score": 213, "tags": "angular|typescript|time|styles|components", "answer_id": 39787056, "answer_date": "2016-09-30T08:32:53.890Z", "answer_score": 454 }
Please answer the following Stack Overflow question: Title: Is there Unicode glyph Symbol to represent "Search" <p>Unicode has a million icon-like glyphs, but they're very hard to search.</p> <p>Is there a Unicode glyph that looks like a "Binocular" or "magnifying glass"? Or is there a symbol that's used to mean "Search", which is in Unicode?</p>
<p>There is <a href="http://www.fileformat.info/info/unicode/char/1f50d/index.htm" rel="noreferrer">U+1F50D LEFT-POINTING MAGNIFYING GLASS</a> () and <a href="http://www.fileformat.info/info/unicode/char/1f50e/index.htm" rel="noreferrer">U+1F50E RIGHT-POINTING MAGNIFYING GLASS</a> ().</p> <p>You should use (in HTML) <code>&amp;#x1F50D;</code> or <code>&amp;#x1F50E;</code></p> <p>They are, however not supported by many fonts (fileformat.info only lists a few fonts as supporting the Codepoint with a proper glyph).</p> <p>Also note that they are outside of <a href="https://en.wikipedia.org/wiki/Plane_%28Unicode%29#Basic_Multilingual_Plane" rel="noreferrer">the BMP</a>, so some Unicode-capable software might have problems rendering them, even if they have fonts that support them.</p> <p>Generally Unicode Glyphs can be searched using a site such as <a href="http://www.fileformat.info/info/unicode/char/search.htm" rel="noreferrer">fileformat.info</a>. This searches &quot;only&quot; in the names and properties of the Unicode glyphs, but they usually contain enough metadata to allow for good search results (for this answer I searched for &quot;glass&quot; and browsed the resulting list, for example).</p> <p>Note that you can use <a href="https://en.wikipedia.org/wiki/Variation_Selectors_(Unicode_block)" rel="noreferrer">Unicode Variant Selectors</a> to explicitly pick how the glyphs will be rendered. Specifically VS15 (U+FE0E) for text-style and VS16 (U+FE0F) for emoji-style are relevant here. Simply append them to your chosen Unicode symbol to indicated if you'd like it to be rendered as text or as an emoji (assuming the software/browser supports the selectors <em>and</em> the relevant representation):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Unicode Symbol</th> <th>Variant Selector</th> <th>HTML encoded</th> <th>Result</th> </tr> </thead> <tbody> <tr> <td>U+1F50E</td> <td>none</td> <td><code>&amp;#x1F50E;</code></td> <td></td> </tr> <tr> <td>U+1F50E</td> <td>VS15 = U+FE0E</td> <td><code>&amp;#x1F50E;&amp;#xFE0E;</code></td> <td>︎</td> </tr> <tr> <td>U+1F50E</td> <td>VS16 = U+FE0F</td> <td><code>&amp;#x1F50E;&amp;#xFE0F;</code></td> <td>️</td> </tr> </tbody> </table> </div> <p>Note that the result might vary depending on platform. For example Chrome seems to always render this character as an Emoji on both Linux and Windows.</p>
{ "question_id": 12036038, "question_date": "2012-08-20T10:29:27.720Z", "question_score": 213, "tags": "unicode|symbols|html-entities", "answer_id": 12036141, "answer_date": "2012-08-20T10:36:59.093Z", "answer_score": 245 }
Please answer the following Stack Overflow question: Title: How to stop INFO messages displaying on spark console? <p>I'd like to stop various messages that are coming on spark shell.</p> <p>I tried to edit the <code>log4j.properties</code> file in order to stop these message.</p> <p>Here are the contents of <code>log4j.properties</code></p> <pre><code># Define the root logger with appender file log4j.rootCategory=WARN, console log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.target=System.err log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{1}: %m%n # Settings to quiet third party logs that are too verbose log4j.logger.org.eclipse.jetty=WARN log4j.logger.org.eclipse.jetty.util.component.AbstractLifeCycle=ERROR log4j.logger.org.apache.spark.repl.SparkIMain$exprTyper=INFO log4j.logger.org.apache.spark.repl.SparkILoop$SparkILoopInterpreter=INFO </code></pre> <p>But messages are still getting displayed on the console.</p> <p>Here are some example messages</p> <pre><code>15/01/05 15:11:45 INFO SparkEnv: Registering BlockManagerMaster 15/01/05 15:11:45 INFO DiskBlockManager: Created local directory at /tmp/spark-local-20150105151145-b1ba 15/01/05 15:11:45 INFO MemoryStore: MemoryStore started with capacity 0.0 B. 15/01/05 15:11:45 INFO ConnectionManager: Bound socket to port 44728 with id = ConnectionManagerId(192.168.100.85,44728) 15/01/05 15:11:45 INFO BlockManagerMaster: Trying to register BlockManager 15/01/05 15:11:45 INFO BlockManagerMasterActor$BlockManagerInfo: Registering block manager 192.168.100.85:44728 with 0.0 B RAM 15/01/05 15:11:45 INFO BlockManagerMaster: Registered BlockManager 15/01/05 15:11:45 INFO HttpServer: Starting HTTP Server 15/01/05 15:11:45 INFO HttpBroadcast: Broadcast server star </code></pre> <p>How do I stop these?</p>
<p>Thanks @AkhlD and @Sachin Janani for suggesting changes in <code>.conf</code> file.</p> <p>Following code solved my issue:</p> <p>1) Added <code>import org.apache.log4j.{Level, Logger}</code> in import section</p> <p>2) Added following line after creation of spark context object i.e. after <code>val sc = new SparkContext(conf)</code>:</p> <pre><code>val rootLogger = Logger.getRootLogger() rootLogger.setLevel(Level.ERROR) </code></pre>
{ "question_id": 27781187, "question_date": "2015-01-05T14:04:46.880Z", "question_score": 213, "tags": "apache-spark|log4j|spark-submit", "answer_id": 34306251, "answer_date": "2015-12-16T07:31:43.147Z", "answer_score": 50 }
Please answer the following Stack Overflow question: Title: Check whether there is an Internet connection available on Flutter app <p>I have a network call to be executed. But before doing that I need to check whether the device have internet connectivity.</p> <p>This is what i have done so far:</p> <pre><code> var connectivityResult = new Connectivity().checkConnectivity();// User defined class if (connectivityResult == ConnectivityResult.mobile || connectivityResult == ConnectivityResult.wifi) {*/ this.getData(); } else { neverSatisfied(); } </code></pre> <p>Above method is not working.</p>
<p>The <a href="https://pub.dartlang.org/packages/connectivity#-readme-tab-" rel="nofollow noreferrer">connectivity</a> plugin states in its docs that it only provides information if there is a network connection, but not if the network is connected to the Internet</p> <blockquote> <p>Note that on Android, this does not guarantee connection to Internet. For instance, the app might have wifi access but it might be a VPN or a hotel WiFi with no access.</p> </blockquote> <p>You can use</p> <pre><code>import 'dart:io'; ... try { final result = await InternetAddress.lookup('example.com'); if (result.isNotEmpty &amp;&amp; result[0].rawAddress.isNotEmpty) { print('connected'); } } on SocketException catch (_) { print('not connected'); } </code></pre> <h2>Update</h2> <p>The <a href="https://pub.dev/packages/connectivity#-readme-tab-" rel="nofollow noreferrer">connectivity</a> package is deprecated. Use the official Flutter Community <a href="https://pub.dev/packages/connectivity_plus" rel="nofollow noreferrer">connectivity_plus</a> package instead.</p>
{ "question_id": 49648022, "question_date": "2018-04-04T09:53:58.777Z", "question_score": 213, "tags": "flutter|dart|internet-connection|flutter-plugin", "answer_id": 49648870, "answer_date": "2018-04-04T10:36:03.373Z", "answer_score": 351 }
Please answer the following Stack Overflow question: Title: Visual Studio move project to a different folder <p>How do I move a project to a different folder in Visual Studio? I am used to this structure in my projects.</p> <pre><code>-- app ---- Project.Something ---- Project.SomethingElse </code></pre> <p>I want to rename the whole namespace SomethingElse to SomethingNew, what's the best way to do that (without manually going into .sln file)?</p>
<p>Remove the project from your solution by right-clicking it in the Solution Explorer window and choosing Remove. Move the entire project folder, including subdirectories wherever you want it to go. Add the project back to your solution.</p> <p>Namespace names is something completely different, just edit the source code.</p>
{ "question_id": 2620027, "question_date": "2010-04-12T05:22:30.647Z", "question_score": 213, "tags": "visual-studio|visual-studio-2008", "answer_id": 2622537, "answer_date": "2010-04-12T13:52:16.037Z", "answer_score": 225 }
Please answer the following Stack Overflow question: Title: Does MySQL foreign_key_checks affect the entire database? <p>When I execute this command in MySQL:</p> <pre><code>SET FOREIGN_KEY_CHECKS=0; </code></pre> <p>Does it affect the whole engine or it is only my current transaction?</p>
<p>It is session-based, when set the way you did in your question.</p> <p><a href="https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html" rel="noreferrer">https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html</a></p> <p>According to this, <code>FOREIGN_KEY_CHECKS</code> is "Both" for scope. This means it can be set for session:</p> <pre><code>SET FOREIGN_KEY_CHECKS=0; </code></pre> <p>or globally:</p> <pre><code>SET GLOBAL FOREIGN_KEY_CHECKS=0; </code></pre>
{ "question_id": 8538636, "question_date": "2011-12-16T18:39:57.683Z", "question_score": 213, "tags": "mysql", "answer_id": 8538716, "answer_date": "2011-12-16T18:46:34.743Z", "answer_score": 264 }
Please answer the following Stack Overflow question: Title: What are "res" and "req" parameters in Express functions? <p>In the following Express function:</p> <pre><code>app.get('/user/:id', function(req, res){ res.send('user' + req.params.id); }); </code></pre> <p>What are <code>req</code> and <code>res</code>? What do they stand for, what do they mean, and what do they do?</p> <p>Thanks!</p>
<p><code>req</code> is an object containing information about the HTTP request that raised the event. In response to <code>req</code>, you use <code>res</code> to send back the desired HTTP response.</p> <p>Those parameters can be named anything. You could change that code to this if it's more clear:</p> <pre><code>app.get('/user/:id', function(request, response){ response.send('user ' + request.params.id); }); </code></pre> <p>Edit:</p> <p>Say you have this method:</p> <pre><code>app.get('/people.json', function(request, response) { }); </code></pre> <p>The request will be an object with properties like these (just to name a few):</p> <ul> <li><code>request.url</code>, which will be <code>"/people.json"</code> when this particular action is triggered</li> <li><code>request.method</code>, which will be <code>"GET"</code> in this case, hence the <code>app.get()</code> call.</li> <li>An array of HTTP headers in <code>request.headers</code>, containing items like <code>request.headers.accept</code>, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc.</li> <li>An array of query string parameters if there were any, in <code>request.query</code> (e.g. <code>/people.json?foo=bar</code> would result in <code>request.query.foo</code> containing the string <code>"bar"</code>).</li> </ul> <p>To respond to that request, you use the response object to build your response. To expand on the <code>people.json</code> example:</p> <pre><code>app.get('/people.json', function(request, response) { // We want to set the content-type header so that the browser understands // the content of the response. response.contentType('application/json'); // Normally, the data is fetched from a database, but we can cheat: var people = [ { name: 'Dave', location: 'Atlanta' }, { name: 'Santa Claus', location: 'North Pole' }, { name: 'Man in the Moon', location: 'The Moon' } ]; // Since the request is for a JSON representation of the people, we // should JSON serialize them. The built-in JSON.stringify() function // does that. var peopleJSON = JSON.stringify(people); // Now, we can use the response object's send method to push that string // of people JSON back to the browser in response to this request: response.send(peopleJSON); }); </code></pre>
{ "question_id": 4696283, "question_date": "2011-01-14T21:43:11.843Z", "question_score": 213, "tags": "node.js|express", "answer_id": 4696338, "answer_date": "2011-01-14T21:48:11.870Z", "answer_score": 313 }
Please answer the following Stack Overflow question: Title: javascript toISOString() ignores timezone offset <p>I am trying to convert Twitter datetime to a local iso-string (for prettyDate) now for 2 days. I'm just not getting the local time right..</p> <p>im using the following function:</p> <pre><code>function getLocalISOTime(twDate) { var d = new Date(twDate); var utcd = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()); // obtain local UTC offset and convert to msec localOffset = d.getTimezoneOffset() * 60000; var newdate = new Date(utcd + localOffset); return newdate.toISOString().replace(".000", ""); } </code></pre> <p>in newdate everything is ok but the toISOString() throws it back to the original time again... Can anybody help me get the local time in iso from the Twitterdate formatted as: Thu, 31 May 2012 08:33:41 +0000</p>
<p><code>moment.js</code> is great but sometimes you don't want to pull a large number of dependencies for simple things.</p> <p>The following works as well:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1); console.log(localISOTime) // =&gt; '2015-01-26T06:40:36.181'</code></pre> </div> </div> </p> <p>The <code>slice(0, -1)</code> gets rid of the trailing <code>Z</code> which represents Zulu timezone and can be replaced by your own.</p>
{ "question_id": 10830357, "question_date": "2012-05-31T08:57:24.160Z", "question_score": 213, "tags": "javascript|datetime|timezone-offset", "answer_id": 28149561, "answer_date": "2015-01-26T11:50:02.183Z", "answer_score": 400 }
Please answer the following Stack Overflow question: Title: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range. <p>The error in the title is thrown only in Google Chrome, according to my tests. I'm base64 encoding a big XML file so that it can be downloaded:</p> <pre><code>this.loader.src = "data:application/x-forcedownload;base64,"+ btoa("&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;" +"&lt;"+this.gamesave.tagName+"&gt;" +this.xml.firstChild.innerHTML +"&lt;/"+this.gamesave.tagName+"&gt;"); </code></pre> <p><code>this.loader</code> is hidden iframe.</p> <p>This error is actually quite a change because normally, Google Chrome would crash upon <code>btoa</code> call. Mozilla Firefox has no problems here, so the issue is browser related. I'm not aware of any strange characters in file. Actually I do believe there are no non-ascii characters.</p> <p><strong>Q:</strong> How do I find the problematic characters and replace them so that Chrome stops complaining?</p> <p><sub>I have tried to use Downloadify to initiate the download, but it does not work. It's unreliable and throws no errors to allow debug.</sub></p>
<p>If you have UTF8, use this (actually works with SVG source), like:</p> <pre><code>btoa(unescape(encodeURIComponent(str))) </code></pre> <p>example:</p> <pre><code> var imgsrc = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(markup))); var img = new Image(1, 1); // width, height values are optional params img.src = imgsrc; </code></pre> <p>If you need to decode that base64, use this:</p> <pre><code>var str2 = decodeURIComponent(escape(window.atob(b64))); console.log(str2); </code></pre> <p>Example:</p> <pre><code>var str = &quot;äöüÄÖÜçéèñ&quot;; var b64 = window.btoa(unescape(encodeURIComponent(str))) console.log(b64); var str2 = decodeURIComponent(escape(window.atob(b64))); console.log(str2); </code></pre> <p><strong>Note:</strong> if you need to get this to work in mobile-safari, you might need to strip all the white-space from the base64 data...</p> <pre><code>function b64_to_utf8( str ) { str = str.replace(/\s/g, ''); return decodeURIComponent(escape(window.atob( str ))); } </code></pre> <hr /> <p><strong>2017 Update</strong></p> <p>This problem has been bugging me again. <br /> The simple truth is, atob doesn't really handle UTF8-strings - it's ASCII only. <br /> Also, I wouldn't use bloatware like js-base64. <br /> But <a href="http://www.webtoolkit.info" rel="noreferrer">webtoolkit</a> does have a small, nice and very maintainable implementation:</p> <pre><code>/** * * Base64 encode / decode * http://www.webtoolkit.info * **/ var Base64 = { // private property _keyStr: &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=&quot; // public method for encoding , encode: function (input) { var output = &quot;&quot;; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = Base64._utf8_encode(input); while (i &lt; input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 &gt;&gt; 2; enc2 = ((chr1 &amp; 3) &lt;&lt; 4) | (chr2 &gt;&gt; 4); enc3 = ((chr2 &amp; 15) &lt;&lt; 2) | (chr3 &gt;&gt; 6); enc4 = chr3 &amp; 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); } // Whend return output; } // End Function encode // public method for decoding ,decode: function (input) { var output = &quot;&quot;; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, &quot;&quot;); while (i &lt; input.length) { enc1 = this._keyStr.indexOf(input.charAt(i++)); enc2 = this._keyStr.indexOf(input.charAt(i++)); enc3 = this._keyStr.indexOf(input.charAt(i++)); enc4 = this._keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 &lt;&lt; 2) | (enc2 &gt;&gt; 4); chr2 = ((enc2 &amp; 15) &lt;&lt; 4) | (enc3 &gt;&gt; 2); chr3 = ((enc3 &amp; 3) &lt;&lt; 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } // Whend output = Base64._utf8_decode(output); return output; } // End Function decode // private method for UTF-8 encoding ,_utf8_encode: function (string) { var utftext = &quot;&quot;; string = string.replace(/\r\n/g, &quot;\n&quot;); for (var n = 0; n &lt; string.length; n++) { var c = string.charCodeAt(n); if (c &lt; 128) { utftext += String.fromCharCode(c); } else if ((c &gt; 127) &amp;&amp; (c &lt; 2048)) { utftext += String.fromCharCode((c &gt;&gt; 6) | 192); utftext += String.fromCharCode((c &amp; 63) | 128); } else { utftext += String.fromCharCode((c &gt;&gt; 12) | 224); utftext += String.fromCharCode(((c &gt;&gt; 6) &amp; 63) | 128); utftext += String.fromCharCode((c &amp; 63) | 128); } } // Next n return utftext; } // End Function _utf8_encode // private method for UTF-8 decoding ,_utf8_decode: function (utftext) { var string = &quot;&quot;; var i = 0; var c, c1, c2, c3; c = c1 = c2 = 0; while (i &lt; utftext.length) { c = utftext.charCodeAt(i); if (c &lt; 128) { string += String.fromCharCode(c); i++; } else if ((c &gt; 191) &amp;&amp; (c &lt; 224)) { c2 = utftext.charCodeAt(i + 1); string += String.fromCharCode(((c &amp; 31) &lt;&lt; 6) | (c2 &amp; 63)); i += 2; } else { c2 = utftext.charCodeAt(i + 1); c3 = utftext.charCodeAt(i + 2); string += String.fromCharCode(((c &amp; 15) &lt;&lt; 12) | ((c2 &amp; 63) &lt;&lt; 6) | (c3 &amp; 63)); i += 3; } } // Whend return string; } // End Function _utf8_decode } </code></pre> <p><a href="https://www.fileformat.info/info/unicode/utf8.htm" rel="noreferrer">https://www.fileformat.info/info/unicode/utf8.htm</a></p> <blockquote> <ul> <li><p>For any character equal to or below 127 (hex 0x7F), the UTF-8 representation is one byte. It is just the lowest 7 bits of the full unicode value. This is also the same as the ASCII value.</p> </li> <li><p>For characters equal to or below 2047 (hex 0x07FF), the UTF-8 representation is spread across two bytes. The first byte will have the two high bits set and the third bit clear (i.e. 0xC2 to 0xDF). The second byte will have the top bit set and the second bit clear (i.e. 0x80 to 0xBF).</p> </li> <li><p>For all characters equal to or greater than 2048 but less than 65535 (0xFFFF), the UTF-8 representation is spread across three bytes.</p> </li> </ul> </blockquote>
{ "question_id": 23223718, "question_date": "2014-04-22T15:23:48.953Z", "question_score": 213, "tags": "javascript|google-chrome", "answer_id": 26603875, "answer_date": "2014-10-28T08:37:09.933Z", "answer_score": 332 }
Please answer the following Stack Overflow question: Title: How do I simply create a patch from my latest git commit? <p>I am looking for the command for creating a patch from the last commit made.</p> <p>My workflow sometimes looks like this:</p> <pre><code>vi some.txt git add some.txt git commit -m &quot;some change&quot; </code></pre> <p>Now I just want to write:</p> <pre><code>git create-patch-from-last-commit-to-file SOME-PATCH0001.patch </code></pre> <p>What should I put there instead of <code>create-patch-from-last-commit-to-file</code>?</p>
<p>In general,</p> <pre><code>git format-patch -n HEAD^ </code></pre> <p>(check help for the many options), although it's really for mailing them. For a single commit just</p> <pre><code>git show HEAD &gt; some-patch0001.patch </code></pre> <p>will give you a useable patch.</p>
{ "question_id": 9396240, "question_date": "2012-02-22T13:58:23.120Z", "question_score": 213, "tags": "git|patch", "answer_id": 9396390, "answer_date": "2012-02-22T14:07:30.100Z", "answer_score": 336 }
Please answer the following Stack Overflow question: Title: git diff between two different files <p>In <code>HEAD</code> (the latest commit), I have a file named <code>foo</code>. In my current working tree, I renamed it to <code>bar</code>, and also edited it.</p> <p>I want to <code>git diff</code> <code>foo</code> in <code>HEAD</code>, and <code>bar</code> in my current working tree.</p>
<p>Specify the paths explicitly:</p> <p><code>git diff HEAD:full/path/to/foo full/path/to/bar</code></p> <p>Check out the <code>--find-renames</code> option in the <code>git-diff</code> <a href="https://www.kernel.org/pub/software/scm/git/docs/git-diff.html" rel="noreferrer">docs</a>.</p> <p>Credit: <a href="https://stackoverflow.com/questions/8131135/git-how-to-diff-two-different-files-in-different-branches">twaggs</a>.</p>
{ "question_id": 16683121, "question_date": "2013-05-22T03:43:48.520Z", "question_score": 213, "tags": "git|diff", "answer_id": 16683184, "answer_date": "2013-05-22T03:52:48.217Z", "answer_score": 233 }
Please answer the following Stack Overflow question: Title: How to send push notification to web browser? <p>I have been reading for past few hours about <a href="http://www.w3.org/TR/push-api/" rel="noreferrer">Push Notification API</a> and <a href="http://www.w3.org/TR/notifications/" rel="noreferrer">Web Notification API</a>. I also discovered that Google &amp; Apple gives push notification service for free via GCM and APNS respectively. </p> <p>I am trying to understand if we can implement push notification to browsers using Desktop Notification, which I believe is what Web Notification API does. I saw a google documentation on how this can be done for Chrome <a href="https://developers.google.com/cloud-messaging/chrome/client" rel="noreferrer">here</a> &amp; <a href="https://developers.google.com/web/fundamentals/getting-started/push-notifications/?hl=en" rel="noreferrer">here</a>.</p> <p>Now what am still not able to understand is:</p> <ol> <li>Can we use GCM/APNS to send push notification to all Web Browsers including Firefox &amp; Safari?</li> <li>If not via GCM can we have our own back-end to do the same?</li> </ol> <p>I believe all these answered in one answer can help a lot of people who are having similar confusions. </p>
<p>So here I am answering my own question. I have got answers to all my queries from people who have build push notification services in the past.</p> <blockquote> <p><strong>Update (May 2022):</strong> <a href="https://developers.google.com/web/fundamentals/push-notifications/" rel="noreferrer">Here is a</a> doc on web push notification from Google.</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API" rel="noreferrer">See this</a> detailed introduction to notification API from Mozilla.</p> <p><a href="https://www.airship.com/resources/explainer/web-push-notifications-explained/" rel="noreferrer">Airships article</a> on the topic and how web push &amp; app push varies.</p> </blockquote> <p>Answer to the original questions asked 6 years ago:</p> <blockquote> <ol> <li>Can we use GCM/APNS to send push notification to all Web Browsers including Firefox &amp; Safari?</li> </ol> </blockquote> <p><strong>Answer:</strong> Google has deprecated GCM as of April 2018. You can now use <a href="https://firebase.google.com/products/cloud-messaging/" rel="noreferrer">Firebase Cloud Messaging</a> (FCM). This supports all platforms including web browsers.</p> <blockquote> <ol start="2"> <li>If not via GCM can we have our own back-end to do the same?</li> </ol> </blockquote> <p><strong>Answer:</strong> Yes, push notification can be sent from our own back-end. Support for the same has come to all major browsers.</p> <p>Check <a href="https://developers.google.com/web/fundamentals/codelabs/push-notifications/" rel="noreferrer">this codelab</a> from Google to better understand the implementation.</p> <p><strong>Some Tutorials:</strong></p> <ul> <li>Implementing push notification in Django <a href="https://www.digitalocean.com/community/tutorials/how-to-send-web-push-notifications-from-django-applications" rel="noreferrer">Here</a>.</li> <li>Using flask to send push notification <a href="https://raturi.in/blog/webpush-notification-using-python-and-flask/" rel="noreferrer">Here</a> &amp; <a href="https://medium.com/@nitinraturi/webpush-notification-using-python-and-flask-ccb3f083ac76" rel="noreferrer">Here</a>.</li> <li>Sending push notifcaiton from Nodejs <a href="https://thecodebarbarian.com/sending-web-push-notifications-from-node-js.html" rel="noreferrer">Here</a></li> <li>Sending push notification using php <a href="https://phpadvices.com/send-push-notification-to-android-using-php-and-firebase/" rel="noreferrer">Here</a> &amp; <a href="https://webdamn.com/build-push-notification-system-with-php-mysql/" rel="noreferrer">Here</a></li> <li>Sending push notification from Wordpress. <a href="https://www.wpbeginner.com/wp-tutorials/how-to-add-web-push-notification-to-your-wordpress-site/" rel="noreferrer">Here</a> &amp; <a href="https://www.ostraining.com/blog/wordpress/push-notifications/" rel="noreferrer">Here</a></li> <li>Sending push notification from Drupal. <a href="https://www.drupal.org/project/web_push_notification" rel="noreferrer">Here</a></li> </ul> <p><strong>Implementing own backend in various programming languages.:</strong></p> <ul> <li><a href="https://nickersoft.github.io/push.js/" rel="noreferrer">NodeJs.</a></li> <li><a href="https://github.com/web-push-libs/web-push-php" rel="noreferrer">PHP</a></li> <li><a href="https://github.com/zaru/webpush" rel="noreferrer">Rails</a></li> <li><a href="https://github.com/web-push-libs/pywebpush" rel="noreferrer">Python</a></li> <li>Go Lang - <a href="https://github.com/gauntface/web-push-go" rel="noreferrer">this</a> and <a href="https://github.com/appleboy/gorush" rel="noreferrer">this</a></li> </ul> <h2><strong>Further Readings:</strong></h2> <ul> <li>Documentation from Firefox website can be <a href="https://support.mozilla.org/en-US/kb/push-notifications-firefox?as=u&amp;utm_source=inproduct" rel="noreferrer">read here</a>.</li> <li>A very good overview of Web Push by Google can be <a href="https://developers.google.com/web/fundamentals/engage-and-retain/push-notifications/" rel="noreferrer">found here.</a></li> <li><a href="https://developers.google.com/web/fundamentals/engage-and-retain/push-notifications/faq" rel="noreferrer">An FAQ answering</a> most common confusions and questions.</li> </ul> <p><strong>Are there any free services to do the same?</strong> There are some companies that provide a similar solution in free, freemium and paid models. Am listing few below:</p> <ol> <li><a href="https://onesignal.com/" rel="noreferrer">https://onesignal.com/</a> (Free | Support all platforms)</li> <li><a href="https://firebase.google.com/products/cloud-messaging/" rel="noreferrer">https://firebase.google.com/products/cloud-messaging/</a> (Free)</li> <li><a href="https://clevertap.com/" rel="noreferrer">https://clevertap.com/</a> (Has free plan)</li> <li><a href="https://goroost.com/" rel="noreferrer">https://goroost.com/</a></li> </ol> <p><strong>Note:</strong> When choosing a free service remember to read the TOS. Free services often work by collecting user data for various purposes including analytics.</p> <p>Apart from that, you need to have HTTPS to send push notifications. However, you can get https freely via <a href="https://letsencrypt.org/" rel="noreferrer">letsencrypt.org</a></p>
{ "question_id": 33687298, "question_date": "2015-11-13T06:50:12.477Z", "question_score": 213, "tags": "javascript|google-cloud-messaging|web-notifications|web-push|push-api", "answer_id": 33976929, "answer_date": "2015-11-28T22:03:09.437Z", "answer_score": 207 }
Please answer the following Stack Overflow question: Title: How to draw border on just one side of a linear layout? <p>I'm able to draw border to a linear layout, but it is getting drawn on all sides. I want to restrict it to right side only, like you do in CSS (border-right:1px solid red;).</p> <p>I've tried this, but it still draws on all sides:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;layer-list xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;item&gt; &lt;shape android:shape="rectangle" &gt; &lt;stroke android:height="2dp" android:width="2dp" android:color="#FF0000" /&gt; &lt;solid android:color="#000000" /&gt; &lt;padding android:bottom="0dp" android:left="0dp" android:right="1dp" android:top="0dp" /&gt; &lt;corners android:bottomLeftRadius="0dp" android:bottomRightRadius="5dp" android:radius="1dp" android:topLeftRadius="5dp" android:topRightRadius="0dp" /&gt; &lt;/shape&gt; &lt;/item&gt; </code></pre> <p></p> <p>Any suggestions on how to accomplish this?</p> <p>BTW, I do not want to use the hack of putting a view of width 1dp on the required side.</p>
<p>You can use this to get border on one side</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;layer-list xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item&gt; &lt;shape android:shape="rectangle"&gt; &lt;solid android:color="#FF0000" /&gt; &lt;/shape&gt; &lt;/item&gt; &lt;item android:left="5dp"&gt; &lt;shape android:shape="rectangle"&gt; &lt;solid android:color="#000000" /&gt; &lt;/shape&gt; &lt;/item&gt; &lt;/layer-list&gt; </code></pre> <p><strong>EDITED</strong></p> <p>As many including me wanted to have a one side border with transparent background, I have implemented a <code>BorderDrawable</code> which could give me borders with different size and color in the same way as we use css. But this could not be used via xml. For supporting XML, I have added a <code>BorderFrameLayout</code> in which your layout can be wrapped.</p> <p>See my <a href="https://github.com/vivekkhandelwal/kLib-android">github</a> for the complete source.</p>
{ "question_id": 9211208, "question_date": "2012-02-09T12:54:58.340Z", "question_score": 213, "tags": "android", "answer_id": 9212584, "answer_date": "2012-02-09T14:24:59.493Z", "answer_score": 385 }
Please answer the following Stack Overflow question: Title: Why call git branch --unset-upstream to fixup? <p>I'm more of a novice when it comes to advanced operations in git. I maintain my <a href="http://jatinganhotra.com" rel="noreferrer">blog</a> using the blogging framework <a href="http://octopress.org/" rel="noreferrer">Octopress</a>. Though Octopress is not under any development since 2011, it serves my purpose well and so I haven't thought of changing anything so far.</p> <p>FYI, my blog is hosted on Github Pages. </p> <p>Today, while working on a new post, <code>git status</code> showed the following message:</p> <pre><code>On branch source Your branch is based on 'origin/master', but the upstream is gone. (use "git branch --unset-upstream" to fixup) </code></pre> <p>The same message repeated for all the subsequent commands such as <code>git add .</code>, <code>git commit -m 'message'</code> and <code>git push origin source</code>. </p> <ul> <li>What does the message mean? </li> <li>Is something broken? </li> <li>If yes, what? </li> <li>Do I need to fix it? </li> </ul> <p>If possible, please point me to a pdf/web article where I can read up on this and understand it for future.</p> <p>More details:</p> <pre><code>bash-3.2$ git branch -a * source remotes/octopress/2.1 remotes/octopress/HEAD -&gt; octopress/master remotes/octopress/gh-pages remotes/octopress/linklog remotes/octopress/master remotes/octopress/refactor_with_tests remotes/octopress/rubygemcli remotes/octopress/site remotes/origin/source </code></pre> <p>Please let me know if more information is needed. Thanks.</p>
<p>TL;DR version: remote-tracking branch <code>origin/master</code> used to exist, but does not now, so local branch <code>source</code> is tracking something that does not exist, which is suspicious at best—it means a different Git feature is unable to do anything for you—and Git is warning you about it. You have been getting along just fine without having the "upstream tracking" feature work as intended, so it's up to you whether to change anything.</p> <p>For another take on upstream settings, see <a href="https://stackoverflow.com/q/37770467/1256452">Why do I have to &quot;git push --set-upstream origin &lt;branch&gt;&quot;?</a></p> <hr> <p>This warning is a new thing in Git, appearing first in Git 1.8.5. The release notes contain just one short bullet-item about it:</p> <blockquote> <ul> <li>"git branch -v -v" (and "git status") did not distinguish among a branch that is not based on any other branch, a branch that is in sync with its upstream branch, and a branch that is configured with an upstream branch that no longer exists.</li> </ul> </blockquote> <p>To describe what it means, you first need to know about "remotes", "remote-tracking branches", and how Git handles "tracking an upstream". (<em>Remote-tracking branches</em> is a terribly flawed term—I've started using <em>remote-tracking names</em> instead, which I think is a slight improvement. Below, though, I'll use "remote-tracking branch" for consistency with Git documentation.)</p> <p>Each "remote" is simply a name, like <code>origin</code> or <code>octopress</code> in this case. Their purpose is to record things like the full URL of the places from which you <code>git fetch</code> or <code>git pull</code> updates. When you use <code>git fetch <em>remote</em>,</code><sup>1</sup> Git goes to that remote (using the saved URL) and brings over the appropriate set of updates. It also <em>records</em> the updates, using "remote-tracking branches". </p> <p>A "remote-tracking branch" (or remote-tracking name) is simply a recording of a branch name as-last-seen on some "remote". Each remote is itself a Git repository, so it has branches. The branches on remote "origin" are recorded in your local repository under <code>remotes/origin/</code>. The text you showed says that there's a branch named <code>source</code> on <code>origin</code>, and branches named <code>2.1</code>, <code>linklog</code>, and so on on <code>octopress</code>.</p> <p>(A "normal" or "local" branch, of course, is just a branch-name that you have created in your own repository.)</p> <p>Last, you can set up a (local) branch to "track" a "remote-tracking branch". Once local branch <em><code>L</code></em> is set to track remote-tracking branch <em><code>R</code></em>, Git will call <em><code>R</code></em> its "upstream" and tell you whether you're "ahead" and/or "behind" the upstream (in terms of commits). It's normal (even recommend-able) for the local branch and remote-tracking branches to use the same name (except for the remote prefix part), like <code>source</code> and <code>origin/source</code>, but that's not actually necessary.</p> <p>And in this case, that's not happening. You have a local branch <code>source</code> tracking a remote-tracking branch <code>origin/master</code>.</p> <p>You're not supposed to need to know the exact mechanics of <em>how</em> Git sets up a local branch to track a remote one, but they are relevant below, so I'll show how this works. We start with your local branch name, <code>source</code>. There are two configuration entries using this name, spelled <code>branch.source.remote</code> and <code>branch.source.merge</code>. From the output you showed, it's clear that these are both set, so that you'd see the following if you ran the given commands:</p> <pre><code>$ git config --get branch.source.remote origin $ git config --get branch.source.merge refs/heads/master </code></pre> <p>Putting these together,<sup>2</sup> this tells Git that your branch <code>source</code> tracks your "remote-tracking branch", <code>origin/master</code>.</p> <p>But now look at the output of <code>git branch -a</code>, which shows all the local and remote-tracking branch names in your repository. The remote-tracking names are listed under <code>remotes/</code> ... and <em>there is no <code>remotes/origin/master</code></em>. Presumably there was, at one time, but it's gone now.</p> <p>Git is telling you that you can <em>remove</em> the tracking information with <code>--unset-upstream</code>. This will clear out both <code>branch.source.origin</code> and <code>branch.source.merge</code>, and stop the warning.</p> <p>It seems fairly likely that what you want, though, is to <em>switch</em> from tracking <code>origin/master</code>, to tracking something else: probably <code>origin/source</code>, but maybe one of the <code>octopress/</code> names.</p> <p>You can do this with <code>git branch --set-upstream-to</code>,<sup>3</sup> e.g.:</p> <pre><code>$ git branch --set-upstream-to=origin/source </code></pre> <p>(assuming you're still on branch "source", and that <code>origin/source</code> is the upstream you want—there is no way for me to tell which one, if any, you actually want, though).</p> <p>(See also <a href="https://stackoverflow.com/q/520650/1256452">How do you make an existing Git branch track a remote branch?</a>)</p> <p>I think the way you got here is that when you first did a <code>git clone</code>, the thing you cloned-from had a branch <code>master</code>. You also had a branch <code>master</code>, which was set to track <code>origin/master</code> (this is a normal, standard setup for git). This meant you had <code>branch.master.remote</code> and <code>branch.master.merge</code> set, to <code>origin</code> and <code>refs/heads/master</code>. But then your <code>origin</code> remote changed its name from <code>master</code> to <code>source</code>. To match, I believe you also changed your local name from <code>master</code> to <code>source</code>. This changed the <em>names</em> of your settings, from <code>branch.master.remote</code> to <code>branch.source.remote</code> and from <code>branch.master.merge</code> to <code>branch.source.merge</code> ... but it left the old <em>values</em>, so <code>branch.source.merge</code> was now wrong.</p> <p>It was at this point that the "upstream" linkage broke, but in Git versions older than 1.8.5, Git never noticed the broken setting. Now that you have 1.8.5, it's pointing this out.</p> <hr> <p>That covers most of the questions, but not the "do I need to fix it" one. It's likely that you have been working around the broken-ness for years now, by doing <code>git pull <em>remote branch</em></code> (e.g., <code>git pull origin source</code>). If you keep doing that, it will keep working around the problem—so, no, you don't <em>need</em> to fix it. If you like, you can use <code>--unset-upstream</code> to remove the upstream and stop the complaints, and not have local branch <code>source</code> marked as having <em>any</em> upstream at all.</p> <p>The point of having an upstream is to make various operations more convenient. For instance, <code>git fetch</code> followed by <code>git merge</code> will generally "do the right thing" if the upstream is set correctly, and <code>git status</code> after <code>git fetch</code> will tell you whether your repo matches the upstream one, for that branch.</p> <p>If you want the convenience, re-set the upstream.</p> <hr> <p><sup>1</sup><code>git pull</code> uses <code>git fetch</code>, and as of Git 1.8.4, this (finally!) also updates the "remote-tracking branch" information. In older versions of Git, the updates did not get recorded in remote-tracking branches with <code>git pull</code>, only with <code>git fetch</code>. Since your Git must be at least version 1.8.5 this is not an issue for you.</p> <p><sup>2</sup>Well, this plus a configuration line I'm deliberately ignoring that is found under <code>remote.origin.fetch</code>. Git has to map the "merge" name to figure out that the full local name for the remote-branch is <code>refs/remotes/origin/master</code>. The mapping almost always works just like this, though, so it's predictable that <code>master</code> goes to <code>origin/master</code>.</p> <p><sup>3</sup>Or, with <code>git config</code>. If you just want to set the upstream to <code>origin/source</code> the only part that has to change is <code>branch.source.merge</code>, and <code>git config branch.source.merge refs/heads/source</code> would do it. But <code>--set-upstream-to</code> says <em>what</em> you want done, rather than making you go do it yourself manually, so that's a "better way".</p>
{ "question_id": 21609781, "question_date": "2014-02-06T17:24:31.597Z", "question_score": 213, "tags": "git|git-branch|github-pages", "answer_id": 21616241, "answer_date": "2014-02-06T23:22:21.787Z", "answer_score": 234 }
Please answer the following Stack Overflow question: Title: Understanding Chrome network log "Stalled" state <p>I've a following network log in chrome:</p> <p><img src="https://i.stack.imgur.com/IJXd5.png" alt="network log"></p> <p>I don't understand one thing in it: what's the difference between filled gray bars and transparent gray bars.</p>
<p>Google gives a breakdown of these fields in the <a href="https://developer.chrome.com/devtools/docs/network" rel="noreferrer">Evaluating network performance</a> section of their DevTools documentation.</p> <h3>Excerpt from <a href="https://developer.chrome.com/devtools/docs/network#resource-network-timing" rel="noreferrer">Resource network timing</a>:</h3> <blockquote> <h3>Stalled/Blocking</h3> <p>Time the request spent waiting before it could be sent. This time is inclusive of any time spent in proxy negotiation. Additionally, this time will include when the browser is waiting for an already established connection to become available for re-use, obeying Chrome's <a href="https://code.google.com/p/chromium/issues/detail?id=12066" rel="noreferrer">maximum six</a> TCP connection per origin rule.</p> </blockquote> <p>(If you forget, Chrome has an &quot;Explanation&quot; link in the hover tooltip and under the &quot;Timing&quot; panel.)</p> <p>Basically, the primary reason you will see this is because Chrome will only download 6 files per-server at a time and other requests will be stalled until a connection slot becomes available.</p> <p>This isn't necessarily something that needs fixing, but one way to avoid the stalled state would be to distribute the files across multiple domain names and/or servers, keeping <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS" rel="noreferrer">CORS</a> in mind if applicable to your needs, however HTTP2 is probably a better option going forward. Resource bundling (like JS and CSS concatenation) can also help to reduce amount of stalled connections.</p>
{ "question_id": 29206067, "question_date": "2015-03-23T08:42:02.310Z", "question_score": 213, "tags": "google-chrome|http|httprequest|google-chrome-devtools", "answer_id": 29564247, "answer_date": "2015-04-10T14:39:39.060Z", "answer_score": 246 }
Please answer the following Stack Overflow question: Title: Using Default Arguments in a Function <p>I am confused about default values for PHP functions. Say I have a function like this:</p> <pre><code>function foo($blah, $x = "some value", $y = "some other value") { // code here! } </code></pre> <p>What if I want to use the default argument for $x and set a different argument for $y? </p> <p>I have been experimenting with different ways and I am just getting more confused. For example, I tried these two:</p> <pre><code>foo("blah", null, "test"); foo("blah", "", "test"); </code></pre> <p>But both of those do not result in a proper default argument for $x. I have also tried to set it by variable name.</p> <pre><code>foo("blah", $x, $y = "test"); </code></pre> <p>I fully expected something like this to work. But it doesn't work as I expected at all. It seems like no matter what I do, I am going to have to end up typing in the default arguments anyway, every time I invoke the function. And I must be missing something obvious. </p>
<p>I would propose changing the function declaration as follows so you can do what you want:</p> <pre><code>function foo($blah, $x = null, $y = null) { if (null === $x) { $x = &quot;some value&quot;; } if (null === $y) { $y = &quot;some other value&quot;; } code here! } </code></pre> <p>This way, you can make a call like <code>foo('blah', null, 'non-default y value');</code> and have it work as you want, where the second parameter <code>$x</code> still gets its default value.</p> <p>With this method, passing a null value means you want the default value for one parameter when you want to override the default value for a parameter that comes after it.</p> <p>As stated in other answers,</p> <blockquote> <p>default parameters only work as the last arguments to the function. If you want to declare the default values in the function definition, there is no way to omit one parameter and override one following it.</p> </blockquote> <p>If I have a method that can accept varying numbers of parameters, and parameters of varying types, I often declare the function similar to the answer shown by Ryan P.</p> <p>Here is another example (this doesn't answer your question, but is hopefully informative:</p> <pre><code>public function __construct($params = null) { if ($params instanceof SOMETHING) { // single parameter, of object type SOMETHING } elseif (is_string($params)) { // single argument given as string } elseif (is_array($params)) { // params could be an array of properties like array('x' =&gt; 'x1', 'y' =&gt; 'y1') } elseif (func_num_args() == 3) { $args = func_get_args(); // 3 parameters passed } elseif (func_num_args() == 5) { $args = func_get_args(); // 5 parameters passed } else { throw new \InvalidArgumentException(&quot;Could not figure out parameters!&quot;); } } </code></pre>
{ "question_id": 9166914, "question_date": "2012-02-06T20:36:37.113Z", "question_score": 213, "tags": "php|arguments|default", "answer_id": 9166950, "answer_date": "2012-02-06T20:40:12.773Z", "answer_score": 213 }
Please answer the following Stack Overflow question: Title: Make a VStack fill the width of the screen in SwiftUI <p>Given this code:</p> <pre class="lang-swift prettyprint-override"><code>import SwiftUI struct ContentView: View { var body: some View { VStack(alignment: .leading) { Text(&quot;Title&quot;) .font(.title) Text(&quot;Content&quot;) .lineLimit(nil) .font(.body) Spacer() } .background(Color.red) } } #if DEBUG struct ContentView_Previews : PreviewProvider { static var previews: some View { ContentView() } } #endif </code></pre> <hr /> <p>It results in this interface:</p> <p><a href="https://i.stack.imgur.com/B87Ym.png" rel="noreferrer"><img src="https://i.stack.imgur.com/B87Ym.png" alt="preview" /></a></p> <p>How can I make the <code>VStack</code> fill the width of the screen even if the labels/text components don't need the full width?</p> <hr /> <p>A trick I've found is to insert an <em>empty</em> <code>HStack</code> in the structure like so:</p> <pre class="lang-swift prettyprint-override"><code>VStack(alignment: .leading) { HStack { Spacer() } Text(&quot;Title&quot;) .font(.title) Text(&quot;Content&quot;) .lineLimit(nil) .font(.body) Spacer() } </code></pre> <p>Which yields the desired design:</p> <p><a href="https://i.stack.imgur.com/XK2cY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XK2cY.png" alt="desired output" /></a></p> <p>Is there a better way?</p>
<p>Try using the <code>.frame</code> modifier with the following options:</p> <pre><code>.frame( minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading ) </code></pre> <pre><code>struct ContentView: View { var body: some View { VStack(alignment: .leading) { Text(&quot;Hello World&quot;) .font(.title) Text(&quot;Another&quot;) .font(.body) Spacer() } .frame( minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading ) .background(Color.red) } } </code></pre> <p>This is described as being a flexible frame (<a href="https://developer.apple.com/wwdc19/204" rel="noreferrer">see the documentation</a>), which will stretch to fill the whole screen, and when it has extra space it will center its contents inside of it.</p>
{ "question_id": 56487323, "question_date": "2019-06-07T02:38:02.517Z", "question_score": 213, "tags": "ios|swift|xcode|swiftui", "answer_id": 56487605, "answer_date": "2019-06-07T03:31:08.440Z", "answer_score": 328 }
Please answer the following Stack Overflow question: Title: How do you create an asynchronous method in C#? <p>Every blog post I've read tells you how to consume an asynchronous method in C#, but for some odd reason never explain how to build your own asynchronous methods to consume. So I have this code right now that consumes my method:</p> <pre class="lang-cs prettyprint-override"><code>private async void button1_Click(object sender, EventArgs e) { var now = await CountToAsync(1000); label1.Text = now.ToString(); } </code></pre> <p>And I wrote this method that is <code>CountToAsync</code>:</p> <pre class="lang-cs prettyprint-override"><code>private Task&lt;DateTime&gt; CountToAsync(int num = 1000) { return Task.Factory.StartNew(() =&gt; { for (int i = 0; i &lt; num; i++) { Console.WriteLine("#{0}", i); } }).ContinueWith(x =&gt; DateTime.Now); } </code></pre> <p><strong>Is this, the use of <code>Task.Factory</code>, the best way to write an asynchronous method, or should I write this another way?</strong></p>
<p>I don't recommend <code>StartNew</code> unless you need that level of complexity.</p> <p>If your async method is dependent on other async methods, the easiest approach is to use the <code>async</code> keyword:</p> <pre><code>private static async Task&lt;DateTime&gt; CountToAsync(int num = 10) { for (int i = 0; i &lt; num; i++) { await Task.Delay(TimeSpan.FromSeconds(1)); } return DateTime.Now; } </code></pre> <p>If your async method is doing CPU work, you should use <code>Task.Run</code>:</p> <pre><code>private static async Task&lt;DateTime&gt; CountToAsync(int num = 10) { await Task.Run(() =&gt; ...); return DateTime.Now; } </code></pre> <p>You may find my <a href="http://blog.stephencleary.com/2012/02/async-and-await.html"><code>async</code>/<code>await</code> intro</a> helpful.</p>
{ "question_id": 16063520, "question_date": "2013-04-17T15:00:50.677Z", "question_score": 213, "tags": "c#|async-await|c#-5.0", "answer_id": 16064191, "answer_date": "2013-04-17T15:30:59.980Z", "answer_score": 254 }
Please answer the following Stack Overflow question: Title: Nodemon Error: System limit for number of file watchers reached <p>I'm learning <code>graphql</code> and using <code>prisma-binding</code> for graphql operations. I'm facing this <code>nodemon</code> error while I'm starting my node server and its giving me the path of schema file which is auto generated by a <code>graphql-cli</code>. Can anyone tell me what this error is all about? </p> <p>Error: </p> <pre><code>Internal watch failed: ENOSPC: System limit for number of file watchers reached, watch '/media/rehan-sattar/Development/All projects/GrpahQl/graph-ql-course/graphql-prisma/src/generated </code></pre>
<p>If you are using Linux, your project is hitting your system's file watchers limit</p> <p>To fix this, on your terminal, try:</p> <pre class="lang-sh prettyprint-override"><code>echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf &amp;&amp; sudo sysctl -p </code></pre>
{ "question_id": 53930305, "question_date": "2018-12-26T09:50:42.193Z", "question_score": 213, "tags": "node.js|graphql|nodemon", "answer_id": 55543310, "answer_date": "2019-04-05T21:01:54.507Z", "answer_score": 482 }
Please answer the following Stack Overflow question: Title: Calling class staticmethod within the class body? <p>When I attempt to use a static method from within the body of the class, and define the static method using the built-in <code>staticmethod</code> function as a decorator, like this:</p> <pre><code>class Klass(object): @staticmethod # use as decorator def _stat_func(): return 42 _ANS = _stat_func() # call the staticmethod def method(self): ret = Klass._stat_func() + Klass._ANS return ret </code></pre> <p>I get the following error:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File &quot;call_staticmethod.py&quot;, line 1, in &lt;module&gt; class Klass(object): File &quot;call_staticmethod.py&quot;, line 7, in Klass _ANS = _stat_func() TypeError: 'staticmethod' object is not callable </code></pre> <p><em>I understand why this is happening (descriptor binding)</em>, and can work around it by manually converting <code>_stat_func()</code> into a staticmethod after its last use, like so:</p> <pre><code>class Klass(object): def _stat_func(): return 42 _ANS = _stat_func() # use the non-staticmethod version _stat_func = staticmethod(_stat_func) # convert function to a static method def method(self): ret = Klass._stat_func() + Klass._ANS return ret </code></pre> <p>So my question is:</p> <p>    <strong>Are there cleaner or more &quot;Pythonic&quot; ways to accomplish this?</strong></p>
<p><code>staticmethod</code> objects apparently have a <code>__func__</code> attribute storing the original raw function (makes sense that they had to). So this will work:</p> <pre><code>class Klass(object): @staticmethod # use as decorator def stat_func(): return 42 _ANS = stat_func.__func__() # call the staticmethod def method(self): ret = Klass.stat_func() return ret </code></pre> <hr> <p>As an aside, though I suspected that a staticmethod object had some sort of attribute storing the original function, I had no idea of the specifics. In the spirit of teaching someone to fish rather than giving them a fish, this is what I did to investigate and find that out (a C&amp;P from my Python session):</p> <pre><code>&gt;&gt;&gt; class Foo(object): ... @staticmethod ... def foo(): ... return 3 ... global z ... z = foo &gt;&gt;&gt; z &lt;staticmethod object at 0x0000000002E40558&gt; &gt;&gt;&gt; Foo.foo &lt;function foo at 0x0000000002E3CBA8&gt; &gt;&gt;&gt; dir(z) ['__class__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] &gt;&gt;&gt; z.__func__ &lt;function foo at 0x0000000002E3CBA8&gt; </code></pre> <p>Similar sorts of digging in an interactive session (<code>dir</code> is very helpful) can often solve these sorts of question very quickly.</p>
{ "question_id": 12718187, "question_date": "2012-10-03T23:12:08.047Z", "question_score": 213, "tags": "python|decorator|static-methods", "answer_id": 12718272, "answer_date": "2012-10-03T23:24:28.450Z", "answer_score": 238 }
Please answer the following Stack Overflow question: Title: The environment is inconsistent, please check the package plan carefully <p>I tried to update or install new packages from anaconda and lately, this message has appeared:</p> <pre><code>The environment is inconsistent, please check the package plan carefully The following package are causing the inconsistency: - defaults/win-32::anaconda==5.3.1=py37_0 done </code></pre> <p>I tried with <code>conda clean --all</code> and then <code>conda update --all</code> but it persists.</p> <p><strong>Conda Info</strong></p> <pre><code>active environment : base active env location : C:\Users\NAME\Continuum shell level : 1 user config file : C:\Users\NAME\.condarc populated config files : C:\Users\NAME\.condarc conda version : 4.6.11 conda-build version : 3.17.7 python version : 3.7.3.final.0 base environment : C:\Users\NAME\Continuum (writable) channel URLs : https://repo.anaconda.com/pkgs/main/win-32 https://repo.anaconda.com/pkgs/main/noarch https://repo.anaconda.com/pkgs/free/win-32 https://repo.anaconda.com/pkgs/free/noarch https://repo.anaconda.com/pkgs/r/win-32 https://repo.anaconda.com/pkgs/r/noarch https://repo.anaconda.com/pkgs/msys2/win-32 https://repo.anaconda.com/pkgs/msys2/noarch package cache : C:\Users\NAME\Continuum\pkgs C:\Users\NAME\.conda\pkgs C:\Users\NAME\AppData\Local\conda\conda\pkgs envs directories : C:\Users\NAME\Continuum\envs C:\Users\NAME\.conda\envs C:\Users\NAME\AppData\Local\conda\conda\envs platform : win-32 user-agent : conda/4.6.11 requests/2.21.0 CPython/3.7.3 Windows/10 Windows/10.0.17763 administrator : False netrc file : None offline mode : False </code></pre>
<p>I had faced the same problem. Simply running</p> <pre><code>conda install anaconda </code></pre> <p>solved the problem for me.</p>
{ "question_id": 55527354, "question_date": "2019-04-05T02:13:09.210Z", "question_score": 213, "tags": "anaconda|conda", "answer_id": 55624247, "answer_date": "2019-04-11T03:25:43.850Z", "answer_score": 131 }
Please answer the following Stack Overflow question: Title: Repository size limits for GitHub.com <p>Lately I have been using GitHub and I am wondering what is the repository size limit for files hosted on github.com?</p>
<p>From GitHub's <a href="https://help.github.com/articles/what-is-my-disk-quota/" rel="noreferrer">documentation</a>:</p> <blockquote> <p>GitHub doesn't have any set disk quotas. We try to provide abundant storage for all Git repositories, within reason. Keeping repositories small ensures that our servers are fast and downloads are quick for our users.</p> </blockquote> <p>and</p> <blockquote> <p>In addition, we place a strict limit of files exceeding 100 MB in size.</p> </blockquote> <p>Now for the non-canned part of my answer. GitHub might allow you to store files up to 100MB, but you should also be vigilant to <em>not</em> version binary or other similar blob type files. The reason for this is that Git doesn't handle binaries well, and storage can be a big penalty. So if you find yourself pushing 100MB per file, you should check what type of file you are dealing with.</p>
{ "question_id": 38768454, "question_date": "2016-08-04T13:17:08.633Z", "question_score": 213, "tags": "git|github|repository|storage|limit", "answer_id": 38768668, "answer_date": "2016-08-04T13:26:13.987Z", "answer_score": 85 }
Please answer the following Stack Overflow question: Title: Creating an empty file in C# <p>What's the simplest/canonical way to create an empty file in C#/.NET?</p> <p>The simplest way I could find so far is:</p> <pre><code>System.IO.File.WriteAllLines(filename, new string[0]); </code></pre>
<p>Using just <code>File.Create</code> will leave the file open, which probably isn't what you want.</p> <p>You could use:</p> <pre><code>using (File.Create(filename)) ; </code></pre> <p>That looks slightly odd, mind you. You could use braces instead:</p> <pre><code>using (File.Create(filename)) {} </code></pre> <p>Or just call <code>Dispose</code> directly:</p> <pre><code>File.Create(filename).Dispose(); </code></pre> <p>Either way, if you're going to use this in more than one place you should probably consider wrapping it in a helper method, e.g.</p> <pre><code>public static void CreateEmptyFile(string filename) { File.Create(filename).Dispose(); } </code></pre> <p>Note that calling <code>Dispose</code> directly instead of using a <code>using</code> statement doesn't really make much difference here as far as I can tell - the only way it <em>could</em> make a difference is if the thread were aborted between the call to <code>File.Create</code> and the call to <code>Dispose</code>. If that race condition exists, I suspect it would <em>also</em> exist in the <code>using</code> version, if the thread were aborted at the very end of the <code>File.Create</code> method, just before the value was returned...</p>
{ "question_id": 802541, "question_date": "2009-04-29T14:14:42.073Z", "question_score": 213, "tags": "c#|.net", "answer_id": 802588, "answer_date": "2009-04-29T14:23:06.687Z", "answer_score": 428 }
Please answer the following Stack Overflow question: Title: How can I open Visual Studio Code's 'settings.json' file? <p>I did it many times, and each time I forgot where it was.</p> <p>Menu <em>File</em> → <em>Preferences</em> → <em>Settings</em>.</p> <p>I get this:</p> <p><a href="https://i.stack.imgur.com/peXuM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/peXuM.png" alt="Enter image description here" /></a></p> <p>I want to open file <em>settings.json</em> (editable JSON file) instead. How can I do that?</p>
<p>To open the <strong>User</strong> settings:</p> <ul> <li>Open the command palette (either with <kbd>F1</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd>)</li> <li>Type <em>&quot;open settings&quot;</em></li> <li>You are presented with two options, choose <strong>Open Settings (JSON)</strong></li> </ul> <p>Which, depending on platform, is one of:</p> <ul> <li><strong>Windows</strong> <code>%APPDATA%\Code\User\settings.json</code></li> <li><strong>macOS</strong> <code>$HOME/Library/Application\ Support/Code/User/settings.json</code></li> <li><strong>Linux</strong> <code>$HOME/.config/Code/User/settings.json</code></li> </ul> <p>The Workspace settings will be in a <code>{workspaceName}.code-workspace</code> file where you saved it, and the Folder settings will be in a <code>.vscode</code> folder if and when it has been created.</p> <hr /> <p><a href="https://code.visualstudio.com/docs/getstarted/settings" rel="noreferrer">Official page on User and Workspace Settings</a></p> <p>As stated by <a href="https://stackoverflow.com/a/70629074/6091017">sevencardz below</a>, VS Code now includes a button in the Settings UI gutter which can be used to switch between editor and graphical view. The <code>workbench.settings.editor</code> option selects which of these is opened by default when not using the above method, such as <kbd>⌘</kbd>+<kbd>,</kbd> or through the application menu.</p>
{ "question_id": 65908987, "question_date": "2021-01-26T20:42:25.210Z", "question_score": 213, "tags": "visual-studio-code", "answer_id": 65909052, "answer_date": "2021-01-26T20:47:07.067Z", "answer_score": 254 }
Please answer the following Stack Overflow question: Title: How can I dynamically add a directive in AngularJS? <p>I have a very boiled down version of what I am doing that gets the problem across.</p> <p>I have a simple <code>directive</code>. Whenever you click an element, it adds another one. However, it needs to be compiled first in order to render it correctly.</p> <p>My research led me to <code>$compile</code>. But all the examples use a complicated structure that I don't really know how to apply here.</p> <p>Fiddles are here: <a href="http://jsfiddle.net/paulocoelho/fBjbP/1/" rel="noreferrer">http://jsfiddle.net/paulocoelho/fBjbP/1/</a></p> <p>And the JS is here:</p> <pre><code>var module = angular.module('testApp', []) .directive('test', function () { return { restrict: 'E', template: '&lt;p&gt;{{text}}&lt;/p&gt;', scope: { text: '@text' }, link:function(scope,element){ $( element ).click(function(){ // TODO: This does not do what it's supposed to :( $(this).parent().append("&lt;test text='n'&gt;&lt;/test&gt;"); }); } }; }); </code></pre> <p>Solution by Josh David Miller: <a href="http://jsfiddle.net/paulocoelho/fBjbP/2/" rel="noreferrer">http://jsfiddle.net/paulocoelho/fBjbP/2/</a></p>
<p>You have a lot of pointless jQuery in there, but the $compile service is actually <em>super simple</em> in this case:</p> <pre class="lang-js prettyprint-override"><code>.directive( 'test', function ( $compile ) { return { restrict: 'E', scope: { text: '@' }, template: '&lt;p ng-click="add()"&gt;{{text}}&lt;/p&gt;', controller: function ( $scope, $element ) { $scope.add = function () { var el = $compile( "&lt;test text='n'&gt;&lt;/test&gt;" )( $scope ); $element.parent().append( el ); }; } }; }); </code></pre> <p>You'll notice I refactored your directive too in order to follow some best practices. Let me know if you have questions about any of those.</p>
{ "question_id": 15279244, "question_date": "2013-03-07T18:45:04.220Z", "question_score": 213, "tags": "angularjs|angularjs-directive|dynamically-generated", "answer_id": 15279343, "answer_date": "2013-03-07T18:51:22.860Z", "answer_score": 262 }
Please answer the following Stack Overflow question: Title: Figure out size of UILabel based on String in Swift <p>I am trying to calculate the height of a UILabel based on different String lengths.</p> <pre><code>func calculateContentHeight() -&gt; CGFloat{ var maxLabelSize: CGSize = CGSizeMake(frame.size.width - 48, CGFloat(9999)) var contentNSString = contentText as NSString var expectedLabelSize = contentNSString.boundingRectWithSize(maxLabelSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(16.0)], context: nil) print("\(expectedLabelSize)") return expectedLabelSize.size.height } </code></pre> <p>Above is the current function I use to determine the height but it is not working. I would greatly appreciate any help I can get. I would perfer the answer in Swift and not Objective C.</p>
<p>Use an extension on <code>String</code></p> <h2>Swift 3</h2> <pre><code>extension String { func height(withConstrainedWidth width: CGFloat, font: UIFont) -&gt; CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return ceil(boundingBox.height) } func width(withConstrainedHeight height: CGFloat, font: UIFont) -&gt; CGFloat { let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return ceil(boundingBox.width) } } </code></pre> <p>and also on <code>NSAttributedString</code> (which is very useful at times)</p> <pre><code>extension NSAttributedString { func height(withConstrainedWidth width: CGFloat) -&gt; CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil) return ceil(boundingBox.height) } func width(withConstrainedHeight height: CGFloat) -&gt; CGFloat { let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height) let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil) return ceil(boundingBox.width) } } </code></pre> <h2>Swift 4 &amp; 5</h2> <p>Just change the value for <code>attributes</code> in the <code>extension String</code> methods</p> <p>from</p> <pre><code>[NSFontAttributeName: font] </code></pre> <p>to</p> <pre><code>[.font : font] </code></pre>
{ "question_id": 30450434, "question_date": "2015-05-26T05:50:46.637Z", "question_score": 213, "tags": "ios|iphone|string|swift3|uilabel", "answer_id": 30450559, "answer_date": "2015-05-26T05:59:13.037Z", "answer_score": 604 }
Please answer the following Stack Overflow question: Title: Finding the source code for built-in Python functions? <p>Is there a way to see how built in functions work in python? I don't mean just how to use them, but also how were they built, what is the code behind <strong><em>sorted</em></strong> or <strong><em>enumerate</em></strong> etc...?</p>
<p>Since Python is open source you can read the <a href="https://github.com/python/cpython" rel="noreferrer">source code</a>.</p> <p>To find out what file a particular module or function is implemented in you can usually print the <code>__file__</code> attribute. Alternatively, you may use the <code>inspect</code> module, see the section <a href="https://docs.python.org/2/library/inspect.html#retrieving-source-code" rel="noreferrer">Retrieving Source Code</a> in the documentation of <code>inspect</code>.</p> <p>For built-in classes and methods this is not so straightforward since <code>inspect.getfile</code> and <code>inspect.getsource</code> will return a type error stating that the object is built-in. However, many of the built-in types can be found in the <a href="https://github.com/python/cpython/blob/master/Objects/" rel="noreferrer"><code>Objects</code> sub-directory of the Python source trunk</a>. For example, see <a href="https://github.com/python/cpython/blob/master/Objects/enumobject.c" rel="noreferrer">here</a> for the implementation of the enumerate class or <a href="https://github.com/python/cpython/blob/master/Objects/listobject.c" rel="noreferrer">here</a> for the implementation of the <code>list</code> type.</p>
{ "question_id": 8608587, "question_date": "2011-12-22T19:02:08.620Z", "question_score": 213, "tags": "python|python-internals", "answer_id": 8608609, "answer_date": "2011-12-22T19:06:01.147Z", "answer_score": 196 }
Please answer the following Stack Overflow question: Title: Strings as Primary Keys in SQL Database <p>I am not very familiar with databases and the theories behind how they work. Is it any slower from a performance standpoint (inserting/updating/querying) to use Strings for Primary Keys than integers? </p>
<p>Technically yes, but if a string makes sense to be the primary key then you should probably use it. This all depends on the size of the table you're making it for and the length of the string that is going to be the primary key (longer strings == harder to compare). I wouldn't necessarily use a string for a table that has millions of rows, but the amount of performance slowdown you'll get by using a string on smaller tables will be minuscule to the headaches that you can have by having an integer that doesn't mean anything in relation to the data.</p>
{ "question_id": 517579, "question_date": "2009-02-05T19:40:22.970Z", "question_score": 213, "tags": "sql|database|database-design|string|primary-key", "answer_id": 517591, "answer_date": "2009-02-05T19:44:16.927Z", "answer_score": 227 }