input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Difference between getContext() , getApplicationContext() , getBaseContext() and "this" <p>What is the difference between <code>getContext()</code> , <code>getApplicationContext()</code> , <code>getBaseContext()</code> , and "<code>this</code>"? </p> <p>Though this is simple question I am unable to understand the basic difference between them. Please give some easy examples if possible.</p>
<ul> <li><p><a href="http://developer.android.com/reference/android/view/View.html#getContext%28%29"><code>View.getContext()</code></a>: Returns the context the view is currently running in. Usually the currently active Activity.</p></li> <li><p><a href="http://developer.android.com/reference/android/content/ContextWrapper.html#getApplicationContext%28%29"><code>Activity.getApplicationContext()</code></a>: Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.</p></li> <li><p><a href="http://developer.android.com/reference/android/content/ContextWrapper.html#getBaseContext%28%29"><code>ContextWrapper.getBaseContext()</code></a>: If you need access to a Context from within another context, you use a ContextWrapper. The Context referred to from inside that ContextWrapper is accessed via getBaseContext().</p></li> </ul>
{ "question_id": 10641144, "question_date": "2012-05-17T18:07:13.180Z", "question_score": 644, "tags": "android|this|android-context", "answer_id": 10641257, "answer_date": "2012-05-17T18:15:25.737Z", "answer_score": 594 }
Please answer the following Stack Overflow question: Title: Should I use past or present tense in git commit messages? <p>I <a href="https://web.archive.org/web/20100827225248/http://progit.org/book/ch5-2.html" rel="noreferrer">read once</a> that git commit messages should be in the imperative present tense, e.g. &quot;Add tests for x&quot;. I always find myself using the past tense, e.g. &quot;Added tests for x&quot; though, which feels a lot more natural to me.</p> <p><a href="http://github.com/jquery/jquery/commit/c5382ad7c118ca54dde630b6c7146f1c3b6afb80" rel="noreferrer">Here's a recent John Resig commit</a> showing the two in one message:</p> <blockquote> <p>Tweak some more jQuery set results in the manipulation tests. Also fixed the order of the expected test results.</p> </blockquote> <p>Does it matter? Which should I use?</p>
<p>The preference for present-tense, imperative-style commit messages comes from Git itself. From <a href="https://git.kernel.org/pub/scm/git/git.git/tree/Documentation/SubmittingPatches?h=v2.36.1#n181" rel="noreferrer">Documentation/SubmittingPatches</a> in the Git repo:</p> <blockquote> <p>Describe your changes in imperative mood, e.g. &quot;make xyzzy do frotz&quot; instead of &quot;[This patch] makes xyzzy do frotz&quot; or &quot;[I] changed xyzzy to do frotz&quot;, as if you are giving orders to the codebase to change its behavior.</p> </blockquote> <p>So you'll see a lot of Git commit messages written in that style. If you're working on a team or on open source software, it is helpful if everyone sticks to that style for consistency. Even if you're working on a private project, and you're the only one who will ever see your git history, it's helpful to use the imperative mood because it establishes good habits that will be appreciated when you're working with others.</p>
{ "question_id": 3580013, "question_date": "2010-08-26T22:21:20.070Z", "question_score": 644, "tags": "git|git-commit|conventions|commit-message", "answer_id": 3580764, "answer_date": "2010-08-27T01:42:01.677Z", "answer_score": 744 }
Please answer the following Stack Overflow question: Title: Why is the result of ('b'+'a'+ + 'a' + 'a').toLowerCase() 'banana'? <p>I was practicing some JavaScript when one of my friends came across this JavaScript code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>document.write(('b' + 'a' + + 'a' + 'a').toLowerCase());</code></pre> </div> </div> </p> <p>The above code answers <code>"banana"</code>! Can anyone explain why?</p>
<p><code>+'a'</code> resolves to <code>NaN</code> ("Not a Number") because it coerces a string to a number, while the character <code>a</code> cannot be parsed as a number. <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>document.write(+'a');</code></pre> </div> </div> To lowercase it becomes <code>banana</code>.</p> <p>Adding <code>NaN</code> to <code>"ba"</code> turns <code>NaN</code> into the string <code>"NaN"</code> due to type conversion, gives <code>baNaN</code>. And then there is an <code>a</code> behind, giving <code>baNaNa</code>.</p> <p>The space between <code>+ +</code> is to make the first one string concatenation and the second one a unary plus (i.e. "positive") operator. You have the same result if you use <code>'ba'+(+'a')+'a'</code>, resolved as <code>'ba'+NaN+'a'</code>, which is equivalent to <code>'ba'+'NaN'+'a'</code> due to type juggling.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>document.write('ba'+(+'a')+'a');</code></pre> </div> </div> </p>
{ "question_id": 57456188, "question_date": "2019-08-12T05:50:43.860Z", "question_score": 644, "tags": "javascript|type-conversion", "answer_id": 57456236, "answer_date": "2019-08-12T05:56:50.730Z", "answer_score": 615 }
Please answer the following Stack Overflow question: Title: Updates were rejected because the tip of your current branch is behind its remote counterpart <p>Our workflow is such. We have a branch called <code>dev</code> which I can reach at <code>origin/dev</code>. When we do changes, we create a branch off dev:</p> <pre><code>git checkout -b FixForBug origin/dev </code></pre> <p>Now I have a branch called <code>FixForBug</code> which is tracking (I think that's the right word) <code>origin/dev</code>. Thus, if I do a <code>git pull</code> it'll bring in new changes from <code>origin/dev</code> which is great. Now, when I'm finished with my fix, I push to a remote branch called the same thing.</p> <p>First I pull down any changes from <code>origin/dev</code> and do a rebase:</p> <pre><code>git pull --rebase </code></pre> <p>Then I push the changes to a remote branch of the same name:</p> <pre><code>git push origin FixForBug </code></pre> <p>Now, there's a branch on the remote server and I can create a pull request for that change to be approved and merged back in to the dev branch. I don't <em>ever</em> push anything to <code>origin/dev</code> myself. I'm guessing this is as pretty common workflow.</p> <p>The first time I do a <code>git push</code>, it works fine and creates the remote branch. However, if I push a <em>second</em> time (let's say during code-review, someone points out a problem), I get the following error:</p> <blockquote> <p>error: failed to push some refs to 'https://github.mydomain.info/Product/product.git'<br /> hint: Updates were rejected because the tip of your current branch is behind its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again.<br /> See the 'Note about fast-forwards' in 'git push --help' for details.</p> </blockquote> <p>However, if I do a <code>git status</code> it says I'm ahead of <code>origin/dev</code> by 1 commit (which makes sense) and if I follow the hint and run <code>git pull</code>, it says everything is up to date. I <em>think</em> this is because I'm pushing to a different branch than my upstream branch. I can fix this issue by running:</p> <p><code>git push -f origin FixForBug</code></p> <p>In that case, it'll push the changes to the remote branch, saying <em>(forced update)</em> and everything <em>appears</em> to be good on the remote branch.</p> <p><strong>My Questions:</strong></p> <p>Why is <code>-f</code> required in this scenario? Usually when you're <em>forcing</em> something, it's because you were doing something wrong or at least against standard practice. Am I ok doing this, or will it mess up something in the remote branch or create a hassle for whoever has to eventually merge my stuff into dev?</p>
<p>The <code>-f</code> <strong>is</strong> actually required because of the rebase. Whenever you do a rebase you would need to do a force push because the remote branch cannot be fast-forwarded to your commit. You'd <strong>always</strong> want to make sure that you do a pull before pushing, but if you don't like to force push to master or dev for that matter, you can create a new branch to push to and then merge or make a PR.</p>
{ "question_id": 39399804, "question_date": "2016-09-08T20:37:58.903Z", "question_score": 643, "tags": "git", "answer_id": 39400690, "answer_date": "2016-09-08T21:47:01.327Z", "answer_score": 722 }
Please answer the following Stack Overflow question: Title: Set the table column width constant regardless of the amount of text in its cells? <p>In my table I set the width of the first cell in a column to be <code>100px</code>.<br /> However, when the text in one of the cell in this column is too long, the width of the column becomes more than <code>100px</code>. How could I disable this expansion?</p>
<p>I played with it for a bit because I had trouble figuring it out. </p> <p>You need to set the cell width (either <code>th</code> or <code>td</code> worked, I set both) AND set the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/table-layout" rel="noreferrer"><code>table-layout</code></a> to <code>fixed</code>. For some reason, the cell width seems to only stay fixed if the table width is set, too (I think that's silly but whatev). </p> <p>Also, it is useful to set the <code>overflow</code> property to <code>hidden</code> to prevent any extra text from coming out of the table.</p> <p>You should make sure to leave all of the bordering and sizing for CSS, too.</p> <p>Ok so here's what I have:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>table { border: 1px solid black; table-layout: fixed; width: 200px; } th, td { border: 1px solid black; width: 100px; overflow: hidden; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table&gt; &lt;tr&gt; &lt;th&gt;header 1&lt;/th&gt; &lt;th&gt;header 234567895678657&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;data asdfasdfasdfasdfasdf&lt;/td&gt; &lt;td&gt;data 2&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/itamark/uAKNx/" rel="noreferrer">Here it is in JSFiddle</a></p> <p>This guy had a similar problem: <a href="https://stackoverflow.com/q/446624/534056">Table cell widths - fixing width, wrapping/truncating long words</a></p>
{ "question_id": 4457506, "question_date": "2010-12-16T04:44:25.680Z", "question_score": 643, "tags": "html|css|column-width", "answer_id": 4457905, "answer_date": "2010-12-16T06:04:31.613Z", "answer_score": 716 }
Please answer the following Stack Overflow question: Title: How to write to file in Ruby? <p>I need to read the data out of database and then save it in a text file.</p> <p>How can I do that in Ruby? Is there any file management system in Ruby?</p>
<p>The Ruby <a href="http://ruby-doc.org/core/classes/File.html" rel="noreferrer">File class</a> will give you the ins and outs of <code>::new</code> and <code>::open</code> but its parent, the <a href="http://ruby-doc.org/core/classes/IO.html" rel="noreferrer">IO class</a>, gets into the depth of <code>#read</code> and <code>#write</code>.</p>
{ "question_id": 2777802, "question_date": "2010-05-06T01:11:39.523Z", "question_score": 643, "tags": "ruby|file-io", "answer_id": 2777872, "answer_date": "2010-05-06T01:31:45.680Z", "answer_score": 190 }
Please answer the following Stack Overflow question: Title: How to access the GET parameters after "?" in Express? <p>I know how to get the params for queries like this:</p> <pre><code>app.get('/sample/:id', routes.sample); </code></pre> <p>In this case, I can use <code>req.params.id</code> to get the parameter (e.g. <code>2</code> in <code>/sample/2</code>).</p> <p>However, for url like <code>/sample/2?color=red</code>, how can I access the variable <code>color</code>?</p> <p>I tried <code>req.params.color</code> but it didn't work.</p>
<p>So, after checking out the <a href="http://expressjs.com/api.html#req.query" rel="noreferrer">express reference</a>, I found that <code>req.query.color</code> would return me the value I'm looking for.</p> <p>req.params refers to items with a ':' in the URL and req.query refers to items associated with the '?'</p> <p>Example: </p> <pre><code>GET /something?color1=red&amp;color2=blue </code></pre> <p>Then in express, the handler: </p> <pre><code>app.get('/something', (req, res) =&gt; { req.query.color1 === 'red' // true req.query.color2 === 'blue' // true }) </code></pre>
{ "question_id": 17007997, "question_date": "2013-06-09T08:51:44.107Z", "question_score": 643, "tags": "node.js|express|query-string", "answer_id": 17008027, "answer_date": "2013-06-09T08:56:28.407Z", "answer_score": 967 }
Please answer the following Stack Overflow question: Title: java.util.Date to XMLGregorianCalendar <p>Isn't there a convenient way of getting from a java.util.Date to a XMLGregorianCalendar?</p>
<p>I should like to take a step back and a modern look at this 10 years old question. The classes mentioned, <code>Date</code> and <code>XMLGregorianCalendar</code>, are old now. I challenge the use of them and offer alternatives.</p> <ul> <li><code>Date</code> was always poorly designed and is more than 20 years old. This is simple: don’t use it.</li> <li><code>XMLGregorianCalendar</code> is old too and has an old-fashioned design. As I understand it, it was used for producing dates and times in XML format for XML documents. Like <code>2009-05-07T19:05:45.678+02:00</code> or <code>2009-05-07T17:05:45.678Z</code>. These formats agree well enough with ISO 8601 that the classes of java.time, the modern Java date and time API, can produce them, which we prefer.</li> </ul> <h2>No conversion necessary</h2> <p>For many (most?) purposes the modern replacement for a <code>Date</code> will be an <code>Instant</code>. An <code>Instant</code> is a point in time (just as a <code>Date</code> is).</p> <pre><code> Instant yourInstant = // ... System.out.println(yourInstant); </code></pre> <p>An example output from this snippet:</p> <blockquote> <p>2009-05-07T17:05:45.678Z</p> </blockquote> <p>It’s the same as the latter of my example <code>XMLGregorianCalendar</code> strings above. As most of you know, it comes from <code>Instant.toString</code> being implicitly called by <code>System.out.println</code>. With java.time, in many cases we don’t need the conversions that in the old days we made between <code>Date</code>, <code>Calendar</code>, <code>XMLGregorianCalendar</code> and other classes (in some cases we do need conversions, though, I am showing you a couple in the next section).</p> <h2>Controlling the offset</h2> <p>Neither a <code>Date</code> nor in <code>Instant</code> has got a time zone nor a UTC offset. The previously accepted and still highest voted answer by Ben Noland uses the JVMs current default time zone for selecting the offset of the <code>XMLGregorianCalendar</code>. To include an offset in a modern object we use an <code>OffsetDateTime</code>. For example:</p> <pre><code> ZoneId zone = ZoneId.of("America/Asuncion"); OffsetDateTime dateTime = yourInstant.atZone(zone).toOffsetDateTime(); System.out.println(dateTime); </code></pre> <blockquote> <p>2009-05-07T13:05:45.678-04:00</p> </blockquote> <p>Again this conforms with XML format. If you want to use the current JVM time zone setting again, set <code>zone</code> to <code>ZoneId.systemDefault()</code>.</p> <h2>What if I absolutely need an XMLGregorianCalendar?</h2> <p>There are more ways to convert <code>Instant</code> to <code>XMLGregorianCalendar</code>. I will present a couple, each with its pros and cons. First, just as an <code>XMLGregorianCalendar</code> produces a string like <code>2009-05-07T17:05:45.678Z</code>, it can also be built from such a string:</p> <pre><code> String dateTimeString = yourInstant.toString(); XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(dateTimeString); System.out.println(date2); </code></pre> <blockquote> <p>2009-05-07T17:05:45.678Z</p> </blockquote> <p>Pro: it’s short and I don’t think it gives any surprises. Con: To me it feels like a waste formatting the instant into a string and parsing it back.</p> <pre><code> ZonedDateTime dateTime = yourInstant.atZone(zone); GregorianCalendar c = GregorianCalendar.from(dateTime); XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c); System.out.println(date2); </code></pre> <blockquote> <p>2009-05-07T13:05:45.678-04:00</p> </blockquote> <p>Pro: It’s the official conversion. Controlling the offset comes naturally. Con: It goes through more steps and is therefore longer.</p> <h2>What if we got a Date?</h2> <p>If you got an old-fashioned <code>Date</code> object from a legacy API that you cannot afford to change just now, convert it to <code>Instant</code>:</p> <pre><code> Instant i = yourDate.toInstant(); System.out.println(i); </code></pre> <p>Output is the same as before:</p> <blockquote> <p>2009-05-07T17:05:45.678Z</p> </blockquote> <p>If you want to control the offset, convert further to an <code>OffsetDateTime</code> in the same way as above.</p> <p>If you’ve got an old-fashioned <code>Date</code> and absolutely need an old-fashioned <code>XMLGregorianCalendar</code>, just use the answer by Ben Noland.</p> <h2>Links</h2> <ul> <li><a href="https://docs.oracle.com/javase/tutorial/datetime/" rel="noreferrer">Oracle tutorial: Date Time</a> explaining how to use java.time.</li> <li><a href="https://www.w3schools.com/xml/schema_dtypes_date.asp" rel="noreferrer">XSD Date and Time Data Types</a> on W3Schools.</li> <li><a href="https://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">Wikipedia article: ISO 8601</a></li> </ul>
{ "question_id": 835889, "question_date": "2009-05-07T17:05:03.327Z", "question_score": 643, "tags": "java|xml|date|xmlgregoriancalendar", "answer_id": 56313273, "answer_date": "2019-05-26T11:57:20.027Z", "answer_score": 67 }
Please answer the following Stack Overflow question: Title: What is the maximum possible length of a query string? <p>Is it browser dependent? Also, do different web stacks have different limits on how much data they can get from the request?</p>
<p><a href="https://www.rfc-editor.org/rfc/rfc2616" rel="noreferrer">RFC 2616</a> (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). <a href="https://www.rfc-editor.org/rfc/rfc3986" rel="noreferrer">RFC 3986</a> (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).</p> <p>While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at <a href="https://web.archive.org/web/20170503192739/https://boutell.com/newfaq/misc/urllength.html" rel="noreferrer">Internet Archive Of Boutell.com</a>:</p> <ul> <li><p><strong>Microsoft Edge (Browser)</strong><br /> The limit appears to be around 81578 characters. See <a href="https://stackoverflow.com/questions/32267442/url-length-limitation-of-microsoft-edge">URL Length limitation of Microsoft Edge</a></p> </li> <li><p><strong>Chrome</strong><br /> It stops <em>displaying</em> the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.</p> </li> <li><p><strong>Firefox (Browser)</strong><br /> After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.</p> </li> <li><p><strong>Safari (Browser)</strong><br /> At least 80,000 characters will work. Testing was not tried beyond that.</p> </li> <li><p><strong>Opera (Browser)</strong><br /> At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable, copyable and pasteable URL in the location bar even at 190,000 characters.</p> </li> <li><p><strong>Microsoft Internet Explorer (Browser)</strong><br /> Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.</p> </li> <li><p><strong>Apache (Server)</strong><br /> Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a &quot;413 Entity Too Large&quot; error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.</p> </li> <li><p><strong>Microsoft Internet Information Server (Server)</strong><br /> The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.</p> </li> <li><p><strong>Perl HTTP::Daemon (Server)</strong><br /> Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.</p> </li> </ul>
{ "question_id": 812925, "question_date": "2009-05-01T19:44:15.647Z", "question_score": 643, "tags": "browser|max|query-string", "answer_id": 812962, "answer_date": "2009-05-01T19:53:30.400Z", "answer_score": 1099 }
Please answer the following Stack Overflow question: Title: Simple argparse example wanted: 1 argument, 3 results <p>The <a href="http://docs.python.org/library/argparse.html" rel="noreferrer">documentation</a> for the <a href="http://www.doughellmann.com/PyMOTW/argparse/" rel="noreferrer">argparse python module</a>, while excellent I'm sure, is too much for my tiny beginner brain to grasp right now. I don't need to do math on the command line or meddle with formatting lines on the screen or change option characters. All I want to do is <em>"If arg is A, do this, if B do that, if none of the above show help and quit"</em>.</p>
<p>My understanding of the original question is two-fold. First, in terms of the simplest possible argparse example, I'm surprised that I haven't seen it here. Of course, to be dead-simple, it's also all overhead with little power, but it might get you started.</p> <pre><code>import argparse parser = argparse.ArgumentParser() parser.add_argument("a") args = parser.parse_args() if args.a == 'magic.name': print 'You nailed it!' </code></pre> <p>But this positional argument is now required. If you leave it out when invoking this program, you'll get an error about missing arguments. This leads me to the second part of the original question. Matt Wilkie seems to want a single <strong>optional</strong> argument without a named label (the --option labels). My suggestion would be to modify the code above as follows:</p> <pre><code>... parser.add_argument("a", nargs='?', default="check_string_for_empty") ... if args.a == 'check_string_for_empty': print 'I can tell that no argument was given and I can deal with that here.' elif args.a == 'magic.name': print 'You nailed it!' else: print args.a </code></pre> <p>There may well be a more elegant solution, but this works and is minimalist.</p>
{ "question_id": 7427101, "question_date": "2011-09-15T07:11:46.343Z", "question_score": 643, "tags": "python|argparse", "answer_id": 22045954, "answer_date": "2014-02-26T15:31:21.683Z", "answer_score": 305 }
Please answer the following Stack Overflow question: Title: How to change the color of header bar and address bar in newest Chrome version on Lollipop? <p>Haven't found anything on this topic yet. I really like the ability to change the color of address bar and header color on Overview? Is there any easy way to do this?</p> <p><img src="https://i.stack.imgur.com/6iShFm.png" alt="Chrome for Android"> <img src="https://i.stack.imgur.com/bmTDdm.jpg" alt="enter image description here">.</p> <p>I think you need Android 5.0 Lollipop for this to work, and Chrome's <em>Merge Tabs and Apps</em> set to <em>On</em>.</p>
<p>Found the solution after some searching.</p> <p>You need to add a <code>&lt;meta&gt;</code> tag in your <code>&lt;head&gt;</code> containing <code>name=&quot;theme-color&quot;</code>, with your HEX code as the content value. For example:</p> <pre><code>&lt;meta name=&quot;theme-color&quot; content=&quot;#999999&quot; /&gt; </code></pre> <h2>Update:</h2> <p>If the android device has native <code>dark-mode</code> enabled, then this <code>meta</code> tag is ignored.</p> <blockquote> <p>Chrome for Android does not use the color on devices with native <code>dark-mode</code> enabled.</p> </blockquote> <p><strong>source:</strong> <a href="https://caniuse.com/#search=theme-color" rel="noreferrer">https://caniuse.com/#search=theme-color</a></p>
{ "question_id": 26960703, "question_date": "2014-11-16T18:48:58.110Z", "question_score": 643, "tags": "android|html|google-chrome", "answer_id": 26960753, "answer_date": "2014-11-16T18:54:22.653Z", "answer_score": 893 }
Please answer the following Stack Overflow question: Title: What's the difference between "super()" and "super(props)" in React when using es6 classes? <p>When is it important to pass <code>props</code> to <code>super()</code>, and why?</p> <pre><code>class MyComponent extends React.Component { constructor(props) { super(); // or super(props) ? } } </code></pre>
<p>There is only one reason when one needs to pass <code>props</code> to <code>super()</code>:</p> <p><strong>When you want to access <code>this.props</code> in constructor.</strong></p> <p>Passing:</p> <pre><code>class MyComponent extends React.Component { constructor(props) { super(props) console.log(this.props) // -&gt; { icon: 'home', … } } } </code></pre> <p>Not passing:</p> <pre><code>class MyComponent extends React.Component { constructor(props) { super() console.log(this.props) // -&gt; undefined // Props parameter is still available console.log(props) // -&gt; { icon: 'home', … } } render() { // No difference outside constructor console.log(this.props) // -&gt; { icon: 'home', … } } } </code></pre> <p>Note that passing or not passing <code>props</code> to <code>super</code> has <strong>no effect</strong> on later uses of <code>this.props</code> outside <code>constructor</code>. That is <code>render</code>, <code>shouldComponentUpdate</code>, or event handlers <strong>always</strong> have access to it.</p> <p>This is explicitly said in one Sophie Alpert's <a href="https://discuss.reactjs.org/t/should-we-include-the-props-parameter-to-class-constructors-when-declaring-components-using-es6-classes/2781/2" rel="noreferrer">answer</a> to a similar question.</p> <hr> <p>The documentation—<a href="https://facebook.github.io/react/docs/state-and-lifecycle.html#adding-local-state-to-a-class" rel="noreferrer">State and Lifecycle, Adding Local State to a Class, point 2</a>—recommends:</p> <blockquote> <p>Class components should always call the base constructor with <code>props</code>.</p> </blockquote> <p>However, no reason is provided. We can speculate it is either because of subclassing or for future compatibility.</p> <p>(Thanks @MattBrowne for the link)</p>
{ "question_id": 30571875, "question_date": "2015-06-01T11:04:52.040Z", "question_score": 643, "tags": "reactjs|ecmascript-6", "answer_id": 34995257, "answer_date": "2016-01-25T14:42:17.697Z", "answer_score": 823 }
Please answer the following Stack Overflow question: Title: In WPF, what are the differences between the x:Name and Name attributes? <p>Sometimes it seems that the <code>Name</code> and <code>x:Name</code> attributes are interchangeable.</p> <p>So, what are the definitive differences between them, and when is it preferable to use one over the other?</p> <p>Are there any performance or memory implications to using them the wrong way?</p>
<p>There really is only one name in XAML, the <code>x:Name</code>. A framework, such as WPF, can optionally map one of its properties to XAML's <code>x:Name</code> by using the <code>RuntimeNamePropertyAttribute</code> on the class that designates one of the classes properties as mapping to the x:Name attribute of XAML.</p> <p>The reason this was done was to allow for frameworks that already have a concept of "Name" at runtime, such as WPF. In WPF, for example, <code>FrameworkElement</code> introduces a Name property.</p> <p>In general, a class does not need to store the name for <code>x:Name</code> to be useable. All <code>x:Name</code> means to XAML is generate a field to store the value in the code behind class. What the runtime does with that mapping is framework dependent.</p> <p>So, why are there two ways to do the same thing? The simple answer is because there are two concepts mapped onto one property. WPF wants the name of an element preserved at runtime (which is usable through Bind, among other things) and XAML needs to know what elements you want to be accessible by fields in the code behind class. WPF ties these two together by marking the Name property as an alias of x:Name.</p> <p>In the future, XAML will have more uses for x:Name, such as allowing you to set properties by referring to other objects by name, but in 3.5 and prior, it is only used to create fields.</p> <p>Whether you should use one or the other is really a style question, not a technical one. I will leave that to others for a recommendation.</p> <p>See also <a href="https://stackoverflow.com/questions/4605777/automationproperties-name-vs-xname">AutomationProperties.Name VS x:Name</a>, AutomationProperties.Name is used by accessibility tools and some testing tools.</p>
{ "question_id": 589874, "question_date": "2009-02-26T09:53:21.610Z", "question_score": 643, "tags": ".net|wpf|xaml|name-attribute", "answer_id": 593151, "answer_date": "2009-02-27T00:52:49.170Z", "answer_score": 513 }
Please answer the following Stack Overflow question: Title: Change color of PNG image via CSS? <p>Given a transparent PNG displaying a simple shape in white, is it possible to somehow change the color of this through CSS? Some kind of overlay or what not?</p>
<p>You can use filters with <code>-webkit-filter</code> and <code>filter</code>: Filters are relatively new to browsers but supported in over 90% of browsers according to the following CanIUse table: <a href="https://caniuse.com/#feat=css-filters" rel="noreferrer">https://caniuse.com/#feat=css-filters</a></p> <p>You can change an image to grayscale, sepia and lot more (look at the example).</p> <p><strong>So you can now change the color of a PNG file with filters.</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background-color:#03030a; min-width: 800px; min-height: 400px } img { width:20%; float:left; margin:0; } /*Filter styles*/ .saturate { filter: saturate(3); } .grayscale { filter: grayscale(100%); } .contrast { filter: contrast(160%); } .brightness { filter: brightness(0.25); } .blur { filter: blur(3px); } .invert { filter: invert(100%); } .sepia { filter: sepia(100%); } .huerotate { filter: hue-rotate(180deg); } .rss.opacity { filter: opacity(50%); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!--- img src http://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/500px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg --&gt; &lt;img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=3&amp;h=750&amp;w=1260" title="original"&gt; &lt;img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=3&amp;h=750&amp;w=1260" title="saturate" class="saturate"&gt; &lt;img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=3&amp;h=750&amp;w=1260" title="grayscale" class="grayscale"&gt; &lt;img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=3&amp;h=750&amp;w=1260" title="contrast" class="contrast"&gt; &lt;img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=3&amp;h=750&amp;w=1260" title="brightness" class="brightness"&gt; &lt;img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=3&amp;h=750&amp;w=1260" title="blur" class="blur"&gt; &lt;img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=3&amp;h=750&amp;w=1260" title="invert" class="invert"&gt; &lt;img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=3&amp;h=750&amp;w=1260" title="sepia" class="sepia"&gt; &lt;img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=3&amp;h=750&amp;w=1260" title="huerotate" class="huerotate"&gt; &lt;img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=3&amp;h=750&amp;w=1260" title="opacity" class="rss opacity"&gt;</code></pre> </div> </div> </p> <p><sub><a href="http://codepen.io/rss/pen/ftnDd" rel="noreferrer">Source</a></sub></p>
{ "question_id": 7415872, "question_date": "2011-09-14T11:53:05.680Z", "question_score": 642, "tags": "html|css|image|png|overlay", "answer_id": 20933311, "answer_date": "2014-01-05T12:03:59.360Z", "answer_score": 726 }
Please answer the following Stack Overflow question: Title: Converting a Pandas GroupBy output from Series to DataFrame <p>I'm starting with input data like this</p> <pre><code>df1 = pandas.DataFrame( { "Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] , "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"] } ) </code></pre> <p>Which when printed appears as this:</p> <pre><code> City Name 0 Seattle Alice 1 Seattle Bob 2 Portland Mallory 3 Seattle Mallory 4 Seattle Bob 5 Portland Mallory </code></pre> <p>Grouping is simple enough:</p> <pre><code>g1 = df1.groupby( [ "Name", "City"] ).count() </code></pre> <p>and printing yields a <code>GroupBy</code> object:</p> <pre><code> City Name Name City Alice Seattle 1 1 Bob Seattle 2 2 Mallory Portland 2 2 Seattle 1 1 </code></pre> <p>But what I want eventually is another DataFrame object that contains all the rows in the GroupBy object. In other words I want to get the following result:</p> <pre><code> City Name Name City Alice Seattle 1 1 Bob Seattle 2 2 Mallory Portland 2 2 Mallory Seattle 1 1 </code></pre> <p>I can't quite see how to accomplish this in the pandas documentation. Any hints would be welcome.</p>
<p><code>g1</code> here <em>is</em> a DataFrame. It has a hierarchical index, though:</p> <pre><code>In [19]: type(g1) Out[19]: pandas.core.frame.DataFrame In [20]: g1.index Out[20]: MultiIndex([('Alice', 'Seattle'), ('Bob', 'Seattle'), ('Mallory', 'Portland'), ('Mallory', 'Seattle')], dtype=object) </code></pre> <p>Perhaps you want something like this?</p> <pre><code>In [21]: g1.add_suffix('_Count').reset_index() Out[21]: Name City City_Count Name_Count 0 Alice Seattle 1 1 1 Bob Seattle 2 2 2 Mallory Portland 2 2 3 Mallory Seattle 1 1 </code></pre> <p>Or something like:</p> <pre><code>In [36]: DataFrame({'count' : df1.groupby( [ "Name", "City"] ).size()}).reset_index() Out[36]: Name City count 0 Alice Seattle 1 1 Bob Seattle 2 2 Mallory Portland 2 3 Mallory Seattle 1 </code></pre>
{ "question_id": 10373660, "question_date": "2012-04-29T16:10:35.413Z", "question_score": 642, "tags": "python|pandas|dataframe|pandas-groupby|multi-index", "answer_id": 10374456, "answer_date": "2012-04-29T17:50:33.950Z", "answer_score": 667 }
Please answer the following Stack Overflow question: Title: Fetch the rows which have the Max value for a column for each distinct value of another column <p>Table: </p> <pre><code>UserId, Value, Date. </code></pre> <p>I want to get the UserId, Value for the max(Date) for each UserId. That is, the Value for each UserId that has the latest date. Is there a way to do this simply in SQL? (Preferably Oracle)</p> <p><strong>Update:</strong> Apologies for any ambiguity: I need to get ALL the UserIds. But for each UserId, only that row where that user has the latest date.</p>
<p>This will retrieve all rows for which the my_date column value is equal to the maximum value of my_date for that userid. This may retrieve multiple rows for the userid where the maximum date is on multiple rows.</p> <pre><code>select userid, my_date, ... from ( select userid, my_date, ... max(my_date) over (partition by userid) max_my_date from users ) where my_date = max_my_date </code></pre> <p>"Analytic functions rock"</p> <p>Edit: With regard to the first comment ...</p> <p>"using analytic queries and a self-join defeats the purpose of analytic queries"</p> <p>There is no self-join in this code. There is instead a predicate placed on the result of the inline view that contains the analytic function -- a very different matter, and completely standard practice.</p> <p>"The default window in Oracle is from the first row in the partition to the current one"</p> <p>The windowing clause is only applicable in the presence of the order by clause. With no order by clause, no windowing clause is applied by default and none can be explicitly specified.</p> <p>The code works.</p>
{ "question_id": 121387, "question_date": "2008-09-23T14:34:13.877Z", "question_score": 642, "tags": "sql|oracle|greatest-n-per-group", "answer_id": 121450, "answer_date": "2008-09-23T14:41:11.677Z", "answer_score": 441 }
Please answer the following Stack Overflow question: Title: Differences between socket.io and websockets <p>What are the differences between socket.io and websockets in node.js?<br> Are they both server push technologies? The only differences I felt was,</p> <ol> <li><p>socket.io allowed me to send/emit messages by specifying an event name.</p></li> <li><p>In the case of socket.io a message from server will reach on all clients, but for the same in websockets I was forced to keep an array of all connections and loop through it to send messages to all clients.</p></li> </ol> <p>Also, I wonder why web inspectors (like Chrome/firebug/fiddler) are unable to catch these messages (from socket.io/websocket) from server?</p> <p>Please clarify this.</p>
<p>Its advantages are that it simplifies the usage of WebSockets as you described in #2, and probably more importantly it provides fail-overs to other protocols in the event that WebSockets are not supported on the browser or server. I would avoid using WebSockets directly unless you are very familiar with what environments they don't work and you are capable of working around those limitations.</p> <p>This is a good read on both WebSockets and Socket.IO.</p> <p><a href="http://davidwalsh.name/websocket" rel="noreferrer">http://davidwalsh.name/websocket</a></p>
{ "question_id": 10112178, "question_date": "2012-04-11T18:57:04.883Z", "question_score": 642, "tags": "node.js|google-chrome|firebug|websocket|socket.io", "answer_id": 10112562, "answer_date": "2012-04-11T19:24:41Z", "answer_score": 393 }
Please answer the following Stack Overflow question: Title: How to use concerns in Rails 4 <p>The default Rails 4 project generator now creates the directory "concerns" under controllers and models. I have found some explanations about how to use routing concerns, but nothing about controllers or models.</p> <p>I am pretty sure it has to do with the current "DCI trend" in the community and would like to give it a try.</p> <p>The question is, how am I supposed to use this feature, is there a convention on how to define the naming / class hierarchy in order to make it work? How can I include a concern in a model or controller?</p>
<p>So I found it out by myself. It is actually a pretty simple but powerful concept. It has to do with code reuse as in the example below. Basically, the idea is to extract common and / or context specific chunks of code in order to clean up the models and avoid them getting too fat and messy.</p> <p>As an example, I'll put one well known pattern, the taggable pattern:</p> <pre><code># app/models/product.rb class Product include Taggable ... end # app/models/concerns/taggable.rb # notice that the file name has to match the module name # (applying Rails conventions for autoloading) module Taggable extend ActiveSupport::Concern included do has_many :taggings, as: :taggable has_many :tags, through: :taggings class_attribute :tag_limit end def tags_string tags.map(&amp;:name).join(', ') end def tags_string=(tag_string) tag_names = tag_string.to_s.split(', ') tag_names.each do |tag_name| tags.build(name: tag_name) end end # methods defined here are going to extend the class, not the instance of it module ClassMethods def tag_limit(value) self.tag_limit_value = value end end end </code></pre> <p>So following the Product sample, you can add Taggable to any class you desire and share its functionality.</p> <p>This is pretty well explained by <a href="http://37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns" rel="noreferrer">DHH</a>:</p> <blockquote> <p>In Rails 4, we’re going to invite programmers to use concerns with the default app/models/concerns and app/controllers/concerns directories that are automatically part of the load path. Together with the ActiveSupport::Concern wrapper, it’s just enough support to make this light-weight factoring mechanism shine.</p> </blockquote>
{ "question_id": 14541823, "question_date": "2013-01-26T21:36:27.560Z", "question_score": 642, "tags": "ruby-on-rails|ruby-on-rails-4|dci", "answer_id": 15078070, "answer_date": "2013-02-25T22:50:30.447Z", "answer_score": 629 }
Please answer the following Stack Overflow question: Title: How to check if any value is NaN in a Pandas DataFrame <p>In Python Pandas, what's the best way to check whether a DataFrame has one (or more) NaN values?</p> <p>I know about the function <code>pd.isnan</code>, but this returns a DataFrame of booleans for each element. <a href="https://stackoverflow.com/questions/27754891/python-nan-value-in-pandas">This post</a> right here doesn't exactly answer my question either.</p>
<p><a href="https://stackoverflow.com/users/1567452/jwilner">jwilner</a>'s response is spot on. I was exploring to see if there's a faster option, since in my experience, summing flat arrays is (strangely) faster than counting. This code seems faster:</p> <pre class="lang-py prettyprint-override"><code>df.isnull().values.any() </code></pre> <p><a href="https://i.stack.imgur.com/7l80g.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7l80g.png" alt="enter image description here" /></a></p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd import perfplot def setup(n): df = pd.DataFrame(np.random.randn(n)) df[df &gt; 0.9] = np.nan return df def isnull_any(df): return df.isnull().any() def isnull_values_sum(df): return df.isnull().values.sum() &gt; 0 def isnull_sum(df): return df.isnull().sum() &gt; 0 def isnull_values_any(df): return df.isnull().values.any() perfplot.save( &quot;out.png&quot;, setup=setup, kernels=[isnull_any, isnull_values_sum, isnull_sum, isnull_values_any], n_range=[2 ** k for k in range(25)], ) </code></pre> <p><code>df.isnull().sum().sum()</code> is a bit slower, but of course, has additional information -- the number of <code>NaNs</code>.</p>
{ "question_id": 29530232, "question_date": "2015-04-09T05:09:39.597Z", "question_score": 641, "tags": "python|pandas|dataframe|nan", "answer_id": 29530601, "answer_date": "2015-04-09T05:39:54.403Z", "answer_score": 769 }
Please answer the following Stack Overflow question: Title: Expand a div to fill the remaining width <p>I want a two-column div layout, where each one can have variable width e.g.</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>div { float: left; } .second { background: #ccc; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt;Tree&lt;/div&gt; &lt;div class="second"&gt;View&lt;/div&gt;</code></pre> </div> </div> </p> <p>I want the 'view' div to expand to the whole width available after 'tree' div has filled needed space.</p> <p>Currently, my 'view' div is resized to content it contains It will also be good if both divs take up the whole height.</p> <hr> <p><strong>Not duplicate disclaimer:</strong></p> <ul> <li><a href="https://stackoverflow.com/questions/1017880/expand-div-to-max-width-when-floatleft-is-set">Expand div to max width when float:left is set</a> because there the left one has a fixed width.</li> <li><a href="https://stackoverflow.com/questions/727012/help-with-div-make-div-fit-the-remaining-width">Help with div - make div fit the remaining width</a> because I need two columns both aligned to left</li> </ul>
<p>The solution to this is actually very easy, but not at <em>all</em> obvious. You have to trigger something called a &quot;block formatting context&quot; (BFC), which interacts with floats in a specific way.</p> <p>Just take that second div, remove the float, and give it <code>overflow:hidden</code> instead. Any overflow value other than visible makes the block it's set on become a BFC. BFCs don't allow descendant floats to escape them, nor do they allow sibling/ancestor floats to intrude into them. The net effect here is that the floated div will do its thing, then the second div will be an ordinary block, taking up all available width <em>except that occupied by the float</em>.</p> <p>This should work across all current browsers, though you may have to trigger hasLayout in IE6 and 7. I can't recall.</p> <p><strong>Demos:</strong></p> <ul> <li>Fixed Left: <a href="http://jsfiddle.net/A8zLY/5/" rel="noreferrer">http://jsfiddle.net/A8zLY/5/</a></li> <li>Fixed Right: <a href="http://jsfiddle.net/A8zLY/2/" rel="noreferrer">http://jsfiddle.net/A8zLY/2/</a></li> </ul> <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>div { float: left; } .second { background: #ccc; float: none; overflow: hidden; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt;Tree&lt;/div&gt; &lt;div class="second"&gt;View&lt;/div&gt;</code></pre> </div> </div> </p>
{ "question_id": 1260122, "question_date": "2009-08-11T12:46:15.763Z", "question_score": 641, "tags": "html|css|multiple-columns", "answer_id": 1767270, "answer_date": "2009-11-19T23:16:41.210Z", "answer_score": 1075 }
Please answer the following Stack Overflow question: Title: What is the difference between re.search and re.match? <p>What is the difference between the <code>search()</code> and <code>match()</code> functions in the <a href="http://docs.python.org/2/library/re.html" rel="noreferrer">Python <code>re</code> module</a>?</p> <p>I've read the <a href="http://www.python.org/doc/2.5.2/lib/matching-searching.html" rel="noreferrer">documentation</a> (<a href="http://docs.python.org/2/library/re.html?highlight=matching%20searching#search-vs-match" rel="noreferrer">current documentation</a>), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head. Or at least I'll have a better place to return with my question and it will take less time to re-learn it.</p>
<p><code>re.match</code> is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using <code>^</code> in the pattern.</p> <p>As the <a href="http://docs.python.org/2/library/re.html#re.match" rel="noreferrer">re.match documentation</a> says:</p> <blockquote> <p>If zero or more characters at the <strong>beginning of string</strong> match the regular expression pattern, return a corresponding <code>MatchObject</code> instance. Return <code>None</code> if the string does not match the pattern; note that this is different from a zero-length match.</p> <p>Note: If you want to locate a match anywhere in string, use <code>search()</code> instead.</p> </blockquote> <p><code>re.search</code> searches the entire string, as <a href="http://docs.python.org/2/library/re.html#re.search" rel="noreferrer">the documentation says</a>:</p> <blockquote> <p><strong>Scan through string</strong> looking for a location where the regular expression pattern produces a match, and return a corresponding <code>MatchObject</code> instance. Return <code>None</code> if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.</p> </blockquote> <p>So if you need to match at the beginning of the string, or to match the entire string use <code>match</code>. It is faster. Otherwise use <code>search</code>.</p> <p>The documentation has a <a href="http://docs.python.org/2/library/re.html#search-vs-match" rel="noreferrer">specific section for <code>match</code> vs. <code>search</code></a> that also covers multiline strings:</p> <blockquote> <p>Python offers two different primitive operations based on regular expressions: <code>match</code> checks for a match <strong>only at the beginning</strong> of the string, while <code>search</code> checks for a match <strong>anywhere</strong> in the string (this is what Perl does by default).</p> <p>Note that <code>match</code> may differ from <code>search</code> even when using a regular expression beginning with <code>'^'</code>: <code>'^'</code> matches only at the start of the string, or in <code>MULTILINE</code> mode also immediately following a newline. The “<code>match</code>” operation succeeds <em>only if the pattern matches at the <strong>start</strong> of the string</em> regardless of mode, or at the starting position given by the optional <code>pos</code> argument regardless of whether a newline precedes it.</p> </blockquote> <p>Now, enough talk. Time to see some example code:</p> <pre><code># example code: string_with_newlines = """something someotherthing""" import re print re.match('some', string_with_newlines) # matches print re.match('someother', string_with_newlines) # won't match print re.match('^someother', string_with_newlines, re.MULTILINE) # also won't match print re.search('someother', string_with_newlines) # finds something print re.search('^someother', string_with_newlines, re.MULTILINE) # also finds something m = re.compile('thing$', re.MULTILINE) print m.match(string_with_newlines) # no match print m.match(string_with_newlines, pos=4) # matches print m.search(string_with_newlines, re.MULTILINE) # also matches </code></pre>
{ "question_id": 180986, "question_date": "2008-10-08T00:51:36.257Z", "question_score": 641, "tags": "python|regex|search|match", "answer_id": 180993, "answer_date": "2008-10-08T00:53:12.117Z", "answer_score": 615 }
Please answer the following Stack Overflow question: Title: How can I stash only staged changes in Git? <p>Is there a way I can stash just my staged changes? The scenario I'm having issues with is when I've worked on several bugs at a given time, and have several unstaged changes. I'd like to be able to stage these files individually, create my .patch files, and stash them away until the code is approved. This way, when it's approved I can stash my entire (current) session, pop that bug and push the code.</p> <p>Am I going about this the wrong way? Am I misunderstanding how git can work in other ways to simplify my process?</p>
<p>Yes, It's possible with <strong>DOUBLE STASH</strong></p> <ol> <li>Stage all your files that you need to stash.</li> <li>Run <code>git stash --keep-index</code>. This command will create a stash with <strong>ALL</strong> of your changes (<em>staged and unstaged</em>), but will leave the staged changes in your working directory (still in state staged).</li> <li>Run <code>git stash push -m "good stash"</code></li> <li>Now your <code>"good stash"</code> has <strong>ONLY staged files</strong>. </li> </ol> <p>Now if you need unstaged files before stash, simply apply first stash (<em>the one created with <code>--keep-index</code></em>) and now you can remove files you stashed to <code>"good stash"</code>.</p> <p>Enjoy</p>
{ "question_id": 14759748, "question_date": "2013-02-07T19:50:04.273Z", "question_score": 641, "tags": "git|git-stash", "answer_id": 32951373, "answer_date": "2015-10-05T14:42:18.620Z", "answer_score": 712 }
Please answer the following Stack Overflow question: Title: Huge number of files generated for every Angular project <p>I wanted to start a simple hello world app for Angular.</p> <p>When I followed the instructions in the official <a href="https://angular.io/docs/js/latest/quickstart.html" rel="noreferrer">quickstart</a> the installation created 32,000 files in my project.</p> <p>I figured this is some mistake or I missed something, so I decided to use <a href="https://cli.angular.io/" rel="noreferrer">angular-cli</a>, but after setting up the project I counted 41,000 files.</p> <p>Where did I go wrong? Am I missing something really really obvious?</p>
<p>There is nothing wrong with your configuration.</p> <p>Angular (since version 2.0) uses npm modules and dependencies for development. That's the sole reason you are seeing such a huge number of files.</p> <p>A basic setup of Angular contains transpiler, typings dependencies which are <em>essential</em> for development purposes only.</p> <p>Once you are done with development, all you will need to do is to bundle this application.</p> <p>After bundling your application, there will be only one <code>bundle.js</code> file which you can then deploy on your server.</p> <p><strong><em>'transpiler'</strong> is just a compiler, thanks @omninonsense for adding that.</em></p>
{ "question_id": 38718690, "question_date": "2016-08-02T11:04:31.423Z", "question_score": 641, "tags": "javascript|angular", "answer_id": 38719154, "answer_date": "2016-08-02T11:26:29.767Z", "answer_score": 388 }
Please answer the following Stack Overflow question: Title: Why am I getting a NoClassDefFoundError in Java? <p>I am getting a <code>NoClassDefFoundError</code> when I run my Java application. What is typically the cause of this?</p>
<p>This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths. </p>
{ "question_id": 34413, "question_date": "2008-08-29T14:59:30.747Z", "question_score": 640, "tags": "java|noclassdeffounderror", "answer_id": 34419, "answer_date": "2008-08-29T15:01:07.607Z", "answer_score": 294 }
Please answer the following Stack Overflow question: Title: How to trigger event in JavaScript? <p>I have attached an event to a text box using <code>addEventListener</code>. It works fine. My problem arose when I wanted to trigger the event programmatically from another function. </p> <p>How can I do it?</p>
<p>Note: the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Event/initEvent" rel="noreferrer">initEvent</a> method is now deprecated. Other answers feature up-to-date and recommended practice.</p> <hr /> <p>You can use <a href="http://msdn.microsoft.com/en-us/library/ms536423%28VS.85%29.aspx" rel="noreferrer">fireEvent</a> on <strong>IE 8</strong> or lower, and W3C's <a href="https://developer.mozilla.org/en/DOM/element.dispatchEvent" rel="noreferrer">dispatchEvent</a> on <em>most</em> other browsers. To create the event you want to fire, you can use either <code>createEvent</code> or <code>createEventObject</code> depending on the browser.</p> <p>Here is a self-explanatory piece of code (from prototype) that fires an event <code>dataavailable</code> on an <code>element</code>:</p> <pre><code>var event; // The custom event that will be created if(document.createEvent){ event = document.createEvent(&quot;HTMLEvents&quot;); event.initEvent(&quot;dataavailable&quot;, true, true); event.eventName = &quot;dataavailable&quot;; element.dispatchEvent(event); } else { event = document.createEventObject(); event.eventName = &quot;dataavailable&quot;; event.eventType = &quot;dataavailable&quot;; element.fireEvent(&quot;on&quot; + event.eventType, event); } </code></pre>
{ "question_id": 2490825, "question_date": "2010-03-22T08:41:36.080Z", "question_score": 640, "tags": "javascript|events|triggers|addeventlistener|dom-events", "answer_id": 2490876, "answer_date": "2010-03-22T08:55:01.557Z", "answer_score": 505 }
Please answer the following Stack Overflow question: Title: Downloading Java JDK on Linux via wget is shown license page instead <p>When I try to download Java from Oracle I instead end up downloading a page telling me that I need agree to the OTN license terms.</p> <blockquote> <h1>Sorry!</h1> <p>In order to download products from Oracle Technology Network you must agree to the OTN license terms.</p> <p>Be sure that...</p> <ul> <li>Your browser has "cookies" and JavaScript enabled.</li> <li>You clicked on "Accept License" for the product you wish to download.</li> <li>You attempt the download within 30 minutes of accepting the license.</li> </ul> </blockquote> <p>How can I download and install Java?</p>
<p><strong>Works as of December 23rd, 2021 for JDK 17</strong></p> <pre><code>wget --no-check-certificate -c --header &quot;Cookie: oraclelicense=accept-securebackup-cookie&quot; https://download.oracle.com/java/17/archive/jdk-17.0.1_linux-x64_bin.rpm </code></pre> <p><strong>Works as of July 27th, 2021 for JDK 16</strong></p> <pre><code>wget --no-check-certificate -c --header &quot;Cookie: oraclelicense=accept-securebackup-cookie&quot; https://download.oracle.com/otn-pub/java/jdk/16.0.2%2B7/d4a915d82b4c4fbb9bde534da945d746/jdk-16.0.2_linux-x64_bin.rpm </code></pre> <p><strong>Works as of November 5th, 2020 for JDK 15</strong></p> <pre><code>wget --no-check-certificate -c --header &quot;Cookie: oraclelicense=accept-securebackup-cookie&quot; https://download.oracle.com/otn-pub/java/jdk/15.0.1+9/51f4f36ad4ef43e39d0dfdbaf6549e32/jdk-15.0.1_linux-x64_bin.rpm </code></pre> <p><strong>Works as of 07-11-2020 for JDK 14</strong></p> <pre><code>wget --no-check-certificate -c --header &quot;Cookie: oraclelicense=accept-securebackup-cookie&quot; https://download.oracle.com/otn-pub/java/jdk/14.0.1+7/664493ef4a6946b186ff29eb326336a2/jdk-14.0.1_linux-x64_bin.rpm -O ~/Downloads/jdk-14.0.1_linux-x64_bin.rpm </code></pre> <p>PS: Alf added this ( me ) :-) this, I couldn't figured out how to just commented at the end... Enjoy it.</p> <p><strong>UPDATED FOR Oracle JDK 11</strong></p> <pre><code>wget --no-check-certificate -c --header &quot;Cookie: oraclelicense=accept-securebackup-cookie&quot; http://download.oracle.com/otn-pub/java/jdk/11+28/55eed80b163941c8885ad9298e6d786a/jdk-11_linux-x64_bin.tar.gz </code></pre> <p><strong>UPDATED FOR JDK 10.0.2</strong></p> <pre><code>wget --no-check-certificate -c --header &quot;Cookie: oraclelicense=accept-securebackup-cookie&quot; http://download.oracle.com/otn-pub/java/jdk/10.0.2+13/19aef61b38124481863b1413dce1855f/jdk-10.0.2_linux-x64_bin.tar.gz </code></pre> <p><strong>UPDATED FOR JDK 10.0.1</strong></p> <pre><code>wget --no-check-certificate -c --header &quot;Cookie: oraclelicense=accept-securebackup-cookie&quot; http://download.oracle.com/otn-pub/java/jdk/10.0.1+10/fb4372174a714e6b8c52526dc134031e/jdk-10.0.1_linux-x64_bin.tar.gz </code></pre> <p><strong>UPDATED FOR JDK 9</strong> it looks like you can download it now directly from java.net without sending a header</p> <pre><code>wget http://download.java.net/java/GA/jdk9/9/binaries/jdk-9+181_linux-x64_bin.tar.gz </code></pre> <p><strong>UPDATED FOR JDK 8u191</strong></p> <p>TAR GZ:</p> <pre><code>wget --no-cookies --no-check-certificate --header &quot;Cookie: gpw_e24=http%3a%2F%2Fwww.oracle.com%2Ftechnetwork%2Fjava%2Fjavase%2Fdownloads%2Fjdk8-downloads-2133151.html; oraclelicense=accept-securebackup-cookie;&quot; &quot;https://download.oracle.com/otn-pub/java/jdk/8u191-b12/2787e4a523244c269598db4e85c51e0c/jdk-8u191-linux-x64.tar.gz&quot; </code></pre> <p>RPM:</p> <pre><code>wget --no-cookies --no-check-certificate --header &quot;Cookie: gpw_e24=http%3a%2F%2Fwww.oracle.com%2Ftechnetwork%2Fjava%2Fjavase%2Fdownloads%2Fjdk8-downloads-2133151.html; oraclelicense=accept-securebackup-cookie;&quot; &quot;https://download.oracle.com/otn-pub/java/jdk/8u191-b12/2787e4a523244c269598db4e85c51e0c/jdk-8u191-linux-x64.rpm&quot; </code></pre> <p><strong>UPDATED FOR JDK 8u131</strong></p> <p>RPM:</p> <pre><code> wget -c --header &quot;Cookie: oraclelicense=accept-securebackup-cookie&quot; http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.rpm </code></pre> <p>TAR GZ:</p> <pre><code> wget -c --header &quot;Cookie: oraclelicense=accept-securebackup-cookie&quot; http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.tar.gz </code></pre> <p>RPM using curl:</p> <pre><code> curl -v -j -k -L -H &quot;Cookie: oraclelicense=accept-securebackup-cookie&quot; http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.rpm &gt; jdk-8u112-linux-x64.rpm </code></pre> <p>In all cases above, subst 'i586' for 'x64' to download the 32-bit build.</p> <ul> <li><strong>-j</strong> -&gt; junk cookies</li> <li><strong>-k</strong> -&gt; ignore certificates</li> <li><strong>-L</strong> -&gt; follow redirects</li> <li><strong>-H [arg]</strong> -&gt; headers</li> </ul> <p><code>curl</code> can be used in place of <code>wget</code>.</p> <p><strong>UPDATE FOR JDK 7u79</strong></p> <p>TAR GZ:</p> <pre><code>wget --no-check-certificate --no-cookies --header &quot;Cookie: oraclelicense=accept-securebackup-cookie&quot; http://download.oracle.com/otn-pub/java/jdk/7u79-b15/jdk-7u79-linux-x64.tar.gz </code></pre> <p>RPM using curl:</p> <pre><code>curl -v -j -k -L -H &quot;Cookie: oraclelicense=accept-securebackup-cookie&quot; http://download.oracle.com/otn-pub/java/jdk/7u79-b15/jdk-7u79-linux-x64.rpm &gt; jdk-7u79-linux-x64.rpm </code></pre> <p>Once again, make sure you specify the correct URL for the version you are downloading. You can find the URL here: <a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html" rel="noreferrer">Oracle JDK download site</a></p> <p><strong>ORIGINAL ANSWER FROM 9th June 2012</strong></p> <p>If you are looking to download the Oracle JDK from the command line using <code>wget</code>, there is a workaround. Run the <code>wget</code> command as follows:</p> <pre><code>wget --no-cookies --header &quot;Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com&quot; &quot;http://download.oracle.com/otn-pub/java/jdk/7/jdk-7-linux-x64.tar.gz&quot; </code></pre> <p>Be sure to replace the download link with the correct one for the version you are downloading.</p>
{ "question_id": 10268583, "question_date": "2012-04-22T14:03:10.920Z", "question_score": 640, "tags": "java|linux|installation|wget", "answer_id": 10959815, "answer_date": "2012-06-09T09:21:56.930Z", "answer_score": 1717 }
Please answer the following Stack Overflow question: Title: Can I make a <button> not submit a form? <p>I've got a form, with 2 buttons</p> <pre><code>&lt;a href="index.html"&gt;&lt;button&gt;Cancel changes&lt;/button&gt;&lt;/a&gt; &lt;button type="submit"&gt;Submit&lt;/button&gt; </code></pre> <p>I use jQuery UI's button on them too, simply like this</p> <pre><code>$('button').button(); </code></pre> <p>However, the first button also submits the form. I would have thought that if it didn't have the <code>type="submit"</code>, it wouldn't.</p> <p>Obviously I could do this</p> <pre><code>$('button[type!=submit]').click(function(event) { event.stopPropagation(); }); </code></pre> <p>But is there a way I can stop that back button from submitting the form without JavaScript intervention?</p> <p>To be honest, I used a button only so I could style it with jQuery UI. I tried calling <code>button()</code> on the link and it didn't work as expected (looked quite ugly!).</p>
<p>The default value for the <a href="https://html.spec.whatwg.org/multipage/form-elements.html#attr-button-type" rel="noreferrer"><code>type</code> attribute of <code>button</code> elements</a> <em>is</em> "submit". Set it to <code>type="button"</code> to produce a button that doesn't submit the form.</p> <pre><code>&lt;button type="button"&gt;Submit&lt;/button&gt; </code></pre> <p>In the words of the <a href="https://html.spec.whatwg.org/multipage/form-elements.html#attr-button-type" rel="noreferrer">HTML Standard</a>: "Does nothing."</p>
{ "question_id": 3314989, "question_date": "2010-07-23T02:29:32.997Z", "question_score": 640, "tags": "javascript|html|jquery|jquery-ui|button", "answer_id": 3315016, "answer_date": "2010-07-23T02:36:48.097Z", "answer_score": 1414 }
Please answer the following Stack Overflow question: Title: What exactly is nullptr? <p>We now have C++11 with many new features. An interesting and confusing one (at least for me) is the new <code>nullptr</code>.</p> <p>Well, no need anymore for the nasty macro <code>NULL</code>.</p> <pre><code>int* x = nullptr; myclass* obj = nullptr; </code></pre> <p>Still, I am not getting how <code>nullptr</code> works. For example, <a href="http://en.wikipedia.org/wiki/C%2B%2B11#Null_pointer_constant" rel="noreferrer">Wikipedia article</a> says:</p> <blockquote> <p>C++11 corrects this by introducing a new <strong>keyword</strong> to serve as a distinguished null pointer constant: nullptr. It is of <strong>type nullptr_t</strong>, which is implicitly convertible and comparable to any pointer type or pointer-to-member type. It is not implicitly convertible or comparable to integral types, except for bool.</p> </blockquote> <p>How is it a keyword and an instance of a type?</p> <p>Also, do you have another example (beside the Wikipedia one) where <code>nullptr</code> is superior to good old <code>0</code>?</p>
<blockquote> <p>How is it a keyword and an instance of a type?</p> </blockquote> <p>This isn't surprising. Both <code>true</code> and <code>false</code> are keywords and as literals they have a type ( <code>bool</code> ). <code>nullptr</code> is a <em>pointer literal</em> of type <code>std::nullptr_t</code>, and it's a prvalue (you cannot take the address of it using <code>&amp;</code>). </p> <ul> <li><p><code>4.10</code> about pointer conversion says that a prvalue of type <code>std::nullptr_t</code> is a null pointer constant, and that an integral null pointer constant can be converted to <code>std::nullptr_t</code>. The opposite direction is not allowed. This allows overloading a function for both pointers and integers, and passing <code>nullptr</code> to select the pointer version. Passing <code>NULL</code> or <code>0</code> would confusingly select the <code>int</code> version. </p></li> <li><p>A cast of <code>nullptr_t</code> to an integral type needs a <code>reinterpret_cast</code>, and has the same semantics as a cast of <code>(void*)0</code> to an integral type (mapping implementation defined). A <code>reinterpret_cast</code> cannot convert <code>nullptr_t</code> to any pointer type. Rely on the implicit conversion if possible or use <code>static_cast</code>. </p></li> <li><p>The Standard requires that <code>sizeof(nullptr_t)</code> be <code>sizeof(void*)</code>. </p></li> </ul>
{ "question_id": 1282295, "question_date": "2009-08-15T16:47:32.060Z", "question_score": 640, "tags": "c++|pointers|c++11|nullptr", "answer_id": 1282345, "answer_date": "2009-08-15T17:06:52.770Z", "answer_score": 436 }
Please answer the following Stack Overflow question: Title: Escape @ character in razor view engine <p>I am creating a sample ASP.NET MVC 3 site using Razor as view engine. The razor syntax starts with <code>@</code> character e.g. <code>@RenderBody()</code>. If I write @test on my cshtml page it gives me parse error</p> <blockquote> <p>CS0103: The name 'test' does not exist in the current context</p> </blockquote> <p>How do I escape '@' character?</p>
<p><code>@@</code> should do it.</p> <p></p>
{ "question_id": 3626250, "question_date": "2010-09-02T10:35:14.080Z", "question_score": 640, "tags": "asp.net-mvc-3|razor|escaping", "answer_id": 3626870, "answer_date": "2010-09-02T12:02:21.733Z", "answer_score": 1051 }
Please answer the following Stack Overflow question: Title: Invoke-customs are only supported starting with android 0 --min-api 26 <p>before i'm use build version gradle 26 but after change buildtoolsversion to 27 like as this image</p> <p>I am using android studio 4.2.2 recently i update all my dependency and</p> <pre><code> sourceCompatibility JavaVersion.VERSION_1_10 targetCompatibility JavaVersion.VERSION_1_10 </code></pre> <p>to</p> <pre><code>compileOptions { sourceCompatibility kotlin_version targetCompatibility kotlin_version } </code></pre> <p>after update i am getting this error please help</p> <p><img src="https://i.stack.imgur.com/3U3MO.png" alt="" /></p> <p>error : error build gradle screenshot <img src="https://i.stack.imgur.com/REjox.png" alt="" /></p>
<p>After hours of struggling, I solved it by including the following within <strong>app/build.gradle</strong>:</p> <pre><code>android { compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } </code></pre> <p><a href="https://github.com/mapbox/mapbox-gl-native/issues/11378" rel="noreferrer">https://github.com/mapbox/mapbox-gl-native/issues/11378</a></p>
{ "question_id": 49891730, "question_date": "2018-04-18T05:22:08.050Z", "question_score": 640, "tags": "android|android-studio|android-gradle-plugin", "answer_id": 50198499, "answer_date": "2018-05-06T10:08:13.733Z", "answer_score": 2344 }
Please answer the following Stack Overflow question: Title: How to get a key in a JavaScript object by its value? <p>I have a quite simple JavaScript object, which I use as an associative array. Is there a simple function allowing me to get the key for a value, or do I have to iterate the object and find it out manually?</p>
<pre><code>function getKeyByValue(object, value) { return Object.keys(object).find(key =&gt; object[key] === value); } </code></pre> <p>ES6, no prototype mutations or external libraries.</p> <p>Example,</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function getKeyByValue(object, value) { return Object.keys(object).find(key =&gt; object[key] === value); } const map = {"first" : "1", "second" : "2"}; console.log(getKeyByValue(map,"2"));</code></pre> </div> </div> </p>
{ "question_id": 9907419, "question_date": "2012-03-28T12:23:57.350Z", "question_score": 639, "tags": "javascript|object", "answer_id": 28191966, "answer_date": "2015-01-28T12:11:46.290Z", "answer_score": 1015 }
Please answer the following Stack Overflow question: Title: Excel to CSV with UTF8 encoding <p>I have an Excel file that has some Spanish characters (tildes, etc.) that I need to convert to a CSV file to use as an import file. However, when I do Save As CSV it mangles the "special" Spanish characters that aren't ASCII characters. It also seems to do this with the left and right quotes and long dashes that appear to be coming from the original user creating the Excel file in Mac.</p> <p>Since CSV is just a text file I'm sure it can handle a UTF8 encoding, so I'm guessing it is an Excel limitation, but I'm looking for a way to get from Excel to CSV and keep the non-ASCII characters intact.</p>
<p>A simple workaround is to use Google Spreadsheet. Paste (values only if you have complex formulas) or import the sheet then download CSV. I just tried a few characters and it works rather well.</p> <p>NOTE: Google Sheets does have limitations when importing. See <a href="https://support.google.com/drive/answer/37603?hl=en" rel="noreferrer">here</a>.</p> <p>NOTE: Be careful of sensitive data with Google Sheets.</p> <p>EDIT: <a href="http://www.excelforum.com/excel-general/400043-csv-and-unicode-or-utf-8-problem.html" rel="noreferrer">Another alternative</a> - basically they use VB macro or addins to force the save as UTF8. I have not tried any of these solutions but they sound reasonable.</p>
{ "question_id": 4221176, "question_date": "2010-11-19T00:48:16.957Z", "question_score": 639, "tags": "excel|encoding|csv|utf-8", "answer_id": 4221256, "answer_date": "2010-11-19T01:08:33.073Z", "answer_score": 421 }
Please answer the following Stack Overflow question: Title: What is the maximum recursion depth in Python, and how to increase it? <p>I have this tail recursive function here:</p> <pre><code>def recursive_function(n, sum): if n &lt; 1: return sum else: return recursive_function(n-1, sum+n) c = 998 print(recursive_function(c, 0)) </code></pre> <p>It works up to <code>n=997</code>, then it just breaks and spits out a <code>RecursionError: maximum recursion depth exceeded in comparison</code>. Is this just a stack overflow? Is there a way to get around it?</p>
<p>It is a guard against a stack overflow, yes. Python (or rather, the CPython implementation) doesn't optimize tail recursion, and unbridled recursion causes stack overflows. You can check the recursion limit with <a href="https://docs.python.org/library/sys.html#sys.getrecursionlimit" rel="noreferrer"><code>sys.getrecursionlimit</code></a>:</p> <pre><code>import sys print(sys.getrecursionlimit()) </code></pre> <p>and change the recursion limit with <a href="https://docs.python.org/library/sys.html#sys.setrecursionlimit" rel="noreferrer"><code>sys.setrecursionlimit</code></a>:</p> <pre><code>sys.setrecursionlimit(1500) </code></pre> <p>but doing so is dangerous -- the standard limit is a little conservative, but Python stackframes can be quite big.</p> <p>Python isn't a functional language and tail recursion is not a particularly efficient technique. Rewriting the algorithm iteratively, if possible, is generally a better idea.</p>
{ "question_id": 3323001, "question_date": "2010-07-23T23:04:50.343Z", "question_score": 639, "tags": "python|recursion", "answer_id": 3323013, "answer_date": "2010-07-23T23:08:59.813Z", "answer_score": 732 }
Please answer the following Stack Overflow question: Title: How to enter in a Docker container already running with a new TTY <p>I have a container that is running the Apache service in the foreground. I would like to be able to access the container from another shell in order to "poke around" inside it and examine the files. At the moment, if I attach to the container, I am left looking at the Apache daemon and cannot run any commands.</p> <p>Is it possible to attach another tty to a running container? Possibly, I can take advantage of the fact that Docker is actually just wrapping around LXC containers? I have tried <code>sudo lxc-console -n [container-id] -t [1-4]</code> but it appears that only one tty is made available and that is the one running the apache daemon. Perhaps there is a way to enable multiple lxc consoles during the build?</p> <p>I would rather <strong>not</strong> configure and build the container with an openssh service if possible.</p>
<p>With docker 1.3, there is a new command <a href="https://docs.docker.com/engine/reference/commandline/exec/" rel="noreferrer"><code>docker exec</code></a>. This allows you to enter a running container:</p> <pre><code>docker exec -it [container-id] bash </code></pre> <p><strong>Note:</strong> this assumes <code>bash</code> is installed on your container. You may run <code>sh</code> or whatever interactive shell is installed on the container.</p>
{ "question_id": 20932357, "question_date": "2014-01-05T10:13:41.533Z", "question_score": 639, "tags": "docker|tty", "answer_id": 26496854, "answer_date": "2014-10-21T21:40:50.790Z", "answer_score": 1253 }
Please answer the following Stack Overflow question: Title: How do I use WPF bindings with RelativeSource? <p>How do I use <code>RelativeSource</code> with WPF bindings and what are the different use-cases?</p>
<p>If you want to bind to another property on the object:</p> <pre><code>{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}} </code></pre> <p>If you want to get a property on an ancestor:</p> <pre><code>{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}} </code></pre> <p>If you want to get a property on the templated parent (so you can do 2 way bindings in a ControlTemplate)</p> <pre><code>{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}} </code></pre> <p>or, shorter (this only works for OneWay bindings):</p> <pre><code>{TemplateBinding Path=PathToProperty} </code></pre>
{ "question_id": 84278, "question_date": "2008-09-17T15:10:53.583Z", "question_score": 639, "tags": ".net|wpf|xaml|data-binding|relativesource", "answer_id": 84317, "answer_date": "2008-09-17T15:14:51.687Z", "answer_score": 845 }
Please answer the following Stack Overflow question: Title: How to convert a nested Python dict to object? <p>I'm searching for an elegant way to get data using attribute access on a dict with some nested dicts and lists (i.e. javascript-style object syntax).</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an object style for dicts?</p>
<p><strong>Update:</strong> In Python 2.6 and onwards, consider whether the <a href="https://docs.python.org/2/library/collections.html#collections.namedtuple" rel="noreferrer"><code>namedtuple</code></a> data structure suits your needs:</p> <pre><code>&gt;&gt;&gt; from collections import namedtuple &gt;&gt;&gt; MyStruct = namedtuple('MyStruct', 'a b d') &gt;&gt;&gt; s = MyStruct(a=1, b={'c': 2}, d=['hi']) &gt;&gt;&gt; s MyStruct(a=1, b={'c': 2}, d=['hi']) &gt;&gt;&gt; s.a 1 &gt;&gt;&gt; s.b {'c': 2} &gt;&gt;&gt; s.c Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'MyStruct' object has no attribute 'c' &gt;&gt;&gt; s.d ['hi'] </code></pre> <p>The alternative (original answer contents) is:</p> <pre><code>class Struct: def __init__(self, **entries): self.__dict__.update(entries) </code></pre> <p>Then, you can use:</p> <pre><code>&gt;&gt;&gt; args = {'a': 1, 'b': 2} &gt;&gt;&gt; s = Struct(**args) &gt;&gt;&gt; s &lt;__main__.Struct instance at 0x01D6A738&gt; &gt;&gt;&gt; s.a 1 &gt;&gt;&gt; s.b 2 </code></pre>
{ "question_id": 1305532, "question_date": "2009-08-20T11:28:18.110Z", "question_score": 639, "tags": "python|object|dictionary", "answer_id": 1305663, "answer_date": "2009-08-20T11:55:39.897Z", "answer_score": 725 }
Please answer the following Stack Overflow question: Title: What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)? <p>I have a Map which is to be modified by several threads concurrently. </p> <p>There seem to be three different synchronized Map implementations in the Java API:</p> <ul> <li><code>Hashtable</code></li> <li><code>Collections.synchronizedMap(Map)</code></li> <li><code>ConcurrentHashMap</code></li> </ul> <p>From what I understand, <code>Hashtable</code> is an old implementation (extending the obsolete <code>Dictionary</code> class), which has been adapted later to fit the <code>Map</code> interface. While it <em>is</em> synchronized, it seems to have serious <a href="http://www.ibm.com/developerworks/java/library/j-jtp07233.html" rel="noreferrer">scalability issues</a> and is discouraged for new projects.</p> <p>But what about the other two? What are the differences between Maps returned by <code>Collections.synchronizedMap(Map)</code> and <code>ConcurrentHashMap</code>s? Which one fits which situation?</p>
<p>For your needs, use <code>ConcurrentHashMap</code>. It allows concurrent modification of the Map from several threads without the need to block them. <code>Collections.synchronizedMap(map)</code> creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly).</p> <p>Use the second option if you need to ensure data consistency, and each thread needs to have an up-to-date view of the map. Use the first if performance is critical, and each thread only inserts data to the map, with reads happening less frequently.</p>
{ "question_id": 510632, "question_date": "2009-02-04T09:22:46.747Z", "question_score": 639, "tags": "java|dictionary|concurrency", "answer_id": 510654, "answer_date": "2009-02-04T09:32:57.333Z", "answer_score": 443 }
Please answer the following Stack Overflow question: Title: The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe <p>R provides two different methods for accessing the elements of a list or data.frame: <code>[]</code> and <code>[[]]</code>.</p> <p>What is the difference between the two, and when should I use one over the other?</p>
<p>The R Language Definition is handy for answering these types of questions:</p> <ul> <li><a href="http://cran.r-project.org/doc/manuals/R-lang.html#Indexing" rel="noreferrer">http://cran.r-project.org/doc/manuals/R-lang.html#Indexing</a></li> </ul> <blockquote> <p> R has three basic indexing operators, with syntax displayed by the following examples <p> <code><pre> x[i] x[i, j] x[[i]] x[[i, j]] x$a x$"a" </pre></code> <p> For vectors and matrices the <code>[[</code> forms are rarely used, although they have some slight semantic differences from the <code>[</code> form (e.g. it drops any names or dimnames attribute, and that partial matching is used for character indices). When indexing multi-dimensional structures with a single index, <code>x[[i]]</code> or <code>x[i]</code> will return the <code>i</code>th sequential element of <code>x</code>. <p> For lists, one generally uses <code>[[</code> to select any single element, whereas <code>[</code> returns a list of the selected elements. <p> The <code>[[</code> form allows only a single element to be selected using integer or character indices, whereas <code>[</code> allows indexing by vectors. Note though that for a list, the index can be a vector and each element of the vector is applied in turn to the list, the selected component, the selected component of that component, and so on. The result is still a single element. </blockquote>
{ "question_id": 1169456, "question_date": "2009-07-23T03:33:18.410Z", "question_score": 639, "tags": "r|list|dataframe|extract|r-faq", "answer_id": 1169495, "answer_date": "2009-07-23T03:46:55.247Z", "answer_score": 392 }
Please answer the following Stack Overflow question: Title: Clearing coverage highlighting in Eclipse <p>After running coverage reports in Eclipse (using cobertura or an EMMA plugin), my source code files get highlighted in green, red and yellow depending on which lines of code were covered by tests.</p> <p>How can I clear this highlighting after I'm done?</p>
<p>Click the "Remove all Sessions" button in the toolbar of the "Coverage" view.</p> <p><img src="https://i.stack.imgur.com/Bi0SO.png" alt="enter image description here"></p>
{ "question_id": 6112561, "question_date": "2011-05-24T15:03:24.003Z", "question_score": 639, "tags": "java|eclipse|code-coverage|cobertura|emma", "answer_id": 6121432, "answer_date": "2011-05-25T08:12:28.857Z", "answer_score": 1090 }
Please answer the following Stack Overflow question: Title: What is the difference between require() and library()? <p>What is the difference between <code>require()</code> and <code>library()</code>?</p>
<p>In addition to the good advice already given, I would add this:</p> <p>It is probably best to avoid using <code>require()</code> <em>unless</em> you actually will be using the value it returns e.g in some error checking loop such as given by thierry.</p> <p>In most other cases it is better to use <code>library()</code>, because this will give an error message at package loading time if the package is not available. <code>require()</code> will just fail without an error if the package is not there. This is the best time to find out if the package needs to be installed (or perhaps doesn't even exist because it it spelled wrong). Getting error feedback early and at the relevant time will avoid possible headaches with tracking down why later code fails when it attempts to use library routines</p>
{ "question_id": 5595512, "question_date": "2011-04-08T13:09:14.127Z", "question_score": 639, "tags": "r|package|r-faq", "answer_id": 28422554, "answer_date": "2015-02-10T01:24:54.410Z", "answer_score": 133 }
Please answer the following Stack Overflow question: Title: Insert text with single quotes in PostgreSQL <p>I have a table <code>test(id,name)</code>.</p> <p>I need to insert values like: <code>user's log</code>, <code>'my user'</code>, <code>customer's</code>.</p> <pre><code> insert into test values (1,'user's log'); insert into test values (2,''my users''); insert into test values (3,'customer's'); </code></pre> <p>I am getting an error if I run any of the above statements.</p> <p>If there is any method to do this correctly please share. I don't want any prepared statements.</p> <p>Is it possible using sql escaping mechanism?</p>
<h3>String literals</h3> <p>Escaping single quotes <code>'</code> by doubling them up → <code>''</code> is the standard way and works of course:</p> <pre class="lang-none prettyprint-override"><code><strike>'user's log'</strike> -- incorrect syntax (unbalanced quote) 'user''s log'</code></pre> <p>Plain single quotes (ASCII / UTF-8 code 39), mind you, not backticks <code>`</code>, which have no special purpose in Postgres (unlike certain other RDBMS) and not double-quotes <code>&quot;</code>, used for identifiers.</p> <p>In old versions or if you still run with <a href="https://www.postgresql.org/docs/current/runtime-config-compatible.html#GUC-STANDARD-CONFORMING-STRINGS" rel="noreferrer"><code>standard_conforming_strings = off</code></a> or, generally, if you prepend your string with <code>E</code> to declare <em>Posix escape string syntax</em>, you can also escape with the backslash <code>\</code>:</p> <pre class="lang-none prettyprint-override"><code>E'user\'s log' </code></pre> <p>Backslash itself is escaped with another backslash. But that's generally not preferable.<br /> If you have to deal with many single quotes or multiple layers of escaping, you can avoid quoting hell in PostgreSQL with <a href="http://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING" rel="noreferrer"><strong>dollar-quoted strings</strong></a>:</p> <pre class="lang-none prettyprint-override"><code>'escape '' with ''''' $$escape ' with ''$$ </code></pre> <p>To further avoid confusion among dollar-quotes, add a unique <em>token</em> to each pair:</p> <pre class="lang-none prettyprint-override"><code>$token$escape ' with ''$token$ </code></pre> <p>Which can be nested any number of levels:</p> <pre class="lang-none prettyprint-override"><code>$token2$Inner string: $token1$escape ' with ''$token1$ is nested$token2$ </code></pre> <p>Pay attention if the <code>$</code> character should have special meaning in your client software. You may have to escape it in addition. This is not the case with standard PostgreSQL clients like psql or pgAdmin.</p> <p>That is all very useful for writing plpgsql functions or ad-hoc SQL commands. It cannot alleviate the need to use prepared statements or some other method to safeguard against SQL injection in your application when user input is possible, though. <a href="https://stackoverflow.com/a/12317363/939860/49718#49718">@Craig's answer</a> has more on that. More details:</p> <ul> <li><a href="https://dba.stackexchange.com/q/49699/3684">SQL injection in Postgres functions vs prepared queries</a></li> </ul> <h3>Values inside Postgres</h3> <p>When dealing with values inside the database, there are a couple of useful functions to quote strings properly:</p> <ul> <li><a href="https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-OTHER" rel="noreferrer"><code>quote_literal()</code> or <code>quote_nullable()</code></a> - the latter outputs the string <code>NULL</code> for null input.<br /> There is also <a href="https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-OTHER" rel="noreferrer"><code>quote_ident()</code></a> to <em>double-quote</em> strings where needed to get valid SQL <em>identifiers</em>.</li> <li><a href="https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-FORMAT" rel="noreferrer"><code>format()</code></a> with the format specifier <code>%L</code> is equivalent to <code>quote_nullable()</code>.<br /> Like: <code>format('%L', string_var)</code></li> <li><a href="https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-FORMAT" rel="noreferrer"><strike><code>concat()</code></strike> or <strike><code>concat_ws()</code></strike></a> are typically no good for this purpose as those do <em>not</em> escape nested single quotes and backslashes.</li> </ul>
{ "question_id": 12316953, "question_date": "2012-09-07T11:11:11.530Z", "question_score": 638, "tags": "sql|postgresql|quotes|string-literals", "answer_id": 12320729, "answer_date": "2012-09-07T15:06:16.447Z", "answer_score": 1098 }
Please answer the following Stack Overflow question: Title: Find first element by predicate <p>I've just started playing with Java 8 lambdas and I'm trying to implement some of the things that I'm used to in functional languages.</p> <p>For example, most functional languages have some kind of find function that operates on sequences, or lists that returns the first element, for which the predicate is <code>true</code>. The only way I can see to achieve this in Java 8 is:</p> <pre><code>lst.stream() .filter(x -&gt; x &gt; 5) .findFirst() </code></pre> <p>However this seems inefficient to me, as the filter will scan the whole list, at least to my understanding (which could be wrong). Is there a better way? </p>
<p>No, filter does not scan the whole stream. It's an intermediate operation, which returns a lazy stream (actually all intermediate operations return a lazy stream). To convince you, you can simply do the following test:</p> <pre><code>List&lt;Integer&gt; list = Arrays.asList(1, 10, 3, 7, 5); int a = list.stream() .peek(num -&gt; System.out.println("will filter " + num)) .filter(x -&gt; x &gt; 5) .findFirst() .get(); System.out.println(a); </code></pre> <p>Which outputs:</p> <pre><code>will filter 1 will filter 10 10 </code></pre> <p>You see that only the two first elements of the stream are actually processed.</p> <p>So you can go with your approach which is perfectly fine.</p>
{ "question_id": 23696317, "question_date": "2014-05-16T13:28:19.830Z", "question_score": 638, "tags": "java|java-8|java-stream", "answer_id": 23696571, "answer_date": "2014-05-16T13:37:48.277Z", "answer_score": 864 }
Please answer the following Stack Overflow question: Title: How to unload a package without restarting R <p>I'd like to unload a package without having to restart R (mostly because restarting R as I try out different, conflicting packages is getting frustrating, but conceivably this could be used in a program to use one function and then another--although namespace referencing is probably a better idea for that use).</p> <p><code>?library</code> doesn't show any options that would unload a package.</p> <p>There is a <a href="https://stackoverflow.com/questions/3536036/rmlist-ls-doesnt-completely-clear-the-workspace/3537342#3537342">suggestion</a> that <code>detach</code> can unload package, but the following both fail:</p> <pre><code>detach(vegan) </code></pre> <blockquote> <p>Error in <code>detach(vegan)</code> : invalid <code>name</code> argument</p> </blockquote> <pre><code>detach("vegan") </code></pre> <blockquote> <p>Error in <code>detach("vegan")</code> : invalid <code>name</code> argument</p> </blockquote> <p>So how do I unload a package?</p>
<p>Try this (see <code>?detach</code> for more details):</p> <pre><code>detach("package:vegan", unload=TRUE) </code></pre> <hr> <p>It is possible to have multiple versions of a package loaded at once (for example, if you have a development version and a stable version in different libraries). To guarantee that all copies are detached, use this function.</p> <pre><code>detach_package &lt;- function(pkg, character.only = FALSE) { if(!character.only) { pkg &lt;- deparse(substitute(pkg)) } search_item &lt;- paste("package", pkg, sep = ":") while(search_item %in% search()) { detach(search_item, unload = TRUE, character.only = TRUE) } } </code></pre> <p>Usage is, for example</p> <pre><code>detach_package(vegan) </code></pre> <p>or</p> <pre><code>detach_package("vegan", TRUE) </code></pre>
{ "question_id": 6979917, "question_date": "2011-08-08T09:12:44.640Z", "question_score": 638, "tags": "r|package|r-faq", "answer_id": 6979989, "answer_date": "2011-08-08T09:19:07.893Z", "answer_score": 791 }
Please answer the following Stack Overflow question: Title: Sort a list by multiple attributes? <p>I have a list of lists:</p> <pre><code>[[12, 'tall', 'blue', 1], [2, 'short', 'red', 9], [4, 'tall', 'blue', 13]] </code></pre> <p>If I wanted to sort by one element, say the tall/short element, I could do it via <code>s = sorted(s, key = itemgetter(1))</code>.</p> <p>If I wanted to sort by <em>both</em> tall/short and colour, I could do the sort twice, once for each element, but is there a quicker way?</p>
<p>A key can be a function that returns a tuple:</p> <pre><code>s = sorted(s, key = lambda x: (x[1], x[2])) </code></pre> <p>Or you can achieve the same using <code>itemgetter</code> (which is faster and avoids a Python function call):</p> <pre><code>import operator s = sorted(s, key = operator.itemgetter(1, 2)) </code></pre> <p>And notice that here you can use <code>sort</code> instead of using <code>sorted</code> and then reassigning:</p> <pre><code>s.sort(key = operator.itemgetter(1, 2)) </code></pre>
{ "question_id": 4233476, "question_date": "2010-11-20T15:30:53.960Z", "question_score": 638, "tags": "python|sorting", "answer_id": 4233482, "answer_date": "2010-11-20T15:32:01.487Z", "answer_score": 1095 }
Please answer the following Stack Overflow question: Title: What are the pros and cons of the SVN plugins for Eclipse, Subclipse and Subversive? <p>SVN in Eclipse is spread into two camps. The SVN people have developed a plugin called <a href="http://subclipse.tigris.org/" rel="noreferrer">Subclipse</a>. The Eclipse people have a plugin called <a href="http://www.eclipse.org/subversive/" rel="noreferrer">Subversive</a>. Broadly speaking they both do the same things. What are the advantages and disadvantages of each?</p>
<p>Both are very similar but Subversive is the "eclipse svn provider". I primarily use Subversive because of a few convenient features:</p> <p><strong>Grouping of history</strong></p> <p>When I'm browsing the history of a branch instead of just seeing a bunch of rows for every commit it can group commits by today, week, etc.</p> <p><strong>Mapping of trunk, branches, and tags</strong></p> <p>Subversive assumes the default svn layout: trunk, branches, tags (which you can change), so whenever you want to tag or branch it is one click and you provide the name of the tag or branch.</p> <p>Like I said these are minor differences that I just find convenient. Both work great with mylyn, but overall there really isn't a whole lot of differences with these two extensions.</p> <p>Merging with Subversive is a pain though (haven't tried Subclipse), I've never been able to successfully merge. The preview of the merge is great but it would never complete the merge or it will take way to long. Most of the time I complete merging through the command line without any issues.</p>
{ "question_id": 61320, "question_date": "2008-09-14T13:14:58.083Z", "question_score": 638, "tags": "svn|eclipse|subclipse|subversive", "answer_id": 61618, "answer_date": "2008-09-14T20:34:46.043Z", "answer_score": 177 }
Please answer the following Stack Overflow question: Title: How do I prevent Conda from activating the base environment by default? <p>I recently installed anaconda2 on my Mac. By default Conda is configured to activate the base environment when I open a fresh terminal session.</p> <p>I want access to the Conda commands (i.e. I want the path to Conda added to my <code>$PATH</code> which Conda does when initialised so that's fine).</p> <p>However I don't ordinarily program in python, and I don't want Conda to activate the base environment by default.</p> <p>When first executing <code>conda init</code> from the prompt, Conda adds the following to my <code>.bash_profile</code>:</p> <pre><code># &gt;&gt;&gt; conda initialize &gt;&gt;&gt; # !! Contents within this block are managed by 'conda init' !! __conda_setup=&quot;$('/Users/geoff/anaconda2/bin/conda' 'shell.bash' 'hook' 2&gt; /dev/null)&quot; if [ $? -eq 0 ]; then eval &quot;$__conda_setup&quot; else if [ -f &quot;/Users/geoff/anaconda2/etc/profile.d/conda.sh&quot; ]; then . &quot;/Users/geoff/anaconda2/etc/profile.d/conda.sh&quot; else export PATH=&quot;/Users/geoff/anaconda2/bin:$PATH&quot; fi # fi unset __conda_setup # &lt;&lt;&lt; conda initialize &lt;&lt;&lt; </code></pre> <p>If I comment out the whole block, then I can't activate any Conda environments.</p> <p>I tried to comment out the whole block except for</p> <pre><code>export PATH=&quot;/Users/geoff/anaconda2/bin:$PATH&quot; </code></pre> <p>But then when I started a new session and tried to activate an environment, I got this error message:</p> <pre><code>CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'. </code></pre> <p><a href="https://askubuntu.com/questions/849470/how-do-i-activate-a-conda-environment-in-my-bashrc">This question</a> (and others like it) are helpful, but doesn't ultimately answer my question and is more suited for linux users.</p> <p>To be clear, I'm not asking to remove the <code>(base)</code> from my <code>$PS1</code> I'm asking for Conda not to activate base when I open a terminal session.</p>
<p>I have conda 4.6 with a similar block of code that was added by conda. In my case, there's a conda configuration setting to disable the automatic base activation:</p> <pre><code>conda config --set auto_activate_base false </code></pre> <p>The first time you run it, it'll create a <code>.condarc</code> in your home directory with that setting to override the default.</p> <p>This wouldn't de-clutter your <code>.bash_profile</code> but it's a cleaner solution without manual editing that section that conda manages.</p>
{ "question_id": 54429210, "question_date": "2019-01-29T20:37:00.837Z", "question_score": 638, "tags": "bash|conda", "answer_id": 54560785, "answer_date": "2019-02-06T19:01:25.507Z", "answer_score": 1290 }
Please answer the following Stack Overflow question: Title: iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta <p>This crash has been a blocking issue I used the following steps to reproduce the issue:</p> <ul> <li>Create a Cocoa Touch Framework project</li> <li>Add a swift file and a class <em>Dog</em></li> <li>Build a framework for device</li> <li>Create a Single View application in Swift</li> <li>Import framework into app project</li> <li>Instantiate swift class from the framework in ViewController</li> <li>Build and run an app on the device</li> </ul> <p>The app immediate crashed upon launching, here is console log:</p> <pre><code>dyld: Library not loaded: @rpath/FrameworkTest03.framework/FrameworkTest03 Referenced from: /var/mobile/Applications/FA6BAAC8-1AAD-49B4-8326-F30F66458CB6/FrameworkTest03App.app/FrameworkTest03App Reason: image not found </code></pre> <p>I have tried to build on iOS 7.1 and 8.0 devices, they both have the same crash. However, I can build an app and run on the simulator fine. Also, I am aware that I can change the framework to form <em>Required</em> to <em>Optional</em> in <em>Link Binary With Libraries</em>, but it did not completely resolve the problem, the app crashed when I create an instance of <em>Dog</em>. The behavior is different on the device and simulator, I suspect that we can't distribute a framework for the device using a beta version of Xcode. Can anyone shed light on this?</p>
<p>In the target's <strong>General</strong> tab, there is an <strong>Embedded Binaries</strong> field. When you add the framework there the crash is resolved.</p> <p>Reference is <a href="https://devforums.apple.com/message/991384#991384" rel="noreferrer">here</a> on Apple Developer Forums.</p>
{ "question_id": 24333981, "question_date": "2014-06-20T19:00:40.390Z", "question_score": 638, "tags": "ios|swift|crash|frameworks|dyld", "answer_id": 24345546, "answer_date": "2014-06-21T20:20:48.707Z", "answer_score": 1038 }
Please answer the following Stack Overflow question: Title: How to debug in Django, the good way? <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="noreferrer">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="noreferrer">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p> <p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p> <p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
<p>There are a bunch of ways to do it, but the most straightforward is to simply use the <a href="https://docs.python.org/2/library/pdb.html" rel="noreferrer">Python debugger</a>. Just add following line in to a Django view function:</p> <pre><code>import pdb; pdb.set_trace() </code></pre> <p>or </p> <pre><code>breakpoint() #from Python3.7 </code></pre> <p>If you try to load that page in your browser, the browser will hang and you get a prompt to carry on debugging on actual executing code.</p> <p>However there are other options (I am not recommending them):</p> <pre><code>* return HttpResponse({variable to inspect}) * print {variable to inspect} * raise Exception({variable to inspect}) </code></pre> <p>But the Python Debugger (pdb) is highly recommended for all types of Python code. If you are already into pdb, you'd also want to have a look at <a href="http://pypi.python.org/pypi/ipdb/" rel="noreferrer"><strong>IPDB</strong></a> that uses <a href="http://ipython.org/" rel="noreferrer"><strong>ipython</strong></a> for debugging.</p> <p>Some more useful extension to pdb are</p> <p><a href="https://pypi.python.org/pypi/pdbpp/" rel="noreferrer"><strong>pdb++</strong></a>, suggested by <a href="https://stackoverflow.com/users/5792269/antash">Antash</a>.</p> <p><a href="https://pypi.python.org/pypi/pudb" rel="noreferrer"><strong>pudb</strong></a>, suggested by <a href="https://stackoverflow.com/users/5081188/patdujour">PatDuJour</a>.</p> <p><a href="https://mike.tig.as/blog/2010/09/14/pdb/" rel="noreferrer"><strong>Using the Python debugger in Django</strong></a>, suggested by <a href="https://stackoverflow.com/users/884640/seafangs">Seafangs</a>.</p>
{ "question_id": 1118183, "question_date": "2009-07-13T07:57:02.647Z", "question_score": 638, "tags": "python|django|debugging", "answer_id": 1118271, "answer_date": "2009-07-13T08:29:24.047Z", "answer_score": 591 }
Please answer the following Stack Overflow question: Title: How to match all occurrences of a regex <p>Is there a quick way to find every match of a regular expression in Ruby? I've looked through the Regex object in the Ruby STL and searched on Google to no avail.</p>
<p>Using <a href="http://ruby-doc.org/core-1.9.3/String.html#method-i-scan" rel="noreferrer"><code>scan</code></a> should do the trick:</p> <pre><code>string.scan(/regex/) </code></pre>
{ "question_id": 80357, "question_date": "2008-09-17T05:46:26.047Z", "question_score": 638, "tags": "ruby|regex", "answer_id": 80387, "answer_date": "2008-09-17T05:53:10.990Z", "answer_score": 882 }
Please answer the following Stack Overflow question: Title: What does int argc, char *argv[] mean? <p>In many C++ IDE's and compilers, when it generates the main function for you, it looks like this:</p> <pre><code>int main(int argc, char *argv[]) </code></pre> <p>When I code C++ without an IDE, just with a command line compiler, I type:</p> <pre><code>int main() </code></pre> <p>without any parameters. What does this mean, and is it vital to my program?</p>
<p><code>argv</code> and <code>argc</code> are how command line arguments are passed to <code>main()</code> in C and C++.</p> <p><code>argc</code> will be the number of strings pointed to by <code>argv</code>. This will (in practice) be 1 plus the number of arguments, as virtually all implementations will prepend the name of the program to the array.</p> <p>The variables are named <code>argc</code> (<em>argument count</em>) and <code>argv</code> (<em>argument vector</em>) by convention, but they can be given any valid identifier: <code>int main(int num_args, char** arg_strings)</code> is equally valid.</p> <p>They can also be omitted entirely, yielding <code>int main()</code>, if you do not intend to process command line arguments.</p> <p>Try the following program:</p> <pre><code>#include &lt;iostream&gt; int main(int argc, char** argv) { std::cout &lt;&lt; "Have " &lt;&lt; argc &lt;&lt; " arguments:" &lt;&lt; std::endl; for (int i = 0; i &lt; argc; ++i) { std::cout &lt;&lt; argv[i] &lt;&lt; std::endl; } } </code></pre> <p>Running it with <code>./test a1 b2 c3</code> will output</p> <pre class="lang-none prettyprint-override"><code>Have 4 arguments: ./test a1 b2 c3 </code></pre>
{ "question_id": 3024197, "question_date": "2010-06-11T15:45:43.077Z", "question_score": 637, "tags": "c++|parameters|command-line-arguments|argv|argc", "answer_id": 3024202, "answer_date": "2010-06-11T15:47:14.157Z", "answer_score": 804 }
Please answer the following Stack Overflow question: Title: How do I use raw_input in Python 3? <p>In Python 2:</p> <pre><code>raw_input() </code></pre> <p>In Python 3, I get an error:</p> <blockquote> <p>NameError: name 'raw_input' is not defined</p> </blockquote>
<p>Starting with Python 3, <code>raw_input()</code> was renamed to <code>input()</code>.</p> <p>From <a href="https://docs.python.org/3/whatsnew/3.0.html#builtins" rel="noreferrer">What’s New In Python 3.0, Builtins section</a> second item.</p>
{ "question_id": 954834, "question_date": "2009-06-05T08:32:23.193Z", "question_score": 637, "tags": "python|python-3.x", "answer_id": 954840, "answer_date": "2009-06-05T08:35:38.023Z", "answer_score": 1146 }
Please answer the following Stack Overflow question: Title: Return JSON response from Flask view <p>I have a function that analyzes a CSV file with Pandas and produces a dict with summary information. I want to return the results as a response from a Flask view. How do I return a JSON response?</p> <pre><code>@app.route("/summary") def summary(): d = make_summary() # send it back as json </code></pre>
<p>As of Flask 1.1.0 a view can directly return a Python dict and Flask will call <a href="https://flask.palletsprojects.com/api/#flask.json.jsonify" rel="noreferrer"><code>jsonify</code></a> automatically.</p> <pre class="lang-py prettyprint-override"><code>@app.route(&quot;/summary&quot;) def summary(): d = make_summary() return d </code></pre> <p>If your Flask version is less than 1.1.0 or to return a different JSON-serializable object, import and use <a href="https://flask.palletsprojects.com/api/#flask.json.jsonify" rel="noreferrer"><code>jsonify</code></a>.</p> <pre class="lang-py prettyprint-override"><code>from flask import jsonify @app.route(&quot;/summary&quot;) def summary(): d = make_summary() return jsonify(d) </code></pre>
{ "question_id": 13081532, "question_date": "2012-10-26T05:56:47.250Z", "question_score": 637, "tags": "python|json|flask", "answer_id": 13089975, "answer_date": "2012-10-26T15:33:57.280Z", "answer_score": 968 }
Please answer the following Stack Overflow question: Title: What's the name for hyphen-separated case? <p>This is PascalCase: <code>SomeSymbol</code></p> <p>This is camelCase: <code>someSymbol</code></p> <p>This is snake_case: <code>some_symbol</code></p> <p>So my questions is whether there is a widely accepted name for this: <code>some-symbol</code>? It's commonly used in url's.</p>
<p>There isn't really a standard name for this case convention, and there is disagreement over what it should be called.</p> <p>That said, as of 2019, there is a strong case to be made that <em>kebab-case</em> is winning:</p> <p><a href="https://trends.google.com/trends/explore?date=all&amp;q=kebab-case,spinal-case,lisp-case,dash-case,caterpillar-case" rel="noreferrer">https://trends.google.com/trends/explore?date=all&amp;q=kebab-case,spinal-case,lisp-case,dash-case,caterpillar-case</a></p> <p><em>spinal-case</em> is a distant second, and no other terms have any traction at all.</p> <p>Additionally, <em>kebab-case</em> has entered the lexicon of several javascript code libraries, e.g.:</p> <ul> <li><a href="https://lodash.com/docs/#kebabCase" rel="noreferrer">https://lodash.com/docs/#kebabCase</a></li> <li><a href="https://www.npmjs.com/package/kebab-case" rel="noreferrer">https://www.npmjs.com/package/kebab-case</a></li> <li><a href="https://v2.vuejs.org/v2/guide/components-props.html#Prop-Casing-camelCase-vs-kebab-case" rel="noreferrer">https://v2.vuejs.org/v2/guide/components-props.html#Prop-Casing-camelCase-vs-kebab-case</a></li> </ul> <p>However, there are still other terms that people use. Lisp has used this convention for decades as described in <a href="http://en.wikipedia.org/wiki/Naming_convention_(programming)#Lisp" rel="noreferrer">this Wikipedia entry</a>, so some people have described it as <em>lisp-case</em>. Some other forms I've seen include <em>caterpillar-case</em>, <em>dash-case</em>, and <em>hyphen-case</em>, but none of these is standard.</p> <p>So the answer to your question is: No, there isn't a single widely-accepted name for this case convention analogous to <em>snake_case</em> or <em>camelCase</em>, which are widely-accepted.</p>
{ "question_id": 11273282, "question_date": "2012-06-30T10:13:48.163Z", "question_score": 637, "tags": "programming-languages|naming-conventions|terminology|kebab-case", "answer_id": 17820138, "answer_date": "2013-07-23T20:12:23.590Z", "answer_score": 537 }
Please answer the following Stack Overflow question: Title: How, in general, does Node.js handle 10,000 concurrent requests? <p>I understand that Node.js uses a single-thread and an event loop to process requests only processing one at a time (which is non-blocking). But still, how does that work, lets say 10,000 concurrent requests. The event loop will process all the requests? Would not that take too long?</p> <p>I can not understand (yet) how it can be faster than a multi-threaded web server. I understand that multi-threaded web server will be more expensive in resources (memory, CPU), but would not it still be faster? I am probably wrong; please explain how this single-thread is faster in lots of requests, and what it typically does (in high level) when servicing lots of requests like 10,000.</p> <p>And also, will that single-thread scale well with that large amount? Please bear in mind that I am just starting to learn Node.js.</p>
<p>If you have to ask this question then you're probably unfamiliar with what most web applications/services do. You're probably thinking that all software do this:</p> <pre><code>user do an action │ v application start processing action └──&gt; loop ... └──&gt; busy processing end loop └──&gt; send result to user </code></pre> <p>However, this is not how web applications, or indeed any application with a database as the back-end, work. Web apps do this:</p> <pre><code>user do an action │ v application start processing action └──&gt; make database request └──&gt; do nothing until request completes request complete └──&gt; send result to user </code></pre> <p>In this scenario, the software spend most of its running time using 0% CPU time waiting for the database to return.</p> <h2>Multithreaded network app:</h2> <p>Multithreaded network apps handle the above workload like this:</p> <pre><code>request ──&gt; spawn thread └──&gt; wait for database request └──&gt; answer request request ──&gt; spawn thread └──&gt; wait for database request └──&gt; answer request request ──&gt; spawn thread └──&gt; wait for database request └──&gt; answer request </code></pre> <p>So the thread spend most of their time using 0% CPU waiting for the database to return data. While doing so they have had to allocate the memory required for a thread which includes a completely separate program stack for each thread etc. Also, they would have to start a thread which while is not as expensive as starting a full process is still not exactly cheap.</p> <h2>Singlethreaded event loop</h2> <p>Since we spend most of our time using 0% CPU, why not run some code when we're not using CPU? That way, each request will still get the same amount of CPU time as multithreaded applications but we don't need to start a thread. So we do this:</p> <pre><code>request ──&gt; make database request request ──&gt; make database request request ──&gt; make database request database request complete ──&gt; send response database request complete ──&gt; send response database request complete ──&gt; send response </code></pre> <p>In practice both approaches return data with roughly the same latency since it's the database response time that dominates the processing.</p> <p>The main advantage here is that we don't need to spawn a new thread so we don't need to do lots and lots of malloc which would slow us down.</p> <h2>Magic, invisible threading</h2> <p>The seemingly mysterious thing is how both the approaches above manage to run workload in "parallel"? The answer is that the database is threaded. So our single-threaded app is actually leveraging the multi-threaded behaviour of another process: the database.</p> <h2>Where singlethreaded approach fails</h2> <p>A singlethreaded app fails big if you need to do lots of CPU calculations before returning the data. Now, I don't mean a for loop processing the database result. That's still mostly O(n). What I mean is things like doing Fourier transform (mp3 encoding for example), ray tracing (3D rendering) etc.</p> <p>Another pitfall of singlethreaded apps is that it will only utilise a single CPU core. So if you have a quad-core server (not uncommon nowdays) you're not using the other 3 cores.</p> <h2>Where multithreaded approach fails</h2> <p>A multithreaded app fails big if you need to allocate lots of RAM per thread. First, the RAM usage itself means you can't handle as many requests as a singlethreaded app. Worse, malloc is slow. Allocating lots and lots of objects (which is common for modern web frameworks) means we can potentially end up being slower than singlethreaded apps. This is where node.js usually win.</p> <p>One use-case that end up making multithreaded worse is when you need to run another scripting language in your thread. First you usually need to malloc the entire runtime for that language, then you need to malloc the variables used by your script.</p> <p>So if you're writing network apps in C or go or java then the overhead of threading will usually not be too bad. If you're writing a C web server to serve PHP or Ruby then it's very easy to write a faster server in javascript or Ruby or Python.</p> <h2>Hybrid approach</h2> <p>Some web servers use a hybrid approach. Nginx and Apache2 for example implement their network processing code as a thread pool of event loops. Each thread runs an event loop simultaneously processing requests single-threaded but requests are load-balanced among multiple threads.</p> <p>Some single-threaded architectures also use a hybrid approach. Instead of launching multiple threads from a single process you can launch multiple applications - for example, 4 node.js servers on a quad-core machine. Then you use a load balancer to spread the workload amongst the processes.</p> <p>In effect the two approaches are technically identical mirror-images of each other.</p>
{ "question_id": 34855352, "question_date": "2016-01-18T12:56:56.193Z", "question_score": 637, "tags": "node.js", "answer_id": 34857298, "answer_date": "2016-01-18T14:37:56.983Z", "answer_score": 1147 }
Please answer the following Stack Overflow question: Title: Need to reset git branch to origin version <p>I was accidentally working on a branch I shouldn't have been for a while, so I branched off of it giving it the appropriate name. Now I want to overwrite the branch I shouldn't have been on to the version from origin (github). Is there an easy way to do this? I tried deleting the branch and then resetting up the tracking branch, but it just gives me the version I was working on again.</p>
<p>If you haven't pushed to origin yet, you can reset your branch to the <a href="https://stackoverflow.com/questions/2739376/definition-of-downstream-and-upstream/2749166#2749166">upstream</a> branch with:</p> <pre><code>git checkout mybranch git reset --hard origin/mybranch </code></pre> <p>(Make sure that you reference your latest commit in a separate branch, like you mention in your question)</p> <p>Note that just after the reset, <code>mybranch@{1}</code> refers to the old commit, before reset.</p> <p>But if you had already pushed, see "<a href="https://stackoverflow.com/a/773728/6309">Create git branch, and revert original to upstream state</a>" for other options.</p> <hr> <p>With <strong>Git 2.23 (August 2019)</strong>, that would be one command: <a href="https://stackoverflow.com/a/57066202/6309"><strong><code>git switch</code></strong></a>.<br> Namely: <a href="https://git-scm.com/docs/git-switch#Documentation/git-switch.txt--Cltnew-branchgt" rel="noreferrer"><code>git switch -C mybranch origin/mybranch</code></a></p> <p>Example</p> <pre><code>C:\Users\vonc\git\git&gt;git switch -C master origin/master Reset branch 'master' Branch 'master' set up to track remote branch 'master' from 'origin'. Your branch is up to date with 'origin/master'. </code></pre> <p>That restores the index and working tree, like a <code>git reset --hard</code> would.</p> <hr> <p>As commented by <a href="https://stackoverflow.com/users/259628/brad-herman">Brad Herman</a>, a <code>reset --hard</code> would <strong>remove any new file or reset modified file to HEAD</strong>. </p> <p>Actually, to be sure you start from a "clean slate", a <code>git clean -f -d</code> after the reset would ensure a working tree <em>exactly</em> identical to the branch you just reset to.</p> <hr> <p>This <a href="http://ocpsoft.org/tutorials/git/reset-and-sync-local-respository-with-remote-branch/" rel="noreferrer">blog post</a> suggests those aliases (for <code>master</code> branch only, but you can adapt/extend those):</p> <blockquote> <pre><code>[alias] resetorigin = !git fetch origin &amp;&amp; git reset --hard origin/master &amp;&amp; git clean -f -d resetupstream = !git fetch upstream &amp;&amp; git reset --hard upstream/master &amp;&amp; git clean -f -d </code></pre> <p>Then you can type:</p> <pre><code>git resetupstream </code></pre> <p>or</p> <pre><code>git resetorigin </code></pre> </blockquote>
{ "question_id": 9301782, "question_date": "2012-02-15T21:33:52.357Z", "question_score": 636, "tags": "git", "answer_id": 9302259, "answer_date": "2012-02-15T22:09:35.023Z", "answer_score": 1167 }
Please answer the following Stack Overflow question: Title: How to build jars from IntelliJ properly? <p>I have a project that contains a single module, and some dependencies. I'd like to create a jar, in a separate directory, that contains the compiled module. In addition, I'd like to have the dependencies present beside my module.</p> <p>No matter how I twist IntelliJ's "build jar" process, the output of my module appears empty (besides a META-INF file).</p>
<p>Here's how to build a jar with IntelliJ 10 <a href="http://blogs.jetbrains.com/idea/2010/08/quickly-create-jar-artifact/" rel="noreferrer">http://blogs.jetbrains.com/idea/2010/08/quickly-create-jar-artifact/</a></p> <p><kbd>File</kbd> -&gt; <kbd>Project Structure</kbd> -&gt; <kbd>Project Settings</kbd> -&gt; <kbd>Artifacts</kbd> -&gt; Click <kbd>green plus sign</kbd> -&gt; <kbd>Jar</kbd> -&gt; <kbd>From modules with dependencies...</kbd></p> <p>Select a <kbd>Main Class</kbd> (the one with <code>main()</code> method) if you need to make the jar runnable.</p> <p>The above sets the &quot;skeleton&quot; to where the jar will be saved to. To actually build and save it do the following:</p> <p>Extract to the target Jar</p> <p>OK</p> <p>Build | Build Artifact | Build</p> <p>Try Extracting the .jar file from</p> <p><strong>ProjectName | out | artifacts | ProjectName_jar | ProjectName.jar</strong></p>
{ "question_id": 1082580, "question_date": "2009-07-04T17:05:35.520Z", "question_score": 636, "tags": "java|intellij-idea|jar|build-process", "answer_id": 4901370, "answer_date": "2011-02-04T18:06:11.893Z", "answer_score": 745 }
Please answer the following Stack Overflow question: Title: Vertically centering a div inside another div <p>I want to center a div which is inside another div.</p> <pre><code>&lt;div id=&quot;outerDiv&quot;&gt; &lt;div id=&quot;innerDiv&quot;&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>This is the CSS I am currently using.</p> <pre><code> #outerDiv { width: 500px; height: 500px; position: relative; } #innerDiv { width: 284px; height: 290px; position: absolute; top: 50%; left: 50%; margin-top: -147px; margin-left: -144px; } </code></pre> <p>As you can see, the approach I use now depends on the width and height of <code>#innerDiv</code>. If the width/height changes, I will have to modify the <code>margin-top</code> and <code>margin-left</code> values. Is there any generic solution that I can use to center the <code>#innerDiv</code> independently of its size?</p> <p>I figured out that using <code>margin: auto</code> can horizontally align the <code>#innerDiv</code> to the middle. But what about vertical alignment?</p>
<p><a href="http://codepen.io/meodai/pen/XbEqZw?editors=010" rel="noreferrer"><strong>tl;dr</strong></a></p> <p>Vertical align middle works, but you will have to use <code>table-cell</code> on your parent element and <code>inline-block</code> on the child.</p> <p>This solution is not going to work in IE6 &amp; 7. <br>Yours is the safer way to go for those. <br>But since you tagged your question with CSS3 and HTML5 I was thinking that you don't mind using a modern solution.</p> <p><strong>The classic solution (table layout)</strong></p> <p>This was my original answer. It still works fine and is the solution with the widest support. Table-layout will <a href="http://www.stubbornella.org/content/2009/03/27/reflows-repaints-css-performance-making-your-javascript-slow/#tables" rel="noreferrer">impact your rendering performance</a> so I would suggest that you use one of the more modern solutions.</p> <p><a href="http://jsfiddle.net/mcSfe/" rel="noreferrer">Here is an example</a></p> <hr> <p><strong>Tested in:</strong> </p> <ul> <li>FF3.5+</li> <li>FF4+</li> <li>Safari 5+</li> <li>Chrome 11+</li> <li>IE9+</li> </ul> <hr> <p><strong>HTML</strong></p> <pre><code>&lt;div class="cn"&gt;&lt;div class="inner"&gt;your content&lt;/div&gt;&lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.cn { display: table-cell; width: 500px; height: 500px; vertical-align: middle; text-align: center; } .inner { display: inline-block; width: 200px; height: 200px; } </code></pre> <hr> <p><strong>Modern solution (transform)</strong></p> <p>Since transforms are <a href="http://caniuse.com/#search=2d%20transforms" rel="noreferrer">fairly well supported now</a> there is an easier way to do it.</p> <p><strong>CSS</strong></p> <pre><code>.cn { position: relative; width: 500px; height: 500px; } .inner { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); width: 200px; height: 200px; } </code></pre> <p><a href="http://jsfiddle.net/0tc6ycvo/1/" rel="noreferrer">Demo</a> </p> <hr> <p><strong>♥ my favourite modern solution (flexbox)</strong></p> <p>I started to use flexbox more and more <a href="http://caniuse.com/#search=flexbox" rel="noreferrer">its also well supported now</a> Its by far the easiest way.</p> <p><strong>CSS</strong></p> <pre><code>.cn { display: flex; justify-content: center; align-items: center; } </code></pre> <p><a href="http://codepen.io/meodai/pen/PqRebp?editors=110" rel="noreferrer">Demo</a></p> <p>More examples &amp; possibilities: <a href="http://codepen.io/meodai/pen/XbEqZw?editors=110" rel="noreferrer">Compare all the methods on one pages</a> </p>
{ "question_id": 6490252, "question_date": "2011-06-27T08:22:03.747Z", "question_score": 636, "tags": "html|css", "answer_id": 6490283, "answer_date": "2011-06-27T08:26:01.177Z", "answer_score": 928 }
Please answer the following Stack Overflow question: Title: Creating a BLOB from a Base64 string in JavaScript <p>I have Base64-encoded binary data in a string:</p> <pre class="lang-javascript prettyprint-override"><code>const contentType = 'image/png'; const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='; </code></pre> <p>I would like to create a <code>blob:</code> URL containing this data and display it to the user:</p> <pre class="lang-javascript prettyprint-override"><code>const blob = new Blob(????, {type: contentType}); const blobUrl = URL.createObjectURL(blob); window.location = blobUrl; </code></pre> <p>I haven't been been able to figure out how to create the BLOB.</p> <p>In some cases I am able to avoid this by using a <code>data:</code> URL instead:</p> <pre class="lang-javascript prettyprint-override"><code>const dataUrl = `data:${contentType};base64,${b64Data}`; window.location = dataUrl; </code></pre> <p>However, in most cases the <code>data:</code> URLs are prohibitively large.</p> <hr> <p>How can I decode a Base64 string to a BLOB object in JavaScript?</p>
<p>The <code>atob</code> function will decode a Base64-encoded string into a new string with a character for each byte of the binary data.</p> <pre class="lang-javascript prettyprint-override"><code>const byteCharacters = atob(b64Data); </code></pre> <p>Each character's code point (charCode) will be the value of the byte. We can create an array of byte values by applying this using the <code>.charCodeAt</code> method for each character in the string.</p> <pre class="lang-javascript prettyprint-override"><code>const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i &lt; byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } </code></pre> <p>You can convert this array of byte values into a real typed byte array by passing it to the <code>Uint8Array</code> constructor.</p> <pre class="lang-javascript prettyprint-override"><code>const byteArray = new Uint8Array(byteNumbers); </code></pre> <p>This in turn can be converted to a BLOB by wrapping it in an array and passing it to the <code>Blob</code> constructor.</p> <pre class="lang-javascript prettyprint-override"><code>const blob = new Blob([byteArray], {type: contentType}); </code></pre> <p>The code above works. However the performance can be improved a little by processing the <code>byteCharacters</code> in smaller slices, rather than all at once. In my rough testing 512 bytes seems to be a good slice size. This gives us the following function.</p> <pre class="lang-javascript prettyprint-override"><code>const b64toBlob = (b64Data, contentType='', sliceSize=512) =&gt; { const byteCharacters = atob(b64Data); const byteArrays = []; for (let offset = 0; offset &lt; byteCharacters.length; offset += sliceSize) { const slice = byteCharacters.slice(offset, offset + sliceSize); const byteNumbers = new Array(slice.length); for (let i = 0; i &lt; slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } const blob = new Blob(byteArrays, {type: contentType}); return blob; } </code></pre> <pre class="lang-javascript prettyprint-override"><code>const blob = b64toBlob(b64Data, contentType); const blobUrl = URL.createObjectURL(blob); window.location = blobUrl; </code></pre> <h3>Full Example:</h3> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const b64toBlob = (b64Data, contentType='', sliceSize=512) =&gt; { const byteCharacters = atob(b64Data); const byteArrays = []; for (let offset = 0; offset &lt; byteCharacters.length; offset += sliceSize) { const slice = byteCharacters.slice(offset, offset + sliceSize); const byteNumbers = new Array(slice.length); for (let i = 0; i &lt; slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } const blob = new Blob(byteArrays, {type: contentType}); return blob; } const contentType = 'image/png'; const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='; const blob = b64toBlob(b64Data, contentType); const blobUrl = URL.createObjectURL(blob); const img = document.createElement('img'); img.src = blobUrl; document.body.appendChild(img);</code></pre> </div> </div> </p>
{ "question_id": 16245767, "question_date": "2013-04-26T21:51:20.443Z", "question_score": 636, "tags": "javascript|base64", "answer_id": 16245768, "answer_date": "2013-04-26T21:51:20.443Z", "answer_score": 1045 }
Please answer the following Stack Overflow question: Title: How to obtain the number of CPUs/cores in Linux from the command line? <p>I have this script, but I do not know how to get the last element in the printout:</p> <pre><code>cat /proc/cpuinfo | awk '/^processor/{print $3}' </code></pre> <p>The last element should be the number of CPUs, minus 1.</p>
<pre><code>grep -c ^processor /proc/cpuinfo </code></pre> <p>will count the number of lines starting with &quot;processor&quot; in <code>/proc/cpuinfo</code></p> <p>For systems with hyper-threading, you can use</p> <pre><code>grep ^cpu\\scores /proc/cpuinfo | uniq | awk '{print $4}' </code></pre> <p>which should return (for example) <code>8</code> (whereas the command above would return <code>16</code>)</p>
{ "question_id": 6481005, "question_date": "2011-06-25T22:52:34.030Z", "question_score": 636, "tags": "linux|bash|cpu|core", "answer_id": 6481016, "answer_date": "2011-06-25T22:56:01.013Z", "answer_score": 765 }
Please answer the following Stack Overflow question: Title: What is a "static" function in C? <p>The question was about plain <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a> functions, not <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged &#39;c++&#39;" rel="tag">c++</a> <code>static</code> methods, as clarified in comments.</p> <p>I understand what a <code>static</code> variable is, but what is a <code>static</code> function?</p> <p>And why is it that if I declare a function, let's say <code>void print_matrix</code>, in let's say <code>a.c</code> (WITHOUT <code>a.h</code>) and include <code>"a.c"</code> - I get <code>"print_matrix@@....) already defined in a.obj"</code>, BUT if I declare it as <code>static void print_matrix</code> then it compiles?</p> <p><strong>UPDATE</strong> Just to clear things up - I know that including <code>.c</code> is bad, as many of you pointed out. I just do it to temporarily clear space in <code>main.c</code> until I have a better idea of how to group all those functions into proper <code>.h</code> and <code>.c</code> files. Just a temporary, quick solution.</p>
<p><code>static</code> functions are functions that are only visible to other functions in the same file (more precisely <em>the same <a href="http://en.wikipedia.org/wiki/Translation_unit_%28programming%29" rel="noreferrer">translation unit</a></em>).</p> <p><strong>EDIT</strong>: For those who thought, that the author of the questions meant a 'class method': As the question is tagged <code>C</code> he means a plain old C function. For (C++/Java/...) class methods, <code>static</code> means that this method can be called on the class itself, no instance of that class necessary.</p>
{ "question_id": 558122, "question_date": "2009-02-17T18:26:02.043Z", "question_score": 636, "tags": "c|function|static|terminology", "answer_id": 558132, "answer_date": "2009-02-17T18:27:31.853Z", "answer_score": 820 }
Please answer the following Stack Overflow question: Title: How can I save application settings in a Windows Forms application? <p>What I want to achieve is very simple: I have a Windows Forms (.NET 3.5) application that uses a path for reading information. This path can be modified by the user, by using the options form I provide.</p> <p>Now, I want to save the path value to a file for later use. This would be one of the many settings saved to this file. This file would sit directly in the application folder.</p> <p>I understand three options are available:</p> <ul> <li>ConfigurationSettings file (appname.exe.config)</li> <li>Registry</li> <li>Custom XML file</li> </ul> <p>I read that the .NET configuration file is not foreseen for saving values back to it. As for the registry, I would like to get as far away from it as possible.</p> <p>Does this mean that I should use a custom XML file to save configuration settings?</p> <p>If so, I would like to see code example of that (C#).</p> <p>I have seen other discussions on this subject, but it is still not clear to me.</p>
<p>If you work with Visual Studio then it is pretty easy to get persistable settings. Right click on the project in Solution Explorer and choose Properties. Select the Settings tab and click on the hyperlink if settings doesn't exist.</p> <p>Use the Settings tab to create application settings. Visual Studio creates the files <code>Settings.settings</code> and <code>Settings.Designer.settings</code> that contain the singleton class <code>Settings</code> inherited from <a href="http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.aspx" rel="noreferrer">ApplicationSettingsBase</a>. You can access this class from your code to read/write application settings:</p> <pre><code>Properties.Settings.Default["SomeProperty"] = "Some Value"; Properties.Settings.Default.Save(); // Saves settings in application configuration file </code></pre> <p>This technique is applicable both for console, Windows Forms, and other project types.</p> <p>Note that you need to set the <em>scope</em> property of your settings. If you select Application scope then Settings.Default.&lt;your property> will be read-only.</p> <p>Reference: <a href="https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-write-user-settings-at-run-time-with-csharp" rel="noreferrer">How To: Write User Settings at Run Time with C#</a> - Microsoft Docs</p>
{ "question_id": 453161, "question_date": "2009-01-17T11:23:36.393Z", "question_score": 636, "tags": "c#|xml|winforms|configuration-files|application-settings", "answer_id": 453230, "answer_date": "2009-01-17T12:18:01.227Z", "answer_score": 645 }
Please answer the following Stack Overflow question: Title: Error: 'node-sass' version 5.0.0 is incompatible with ^4.0.0 <p>I've created a blank React project, using the command: <code>npx create-react-app</code> on npm v7.0.7 and Node.js v15.0.1</p> <p>Installed:</p> <ul> <li>React v17.0.1,</li> <li>node-sass v5.0.0,</li> </ul> <p>Then I tried to import a blank .scss file to the App component:</p> <h3>File <em>App.js</em></h3> <pre><code>import './App.scss' function App() { return ( &lt;div className=&quot;App&quot;&gt; App &lt;/div&gt; ); } export default App; </code></pre> <p><em><strong>It throws an error:</strong></em></p> <pre><code>Failed to compile. ./src/App.scss (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-6-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--5-oneOf-6-3!./node_modules/s ass-loader/dist/cjs.js??ref--5-oneOf-6-4!./src/App.scss) Error: Node Sass version 5.0.0 is incompatible with ^4.0.0. </code></pre> <h3>File <em>package.json</em></h3> <pre><code>{ &quot;name&quot;: &quot;react-17-node-sass-5&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;private&quot;: true, &quot;dependencies&quot;: { &quot;@testing-library/jest-dom&quot;: &quot;^5.11.5&quot;, &quot;@testing-library/react&quot;: &quot;^11.1.0&quot;, &quot;@testing-library/user-event&quot;: &quot;^12.1.10&quot;, &quot;node-sass&quot;: &quot;^5.0.0&quot;, &quot;react&quot;: &quot;^17.0.1&quot;, &quot;react-dom&quot;: &quot;^17.0.1&quot;, &quot;react-scripts&quot;: &quot;4.0.0&quot;, &quot;web-vitals&quot;: &quot;^0.2.4&quot; }, ... } } </code></pre>
<p><strong>TL;DR</strong></p> <ol> <li><code>npm uninstall node-sass</code></li> <li><code>npm install sass</code></li> </ol> <p>Or, if using Yarn</p> <ol> <li><code>yarn remove node-sass</code></li> <li><code>yarn add sass</code></li> </ol> <p><strong>Edit3</strong>: yes, another edit. Moving to sass (dart-sass) is the best solution. Previous one included locking node-sass to version 4.x.x, which is 2 years old and lacks newer SCSS features.</p> <hr /> <p><strong>Edit2</strong>: sass-loader <a href="https://github.com/webpack-contrib/sass-loader/releases/tag/v10.0.5" rel="noreferrer">v10.0.5</a> fixes it. The problem is you might not be using it as a project dependency, but more as a dependency of your dependencies. CRA uses a fixed version, angular-cli locks to node-sass v4, and so on.</p> <p>The recommendation for now is: if you're installing just node-sass, check the below workaround (and the note). If you're working on a blank project and you can manage your <a href="https://en.wikipedia.org/wiki/Webpack" rel="noreferrer">Webpack</a> configuration (not using CRA or a CLI to scaffold your project), install the latest sass-loader.</p> <hr /> <p><strong>Edit</strong>: this error comes from <a href="https://github.com/webpack-contrib/sass-loader/issues/898" rel="noreferrer">sass-loader</a>. There is a <a href="https://semver.org/" rel="noreferrer">semantic versioning</a> mismatch since node-sass @latest is v5.0.0 and sass-loader expects ^4.0.0.</p> <p>There is an open issue on their repository with an associated fix that needs to be reviewed. Until then, refer to the solution below.</p> <hr /> <p><strong>Workaround</strong>: don't install node-sass 5.0.0 yet (the major version was just bumped).</p> <p>Uninstall node-sass</p> <p><code>npm uninstall node-sass</code></p> <p>Then install the latest version (before 5.0)</p> <p><code>npm install [email protected]</code></p> <hr /> <p>Note: LibSass (hence node-sass as well) <a href="https://sass-lang.com/blog/libsass-is-deprecated" rel="noreferrer">is deprecated</a> and dart-sass is the recommended implementation. <a href="https://www.npmjs.com/package/sass" rel="noreferrer">You can use <code>sass</code> instead</a>, which is a Node.js distribution of dart-sass compiled to pure JavaScript.</p>
{ "question_id": 64625050, "question_date": "2020-10-31T18:19:20.300Z", "question_score": 636, "tags": "reactjs|webpack|sass|create-react-app|node-sass", "answer_id": 64626556, "answer_date": "2020-10-31T21:26:02.100Z", "answer_score": 1134 }
Please answer the following Stack Overflow question: Title: How can I get the latest tag name in current branch in Git? <p>What's the simplest way to get the most recent tag in Git?</p> <pre><code>git tag a HEAD git tag b HEAD^^ git tag c HEAD^ git tag </code></pre> <p>output:</p> <pre><code>a b c </code></pre> <p>Should I write a script to get each tag's datetime and compare them?</p>
<p>You could take a look at <code>git describe</code>, which does something close to what you're asking.</p>
{ "question_id": 1404796, "question_date": "2009-09-10T11:43:39.200Z", "question_score": 636, "tags": "git|git-checkout|git-tag|getlatest", "answer_id": 1404862, "answer_date": "2009-09-10T11:58:14.707Z", "answer_score": 503 }
Please answer the following Stack Overflow question: Title: How to pretty print XML from the command line? <p>Related: <a href="https://stackoverflow.com/questions/352098/how-to-pretty-print-json-from-the-command-line">How can I pretty-print JSON in (unix) shell script?</a></p> <p>Is there a (unix) shell script to format XML in human-readable form?</p> <p>Basically, I want it to transform the following:</p> <pre><code>&lt;root&gt;&lt;foo a="b"&gt;lorem&lt;/foo&gt;&lt;bar value="ipsum" /&gt;&lt;/root&gt; </code></pre> <p>... into something like this:</p> <pre><code>&lt;root&gt; &lt;foo a="b"&gt;lorem&lt;/foo&gt; &lt;bar value="ipsum" /&gt; &lt;/root&gt; </code></pre>
<p><strong><code>xmllint</code></strong></p> <p>This utility comes with <a href="https://gitlab.gnome.org/GNOME/libxml2" rel="noreferrer"><code>libxml2-utils</code></a>:</p> <pre><code>echo '&lt;root&gt;&lt;foo a=&quot;b&quot;&gt;lorem&lt;/foo&gt;&lt;bar value=&quot;ipsum&quot; /&gt;&lt;/root&gt;' | xmllint --format - </code></pre> <p><strong>Perl's <code>XML::Twig</code></strong></p> <p>This command comes with <a href="https://metacpan.org/pod/XML::Twig" rel="noreferrer">XML::Twig</a> <a href="/questions/tagged/perl" class="post-tag" title="show questions tagged &#39;perl&#39;" rel="tag">perl</a> module, sometimes <code>xml-twig-tools</code> package:</p> <pre><code>echo '&lt;root&gt;&lt;foo a=&quot;b&quot;&gt;lorem&lt;/foo&gt;&lt;bar value=&quot;ipsum&quot; /&gt;&lt;/root&gt;' | xml_pp </code></pre> <p><strong><code>xmlstarlet</code></strong></p> <p>This command comes with <a href="https://sourceforge.net/projects/xmlstar/" rel="noreferrer"><code>xmlstarlet</code></a>:</p> <pre><code>echo '&lt;root&gt;&lt;foo a=&quot;b&quot;&gt;lorem&lt;/foo&gt;&lt;bar value=&quot;ipsum&quot; /&gt;&lt;/root&gt;' | xmlstarlet format --indent-tab </code></pre> <p><strong><code>tidy</code></strong></p> <p>Check the <a href="https://github.com/htacg/tidy-html5" rel="noreferrer"><code>tidy</code></a> package:</p> <pre><code>echo '&lt;root&gt;&lt;foo a=&quot;b&quot;&gt;lorem&lt;/foo&gt;&lt;bar value=&quot;ipsum&quot; /&gt;&lt;/root&gt;' | tidy -xml -i - </code></pre> <p><strong>Python</strong></p> <p>Python's <a href="https://docs.python.org/3/library/xml.dom.minidom.html" rel="noreferrer"><code>xml.dom.minidom</code></a> can format XML (works also on legacy python2):</p> <pre><code>echo '&lt;root&gt;&lt;foo a=&quot;b&quot;&gt;lorem&lt;/foo&gt;&lt;bar value=&quot;ipsum&quot; /&gt;&lt;/root&gt;' | python -c 'import sys; import xml.dom.minidom; s=sys.stdin.read(); print(xml.dom.minidom.parseString(s).toprettyxml())' </code></pre> <p><strong><code>saxon-lint</code></strong></p> <p>You need <a href="https://github.com/sputnick-dev/saxon-lint" rel="noreferrer"><code>saxon-lint</code></a>:</p> <pre><code>echo '&lt;root&gt;&lt;foo a=&quot;b&quot;&gt;lorem&lt;/foo&gt;&lt;bar value=&quot;ipsum&quot; /&gt;&lt;/root&gt;' | saxon-lint --indent --xpath '/' - </code></pre> <p><strong><code>saxon-HE</code></strong></p> <p>You need <a href="https://saxonica.plan.io/projects/saxon" rel="noreferrer"><code>saxon-HE</code></a>:</p> <pre><code> echo '&lt;root&gt;&lt;foo a=&quot;b&quot;&gt;lorem&lt;/foo&gt;&lt;bar value=&quot;ipsum&quot; /&gt;&lt;/root&gt;' | java -cp /usr/share/java/saxon/saxon9he.jar net.sf.saxon.Query \ -s:- -qs:/ '!indent=yes' </code></pre>
{ "question_id": 16090869, "question_date": "2013-04-18T18:50:04.107Z", "question_score": 636, "tags": "xml|unix|command-line", "answer_id": 16090892, "answer_date": "2013-04-18T18:51:29.917Z", "answer_score": 1107 }
Please answer the following Stack Overflow question: Title: Getting all types that implement an interface <p>Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?</p> <p>This is what I want to re-write:</p> <pre><code>foreach (Type t in this.GetType().Assembly.GetTypes()) if (t is IMyInterface) ; //do stuff </code></pre>
<p>Mine would be this in c# 3.0 :)</p> <pre><code>var type = typeof(IMyInterface); var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s =&gt; s.GetTypes()) .Where(p =&gt; type.IsAssignableFrom(p)); </code></pre> <p>Basically, the least amount of iterations will always be:</p> <pre><code>loop assemblies loop types see if implemented. </code></pre>
{ "question_id": 26733, "question_date": "2008-08-25T19:57:21.903Z", "question_score": 636, "tags": "c#|optimization|reflection|lambda|c#-3.0", "answer_id": 26750, "answer_date": "2008-08-25T20:11:21.243Z", "answer_score": 919 }
Please answer the following Stack Overflow question: Title: What does the NS prefix mean? <p>Many classes in Cocoa/Cocoa Touch have the NS prefix. What does it mean?</p>
<p>It's from the <a href="https://en.wikipedia.org/wiki/NeXTSTEP" rel="noreferrer">NeXTSTEP</a> heritage.</p>
{ "question_id": 473758, "question_date": "2009-01-23T17:22:44.037Z", "question_score": 636, "tags": "ios|objective-c|cocoa|cocoa-touch|terminology", "answer_id": 473764, "answer_date": "2009-01-23T17:24:11.960Z", "answer_score": 496 }
Please answer the following Stack Overflow question: Title: Best way to get application folder path <p>I see that there are some ways to get the application folder path:</p> <ol> <li><code>Application.StartupPath</code></li> <li><code>System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location)</code></li> <li><code>AppDomain.CurrentDomain.BaseDirectory</code></li> <li><code>System.IO.Directory.GetCurrentDirectory()</code></li> <li><code>Environment.CurrentDirectory</code></li> <li><code>System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)</code></li> <li><code>System.IO.Path.GetDirectory(Application.ExecutablePath)</code></li> </ol> <p>What is the best way depending on the situation?</p>
<p><code>AppDomain.CurrentDomain.BaseDirectory</code> is probably the most useful for accessing files whose location is relative to the application install directory.</p> <p>In an ASP.NET application, this will be the application root directory, not the bin subfolder - which is probably what you usually want. In a client application, it will be the directory containing the main executable.</p> <p>In a VSTO 2005 application, it will be the directory containing the VSTO managed assemblies for your application, not, say, the path to the Excel executable.</p> <p>The others may return different directories depending on your environment - for example see @Vimvq1987's answer.</p> <p><code>CodeBase</code> is the place where a file was found and can be a URL beginning with http://. In which case <code>Location</code> will probably be the assembly download cache. CodeBase is not guaranteed to be set for assemblies in the <a href="http://en.wikipedia.org/wiki/Global_Assembly_Cache" rel="noreferrer">GAC</a>.</p> <p><strong>UPDATE</strong> These days (.NET Core, .NET Standard 1.3+ or .NET Framework 4.6+) it's better to use <code>AppContext.BaseDirectory</code> rather than <code>AppDomain.CurrentDomain.BaseDirectory</code>. Both are equivalent, but <a href="https://docs.microsoft.com/en-us/dotnet/core/porting/net-framework-tech-unavailable" rel="noreferrer">multiple AppDomains are no longer supported</a>.</p>
{ "question_id": 6041332, "question_date": "2011-05-18T07:35:43.677Z", "question_score": 635, "tags": "c#|.net", "answer_id": 6041505, "answer_date": "2011-05-18T07:55:13.057Z", "answer_score": 642 }
Please answer the following Stack Overflow question: Title: Convert Int to String in Swift <p>I'm trying to work out how to cast an <code>Int</code> into a <code>String</code> in Swift.</p> <p>I figure out a workaround, using <code>NSNumber</code> but I'd love to figure out how to do it all in Swift.</p> <pre><code>let x : Int = 45 let xNSNumber = x as NSNumber let xString : String = xNSNumber.stringValue </code></pre>
<p>Converting <code>Int</code> to <code>String</code>:</p> <pre><code>let x : Int = 42 var myString = String(x) </code></pre> <p>And the other way around - converting <code>String</code> to <code>Int</code>:</p> <pre><code>let myString : String = "42" let x: Int? = myString.toInt() if (x != nil) { // Successfully converted String to Int } </code></pre> <p>Or if you're using Swift 2 or 3:</p> <pre><code>let x: Int? = Int(myString) </code></pre>
{ "question_id": 24161336, "question_date": "2014-06-11T11:05:26.207Z", "question_score": 635, "tags": "string|casting|int|converter|swift", "answer_id": 24161392, "answer_date": "2014-06-11T11:08:09.370Z", "answer_score": 1082 }
Please answer the following Stack Overflow question: Title: How to get the full URL in Express? <p>Let's say my sample URL is</p> <blockquote> <p><a href="http://example.com/one/two" rel="noreferrer">http://example.com/one/two</a></p> </blockquote> <p>and I say I have the following route</p> <pre><code>app.get('/one/two', function (req, res) { var url = req.url; } </code></pre> <p>The value of <code>url</code> will be <code>/one/two</code>.</p> <p>How do I get the <strong>full URL</strong> in Express? For example, in the case above, I would like to receive <code>http://example.com/one/two</code>.</p>
<ol> <li><p>The protocol is available as <code>req.protocol</code>. <a href="http://expressjs.com/api.html#req.protocol">docs here</a></p> <ol> <li>Before express 3.0, the protocol you can assume to be <code>http</code> unless you see that <code>req.get('X-Forwarded-Protocol')</code> is set and has the value <code>https</code>, in which case you know that's your protocol</li> </ol></li> <li><p>The host comes from <code>req.get('host')</code> as Gopal has indicated</p></li> <li><p>Hopefully you don't need a non-standard port in your URLs, but if you did need to know it you'd have it in your application state because it's whatever you passed to <code>app.listen</code> at server startup time. However, in the case of local development on a non-standard port, Chrome seems to include the port in the host header so <code>req.get('host')</code> returns <code>localhost:3000</code>, for example. So at least for the cases of a production site on a standard port and browsing directly to your express app (without reverse proxy), the <code>host</code> header seems to do the right thing regarding the port in the URL.</p></li> <li><p>The path comes from <code>req.originalUrl</code> (thanks @pgrassant). Note this DOES include the query string. <a href="http://expressjs.com/api.html#req.originalUrl">docs here on req.url and req.originalUrl</a>. Depending on what you intend to do with the URL, <code>originalUrl</code> may or may not be the correct value as compared to <code>req.url</code>.</p></li> </ol> <p>Combine those all together to reconstruct the absolute URL.</p> <pre><code> var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl; </code></pre>
{ "question_id": 10183291, "question_date": "2012-04-16T23:57:06.567Z", "question_score": 635, "tags": "node.js|url|express", "answer_id": 10185427, "answer_date": "2012-04-17T05:12:03.537Z", "answer_score": 927 }
Please answer the following Stack Overflow question: Title: How can I get useful error messages in PHP? <p>Quite often I will try and run a PHP script and just get a blank screen back. No error message; just an empty screen. The cause might have been a simple syntax error (wrong bracket, missing semicolon), or a failed function call, or something else entirely.</p> <p>It is very difficult to figure out what went wrong. I end up commenting out code, entering "echo" statements everywhere, etc. trying to narrow down the problem. But there surely must be a better way, right?</p> <p>Is there a way to get PHP to produce a useful error message, like Java does?</p>
<p>For syntax errors, you need to enable error display in the php.ini. By default these are turned off because you don't want a "customer" seeing the error messages. <a href="http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting" rel="noreferrer">Check this page</a> in the PHP documentation for information on the 2 directives: <code>error_reporting</code> and <code>display_errors</code>. <code>display_errors</code> is probably the one you want to change. If you can't modify the php.ini, you can also add the following lines to an .htaccess file:</p> <pre><code>php_flag display_errors on php_value error_reporting 2039 </code></pre> <p>You may want to consider using the value of E_ALL (as mentioned by Gumbo) for your version of PHP for <code>error_reporting</code> to get all of the errors. <a href="http://docs.php.net/manual/en/errorfunc.constants.php" rel="noreferrer">more info</a></p> <p>3 other items: (1) You can check the error log file as it will have all of the errors (unless logging has been disabled). (2) Adding the following 2 lines will help you debug errors that are not syntax errors:</p> <pre><code>error_reporting(-1); ini_set('display_errors', 'On'); </code></pre> <p>(3) Another option is to use an editor that checks for errors when you type, such as <a href="http://www.nusphere.com/products/phped.htm" rel="noreferrer">PhpEd</a>. PhpEd also comes with a debugger which can provide more detailed information. (The PhpEd debugger is very similar to xdebug and integrates directly into the editor so you use 1 program to do everything.)</p> <p>Cartman's <a href="http://www.ibm.com/developerworks/library/os-debug/" rel="noreferrer">link</a> is also very good: <a href="http://www.ibm.com/developerworks/library/os-debug/" rel="noreferrer">http://www.ibm.com/developerworks/library/os-debug/</a></p>
{ "question_id": 845021, "question_date": "2009-05-10T09:48:12.687Z", "question_score": 635, "tags": "php|debugging|error-handling", "answer_id": 845025, "answer_date": "2009-05-10T09:52:35.640Z", "answer_score": 522 }
Please answer the following Stack Overflow question: Title: See changes to a specific file using git <p>I know that I can use the <code>git diff</code> command to check the changes, but, as far as I understood, it is directory based. This means it gives all the changes of all files on the current directory.</p> <p><em>How can I check only the changes in one specific file?</em> Say, I have changed files <code>file_1.rb</code>, <code>file_2.rb</code>, ..., <code>file_N.rb</code>, but I am only interested in the changes in the file <code>file_2.rb</code>. How do I check these changes then (before I commit)?</p>
<p>Use a command like:</p> <pre><code>git diff file_2.rb </code></pre> <p>See the <a href="http://schacon.github.com/git/git-diff.html" rel="noreferrer"><code>git diff</code> documentation</a> for full information on the kinds of things you can get differences for.</p> <p>Normally, <code>git diff</code> by itself shows all the changes in the whole <em>repository</em> (not just the current directory).</p>
{ "question_id": 8048584, "question_date": "2011-11-08T09:55:06.510Z", "question_score": 635, "tags": "git|git-svn", "answer_id": 8048608, "answer_date": "2011-11-08T09:56:39.530Z", "answer_score": 836 }
Please answer the following Stack Overflow question: Title: CSS transition shorthand with multiple properties? <p>I can't seem to find the correct syntax for the CSS transition <strong>shorthand</strong> with multiple properties. This doesn't do anything:</p> <pre class="lang-css prettyprint-override"><code>.element { -webkit-transition: height .5s, opacity .5s .5s; -moz-transition: height .5s, opacity .5s .5s; -ms-transition: height .5s, opacity .5s .5s; transition: height .5s, opacity .5s .5s; height: 0; opacity: 0; overflow: 0; } .element.show { height: 200px; opacity: 1; } </code></pre> <p>I add the show class with javascript. The element becomes higher and visible, it just doesn't transition. Testing in latest Chrome, FF and Safari.</p> <p>What am I doing wrong?</p> <p>EDIT: Just to be clear, I'm looking for the shorthand version to scale my CSS down. It's bloated enough with all the vendor prefixes. Also expanded the example code.</p>
<p>Syntax:</p> <pre><code>transition: &lt;property&gt; || &lt;duration&gt; || &lt;timing-function&gt; || &lt;delay&gt; [, ...]; </code></pre> <p>Note that the duration must come before the delay, if the latter is specified.</p> <p>Individual transitions combined in shorthand declarations:</p> <pre><code>-webkit-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s; -moz-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s; -o-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s; transition: height 0.3s ease-out, opacity 0.3s ease 0.5s; </code></pre> <p>Or just transition them all:</p> <pre><code>-webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; -o-transition: all 0.3s ease-out; transition: all 0.3s ease-out; </code></pre> <p>Here is <a href="http://jsfiddle.net/remibreton/qAxnK/18/" rel="noreferrer">a straightforward example</a>. Here is another one <a href="http://jsfiddle.net/remibreton/qAxnK/19/" rel="noreferrer">with the delay property</a>.</p> <hr> <p><strong>Edit:</strong> previously listed here were the compatibilities and known issues regarding <code>transition</code>. Removed for readability.</p> <p>Bottom-line: just use it. The nature of this property is non-breaking for all applications and compatibility is now well above 94% globally.</p> <p>If you still want to be sure, refer to <a href="http://caniuse.com/css-transitions" rel="noreferrer">http://caniuse.com/css-transitions</a></p>
{ "question_id": 9670075, "question_date": "2012-03-12T15:37:40.317Z", "question_score": 635, "tags": "css|webkit|css-transitions|shorthand", "answer_id": 9670311, "answer_date": "2012-03-12T15:51:30.600Z", "answer_score": 899 }
Please answer the following Stack Overflow question: Title: Why `PagerAdapter::notifyDataSetChanged` is not updating the View? <p>I'm using the ViewPager from the compatibility library. I have succussfully got it displaying several views which I can page through.</p> <p>However, I'm having a hard time figuring out how to update the ViewPager with a new set of Views.</p> <p>I've tried all sorts of things like calling <code>mAdapter.notifyDataSetChanged()</code>, <code>mViewPager.invalidate()</code> even creating a brand new adapter each time I want to use a new List of data.</p> <p>Nothing has helped, the textviews remain unchanged from the original data.</p> <p><strong>Update:</strong> I made a little test project and I've almost been able to update the views. I'll paste the class below.</p> <p>What doesn't appear to update however is the 2nd view, the 'B' remains, it should display 'Y' after pressing the update button.</p> <pre><code>public class ViewPagerBugActivity extends Activity { private ViewPager myViewPager; private List&lt;String&gt; data; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); data = new ArrayList&lt;String&gt;(); data.add("A"); data.add("B"); data.add("C"); myViewPager = (ViewPager) findViewById(R.id.my_view_pager); myViewPager.setAdapter(new MyViewPagerAdapter(this, data)); Button updateButton = (Button) findViewById(R.id.update_button); updateButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { updateViewPager(); } }); } private void updateViewPager() { data.clear(); data.add("X"); data.add("Y"); data.add("Z"); myViewPager.getAdapter().notifyDataSetChanged(); } private class MyViewPagerAdapter extends PagerAdapter { private List&lt;String&gt; data; private Context ctx; public MyViewPagerAdapter(Context ctx, List&lt;String&gt; data) { this.ctx = ctx; this.data = data; } @Override public int getCount() { return data.size(); } @Override public Object instantiateItem(View collection, int position) { TextView view = new TextView(ctx); view.setText(data.get(position)); ((ViewPager)collection).addView(view); return view; } @Override public void destroyItem(View collection, int position, Object view) { ((ViewPager) collection).removeView((View) view); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Parcelable saveState() { return null; } @Override public void restoreState(Parcelable arg0, ClassLoader arg1) { } @Override public void startUpdate(View arg0) { } @Override public void finishUpdate(View arg0) { } } } </code></pre>
<p>There are several ways to achieve this.</p> <p>The first option is easier, but bit more inefficient.</p> <p>Override <code>getItemPosition</code> in your <code>PagerAdapter</code> like this:</p> <pre><code>public int getItemPosition(Object object) { return POSITION_NONE; } </code></pre> <p>This way, when you call <code>notifyDataSetChanged()</code>, the view pager will remove all views and reload them all. As so the reload effect is obtained.</p> <p>The second option, <a href="https://stackoverflow.com/a/8024557">suggested by Alvaro Luis Bustamante (previously alvarolb)</a>, is to <code>setTag()</code> method in <code>instantiateItem()</code> when instantiating a new view. Then instead of using <code>notifyDataSetChanged()</code>, you can use <code>findViewWithTag()</code> to find the view you want to update.</p> <h2>Conclusion</h2> <p>If you have a lot of views, or want to support modifying any specific item and/or view (fastly at any time), then the second approach (tagging) is very flexible and high performant, as it prevents recreating all the <strong>not</strong> modified views.<br /> (Kudos to alvarolb for the original research.)</p> <p>But if your App has only a &quot;refresh&quot; feature (without single item changes being even allowed), or has just few items, use the first approach, as it saves development time.</p>
{ "question_id": 7263291, "question_date": "2011-08-31T20:54:52.513Z", "question_score": 635, "tags": "android|android-viewpager|android-adapter|android-viewpager2", "answer_id": 7287121, "answer_date": "2011-09-02T17:28:20.010Z", "answer_score": 903 }
Please answer the following Stack Overflow question: Title: Difference Between Cohesion and Coupling <p>What is the difference between cohesion and coupling?</p> <p>How can coupling and cohesion lead to either good or poor software design?</p> <p>What are some examples that outline the difference between the two, and their impact on overall code quality?</p>
<p><strong>Cohesion</strong> refers to what the class (or module) can do. Low cohesion would mean that the class does a great variety of actions - it is broad, unfocused on what it should do. High cohesion means that the class is focused on what it should be doing, i.e. only methods relating to the intention of the class.</p> <p>Example of Low Cohesion:</p> <pre><code>------------------- | Staff | ------------------- | checkEmail() | | sendEmail() | | emailValidate() | | PrintLetter() | ------------------- </code></pre> <p>Example of High Cohesion:</p> <pre><code>---------------------------- | Staff | ---------------------------- | -salary | | -emailAddr | ---------------------------- | setSalary(newSalary) | | getSalary() | | setEmailAddr(newEmail) | | getEmailAddr() | ---------------------------- </code></pre> <p>As for <strong>coupling</strong>, it refers to how related or dependent two classes/modules are toward each other. For low coupled classes, changing something major in one class should not affect the other. High coupling would make it difficult to change and maintain your code; since classes are closely knit together, making a change could require an entire system revamp.</p> <p>Good software design has <strong>high cohesion</strong> and <strong>low coupling</strong>.</p>
{ "question_id": 3085285, "question_date": "2010-06-21T14:01:45.180Z", "question_score": 635, "tags": "oop|architecture|theory|software-design|ooad", "answer_id": 3085419, "answer_date": "2010-06-21T14:17:26.123Z", "answer_score": 910 }
Please answer the following Stack Overflow question: Title: Search all the occurrences of a string in the entire project in Android Studio <p>I've just started using Android Studio (IntelliJ), and I now look for the feature to find the occurrence of a string in any of the files in my project. For example: I want to find all the files that contain the string "<code>.getUuid()</code>"</p> <p>The search at the top right doesn't give me the correct results, and I don't think I can find this feature under Edit > Find.</p> <p>Could anybody point me at the right direction?</p>
<p><strong>TLDR:</strong> ⌃⇧F on MacOS will open &quot;Find in path&quot; dialog.</p> <p>First of all, this IDEA has a nice &quot;<code>Find Usages</code>&quot; command. It can be found in the context menu, when the cursor is on some field, method, etc.</p> <p>It's context-aware, and as far as I know, is the best way to find class, method or field usage.</p> <p>Alternatively, you can use the</p> <blockquote> <p>Edit &gt; Find &gt; Find in path…</p> </blockquote> <p><strong>dialog</strong>, which allows you to search the whole workspace.</p> <p>Also in IDEA 13 there is an awesome &quot;<code>Search Everywhere</code>&quot; option, by default called by double Shift. It allows you to search in project, files, classes, settings, and so on.</p> <p>Also you can search from Project Structure dialog with &quot;<code>Find in Path…</code>&quot;. Just call it by right mouse button on concrete directory and the search will be scoped, only inside that directory and it's sub-directory.</p> <p>Enjoy!</p>
{ "question_id": 20252180, "question_date": "2013-11-27T20:11:01.630Z", "question_score": 635, "tags": "android-studio|search|intellij-idea", "answer_id": 20252716, "answer_date": "2013-11-27T20:43:44.070Z", "answer_score": 850 }
Please answer the following Stack Overflow question: Title: Difference between partition key, composite key and clustering key in Cassandra? <p>I have been reading articles around the net to understand the differences between the following <code>key</code> types. But it just seems hard for me to grasp. Examples will definitely help make understanding better.</p> <pre><code>primary key, partition key, composite key clustering key </code></pre>
<p>There is a lot of confusion around this, I will try to make it as simple as possible.</p> <p>The primary key is a general concept to indicate one or more columns used to retrieve data from a Table.</p> <p>The primary key may be <em><strong>SIMPLE</strong></em> and even declared inline:</p> <pre><code> create table stackoverflow_simple ( key text PRIMARY KEY, data text ); </code></pre> <p>That means that it is made by a single column.</p> <p>But the primary key can also be <em><strong>COMPOSITE</strong></em> (aka <em><strong>COMPOUND</strong></em>), generated from more columns.</p> <pre><code> create table stackoverflow_composite ( key_part_one text, key_part_two int, data text, PRIMARY KEY(key_part_one, key_part_two) ); </code></pre> <p>In a situation of <em><strong>COMPOSITE</strong></em> primary key, the &quot;first part&quot; of the key is called <em><strong>PARTITION KEY</strong></em> (in this example <strong>key_part_one</strong> is the partition key) and the second part of the key is the <em><strong>CLUSTERING KEY</strong></em> (in this example <strong>key_part_two</strong>)</p> <p><strong>Please note that both partition and clustering key can be made by more columns</strong>, here's how:</p> <pre><code> create table stackoverflow_multiple ( k_part_one text, k_part_two int, k_clust_one text, k_clust_two int, k_clust_three uuid, data text, PRIMARY KEY((k_part_one, k_part_two), k_clust_one, k_clust_two, k_clust_three) ); </code></pre> <p>Behind these names ...</p> <ul> <li>The <strong>Partition Key</strong> is responsible for data distribution across your nodes.</li> <li>The <strong>Clustering Key</strong> is responsible for data sorting within the partition.</li> <li>The <strong>Primary Key</strong> is equivalent to the <strong>Partition Key</strong> in a single-field-key table (i.e. <strong>Simple</strong>).</li> <li>The <strong>Composite/Compound Key</strong> is just any multiple-column key</li> </ul> <p>Further usage information: <a href="http://www.datastax.com/documentation/cql/3.0/cql/cql_reference/create_table_r.html" rel="noreferrer">DATASTAX DOCUMENTATION</a></p> <hr> Small usage and content examples<br/> ***SIMPLE*** KEY: <pre><code>insert into stackoverflow_simple (key, data) VALUES ('han', 'solo'); select * from stackoverflow_simple where key='han'; </code></pre> <p><strong>table content</strong></p> <pre><code>key | data ----+------ han | solo </code></pre> <p><em><strong>COMPOSITE/COMPOUND KEY</strong></em> can retrieve &quot;wide rows&quot; (i.e. you can query by just the partition key, even if you have clustering keys defined)</p> <pre><code>insert into stackoverflow_composite (key_part_one, key_part_two, data) VALUES ('ronaldo', 9, 'football player'); insert into stackoverflow_composite (key_part_one, key_part_two, data) VALUES ('ronaldo', 10, 'ex-football player'); select * from stackoverflow_composite where key_part_one = 'ronaldo'; </code></pre> <p><strong>table content</strong></p> <pre><code> key_part_one | key_part_two | data --------------+--------------+-------------------- ronaldo | 9 | football player ronaldo | 10 | ex-football player </code></pre> <p>But you can query with all keys (both partition and clustering) ...</p> <pre><code>select * from stackoverflow_composite where key_part_one = 'ronaldo' and key_part_two = 10; </code></pre> <p><strong>query output</strong></p> <pre><code> key_part_one | key_part_two | data --------------+--------------+-------------------- ronaldo | 10 | ex-football player </code></pre> <p>Important note: the partition key is the minimum-specifier needed to perform a query using a <code>where clause</code>. If you have a composite partition key, like the following</p> <p>eg: <code>PRIMARY KEY((col1, col2), col10, col4))</code></p> <p>You can perform query only by passing at least both col1 and col2, these are the 2 columns that define the partition key. The &quot;general&quot; rule to make query is you must pass at least all partition key columns, then you can add optionally each clustering key in the order they're set.</p> <p>so, the valid queries are (<strong>excluding secondary indexes</strong>)</p> <ul> <li>col1 and col2</li> <li>col1 and col2 and col10</li> <li>col1 and col2 and col10 and col 4</li> </ul> <p>Invalid:</p> <ul> <li>col1 and col2 and col4</li> <li>anything that does not contain both col1 and col2</li> </ul>
{ "question_id": 24949676, "question_date": "2014-07-25T06:49:46.067Z", "question_score": 635, "tags": "database|cassandra|cql", "answer_id": 24953331, "answer_date": "2014-07-25T10:12:44.090Z", "answer_score": 1368 }
Please answer the following Stack Overflow question: Title: Xcode 6 Bug: Unknown class in Interface Builder file <p>I upgraded to Xcode 6 beta 4 and now my App continuously crashes with the message</p> <blockquote> <p>Unknown class X in Interface Builder file.</p> </blockquote> <p>It crashes because supposedly Xcode can't find my custom classes that I have linked in my Storyboard but it shows that they are linked correctly in the Xcode interface.</p> <p>I'm positive everything is linked correctly. My only other option may be to delete the entire storyboard file and start from scratch because it might be corrupted somehow.</p> <p>Edit: I would also like to add that I tried cleaning, reseting simulator, messing with build phases etc. None of that works.</p>
<p>I resolved this issue as I was typing the question. I figured I'd answer my question and leave it here for anyone else who may face this issue when using Xcode 6 beta 4.</p> <p>To resolve this issue, you need to select each of your custom class objects in Storyboard (this includes any custom views, even the custom view controllers themselves).</p> <p>Then with those objects selected, open the identity inspector and under &quot;Custom Class&quot; you should see the Module option. Finally:</p> <ul> <li>Click inside the Module text box, and press enter.</li> <li><strong>Or</strong> <sup>(update 2022)</sup>, check the &quot;Inherit Module From Target&quot; option.</li> </ul> <p>That's it! The current module for all of my custom objects must have been internally incorrectly set somehow in Xcode 6 beta 4. But there was no visual indication of this in the inspector.</p> <p>Note that if pressing enter inside the Module text box doesn't work, try selecting the arrow to the right and manually select your current module, then clear the text box and press enter. You can also try pressing enter inside the class text box (although this usually is to resolve a different issue).</p> <p>Here is an image to make things more clear: <img src="https://i.stack.imgur.com/7u8bd.png" alt="enter image description here" /></p>
{ "question_id": 24924966, "question_date": "2014-07-24T04:09:35.247Z", "question_score": 635, "tags": "ios|xcode|xcode6|interface-builder|uistoryboard", "answer_id": 24924967, "answer_date": "2014-07-24T04:09:35.247Z", "answer_score": 1507 }
Please answer the following Stack Overflow question: Title: How do I find the duplicates in a list and create another list with them? <p>How do I find the duplicates in a list of integers and create another list of the duplicates?</p>
<p>To remove duplicates use <code>set(a)</code>. To print duplicates, something like:</p> <pre><code>a = [1,2,3,2,1,5,6,5,5,5] import collections print([item for item, count in collections.Counter(a).items() if count &gt; 1]) ## [1, 2, 5] </code></pre> <p>Note that <code>Counter</code> is not particularly efficient (<a href="https://stackoverflow.com/a/25706298/989121">timings</a>) and probably overkill here. <code>set</code> will perform better. This code computes a list of unique elements in the source order:</p> <pre><code>seen = set() uniq = [] for x in a: if x not in seen: uniq.append(x) seen.add(x) </code></pre> <p>or, more concisely:</p> <pre><code>seen = set() uniq = [x for x in a if x not in seen and not seen.add(x)] </code></pre> <p>I don't recommend the latter style, because it is not obvious what <code>not seen.add(x)</code> is doing (the set <code>add()</code> method always returns <code>None</code>, hence the need for <code>not</code>).</p> <p>To compute the list of duplicated elements without libraries:</p> <pre><code>seen = set() dupes = [] for x in a: if x in seen: dupes.append(x) else: seen.add(x) </code></pre> <p>or, more concisely:</p> <pre><code>seen = set() dupes = [x for x in a if x in seen or seen.add(x)] </code></pre> <p>If list elements are not hashable, you cannot use sets/dicts and have to resort to a quadratic time solution (compare each with each). For example:</p> <pre><code>a = [[1], [2], [3], [1], [5], [3]] no_dupes = [x for n, x in enumerate(a) if x not in a[:n]] print no_dupes # [[1], [2], [3], [5]] dupes = [x for n, x in enumerate(a) if x in a[:n]] print dupes # [[1], [3]] </code></pre>
{ "question_id": 9835762, "question_date": "2012-03-23T07:59:59.350Z", "question_score": 634, "tags": "python|list|duplicates", "answer_id": 9835819, "answer_date": "2012-03-23T08:05:44.170Z", "answer_score": 852 }
Please answer the following Stack Overflow question: Title: Formatting a number with exactly two decimals in JavaScript <p>I have this line of code which rounds my numbers to two decimal places. But I get numbers like this: 10.8, 2.4, etc. These are not my idea of two decimal places so how I can improve the following?</p> <pre><code>Math.round(price*Math.pow(10,2))/Math.pow(10,2); </code></pre> <p>I want numbers like 10.80, 2.40, etc. Use of jQuery is fine with me.</p>
<p>To format a number using fixed-point notation, you can simply use the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number/toFixed" rel="noreferrer">toFixed</a> method:</p> <pre><code>(10.8).toFixed(2); // &quot;10.80&quot; var num = 2.4; alert(num.toFixed(2)); // &quot;2.40&quot; </code></pre> <p>Note that <code>toFixed()</code> returns a string.</p> <p><strong>IMPORTANT</strong>: Note that toFixed does not round 90% of the time, it will return the rounded value, but for many cases, it doesn't work.</p> <p>For instance:</p> <p><code>2.005.toFixed(2) === &quot;2.00&quot;</code></p> <h1>UPDATE:</h1> <p>Nowadays, you can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat" rel="noreferrer"><code>Intl.NumberFormat</code></a> constructor. It's part of the <a href="https://tc39.es/ecma402/" rel="noreferrer">ECMAScript Internationalization API Specification</a> (ECMA402). It has <a href="https://caniuse.com/#search=NumberFormat" rel="noreferrer">pretty good browser support</a>, including even IE11, and it is <a href="https://nodejs.org/api/intl.html" rel="noreferrer">fully supported in Node.js</a>.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const formatter = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, }); console.log(formatter.format(2.005)); // "2.01" console.log(formatter.format(1.345)); // "1.35"</code></pre> </div> </div> </p> <p>You can alternatively use the <code>toLocaleString</code> method, which internally will use the <code>Intl</code> API:</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 format = (num, decimals) =&gt; num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, }); console.log(format(2.005)); // "2.01" console.log(format(1.345)); // "1.35"</code></pre> </div> </div> </p> <p>This API also provides you a wide variety of options to format, like thousand separators, currency symbols, etc.</p>
{ "question_id": 1726630, "question_date": "2009-11-13T01:46:18.047Z", "question_score": 634, "tags": "javascript|rounding|decimal-point", "answer_id": 1726662, "answer_date": "2009-11-13T02:02:17.033Z", "answer_score": 1127 }
Please answer the following Stack Overflow question: Title: default select option as blank <p>I have a very weird requirement, wherein I am required to have no option selected by default in drop down menu in HTML. However,</p> <p>I cannot use 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-html lang-html prettyprint-override"><code>&lt;select&gt; &lt;option&gt;&lt;/option&gt; &lt;option&gt;Option 1&lt;/option&gt; &lt;option&gt;Option 2&lt;/option&gt; &lt;option&gt;Option 3&lt;/option&gt; &lt;/select&gt;</code></pre> </div> </div> </p> <p>Because, for this I will have to do validation to handle the first option. Can anyone help me in achieving this target without actually including the first option as part of the select tag? </p>
<p>Maybe this will be helpful</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;select&gt; &lt;option disabled selected value&gt; -- select an option -- &lt;/option&gt; &lt;option&gt;Option 1&lt;/option&gt; &lt;option&gt;Option 2&lt;/option&gt; &lt;option&gt;Option 3&lt;/option&gt; &lt;/select&gt;</code></pre> </div> </div> </p> <p><code>-- select an option --</code> Will be displayed by default. But if you choose an option, you will not be able to select it back.</p> <p>You can also hide it using by adding an empty <code>option</code></p> <p><code>&lt;option style=&quot;display:none&quot;&gt;</code></p> <p>so it won't show up in the list anymore.</p> <p><strong>Option 2</strong></p> <p>If you don't want to write CSS and expect the same behaviour of the solution above, just use:</p> <p><code>&lt;option hidden disabled selected value&gt; -- select an option -- &lt;/option&gt;</code></p>
{ "question_id": 8605516, "question_date": "2011-12-22T14:48:08.883Z", "question_score": 634, "tags": "html", "answer_id": 23638053, "answer_date": "2014-05-13T17:37:02.553Z", "answer_score": 1384 }
Please answer the following Stack Overflow question: Title: How do I use itertools.groupby()? <p>I haven't been able to find an understandable explanation of how to actually use Python's <code>itertools.groupby()</code> function. What I'm trying to do is this:</p> <ul> <li>Take a list - in this case, the children of an objectified <code>lxml</code> element</li> <li>Divide it into groups based on some criteria</li> <li>Then later iterate over each of these groups separately.</li> </ul> <p>I've reviewed <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="noreferrer">the documentation</a>, but I've had trouble trying to apply them beyond a simple list of numbers.</p> <p>So, how do I use of <code>itertools.groupby()</code>? Is there another technique I should be using? Pointers to good &quot;prerequisite&quot; reading would also be appreciated.</p>
<p><strong>IMPORTANT NOTE:</strong> You have to <strong>sort your data</strong> first.</p> <hr /> <p>The part I didn't get is that in the example construction</p> <pre><code>groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) </code></pre> <p><code>k</code> is the current grouping key, and <code>g</code> is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the <code>groupby</code> iterator itself returns iterators.</p> <p>Here's an example of that, using clearer variable names:</p> <pre><code>from itertools import groupby things = [(&quot;animal&quot;, &quot;bear&quot;), (&quot;animal&quot;, &quot;duck&quot;), (&quot;plant&quot;, &quot;cactus&quot;), (&quot;vehicle&quot;, &quot;speed boat&quot;), (&quot;vehicle&quot;, &quot;school bus&quot;)] for key, group in groupby(things, lambda x: x[0]): for thing in group: print(&quot;A %s is a %s.&quot; % (thing[1], key)) print(&quot;&quot;) </code></pre> <p>This will give you the output:</p> <blockquote> <p>A bear is a animal.<br /> A duck is a animal.</p> <p>A cactus is a plant.</p> <p>A speed boat is a vehicle.<br /> A school bus is a vehicle.</p> </blockquote> <p>In this example, <code>things</code> is a list of tuples where the first item in each tuple is the group the second item belongs to.</p> <p>The <code>groupby()</code> function takes two arguments: (1) the data to group and (2) the function to group it with.</p> <p>Here, <code>lambda x: x[0]</code> tells <code>groupby()</code> to use the first item in each tuple as the grouping key.</p> <p>In the above <code>for</code> statement, <code>groupby</code> returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group.</p> <p>Here's a slightly different example with the same data, using a list comprehension:</p> <pre><code>for key, group in groupby(things, lambda x: x[0]): listOfThings = &quot; and &quot;.join([thing[1] for thing in group]) print(key + &quot;s: &quot; + listOfThings + &quot;.&quot;) </code></pre> <p>This will give you the output:</p> <blockquote> <p>animals: bear and duck.<br /> plants: cactus.<br /> vehicles: speed boat and school bus.</p> </blockquote>
{ "question_id": 773, "question_date": "2008-08-03T18:27:09.687Z", "question_score": 634, "tags": "python|itertools", "answer_id": 7286, "answer_date": "2008-08-10T18:45:32.430Z", "answer_score": 812 }
Please answer the following Stack Overflow question: Title: ReactJS - Does render get called any time "setState" is called? <p>Does React re-render all components and sub components every time <code>setState()</code> is called?</p> <p>If so, why? I thought the idea was that React only rendered as little as needed - when state changed.</p> <p>In the following simple example, both classes render again when the text is clicked, despite the fact that the state doesn't change on subsequent clicks, as the onClick handler always sets the <code>state</code> to the same value:</p> <pre><code>this.setState({'test':'me'}); </code></pre> <p>I would've expected that renders would only happen if <code>state</code> data had changed.</p> <p>Here's the code of the example, <a href="http://jsfiddle.net/fp2tncmb/2/" rel="noreferrer">as a JS Fiddle</a>, and embedded snippet:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var TimeInChild = React.createClass({ render: function() { var t = new Date().getTime(); return ( &lt;p&gt;Time in child:{t}&lt;/p&gt; ); } }); var Main = React.createClass({ onTest: function() { this.setState({'test':'me'}); }, render: function() { var currentTime = new Date().getTime(); return ( &lt;div onClick={this.onTest}&gt; &lt;p&gt;Time in main:{currentTime}&lt;/p&gt; &lt;p&gt;Click me to update time&lt;/p&gt; &lt;TimeInChild/&gt; &lt;/div&gt; ); } }); ReactDOM.render(&lt;Main/&gt;, document.body);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
<blockquote> <p>Does React re-render all components and sub-components every time setState is called?</p> </blockquote> <p>By default - yes.</p> <p>There is a method <strong>boolean shouldComponentUpdate(object nextProps, object nextState)</strong>, each component has this method and it's responsible to determine "should component update (run <em>render</em> function)?" every time you change <em>state</em> or pass new <em>props</em> from parent component.</p> <p>You can write your own implementation of <em>shouldComponentUpdate</em> method for your component, but default implementation always returns true - meaning always re-run render function.</p> <p>Quote from official docs <a href="http://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate" rel="noreferrer">http://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate</a></p> <blockquote> <p>By default, shouldComponentUpdate always returns true to prevent subtle bugs when the state is mutated in place, but if you are careful to always treat the state as immutable and to read-only from props and state in render() then you can override shouldComponentUpdate with an implementation that compares the old props and state to their replacements.</p> </blockquote> <p>Next part of your question:</p> <blockquote> <p>If so, why? I thought the idea was that React only rendered as little as needed - when the state changed. </p> </blockquote> <p>There are two steps of what we may call "render":</p> <ol> <li><p>Virtual DOM renders: when <em>render</em> method is called it returns a new <em>virtual dom</em> structure of the component. As I mentioned before, this <em>render</em> method is called always when you call <em>setState()</em>, because <em>shouldComponentUpdate</em> always returns true by default. So, by default, there is no optimization here in React.</p></li> <li><p>Native DOM renders: React changes real DOM nodes in your browser only if they were changed in the Virtual DOM and as little as needed - this is that great React's feature which optimizes real DOM mutation and makes React fast.</p></li> </ol>
{ "question_id": 24718709, "question_date": "2014-07-13T01:11:07.950Z", "question_score": 634, "tags": "javascript|reactjs", "answer_id": 24719289, "answer_date": "2014-07-13T03:30:44.850Z", "answer_score": 656 }
Please answer the following Stack Overflow question: Title: Placing border inside of div and not on its edge <p>I have a <code>&lt;div&gt;</code> element and I want to put a border on it. I know I can write <code>style="border: 1px solid black"</code>, but this adds 2px to either side of the div, which is not what I want. </p> <p>I would rather have this border be -1px from the edge of the div. The div itself is 100px x 100px, and if I add a border, then I have to do some mathematics to make the border appear.</p> <p>Is there any way that I can make the border appear, and ensure the box will still be 100px (including the border)?</p>
<p>Set <code>box-sizing</code> property to <code>border-box</code>:</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>div { box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; width: 100px; height: 100px; border: 20px solid #f00; background: #00f; margin: 10px; } div + div { border: 10px solid red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt;Hello!&lt;/div&gt; &lt;div&gt;Hello!&lt;/div&gt;</code></pre> </div> </div> </p> <p>It works on <a href="http://caniuse.com/#search=box-sizing" rel="noreferrer">IE8 &amp; above</a>.</p>
{ "question_id": 9601357, "question_date": "2012-03-07T12:16:24.807Z", "question_score": 633, "tags": "html|css|border", "answer_id": 9601431, "answer_date": "2012-03-07T12:22:21.043Z", "answer_score": 776 }
Please answer the following Stack Overflow question: Title: Reset/remove CSS styles for element only <p>I'm sure this must have been mentioned/asked before but have been searching for an age with no luck, my terminology must be wrong!</p> <p><strong>I vaguely remember a tweet I saw a while ago that suggested that there was a css rule available that would remove any styles previously set in the stylesheet for a particular element.</strong></p> <p>A good use example might be in a mobile-first RWD site where much of the styling used for a particular element in the small-screen views needs 'resetting' or removing for the same element in the desktop view.</p> <p>A css rule that could achieve something like:</p> <pre><code>.element { all: none; } </code></pre> <p>Example usage:</p> <pre><code>/* mobile first */ .element { margin: 0 10; transform: translate3d(0, 0, 0); z-index: 50; display: block; etc.. etc.. } @media only screen and (min-width: 980px) { .element { all: none; } } </code></pre> <p>So we could quickly remove or re-set styling without having to declare every property.</p> <p><em>Makes sense?</em></p>
<p>The CSS3 keyword <code>initial</code> sets the <a href="http://www.w3.org/TR/css3-values/#keywords" rel="noreferrer">CSS3 property to the initial value as defined in the spec</a>. The <code>initial</code> keyword has <a href="https://caniuse.com/#feat=css-initial-value" rel="noreferrer">broad browser support</a> except for the IE and Opera Mini families.</p> <p>Since IE's lack of support may cause issue here are some of the ways you can reset some CSS properties to their initial values:</p> <pre><code>.reset-this { animation : none; animation-delay : 0; animation-direction : normal; animation-duration : 0; animation-fill-mode : none; animation-iteration-count : 1; animation-name : none; animation-play-state : running; animation-timing-function : ease; backface-visibility : visible; background : 0; background-attachment : scroll; background-clip : border-box; background-color : transparent; background-image : none; background-origin : padding-box; background-position : 0 0; background-position-x : 0; background-position-y : 0; background-repeat : repeat; background-size : auto auto; border : 0; border-style : none; border-width : medium; border-color : inherit; border-bottom : 0; border-bottom-color : inherit; border-bottom-left-radius : 0; border-bottom-right-radius : 0; border-bottom-style : none; border-bottom-width : medium; border-collapse : separate; border-image : none; border-left : 0; border-left-color : inherit; border-left-style : none; border-left-width : medium; border-radius : 0; border-right : 0; border-right-color : inherit; border-right-style : none; border-right-width : medium; border-spacing : 0; border-top : 0; border-top-color : inherit; border-top-left-radius : 0; border-top-right-radius : 0; border-top-style : none; border-top-width : medium; bottom : auto; box-shadow : none; box-sizing : content-box; caption-side : top; clear : none; clip : auto; color : inherit; columns : auto; column-count : auto; column-fill : balance; column-gap : normal; column-rule : medium none currentColor; column-rule-color : currentColor; column-rule-style : none; column-rule-width : none; column-span : 1; column-width : auto; content : normal; counter-increment : none; counter-reset : none; cursor : auto; direction : ltr; display : inline; empty-cells : show; float : none; font : normal; font-family : inherit; font-size : medium; font-style : normal; font-variant : normal; font-weight : normal; height : auto; hyphens : none; left : auto; letter-spacing : normal; line-height : normal; list-style : none; list-style-image : none; list-style-position : outside; list-style-type : disc; margin : 0; margin-bottom : 0; margin-left : 0; margin-right : 0; margin-top : 0; max-height : none; max-width : none; min-height : 0; min-width : 0; opacity : 1; orphans : 0; outline : 0; outline-color : invert; outline-style : none; outline-width : medium; overflow : visible; overflow-x : visible; overflow-y : visible; padding : 0; padding-bottom : 0; padding-left : 0; padding-right : 0; padding-top : 0; page-break-after : auto; page-break-before : auto; page-break-inside : auto; perspective : none; perspective-origin : 50% 50%; position : static; /* May need to alter quotes for different locales (e.g fr) */ quotes : '\201C' '\201D' '\2018' '\2019'; right : auto; tab-size : 8; table-layout : auto; text-align : inherit; text-align-last : auto; text-decoration : none; text-decoration-color : inherit; text-decoration-line : none; text-decoration-style : solid; text-indent : 0; text-shadow : none; text-transform : none; top : auto; transform : none; transform-style : flat; transition : none; transition-delay : 0s; transition-duration : 0s; transition-property : none; transition-timing-function : ease; unicode-bidi : normal; vertical-align : baseline; visibility : visible; white-space : normal; widows : 0; width : auto; word-spacing : normal; z-index : auto; /* basic modern patch */ all: initial; all: unset; } /* basic modern patch */ #reset-this-root { all: initial; * { all: unset; } } </code></pre> <ul> <li><a href="https://github.com/iamstarkov/css-initials" rel="noreferrer">Relevent github repo with a <em>december 2017</em> more exaustive list</a></li> <li><a href="https://stackoverflow.com/questions/8228980/reset-css-display-property-to-default-value">Related</a></li> <li><a href="https://developer.mozilla.org/en-US/docs/CSS/initial_value" rel="noreferrer">Related from MDN</a></li> <li><a href="http://www.w3.org/TR/css3-cascade/#initial" rel="noreferrer">Related W3C specs</a></li> </ul> <p>As mentioned in a comment by @user566245 :</p> <blockquote> <p>this is correct in principle, but individual mileage may vary. For example certain elements like textarea by default have a border, applying this reset will render those textarea's border less.</p> </blockquote> <hr /> <p>JAVASCRIPT ?</p> <p>Nobody thought about other than css to reset css? Yes?</p> <p>There is that snip fully relevant : <a href="https://stackoverflow.com/a/14791113/845310">https://stackoverflow.com/a/14791113/845310</a></p> <blockquote> <p>getElementsByTagName(&quot;*&quot;) will return all elements from DOM. Then you may set styles for each element in the collection:</p> </blockquote> <p><em>answered Feb 9 '13 at 20:15 by VisioN</em></p> <pre><code>var allElements = document.getElementsByTagName(&quot;*&quot;); for (var i = 0, len = allElements.length; i &lt; len; i++) { var element = allElements[i]; // element.style.border = ... } </code></pre> <hr /> <p>With all this said; i don't think a css reset is something feasable unless we end up with only one web browser .. if the 'default' is set by browser in the end.</p> <p>For comparison, here is Firefox 40.0 values list for a <code>&lt;blockquote style=&quot;all: unset;font-style: oblique&quot;&gt;</code> where <code>font-style: oblique</code> triggers DOM operation.</p> <pre><code>align-content: unset; align-items: unset; align-self: unset; animation: unset; appearance: unset; backface-visibility: unset; background-blend-mode: unset; background: unset; binding: unset; block-size: unset; border-block-end: unset; border-block-start: unset; border-collapse: unset; border-inline-end: unset; border-inline-start: unset; border-radius: unset; border-spacing: unset; border: unset; bottom: unset; box-align: unset; box-decoration-break: unset; box-direction: unset; box-flex: unset; box-ordinal-group: unset; box-orient: unset; box-pack: unset; box-shadow: unset; box-sizing: unset; caption-side: unset; clear: unset; clip-path: unset; clip-rule: unset; clip: unset; color-adjust: unset; color-interpolation-filters: unset; color-interpolation: unset; color: unset; column-fill: unset; column-gap: unset; column-rule: unset; columns: unset; content: unset; control-character-visibility: unset; counter-increment: unset; counter-reset: unset; cursor: unset; display: unset; dominant-baseline: unset; empty-cells: unset; fill-opacity: unset; fill-rule: unset; fill: unset; filter: unset; flex-flow: unset; flex: unset; float-edge: unset; float: unset; flood-color: unset; flood-opacity: unset; font-family: unset; font-feature-settings: unset; font-kerning: unset; font-language-override: unset; font-size-adjust: unset; font-size: unset; font-stretch: unset; font-style: oblique; font-synthesis: unset; font-variant: unset; font-weight: unset; font: ; force-broken-image-icon: unset; height: unset; hyphens: unset; image-orientation: unset; image-region: unset; image-rendering: unset; ime-mode: unset; inline-size: unset; isolation: unset; justify-content: unset; justify-items: unset; justify-self: unset; left: unset; letter-spacing: unset; lighting-color: unset; line-height: unset; list-style: unset; margin-block-end: unset; margin-block-start: unset; margin-inline-end: unset; margin-inline-start: unset; margin: unset; marker-offset: unset; marker: unset; mask-type: unset; mask: unset; max-block-size: unset; max-height: unset; max-inline-size: unset; max-width: unset; min-block-size: unset; min-height: unset; min-inline-size: unset; min-width: unset; mix-blend-mode: unset; object-fit: unset; object-position: unset; offset-block-end: unset; offset-block-start: unset; offset-inline-end: unset; offset-inline-start: unset; opacity: unset; order: unset; orient: unset; outline-offset: unset; outline-radius: unset; outline: unset; overflow: unset; padding-block-end: unset; padding-block-start: unset; padding-inline-end: unset; padding-inline-start: unset; padding: unset; page-break-after: unset; page-break-before: unset; page-break-inside: unset; paint-order: unset; perspective-origin: unset; perspective: unset; pointer-events: unset; position: unset; quotes: unset; resize: unset; right: unset; ruby-align: unset; ruby-position: unset; scroll-behavior: unset; scroll-snap-coordinate: unset; scroll-snap-destination: unset; scroll-snap-points-x: unset; scroll-snap-points-y: unset; scroll-snap-type: unset; shape-rendering: unset; stack-sizing: unset; stop-color: unset; stop-opacity: unset; stroke-dasharray: unset; stroke-dashoffset: unset; stroke-linecap: unset; stroke-linejoin: unset; stroke-miterlimit: unset; stroke-opacity: unset; stroke-width: unset; stroke: unset; tab-size: unset; table-layout: unset; text-align-last: unset; text-align: unset; text-anchor: unset; text-combine-upright: unset; text-decoration: unset; text-emphasis-position: unset; text-emphasis: unset; text-indent: unset; text-orientation: unset; text-overflow: unset; text-rendering: unset; text-shadow: unset; text-size-adjust: unset; text-transform: unset; top: unset; transform-origin: unset; transform-style: unset; transform: unset; transition: unset; user-focus: unset; user-input: unset; user-modify: unset; user-select: unset; vector-effect: unset; vertical-align: unset; visibility: unset; white-space: unset; width: unset; will-change: unset; window-dragging: unset; word-break: unset; word-spacing: unset; word-wrap: unset; writing-mode: unset; z-index: unset; </code></pre>
{ "question_id": 15901030, "question_date": "2013-04-09T11:49:16.573Z", "question_score": 633, "tags": "css", "answer_id": 15903168, "answer_date": "2013-04-09T13:23:10.027Z", "answer_score": 719 }
Please answer the following Stack Overflow question: Title: Regex Match all characters between two strings <p>Example: <code>This is just\na simple sentence</code>.</p> <p>I want to match every character between <code>This is</code> and <code>sentence</code>. Line breaks should be ignored. I can't figure out the correct syntax.</p>
<p>For example</p> <pre><code>(?&lt;=This is)(.*)(?=sentence) </code></pre> <p><a href="http://regexr.com?2tr28" rel="noreferrer">Regexr</a></p> <p>I used lookbehind <code>(?&lt;=)</code> and look ahead <code>(?=)</code> so that "This is" and "sentence" is not included in the match, but this is up to your use case, you can also simply write <code>This is(.*)sentence</code>.</p> <p>The important thing here is that you activate the "dotall" mode of your regex engine, so that the <code>.</code> is matching the newline. But how you do this depends on your regex engine.</p> <p>The next thing is if you use <code>.*</code> or <code>.*?</code>. The first one is greedy and will match till the last "sentence" in your string, the second one is lazy and will match till the next "sentence" in your string.</p> <p><strong>Update</strong></p> <p><a href="http://gskinner.com/RegExr/?2tr2n" rel="noreferrer">Regexr</a></p> <pre><code>This is(?s)(.*)sentence </code></pre> <p>Where the (?s) turns on the dotall modifier, making the <code>.</code> matching the newline characters.</p> <p><strong>Update 2:</strong></p> <pre><code>(?&lt;=is \()(.*?)(?=\s*\)) </code></pre> <p>is matching your example "This is (a simple) sentence". See here on <a href="http://regexr.com?2tr5t" rel="noreferrer">Regexr</a></p>
{ "question_id": 6109882, "question_date": "2011-05-24T11:45:58.417Z", "question_score": 633, "tags": "regex", "answer_id": 6110113, "answer_date": "2011-05-24T12:05:51.200Z", "answer_score": 951 }
Please answer the following Stack Overflow question: Title: How to get all possible combinations of a list’s elements? <p>I have a list with 15 numbers, and I need to write some code that produces all 32,768 combinations of those numbers.</p> <p>I've found <a href="http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/" rel="nofollow noreferrer">some code</a> (by Googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.</p> <p>The only thing that occurs to me would be to just loop through the decimal integers 1–32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers.</p> <p>Does anyone know of a better way? Using <code>map()</code>, maybe?</p>
<p>Have a look at <a href="http://docs.python.org/library/itertools.html#itertools.combinations" rel="noreferrer">itertools.combinations</a>:</p> <blockquote> <pre><code>itertools.combinations(iterable, r) </code></pre> <p>Return r length subsequences of elements from the input iterable.</p> <p>Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.</p> </blockquote> <p>Since 2.6, batteries are included!</p>
{ "question_id": 464864, "question_date": "2009-01-21T11:13:40.053Z", "question_score": 633, "tags": "python|combinations", "answer_id": 464882, "answer_date": "2009-01-21T11:20:04.160Z", "answer_score": 648 }
Please answer the following Stack Overflow question: Title: MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client <p>I can't make a simple connection to the server for some reason. I install the newest MySQL Community 8.0 database along with Node.JS with default settings.</p> <p><strong>This is my node.js code</strong></p> <pre><code> var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "password", insecureAuth : true }); con.connect(function(err) { if (err) throw err; console.log("Connected!"); }); </code></pre> <p><strong>Below is the error found in Command Prompt:</strong></p> <pre><code>C:\Users\mysql-test&gt;node app.js C:\Users\mysql-test\node_modules\mysql\lib\protocol\Parse r.js:80 throw err; // Rethrow non-MySQL errors ^ Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client at Handshake.Sequence._packetToError (C:\Users\mysql- test\node_modules\mysql\lib\protocol\sequences\Sequence.js:52:14) at Handshake.ErrorPacket (C:\Users\mysql-test\node_mo dules\mysql\lib\protocol\sequences\Handshake.js:130:18) at Protocol._parsePacket (C:\Users\mysql-test\node_mo dules\mysql\lib\protocol\Protocol.js:279:23) at Parser.write (C:\Users\mysql-test\node_modules\mys ql\lib\protocol\Parser.js:76:12) at Protocol.write (C:\Users\mysql-test\node_modules\m ysql\lib\protocol\Protocol.js:39:16) at Socket.&lt;anonymous&gt; (C:\Users\mysql-test\node_modul es\mysql\lib\Connection.js:103:28) at Socket.emit (events.js:159:13) at addChunk (_stream_readable.js:265:12) at readableAddChunk (_stream_readable.js:252:11) at Socket.Readable.push (_stream_readable.js:209:10) -------------------- at Protocol._enqueue (C:\Users\mysql-test\node_module s\mysql\lib\protocol\Protocol.js:145:48) at Protocol.handshake (C:\Users\mysql-test\node_modul es\mysql\lib\protocol\Protocol.js:52:23) at Connection.connect (C:\Users\mysql-test\node_modul es\mysql\lib\Connection.js:130:18) at Object.&lt;anonymous&gt; (C:\Users\mysql-test\server.js: 11:5) at Module._compile (module.js:660:30) at Object.Module._extensions..js (module.js:671:10) at Module.load (module.js:573:32) at tryModuleLoad (module.js:513:12) at Function.Module._load (module.js:505:3) at Function.Module.runMain (module.js:701:10) </code></pre> <p>I've read up on some things such as: <a href="https://dev.mysql.com/doc/refman/5.5/en/old-client.html" rel="noreferrer">https://dev.mysql.com/doc/refman/5.5/en/old-client.html</a> <a href="https://github.com/mysqljs/mysql/issues/1507" rel="noreferrer">https://github.com/mysqljs/mysql/issues/1507</a></p> <p>But I am still not sure how to fix my problem. Any help would be appreciated :D</p>
<p>Execute the following query in MYSQL Workbench</p> <p><code>ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';</code></p> <p>Where <code>root</code> as your user <code>localhost</code> as your URL and <code>password</code> as your password</p> <p>Then run this query to refresh privileges:</p> <p><code>flush privileges;</code></p> <p>Try connecting using node after you do so.</p> <p>If that doesn't work, try it without <code>@'localhost'</code> part.</p>
{ "question_id": 50093144, "question_date": "2018-04-30T02:04:31.957Z", "question_score": 633, "tags": "mysql|node.js", "answer_id": 50131831, "answer_date": "2018-05-02T09:58:11.230Z", "answer_score": 1606 }
Please answer the following Stack Overflow question: Title: Redis command to get all available keys? <p>Is there a Redis command for fetching all keys in the database? I have seen some python-redis libraries fetching them. But was wondering if it is possible from redis-client.</p>
<p>Try to look at <a href="http://redis.io/commands/keys" rel="noreferrer"><code>KEYS</code></a> command. <code>KEYS *</code> will list all keys stored in redis.</p> <p><strong>EDIT:</strong> please note the warning at the top of <code>KEYS</code> documentation page:</p> <blockquote> <p><strong>Time complexity:</strong> O(N) with N being the number of keys in the database, under the assumption that the key names in the database and the given pattern have limited length.</p> </blockquote> <p><strong>UPDATE (V2.8 or greater):</strong> <a href="https://redis.io/commands/scan" rel="noreferrer"><code>SCAN</code></a> is a superior alternative to <code>KEYS</code>, in the sense that it does not block the server nor does it consume significant resources. Prefer using it. </p>
{ "question_id": 5252099, "question_date": "2011-03-09T21:00:35.557Z", "question_score": 633, "tags": "redis|redis-cli|redis-commands", "answer_id": 5252511, "answer_date": "2011-03-09T21:40:41.547Z", "answer_score": 878 }
Please answer the following Stack Overflow question: Title: CSS display: inline vs inline-block <p>In CSS, <code>display</code> can have values of <code>inline</code> and <code>inline-block</code>. Can anyone explain in detail the difference between <code>inline</code> and <code>inline-block</code>?</p> <p>I searched everywhere, the most detailed explanation tells me <code>inline-block</code> is placed as <code>inline</code>, but behaves like <code>block</code>. But it does not explain what exactly "behave as a block" means. Is it any special feature?</p> <p>An example would be an even better answer. Thanks.</p>
<p>Inline elements:</p> <ol> <li>respect left &amp; right margins and padding, but <strong>not</strong> top &amp; bottom</li> <li><strong>cannot</strong> have a width and height set</li> <li>allow other elements to sit to their left and right.</li> <li>see very important side notes on this <a href="https://hacks.mozilla.org/2015/03/understanding-inline-box-model/" rel="noreferrer" title="mozzila docs">here</a>.</li> </ol> <p>Block elements:</p> <ol> <li>respect all of those</li> <li>force a line break after the block element</li> <li>acquires full-width if width not defined</li> </ol> <p>Inline-block elements:</p> <ol> <li>allow other elements to sit to their left and right</li> <li>respect top &amp; bottom margins and padding</li> <li>respect height and width</li> </ol> <p>From <a href="http://www.w3schools.com/cssref/pr_class_display.asp" rel="noreferrer">W3Schools</a>:</p> <blockquote> <ul> <li><p>An inline element has no line break before or after it, and it tolerates HTML elements next to it.</p> </li> <li><p>A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.</p> </li> <li><p>An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.</p> </li> </ul> </blockquote> <p>When you visualize this, it looks like this:</p> <p><img src="https://i.stack.imgur.com/mGTYI.png" alt="CSS block vs inline vs inline-block" /></p> <p>The image is taken from <a href="http://dustwell.com/div-span-inline-block.html" rel="noreferrer">this page</a>, which also talks some more about this subject.</p>
{ "question_id": 9189810, "question_date": "2012-02-08T08:24:15.330Z", "question_score": 633, "tags": "css", "answer_id": 9189873, "answer_date": "2012-02-08T08:30:06.697Z", "answer_score": 1305 }
Please answer the following Stack Overflow question: Title: How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)? <p>Question: is there a simple sh/bash/zsh/fish/... command to print the absolute path of whichever file I feed it?</p> <p>Usage case: I'm in directory <code>/a/b</code> and I'd like to print the full path to file <code>c</code> on the command-line so that I can easily paste it into another program: <code>/a/b/c</code>. Simple, yet a little program to do this could probably save me 5 or so seconds when it comes to handling long paths, which in the end adds up. So it surprises me that I can't find a standard utility to do this — is there really none?</p> <p>Here's a sample implementation, abspath.py:</p> <pre><code>#!/usr/bin/python # Author: Diggory Hardy &lt;[email protected]&gt; # Licence: public domain # Purpose: print the absolute path of all input paths import sys import os.path if len(sys.argv)&gt;1: for i in range(1,len(sys.argv)): print os.path.abspath( sys.argv[i] ) sys.exit(0) else: print &gt;&gt; sys.stderr, "Usage: ",sys.argv[0]," PATH." sys.exit(1) </code></pre>
<p>Use <a href="https://man7.org/linux/man-pages/man1/realpath.1.html" rel="noreferrer"><code>realpath</code></a></p> <pre><code>$ realpath example.txt /home/username/example.txt </code></pre>
{ "question_id": 3915040, "question_date": "2010-10-12T13:12:09.800Z", "question_score": 633, "tags": "bash|shell|path", "answer_id": 3915075, "answer_date": "2010-10-12T13:16:11.753Z", "answer_score": 848 }
Please answer the following Stack Overflow question: Title: "Find next" in Vim <p>To search forward in Vim for <code>cake</code>, I'd type <code>/cake</code>, but the cursor jumps to the first match when I press return. <strong>Is there a Vim command analogous to "find next"?</strong></p>
<p>It is <kbd>n</kbd> for next and <kbd>N</kbd> for previous.</p> <p>And if you use reverse search with <code>?</code> (for example, <code>?cake</code>) instead of <code>/</code>, it is the other way round.</p> <p>If it is installed on your system, you should try to run <code>vimtutor</code> command from your terminal, which will start a tutorial of the basic Vim commands.</p> <p><a href="https://stackoverflow.com/a/6607664">Rob Wells advice</a> about <kbd>*</kbd> and <kbd>#</kbd> is also very pertinent.</p>
{ "question_id": 6607630, "question_date": "2011-07-07T08:11:06.020Z", "question_score": 633, "tags": "vim|editing", "answer_id": 6607635, "answer_date": "2011-07-07T08:12:07.517Z", "answer_score": 1033 }
Please answer the following Stack Overflow question: Title: Retrieve the commit log for a specific line in a file? <p>Is there any way to get git to give you a commit log for just commits that touched a particular <em>line</em> in a file?</p> <p>Like <code>git blame</code>, but <code>git blame</code> will show you the LAST commit that touched a particular line. </p> <p>I'd really like to get a similar log of, not the list of commits to anywhere in the file, but just the commits that touched a particular line.</p>
<p>See also <a href="https://stackoverflow.com/questions/14142609/git-discover-which-commits-ever-touched-a-range-of-lines">Git: discover which commits ever touched a range of lines</a>.</p> <hr> <p><a href="https://github.com/git/git/blob/v1.8.4/Documentation/RelNotes/1.8.4.txt#L210" rel="noreferrer">Since Git 1.8.4</a>, <code>git log</code> has <a href="https://github.com/git/git/blob/v1.8.4/Documentation/RelNotes/1.8.4.txt#L210" rel="noreferrer"><code>-L</code></a> to view the evolution of a range of lines.</p> <p>For example, suppose you look at <code>git blame</code>'s output. Here <a href="https://git-scm.com/docs/git-blame#git-blame--Lltstartgtltendgt" rel="noreferrer"><code>-L 150,+11</code></a> means "only look at the lines 150 to 150+11":</p> <pre><code>$ git blame -L 150,+11 -- git-web--browse.sh a180055a git-web--browse.sh (Giuseppe Bilotta 2010-12-03 17:47:36 +0100 150) die "The browser $browser is not a180055a git-web--browse.sh (Giuseppe Bilotta 2010-12-03 17:47:36 +0100 151) fi 5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 152) fi 5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 153) 5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 154) case "$browser" in 81f42f11 git-web--browse.sh (Giuseppe Bilotta 2010-12-03 17:47:38 +0100 155) firefox|iceweasel|seamonkey|iceape) 5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 156) # Check version because firefox &lt; 2.0 do 5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 157) vers=$(expr "$($browser_path -version)" 5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 158) NEWTAB='-new-tab' 5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 159) test "$vers" -lt 2 &amp;&amp; NEWTAB='' a0685a4f git-web--browse.sh (Dmitry Potapov 2008-02-09 23:22:22 -0800 160) "$browser_path" $NEWTAB "$@" &amp; </code></pre> <p>And you want to know the history of what is now line 155.</p> <p>Then, use <code>git log</code>. Here, <code>-L 155,155:git-web--browse.sh</code> means "trace the evolution of lines 155 to 155 in the file named <code>git-web--browse.sh</code>".</p> <pre><code>$ git log --pretty=short -u -L 155,155:git-web--browse.sh commit 81f42f11496b9117273939c98d270af273c8a463 Author: Giuseppe Bilotta &lt;[email protected]&gt; web--browse: support opera, seamonkey and elinks diff --git a/git-web--browse.sh b/git-web--browse.sh --- a/git-web--browse.sh +++ b/git-web--browse.sh @@ -143,1 +143,1 @@ -firefox|iceweasel) +firefox|iceweasel|seamonkey|iceape) commit a180055a47c6793eaaba6289f623cff32644215b Author: Giuseppe Bilotta &lt;[email protected]&gt; web--browse: coding style diff --git a/git-web--browse.sh b/git-web--browse.sh --- a/git-web--browse.sh +++ b/git-web--browse.sh @@ -142,1 +142,1 @@ - firefox|iceweasel) +firefox|iceweasel) commit 5884f1fe96b33d9666a78e660042b1e3e5f9f4d9 Author: Christian Couder &lt;[email protected]&gt; Rename 'git-help--browse.sh' to 'git-web--browse.sh'. diff --git a/git-web--browse.sh b/git-web--browse.sh --- /dev/null +++ b/git-web--browse.sh @@ -0,0 +127,1 @@ + firefox|iceweasel) </code></pre>
{ "question_id": 8435343, "question_date": "2011-12-08T17:51:47.933Z", "question_score": 633, "tags": "git", "answer_id": 19757493, "answer_date": "2013-11-03T20:08:22.937Z", "answer_score": 785 }
Please answer the following Stack Overflow question: Title: How to iterate over a list in chunks <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p> <pre><code>for i in range(0, len(ints), 4): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like &quot;C-think&quot;, though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite &quot;feel&quot; right, though. :-/</p> <p>Related question: <a href="https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
<p>Modified from the <a href="https://docs.python.org/library/itertools.html#itertools-recipes" rel="noreferrer">Recipes</a> section of Python's <a href="http://docs.python.org/library/itertools.html" rel="noreferrer"><code>itertools</code></a> docs:</p> <pre><code>from itertools import zip_longest def grouper(iterable, n, fillvalue=None): args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) </code></pre> <p><strong>Example</strong></p> <pre><code>grouper('ABCDEFG', 3, 'x') # --&gt; 'ABC' 'DEF' 'Gxx' </code></pre> <p><strong>Note:</strong> on Python 2 use <code>izip_longest</code> instead of <code>zip_longest</code>.</p>
{ "question_id": 434287, "question_date": "2009-01-12T02:48:22.960Z", "question_score": 633, "tags": "python|list|loops|optimization|chunks", "answer_id": 434411, "answer_date": "2009-01-12T04:07:20.850Z", "answer_score": 414 }
Please answer the following Stack Overflow question: Title: What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”? <p>I have been reading a lot of Javascript lately and I have been noticing that the whole file is wrapped like the following in the .js files to be imported.</p> <pre><code>(function() { ... code ... })(); </code></pre> <p>What is the reason for doing this rather than a simple set of constructor functions?</p>
<p>It's usually to namespace (see later) and control the visibility of member functions and/or variables. Think of it like an object definition. The technical name for it is an <strong>Immediately Invoked Function Expression</strong> (IIFE). jQuery plugins are usually written like this.</p> <p>In Javascript, you can nest functions. So, the following is legal:</p> <pre><code>function outerFunction() { function innerFunction() { // code } } </code></pre> <p>Now you can call <code>outerFunction()</code>, but the visiblity of <code>innerFunction()</code> is limited to the scope of <code>outerFunction()</code>, meaning it is private to <code>outerFunction()</code>. It basically follows the same principle as variables in Javascript:</p> <pre><code>var globalVariable; function someFunction() { var localVariable; } </code></pre> <p>Correspondingly:</p> <pre><code>function globalFunction() { var localFunction1 = function() { //I'm anonymous! But localFunction1 is a reference to me! }; function localFunction2() { //I'm named! } } </code></pre> <p>In the above scenario, you can call <code>globalFunction()</code> from anywhere, but you cannot call <code>localFunction1</code> or <code>localFunction2</code>.</p> <p>What you're doing when you write <code>(function() { ... })()</code>, is you're making the code inside the first set of parentheses a function literal (meaning the whole "object" is actually a function). After that, you're self-invoking the function (the final <code>()</code>) that you just defined. So the major advantage of this as I mentioned before, is that you can have private methods/functions and properties:</p> <pre><code>(function() { var private_var; function private_function() { //code } })(); </code></pre> <p>In the first example, you would explicitly invoke <code>globalFunction</code> by name to run it. That is, you would just do <code>globalFunction()</code> to run it. But in the above example, you're not just defining a function; you're defining <em>and</em> invoking it in one go. This means that when the your JavaScript file is loaded, it is immediately executed. Of course, you could do:</p> <pre><code>function globalFunction() { // code } globalFunction(); </code></pre> <p>The behavior would largely be the same except for one significant difference: you avoid polluting the global scope when you use an IIFE (as a consequence it also means that you cannot invoke the function multiple times since it doesn't have a name, but since this function is only meant to be executed once it really isn't an issue).</p> <p>The neat thing with IIFEs is that you can also define things inside and only expose the parts that you want to the outside world so (an example of namespacing so you can basically create your own library/plugin):</p> <pre><code>var myPlugin = (function() { var private_var; function private_function() { } return { public_function1: function() { }, public_function2: function() { } } })() </code></pre> <p>Now you can call <code>myPlugin.public_function1()</code>, but you cannot access <code>private_function()</code>! So pretty similar to a class definition. To understand this better, I recommend the following links for some further reading:</p> <ul> <li><a href="http://archive.is/yXtVK" rel="noreferrer">Namespacing your Javascript</a></li> <li><a href="http://www.crockford.com/javascript/private.html" rel="noreferrer">Private members in Javascript (by Douglas Crockford)</a></li> </ul> <p><strong>EDIT</strong></p> <p>I forgot to mention. In that final <code>()</code>, you can pass anything you want inside. For example, when you create jQuery plugins, you pass in <code>jQuery</code> or <code>$</code> like so: </p> <pre><code>(function(jQ) { ... code ... })(jQuery) </code></pre> <p>So what you're doing here is defining a function that takes in one parameter (called <code>jQ</code>, a local variable, and known <em>only</em> to that function). Then you're self-invoking the function and passing in a parameter (also called <code>jQuery</code>, but <em>this</em> one is from the outside world and a reference to the actual jQuery itself). There is no pressing need to do this, but there are some advantages:</p> <ul> <li>You can redefine a global parameter and give it a name that makes sense in the local scope.</li> <li>There is a slight performance advantage since it is faster to look things up in the local scope instead of having to walk up the scope chain into the global scope.</li> <li>There are benefits for compression (minification).</li> </ul> <p>Earlier I described how these functions run automatically at startup, but if they run automatically who is passing in the arguments? This technique assumes that all the parameters you need are already defined as global variables. So if jQuery wasn't already defined as a global variable this example would not work. As you might guess, one things jquery.js does during its initialization is define a 'jQuery' global variable, as well as its more famous '$' global variable, which allows this code to work after jQuery has been included.</p>
{ "question_id": 2421911, "question_date": "2010-03-11T01:20:01.773Z", "question_score": 633, "tags": "javascript|scope|coding-style|iife", "answer_id": 2421949, "answer_date": "2010-03-11T01:32:59.407Z", "answer_score": 842 }
Please answer the following Stack Overflow question: Title: Finding the average of a list <p>How do I find the mean average of a list in Python?</p> <pre><code>[1, 2, 3, 4] ⟶ 2.5 </code></pre>
<p>For Python 3.8+, use <a href="https://docs.python.org/3/library/statistics.html#statistics.fmean" rel="noreferrer"><code>statistics.fmean</code></a> for numerical stability with floats. (Fast.)</p> <p>For Python 3.4+, use <a href="https://docs.python.org/3/library/statistics.html#statistics.mean" rel="noreferrer"><code>statistics.mean</code></a> for numerical stability with floats. (Slower.)</p> <pre><code>xs = [15, 18, 2, 36, 12, 78, 5, 6, 9] import statistics statistics.mean(xs) # = 20.11111111111111 </code></pre> <p>For older versions of Python 3, use</p> <pre><code>sum(xs) / len(xs) </code></pre> <p>For Python 2, convert <code>len</code> to a float to get float division:</p> <pre><code>sum(xs) / float(len(xs)) </code></pre>
{ "question_id": 9039961, "question_date": "2012-01-27T20:58:18.307Z", "question_score": 632, "tags": "python|list|average|mean|reduce", "answer_id": 9039992, "answer_date": "2012-01-27T21:00:36.237Z", "answer_score": 776 }
Please answer the following Stack Overflow question: Title: Define a global variable in a JavaScript function <p>Is it possible to define a global variable in a JavaScript function?</p> <p>I want use the <code>trailimage</code> variable (declared in the <code>makeObj</code> function) in other functions.</p> <pre><code>&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt; &lt;head id=&quot;Head1&quot; runat=&quot;server&quot;&gt; &lt;title&gt;&lt;/title&gt; &lt;script type=&quot;text/javascript&quot;&gt; var offsetfrommouse = [10, -20]; var displayduration = 0; var obj_selected = 0; function makeObj(address) { **var trailimage = [address, 50, 50];** document.write('&lt;img id=&quot;trailimageid&quot; src=&quot;' + trailimage[0] + '&quot; border=&quot;0&quot; style=&quot; position: absolute; visibility:visible; left: 0px; top: 0px; width: ' + trailimage[1] + 'px; height: ' + trailimage[2] + 'px&quot;&gt;'); obj_selected = 1; } function truebody() { return (!window.opera &amp;&amp; document.compatMode &amp;&amp; document.compatMode != &quot;BackCompat&quot;) ? document.documentElement : document.body; } function hidetrail() { var x = document.getElementById(&quot;trailimageid&quot;).style; x.visibility = &quot;hidden&quot;; document.onmousemove = &quot;&quot;; } function followmouse(e) { var xcoord = offsetfrommouse[0]; var ycoord = offsetfrommouse[1]; var x = document.getElementById(&quot;trailimageid&quot;).style; if (typeof e != &quot;undefined&quot;) { xcoord += e.pageX; ycoord += e.pageY; } else if (typeof window.event != &quot;undefined&quot;) { xcoord += truebody().scrollLeft + event.clientX; ycoord += truebody().scrollTop + event.clientY; } var docwidth = 1395; var docheight = 676; if (xcoord + trailimage[1] + 3 &gt; docwidth || ycoord + trailimage[2] &gt; docheight) { x.display = &quot;none&quot;; alert(&quot;inja&quot;); } else x.display = &quot;&quot;; x.left = xcoord + &quot;px&quot;; x.top = ycoord + &quot;px&quot;; } if (obj_selected = 1) { alert(&quot;obj_selected = true&quot;); document.onmousemove = followmouse; if (displayduration &gt; 0) setTimeout(&quot;hidetrail()&quot;, displayduration * 1000); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form id=&quot;form1&quot; runat=&quot;server&quot;&gt; &lt;img alt=&quot;&quot; id=&quot;house&quot; src=&quot;Pictures/sides/right.gif&quot; style=&quot;z-index: 1; left: 372px; top: 219px; position: absolute; height: 138px; width: 120px&quot; onclick=&quot;javascript:makeObj('Pictures/sides/sides-not-clicked.gif');&quot; /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>As the others have said, you can use <code>var</code> at global scope (outside of all functions and modules) to declare a global variable:</p> <pre><code>&lt;script&gt; var yourGlobalVariable; function foo() { // ... } &lt;/script&gt; </code></pre> <p>(Note that that's only true at <em>global</em> scope. If that code were in a module — <code>&lt;script type=&quot;module&quot;&gt;...&lt;/script&gt;</code> — it wouldn't be at global scope, so that wouldn't create a global.)</p> <p>Alternatively:</p> <p>In modern environments, you can assign to a property on the object that <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis" rel="noreferrer"><code>globalThis</code></a> refers to (<code>globalThis</code> was added in ES2020):</p> <pre><code>&lt;script&gt; function foo() { globalThis.yourGlobalVariable = ...; } &lt;/script&gt; </code></pre> <p>On browsers, you can do the same thing with the global called <code>window</code>:</p> <pre><code>&lt;script&gt; function foo() { window.yourGlobalVariable = ...; } &lt;/script&gt; </code></pre> <p>...because in browsers, <s>all global variables</s> global variables declared with <code>var</code> are properties of the <code>window</code> object. (In the latest specification, ECMAScript 2015, the new <code>let</code>, <code>const</code>, and <code>class</code> statements at global scope create globals that aren't properties of the global object; a new concept in ES2015.)</p> <p>(There's also <a href="http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html" rel="noreferrer">the horror of implicit globals</a>, but don't do it on purpose and do your best to avoid doing it by accident, perhaps by using ES5's <code>&quot;use strict&quot;</code>.)</p> <p>All that said: I'd avoid global variables if you possibly can (and you almost certainly can). As I mentioned, they end up being properties of <code>window</code>, and <code>window</code> is already <a href="http://www.w3.org/TR/Window/" rel="noreferrer"><em>plenty crowded enough</em></a> what with all elements with an <code>id</code> (and many with just a <code>name</code>) being dumped in it (and regardless that upcoming specification, IE dumps just about anything with a <code>name</code> on there).</p> <p>Instead, in modern environments, use modules:</p> <pre><code>&lt;script type=&quot;module&quot;&gt; let yourVariable = 42; // ... &lt;/script&gt; </code></pre> <p>The top level code in a module is at module scope, not global scope, so that creates a variable that all of the code in that module can see, but that isn't global.</p> <p>In obsolete environments without module support, wrap your code in a scoping function and use variables local to that scoping function, and make your other functions closures within it:</p> <pre><code>&lt;script&gt; (function() { // Begin scoping function var yourGlobalVariable; // Global to your code, invisible outside the scoping function function foo() { // ... } })(); // End scoping function &lt;/script&gt; </code></pre>
{ "question_id": 5786851, "question_date": "2011-04-26T06:36:57.937Z", "question_score": 632, "tags": "javascript|function|variables|scope|declaration", "answer_id": 5786899, "answer_date": "2011-04-26T06:44:30.643Z", "answer_score": 882 }
Please answer the following Stack Overflow question: Title: MySQL - UPDATE query based on SELECT Query <p>I need to check (from the same table) if there is an association between two events based on date-time.</p> <p>One set of data will contain the ending date-time of certain events and the other set of data will contain the starting date-time for other events.</p> <p>If the first event completes before the second event then I would like to link them up.</p> <p>What I have so far is:</p> <pre><code>SELECT name as name_A, date-time as end_DTS, id as id_A FROM tableA WHERE criteria = 1 SELECT name as name_B, date-time as start_DTS, id as id_B FROM tableA WHERE criteria = 2 </code></pre> <p>Then I join them:</p> <pre><code>SELECT name_A, name_B, id_A, id_B, if(start_DTS &gt; end_DTS,'VALID','') as validation_check FROM tableA LEFT JOIN tableB ON name_A = name_B </code></pre> <p>Can I then, based on my validation_check field, run a UPDATE query with the SELECT nested?</p>
<p>You can actually do this one of two ways:</p> <p>MySQL update join syntax:</p> <pre><code>UPDATE tableA a INNER JOIN tableB b ON a.name_a = b.name_b SET validation_check = if(start_dts &gt; end_dts, 'VALID', '') -- where clause can go here </code></pre> <p>ANSI SQL syntax:</p> <pre><code>UPDATE tableA SET validation_check = (SELECT if(start_DTS &gt; end_DTS, 'VALID', '') AS validation_check FROM tableA INNER JOIN tableB ON name_A = name_B WHERE id_A = tableA.id_A) </code></pre> <p>Pick whichever one seems most natural to you.</p>
{ "question_id": 1262786, "question_date": "2009-08-11T20:39:40.993Z", "question_score": 632, "tags": "mysql|select|sql-update", "answer_id": 1262848, "answer_date": "2009-08-11T20:53:47.157Z", "answer_score": 1001 }
Please answer the following Stack Overflow question: Title: How do I restore a dump file from mysqldump? <p>I was given a MySQL database file that I need to restore as a database on my Windows Server 2008 machine.</p> <p>I tried using MySQL Administrator, but I got the following error:</p> <blockquote> <p>The selected file was generated by mysqldump and cannot be restored by this application.</p> </blockquote> <p>How do I get this working?</p>
<p>It should be as simple as running this: </p> <pre><code>mysql -u &lt;user&gt; -p &lt; db_backup.dump </code></pre> <p>If the dump is of a single database you may have to add a line at the top of the file:</p> <pre><code>USE &lt;database-name-here&gt;; </code></pre> <p>If it was a dump of many databases, the use statements are already in there.</p> <p>To run these commands, open up a command prompt (in Windows) and <code>cd</code> to the directory where the <code>mysql.exe</code> executable is (you may have to look around a bit for it, it'll depend on how you installed mysql, i.e. standalone or as part of a package like WAMP). Once you're in that directory, you should be able to just type the command as I have it above.</p>
{ "question_id": 105776, "question_date": "2008-09-19T21:27:00.673Z", "question_score": 632, "tags": "mysql|sql|database", "answer_id": 105798, "answer_date": "2008-09-19T21:29:38.840Z", "answer_score": 656 }
Please answer the following Stack Overflow question: Title: Inserting a PDF file in LaTeX <p>I am trying to insert a PDF or doc file as an appendix in my LaTeX file. Do you know how I can do this?</p>
<p>Use the <a href="http://www.ctan.org/pkg/pdfpages" rel="noreferrer"><code>pdfpages</code></a> package.</p> <pre><code>\usepackage{pdfpages} </code></pre> <p>To include all the pages in the PDF file:</p> <pre><code>\includepdf[pages=-]{myfile.pdf} </code></pre> <p>To include just the first page of a PDF:</p> <pre><code>\includepdf[pages={1}]{myfile.pdf} </code></pre> <p>Run <code>texdoc pdfpages</code> in a shell to see the complete manual for <code>pdfpages</code>.</p>
{ "question_id": 2739159, "question_date": "2010-04-29T16:48:51.280Z", "question_score": 632, "tags": "pdf|latex|include", "answer_id": 2739710, "answer_date": "2010-04-29T18:16:42.770Z", "answer_score": 913 }
Please answer the following Stack Overflow question: Title: Algorithm to return all combinations of k elements from n <p>I want to write a function that takes an array of letters as an argument and a number of those letters to select. </p> <p>Say you provide an array of 8 letters and want to select 3 letters from that. Then you should get:</p> <pre><code>8! / ((8 - 3)! * 3!) = 56 </code></pre> <p>Arrays (or words) in return consisting of 3 letters each.</p>
<p><a href="http://portal.acm.org/citation.cfm?id=1036677&amp;dl=&amp;coll=" rel="noreferrer">Art of Computer Programming Volume 4: Fascicle 3</a> has a ton of these that might fit your particular situation better than how I describe.</p> <h2>Gray Codes</h2> <p>An issue that you will come across is of course memory and pretty quickly, you'll have problems by 20 elements in your set -- <sup>20</sup>C<sub>3</sub> = 1140. And if you want to iterate over the set it's best to use a modified gray code algorithm so you aren't holding all of them in memory. These generate the next combination from the previous and avoid repetitions. There are many of these for different uses. Do we want to maximize the differences between successive combinations? minimize? et cetera.</p> <p>Some of the original papers describing gray codes:</p> <ol> <li><a href="http://portal.acm.org/citation.cfm?id=2422.322413" rel="noreferrer">Some Hamilton Paths and a Minimal Change Algorithm</a></li> <li><a href="http://portal.acm.org/citation.cfm?id=49203&amp;jmp=indexterms&amp;coll=GUIDE&amp;dl=GUIDE&amp;CFID=81503149&amp;CFTOKEN=96444237" rel="noreferrer">Adjacent Interchange Combination Generation Algorithm</a></li> </ol> <p>Here are some other papers covering the topic:</p> <ol> <li><a href="http://www.cs.uvic.ca/%7Eruskey/Publications/EHR/HoughRuskey.pdf" rel="noreferrer">An Efficient Implementation of the Eades, Hickey, Read Adjacent Interchange Combination Generation Algorithm</a> (PDF, with code in Pascal)</li> <li><a href="http://portal.acm.org/citation.cfm?doid=355826.355830" rel="noreferrer">Combination Generators</a></li> <li><a href="http://www4.ncsu.edu/%7Esavage/AVAILABLE_FOR_MAILING/survey.ps" rel="noreferrer">Survey of Combinatorial Gray Codes</a> (PostScript)</li> <li><a href="https://link.springer.com/content/pdf/10.1007/BF02248780.pdf" rel="noreferrer">An Algorithm for Gray Codes</a></li> </ol> <h2>Chase's Twiddle (algorithm)</h2> <p>Phillip J Chase, `<a href="http://portal.acm.org/citation.cfm?id=362502" rel="noreferrer">Algorithm 382: Combinations of M out of N Objects</a>' (1970)</p> <p><a href="http://www.netlib.no/netlib/toms/382" rel="noreferrer">The algorithm in C</a>...</p> <h2>Index of Combinations in Lexicographical Order (Buckles Algorithm 515)</h2> <p>You can also reference a combination by its index (in lexicographical order). Realizing that the index should be some amount of change from right to left based on the index we can construct something that should recover a combination.</p> <p>So, we have a set {1,2,3,4,5,6}... and we want three elements. Let's say {1,2,3} we can say that the difference between the elements is one and in order and minimal. {1,2,4} has one change and is lexicographically number 2. So the number of 'changes' in the last place accounts for one change in the lexicographical ordering. The second place, with one change {1,3,4} has one change but accounts for more change since it's in the second place (proportional to the number of elements in the original set).</p> <p>The method I've described is a deconstruction, as it seems, from set to the index, we need to do the reverse – which is much trickier. This is how <a href="http://portal.acm.org/citation.cfm?id=355739" rel="noreferrer">Buckles</a> solves the problem. I wrote some <a href="https://stackoverflow.com/questions/561/using-combinations-of-sets-as-test-data#794">C to compute them</a>, with minor changes – I used the index of the sets rather than a number range to represent the set, so we are always working from 0...n. Note:</p> <ol> <li>Since combinations are unordered, {1,3,2} = {1,2,3} --we order them to be lexicographical.</li> <li>This method has an implicit 0 to start the set for the first difference.</li> </ol> <h2>Index of Combinations in Lexicographical Order (McCaffrey)</h2> <p>There is <a href="https://web.archive.org/web/20170325012457/https://msdn.microsoft.com/en-us/library/aa289166.aspx" rel="noreferrer">another way</a>:, its concept is easier to grasp and program but it's without the optimizations of Buckles. Fortunately, it also does not produce duplicate combinations:</p> <p>The set <a href="https://i.stack.imgur.com/Txetz.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/Txetz.gif" alt="x_k...x_1 in N" /></a> that maximizes <a href="https://i.stack.imgur.com/HOj5o.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/HOj5o.gif" alt="i = C(x_1,k) + C(x_2,k-1) + ... + C(x_k,1)" /></a>, where <a href="https://i.stack.imgur.com/vIeiI.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/vIeiI.gif" alt="C(n,r) = {n choose r}" /></a>.</p> <p>For an example: <code>27 = C(6,4) + C(5,3) + C(2,2) + C(1,1)</code>. So, the 27th lexicographical combination of four things is: {1,2,5,6}, those are the indexes of whatever set you want to look at. Example below (OCaml), requires <code>choose</code> function, left to reader:</p> <pre class="lang-fs prettyprint-override"><code>(* this will find the [x] combination of a [set] list when taking [k] elements *) let combination_maccaffery set k x = (* maximize function -- maximize a that is aCb *) (* return largest c where c &lt; i and choose(c,i) &lt;= z *) let rec maximize a b x = if (choose a b ) &lt;= x then a else maximize (a-1) b x in let rec iterate n x i = match i with | 0 -&gt; [] | i -&gt; let max = maximize n i x in max :: iterate n (x - (choose max i)) (i-1) in if x &lt; 0 then failwith &quot;errors&quot; else let idxs = iterate (List.length set) x k in List.map (List.nth set) (List.sort (-) idxs) </code></pre> <h2>A small and simple combinations iterator</h2> <p>The following two algorithms are provided for didactic purposes. They implement an iterator and (a more general) folder overall combinations. They are as fast as possible, having the complexity O(<sup>n</sup>C<sub>k</sub>). The memory consumption is bound by <code>k</code>.</p> <p>We will start with the iterator, which will call a user provided function for each combination</p> <pre class="lang-fs prettyprint-override"><code>let iter_combs n k f = let rec iter v s j = if j = k then f v else for i = s to n - 1 do iter (i::v) (i+1) (j+1) done in iter [] 0 0 </code></pre> <p>A more general version will call the user provided function along with the state variable, starting from the initial state. Since we need to pass the state between different states we won't use the for-loop, but instead, use recursion,</p> <pre class="lang-fs prettyprint-override"><code>let fold_combs n k f x = let rec loop i s c x = if i &lt; n then loop (i+1) s c @@ let c = i::c and s = s + 1 and i = i + 1 in if s &lt; k then loop i s c x else f c x else x in loop 0 0 [] x </code></pre>
{ "question_id": 127704, "question_date": "2008-09-24T15:02:24.957Z", "question_score": 632, "tags": "algorithm|combinations", "answer_id": 127856, "answer_date": "2008-09-24T15:24:50.300Z", "answer_score": 447 }