input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: How do I convert a float number to a whole number in JavaScript?
<p>I'd like to convert a float to a whole number in JavaScript. Actually, I'd like to know how to do BOTH of the standard conversions: by truncating and by rounding. And efficiently, not via converting to a string and parsing.</p>
|
<pre><code>var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue );
var intvalue = Math.round( floatvalue );
// `Math.trunc` was added in ECMAScript 6
var intvalue = Math.trunc( floatvalue );
</code></pre>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math" rel="noreferrer">Math object reference</a></p>
<hr />
<h3>Examples</h3>
<strong>Positive</strong>
<pre><code>// value=x // x=5 5<x<5.5 5.5<=x<6
Math.floor(value) // 5 5 5
Math.ceil(value) // 5 6 6
Math.round(value) // 5 5 6
Math.trunc(value) // 5 5 5
parseInt(value) // 5 5 5
~~value // 5 5 5
value | 0 // 5 5 5
value >> 0 // 5 5 5
value >>> 0 // 5 5 5
value - value % 1 // 5 5 5
</code></pre>
<strong>Negative</strong>
<pre><code>// value=x // x=-5 -5>x>=-5.5 -5.5>x>-6
Math.floor(value) // -5 -6 -6
Math.ceil(value) // -5 -5 -5
Math.round(value) // -5 -5 -6
Math.trunc(value) // -5 -5 -5
parseInt(value) // -5 -5 -5
value | 0 // -5 -5 -5
~~value // -5 -5 -5
value >> 0 // -5 -5 -5
value >>> 0 // 4294967291 4294967291 4294967291
value - value % 1 // -5 -5 -5
</code></pre>
<strong>Positive - Larger numbers</strong>
<pre><code>// x = Number.MAX_SAFE_INTEGER/10 // =900719925474099.1
// value=x x=900719925474099 x=900719925474099.4 x=900719925474099.5
Math.floor(value) // 900719925474099 900719925474099 900719925474099
Math.ceil(value) // 900719925474099 900719925474100 900719925474100
Math.round(value) // 900719925474099 900719925474099 900719925474100
Math.trunc(value) // 900719925474099 900719925474099 900719925474099
parseInt(value) // 900719925474099 900719925474099 900719925474099
value | 0 // 858993459 858993459 858993459
~~value // 858993459 858993459 858993459
value >> 0 // 858993459 858993459 858993459
value >>> 0 // 858993459 858993459 858993459
value - value % 1 // 900719925474099 900719925474099 900719925474099
</code></pre>
<strong>Negative - Larger numbers</strong>
<pre><code>// x = Number.MAX_SAFE_INTEGER/10 * -1 // -900719925474099.1
// value = x // x=-900719925474099 x=-900719925474099.5 x=-900719925474099.6
Math.floor(value) // -900719925474099 -900719925474100 -900719925474100
Math.ceil(value) // -900719925474099 -900719925474099 -900719925474099
Math.round(value) // -900719925474099 -900719925474099 -900719925474100
Math.trunc(value) // -900719925474099 -900719925474099 -900719925474099
parseInt(value) // -900719925474099 -900719925474099 -900719925474099
value | 0 // -858993459 -858993459 -858993459
~~value // -858993459 -858993459 -858993459
value >> 0 // -858993459 -858993459 -858993459
value >>> 0 // 3435973837 3435973837 3435973837
value - value % 1 // -900719925474099 -900719925474099 -900719925474099
</code></pre>
|
{
"question_id": 596467,
"question_date": "2009-02-27T20:15:07.317Z",
"question_score": 1423,
"tags": "javascript|syntax",
"answer_id": 596503,
"answer_date": "2009-02-27T20:21:02.077Z",
"answer_score": 2062
}
|
Please answer the following Stack Overflow question:
Title: Hex transparency in colors
<p>I'm working on implementing a widget transparency option for my app widget although I'm having some trouble getting the hex color values right. Being completely new to hex color transparency I searched around a bit although I couldn't find a specific answer to my question. </p>
<p>I want to set transparency by hex color so let's say my hex color id "#33b5e5" and I want it to be 50% transparent. Then I'll use "#8033b5e5" because 80 is 50%. </p>
<p>I found a useful chart here: <a href="http://www.dtp-aus.com/hexadeci.htm" rel="noreferrer">http://www.dtp-aus.com/hexadeci.htm</a> . With this data I managed to come up with this:</p>
<pre><code>0% = #00
10% = #16
20% = #32
30% = #48
40% = #64
50% = #80
60% = #96
70% = #112
80% = #128
90% = #144
</code></pre>
<p>Now the issues start appearing when I get higher than 100 in hex. Hex color codes can only be 8 symbols long right? For example #11233b5e5 (80%) crashes.</p>
<p>What can I do to enable me to use the higher numbers aswell?</p>
|
<p>Here's a correct table of percentages to hex values for opacity. E.g. for 50% white you'd use #80FFFFFF. To think in terms of transparency instead, flip the order of the percentages (more opaque = less transparent).</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>%</th>
<th>Hex</th>
</tr>
</thead>
<tbody>
<tr>
<td>100%</td>
<td>FF</td>
</tr>
<tr>
<td>95%</td>
<td>F2</td>
</tr>
<tr>
<td>90%</td>
<td>E6</td>
</tr>
<tr>
<td>85%</td>
<td>D9</td>
</tr>
<tr>
<td>80%</td>
<td>CC</td>
</tr>
<tr>
<td>75%</td>
<td>BF</td>
</tr>
<tr>
<td>70%</td>
<td>B3</td>
</tr>
<tr>
<td>65%</td>
<td>A6</td>
</tr>
<tr>
<td>60%</td>
<td>99</td>
</tr>
<tr>
<td>55%</td>
<td>8C</td>
</tr>
<tr>
<td>50%</td>
<td>80</td>
</tr>
<tr>
<td>45%</td>
<td>73</td>
</tr>
<tr>
<td>40%</td>
<td>66</td>
</tr>
<tr>
<td>35%</td>
<td>59</td>
</tr>
<tr>
<td>30%</td>
<td>4D</td>
</tr>
<tr>
<td>25%</td>
<td>40</td>
</tr>
<tr>
<td>20%</td>
<td>33</td>
</tr>
<tr>
<td>15%</td>
<td>26</td>
</tr>
<tr>
<td>10%</td>
<td>1A</td>
</tr>
<tr>
<td>5%</td>
<td>0D</td>
</tr>
<tr>
<td>0%</td>
<td>00</td>
</tr>
</tbody>
</table>
</div>
<p>(<a href="https://stackoverflow.com/questions/5445085/understanding-colors-on-android-six-characters">source question</a>)</p>
|
{
"question_id": 15852122,
"question_date": "2013-04-06T14:30:26.450Z",
"question_score": 1422,
"tags": "android|colors|hex|transparency",
"answer_id": 17239853,
"answer_date": "2013-06-21T16:15:35.430Z",
"answer_score": 4037
}
|
Please answer the following Stack Overflow question:
Title: How to round a number to n decimal places in Java
<p>What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations.</p>
<p>I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes.</p>
<p>I know one method of doing this is to use the <code>String.format</code> method:</p>
<pre><code>String.format("%.5g%n", 0.912385);
</code></pre>
<p>returns:</p>
<pre><code>0.91239
</code></pre>
<p>which is great, however it always displays numbers with 5 decimal places even if they are not significant: </p>
<pre><code>String.format("%.5g%n", 0.912300);
</code></pre>
<p>returns:</p>
<pre><code>0.91230
</code></pre>
<p>Another method is to use the <code>DecimalFormatter</code>:</p>
<pre><code>DecimalFormat df = new DecimalFormat("#.#####");
df.format(0.912385);
</code></pre>
<p>returns:</p>
<pre><code>0.91238
</code></pre>
<p>However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this:</p>
<pre><code>0.912385 -> 0.91239
0.912300 -> 0.9123
</code></pre>
<p>What is the best way to achieve this in Java?</p>
|
<p>Use <a href="http://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html#setRoundingMode(java.math.RoundingMode)" rel="noreferrer"><code>setRoundingMode</code></a>, set the <a href="http://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html" rel="noreferrer"><code>RoundingMode</code></a> explicitly to handle your issue with the half-even round, then use the format pattern for your required output.</p>
<p>Example:</p>
<pre><code>DecimalFormat df = new DecimalFormat("#.####");
df.setRoundingMode(RoundingMode.CEILING);
for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {
Double d = n.doubleValue();
System.out.println(df.format(d));
}
</code></pre>
<p>gives the output:</p>
<pre><code>12
123.1235
0.23
0.1
2341234.2125
</code></pre>
<hr>
<p><strong>EDIT</strong>: The original answer does not address the accuracy of the double values. That is fine if you don't care much whether it rounds up or down. But if you want accurate rounding, then you need to take the expected accuracy of the values into account. Floating point values have a binary representation internally. That means that a value like 2.7735 does not actually have that exact value internally. It can be slightly larger or slightly smaller. If the internal value is slightly smaller, then it will not round up to 2.7740. To remedy that situation, you need to be aware of the accuracy of the values that you are working with, and add or subtract that value before rounding. For example, when you know that your values are accurate up to 6 digits, then to round half-way values up, add that accuracy to the value:</p>
<pre><code>Double d = n.doubleValue() + 1e-6;
</code></pre>
<p>To round down, subtract the accuracy. </p>
|
{
"question_id": 153724,
"question_date": "2008-09-30T16:01:34.613Z",
"question_score": 1421,
"tags": "java|decimal|rounding|digits",
"answer_id": 153785,
"answer_date": "2008-09-30T16:14:15.940Z",
"answer_score": 859
}
|
Please answer the following Stack Overflow question:
Title: Is there a way to get the source code from an APK file?
<p>The hard drive on my laptop just crashed and I lost all the source code for an app that I have been working on for the past two months.
All I have is the APK file that is stored in my email from when I sent it to a friend. </p>
<p>Is there any way to extract my source code from this APK file?</p>
|
<p>Simple way: use online tool <a href="https://www.decompiler.com/" rel="nofollow noreferrer">https://www.decompiler.com/</a>, upload apk and get source code.</p>
<hr />
<p>Procedure for decoding .apk files, step-by-step method:</p>
<h3>Step 1:</h3>
<ol>
<li><p>Make a new folder and copy over the .apk file that you want to decode.</p>
</li>
<li><p>Now rename the extension of this .apk file to .zip (e.g. rename from filename.apk to filename.zip) and save it. Now you can access the classes.dex files, etc. At this stage you are able to see drawables but not xml and java files, so continue.</p>
</li>
</ol>
<h3>Step 2:</h3>
<ol>
<li><p>Now extract this .zip file in the same folder (or NEW FOLDER).</p>
</li>
<li><p><a href="https://github.com/pxb1988/dex2jar" rel="nofollow noreferrer">Download dex2jar</a> (Don't download the code, click on the releases button that's on the right then download that) and extract it to the same folder (or NEW FOLDER).</p>
</li>
<li><p>Move the classes.dex file into the dex2jar folder.</p>
</li>
<li><p>Now open command prompt and change directory to that folder (or NEW FOLDER). Then write <code>d2j-dex2jar classes.dex</code> (for mac terminal or ubuntu write <code>./d2j-dex2jar.sh classes.dex</code>) and press enter. You now have the classes.dex.dex2jar file in the same folder.</p>
</li>
<li><p><a href="http://jd.benow.ca/" rel="nofollow noreferrer">Download java decompiler</a>, double click on jd-gui, click on open file, and open classes.dex.dex2jar file from that folder: now you get class files.</p>
</li>
<li><p>Save all of these class files (In jd-gui, click File -> Save All Sources) by src name. At this stage you get the java source but the .xml files are still unreadable, so continue.</p>
</li>
</ol>
<h3>Step 3:</h3>
<p>Now open another new folder</p>
<ol>
<li><p>Put in the .apk file which you want to decode</p>
</li>
<li><p>Download the latest version of <a href="http://ibotpeaches.github.io/Apktool/install/" rel="nofollow noreferrer">apktool <strong>AND</strong> apktool install window</a> (both can be downloaded from the same link) and place them in the same folder</p>
</li>
<li><p>Open a command window</p>
</li>
<li><p>Now run command like <code>apktool if framework-res.apk</code> (if you don't have it <a href="http://www.androidfilehost.com/?fid=23212708291677144" rel="nofollow noreferrer">get it here</a>)and next</p>
</li>
<li><p><code>apktool d myApp.apk</code> (where myApp.apk denotes the filename that you want to decode)</p>
</li>
</ol>
<p>now you get a file folder in that folder and can easily read the apk's xml files.</p>
<h3>Step 4:</h3>
<p>It's not any step, just copy contents of both folders(in this case, both new folders) to the single one</p>
<p>and enjoy the source code...</p>
|
{
"question_id": 3593420,
"question_date": "2010-08-29T03:40:13.510Z",
"question_score": 1421,
"tags": "android|android-resources|decompiling|apk",
"answer_id": 6081365,
"answer_date": "2011-05-21T11:20:04.800Z",
"answer_score": 1714
}
|
Please answer the following Stack Overflow question:
Title: How to remove old Docker containers
<p>This question is related to <em><a href="https://stackoverflow.com/questions/17014263/should-i-be-concerned-about-excess-non-running-docker-containers">Should I be concerned about excess, non-running, Docker containers?</a></em>.</p>
<p>I'm wondering how to remove old containers. The <code>docker rm 3e552code34a</code> lets you remove a single one, but I have lots already. <code>docker rm --help</code> doesn't give a selection option (like all, or by image name).</p>
<p>Maybe there is a directory in which these containers are stored where I can delete them easily manually?</p>
|
<p>Since <a href="https://github.com/moby/moby/blob/master/CHANGELOG.md#1130-2017-01-18" rel="noreferrer">Docker 1.13.x</a> you can use <a href="https://docs.docker.com/engine/reference/commandline/container_prune/" rel="noreferrer">Docker container prune</a>:</p>
<pre><code>docker container prune
</code></pre>
<p>This will remove all stopped containers and should work on all platforms the same way.</p>
<p>There is also a <a href="https://docs.docker.com/engine/reference/commandline/system_prune/" rel="noreferrer">Docker system prune</a>:</p>
<pre><code>docker system prune
</code></pre>
<p>which will clean up all unused containers, networks, images (both dangling and unreferenced), and optionally, volumes, in one command.</p>
<hr>
<p>For older Docker versions, you can string Docker commands together with other Unix commands to get what you need. Here is an example on how to clean up old containers that are weeks old:</p>
<pre><code>$ docker ps --filter "status=exited" | grep 'weeks ago' | awk '{print $1}' | xargs --no-run-if-empty docker rm
</code></pre>
<p>To give credit, where it is due, this example is from <a href="https://twitter.com/jpetazzo/status/347431091415703552" rel="noreferrer">https://twitter.com/jpetazzo/status/347431091415703552</a>.</p>
|
{
"question_id": 17236796,
"question_date": "2013-06-21T13:41:42.820Z",
"question_score": 1419,
"tags": "docker",
"answer_id": 17237701,
"answer_date": "2013-06-21T14:25:51.793Z",
"answer_score": 1722
}
|
Please answer the following Stack Overflow question:
Title: What does the exclamation mark do before the function?
<pre><code>!function () {}();
</code></pre>
|
<p>JavaScript syntax 101: here is a <strong>function declaration</strong>:</p>
<pre class="lang-js prettyprint-override"><code>function foo() {}
</code></pre>
<p>Note that there’s no semicolon; this is just a function <strong>declaration</strong>. You would need an invocation, <code>foo()</code>, to actually run the function.</p>
<p>Now, when we add the seemingly innocuous exclamation mark: <code>!function foo() {}</code> it turns it into an <strong>expression</strong>. It is now a <strong>function expression</strong>.</p>
<p>The <code>!</code> alone doesn’t invoke the function, of course, but we can now put <code>()</code> at the end: <code>!function foo() {}()</code>, which has higher precedence than <code>!</code> and instantly calls the function.</p>
<p><code>function foo() {}()</code> would be a syntax error because you can’t put arguments (<code>()</code>) right after a function declaration.</p>
<p>So what the author is doing is saving a byte per function expression; a more readable way of writing it would be this:</p>
<pre class="lang-js prettyprint-override"><code>(function(){})();
</code></pre>
<p>Lastly, <code>!</code> makes the expression return a boolean based on the return value of the function. Usually, an immediately invoked function expression (IIFE) doesn’t explicitly return anything, so its return value will be <code>undefined</code>, which leaves us with <code>!undefined</code> which is <code>true</code>. This boolean isn’t used.</p>
|
{
"question_id": 3755606,
"question_date": "2010-09-20T21:21:51.393Z",
"question_score": 1419,
"tags": "javascript|function",
"answer_id": 5654929,
"answer_date": "2011-04-13T20:02:29.310Z",
"answer_score": 2357
}
|
Please answer the following Stack Overflow question:
Title: Difference between git stash pop and git stash apply
<p>I've been using <code>git stash pop</code> for quite some time. I recently found out about the <code>git stash apply</code> command. When I tried it out, it seemed to work the same as <code>git stash pop</code>. </p>
<p>What is the difference between <code>git stash pop</code> and <code>git stash apply</code>?</p>
|
<p><code>git stash pop</code> <strong>throws away</strong> the (topmost, by default) stash after applying it, whereas <code>git stash apply</code> <strong>leaves it in the stash list</strong> for possible later reuse (or you can then <code>git stash drop</code> it). </p>
<p>This happens unless there are conflicts after <code>git stash pop</code>, in which case it will not remove the stash, leaving it to behave exactly like <code>git stash apply</code>.</p>
<p>Another way to look at it: <code>git stash pop</code> is <code>git stash apply && git stash drop</code>.</p>
|
{
"question_id": 15286075,
"question_date": "2013-03-08T03:14:02.300Z",
"question_score": 1418,
"tags": "git|git-stash",
"answer_id": 15286090,
"answer_date": "2013-03-08T03:15:45.923Z",
"answer_score": 2242
}
|
Please answer the following Stack Overflow question:
Title: Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?
<p>A long time ago I have read an article (I believe a blog entry) which put me on the "right" track on naming objects: Be very very scrupulous about naming things in your program.</p>
<p>For example if my application was (as a typical business app) handling users, companies and addresses I'd have a <code>User</code>, a <code>Company</code> and an <code>Address</code> domain class - and probably somewhere a <code>UserManager</code>, a <code>CompanyManager</code> and an <code>AddressManager</code> would pop up that handles those things.</p>
<p>So can you tell what those <code>UserManager</code>, <code>CompanyManager</code> and <code>AddressManager</code> do? No, because Manager is a very very generic term that fits to anything you can do with your domain objects.</p>
<p>The article I read recommended using very specific names. If it was a C++ application and the <code>UserManager</code>'s job was allocating and freeing users from the heap it would not manage the users but guard their birth and death. Hmm, maybe we could call this a <code>UserShepherd</code>.</p>
<p>Or maybe the <code>UserManager</code>'s job is to examine each User object's data and sign the data cryptographically. Then we'd have a <code>UserRecordsClerk</code>.</p>
<p>Now that this idea stuck with me I try to apply it. And find this simple idea amazingly hard.</p>
<p>I can describe what the classes do and (as long as I don't slip into quick & dirty coding) the classes I write do exactly <strong>one</strong> thing. What I miss to go from that description to the names is a kind of catalogue of names, a vocabulary that maps the concepts to names.</p>
<p>Ultimately I'd like to have something like a pattern catalogue in my mind (frequently design patterns easily provide the object names, e.g. a <em>factory</em>)</p>
<ul>
<li>Factory - Creates other objects (naming taken from the design pattern)</li>
<li>Shepherd - A shepherd handles the lifetime of objects, their creation and shutdown</li>
<li>Synchronizer - Copies data between two or more objects (or object hierarchies)</li>
<li><p>Nanny - Helps objects reach "usable" state after creation - for example by wiring to other objects</p></li>
<li><p>etc etc.</p></li>
</ul>
<p>So, how do you handle that issue? Do you have a fixed vocabulary, do you invent new names on the fly or do you consider naming things not-so-important or wrong?</p>
<p>P.S.: I'm also interested in links to articles and blogs discussing the issue. As a start, here is the original article that got me thinking about it: <a href="http://www.bright-green.com/blog/2003_02_25/naming_java_classes_without_a.html" rel="noreferrer">Naming Java Classes without a 'Manager'</a></p>
<hr>
<h2>Update: Summary of answers</h2>
<p>Here's a little summary of what I learned from this question in the meantime.</p>
<ul>
<li>Try not to create new metaphors (Nanny)</li>
<li>Have a look at what other frameworks do</li>
</ul>
<p>Further articles/books on this topic:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/1194403/what-names-do-you-find-yourself-prepending-appending-to-classes-regularly">What names do you find yourself prepending/appending to classes regularly?</a> </li>
<li><a href="https://stackoverflow.com/questions/38019/whats-the-best-approach-to-naming-classes">What’s the best approach to naming classes?</a></li>
<li>Book: <a href="https://rads.stackoverflow.com/amzn/click/com/0201633612" rel="noreferrer" rel="nofollow noreferrer">Design Patterns: Elements of Reusable Object-Oriented Software (Hardcover)</a></li>
<li>Book: <a href="https://rads.stackoverflow.com/amzn/click/com/0321127420" rel="noreferrer" rel="nofollow noreferrer">Patterns of Enterprise Application Architecture (Hardcover)</a></li>
<li>Book: <a href="https://rads.stackoverflow.com/amzn/click/com/0321413091" rel="noreferrer" rel="nofollow noreferrer">Implementation Patterns (Paperback)</a></li>
</ul>
<p>And a current list of name prefixes/suffixes I collected (subjectively!) from the answers:</p>
<ul>
<li>Coordinator</li>
<li>Builder</li>
<li>Writer</li>
<li>Reader</li>
<li>Handler</li>
<li>Container</li>
<li>Protocol</li>
<li>Target</li>
<li>Converter</li>
<li>Controller</li>
<li>View</li>
<li>Factory</li>
<li>Entity</li>
<li>Bucket</li>
</ul>
<p>And a good tip for the road:</p>
<blockquote>
<p>Don't get naming paralysis. Yes, names are very important but they're not important enough to waste huge amounts of time on. If you can't think up a good name in 10 minutes, move on.</p>
</blockquote>
|
<p>I asked a <a href="https://stackoverflow.com/questions/1194403/what-names-do-you-find-yourself-prepending-appending-to-classes-regularly">similar question</a>, but where possible I try to copy the names already in the <strong>.NET</strong> framework, and I look for ideas in the <strong>Java</strong> and <strong>Android</strong> frameworks.</p>
<p>It seems <code>Helper</code>, <code>Manager</code>, and <code>Util</code> are the unavoidable nouns you attach for coordinating classes that contain no state and are generally procedural and static. An alternative is <code>Coordinator</code>.</p>
<p>You could get particularly purple prosey with the names and go for things like <code>Minder</code>, <code>Overseer</code>, <code>Supervisor</code>, <code>Administrator</code>, and <code>Master</code>, but as I said I prefer keeping it like the framework names you're used to.</p>
<hr />
<p>Some other common suffixes (if that is the correct term) you also find in the <strong>.NET</strong> framework are:</p>
<ul>
<li><code>Builder</code><br />
A type that use some parameters to construct an instance of a special type. <code>Builder</code> is usually a throwaway. It may not even need to allocate a variable.<br />
If the type needs to repeatedly create objects, please use <code>Factory</code>.<br />
if the type responsible for create multiple different type objects, please use <code>Factories</code>.</li>
<li><code>Writer</code><br />
Write some variable into something.</li>
<li><code>Reader</code><br />
Read something as variable.</li>
<li><code>Handler</code><br />
Designed to deal with a situation or something.</li>
<li><code>Container</code><br />
Can put something into it.</li>
</ul>
|
{
"question_id": 1866794,
"question_date": "2009-12-08T12:55:28.710Z",
"question_score": 1416,
"tags": "design-patterns|oop|naming-conventions|naming",
"answer_id": 2071812,
"answer_date": "2010-01-15T13:31:13.893Z",
"answer_score": 256
}
|
Please answer the following Stack Overflow question:
Title: Null object in Python
<p>How do I refer to the <a href="https://en.wikipedia.org/wiki/Null_pointer" rel="noreferrer">null object</a> in Python?</p>
|
<p>In Python, the 'null' object is the singleton <code>None</code>.</p>
<p>To check if something is <code>None</code>, use the <a href="https://docs.python.org/3/reference/expressions.html#is" rel="noreferrer"><code>is</code></a> identity operator:</p>
<pre><code>if foo is None:
...
</code></pre>
|
{
"question_id": 3289601,
"question_date": "2010-07-20T11:53:41.243Z",
"question_score": 1415,
"tags": "python|object|null",
"answer_id": 3289606,
"answer_date": "2010-07-20T11:54:27.777Z",
"answer_score": 1866
}
|
Please answer the following Stack Overflow question:
Title: What is the difference between MVC and MVVM?
<p>Is there a difference between the standard "Model View Controller" pattern and Microsoft's Model/View/ViewModel pattern?</p>
|
<h2>MVC/MVVM is not an <em>either/or</em> choice.</h2>
<p>The two patterns crop up, in different ways, in both ASP.Net and Silverlight/WPF development.</p>
<p>For ASP.Net, MVVM is used to <em>two-way bind</em> data within views. This is usually a client-side implementation (e.g. using Knockout.js). MVC on the other hand is a way of separating concerns <em>on the server-side</em>.</p>
<p>For Silverlight and WPF, the MVVM pattern is more encompassing and can <em>appear</em> to act as a replacement for MVC (or other patterns of organising software into separate responsibilities). One assumption, that frequently came out of this pattern, was that the <code>ViewModel</code> simply replaced the controller in <code>MVC</code> (as if you could just substitute <code>VM</code> for <code>C</code> in the acronym and all would be forgiven)...</p>
<h2>The ViewModel does <em>not</em> necessarily replace the need for separate Controllers.</h2>
<p>The problem is: that to be independently testable*, and especially reusable when needed, a view-model has no idea what view is displaying it, but more importantly <em>no idea where its data is coming from</em>.</p>
<p>*Note: in practice Controllers remove most of the logic, from the ViewModel, that requires unit testing. The VM then becomes a dumb container that requires little, if any, testing. This is a good thing as the VM is just a bridge, between the designer and the coder, so should be kept simple.</p>
<p>Even in MVVM, controllers will typically contain all processing logic and decide what data to display in which views using which view models.</p>
<p>From what we have seen so far the main benefit of the ViewModel pattern to remove code from XAML code-behind <em>to make XAML editing a more independent task</em>. We still create controllers, as and when needed, to control (no pun intended) the overall logic of our applications.</p>
<h2>The basic MVCVM guidelines we follow are:</h2>
<ul>
<li>Views <em>display a certain shape of data</em>. They have no idea where the data comes from.</li>
<li>ViewModels <em>hold a certain shape of data and commands</em>, they do not know where the data, or code, comes from or how it is displayed.</li>
<li>Models <em>hold the actual data</em> (various context, store or other methods)</li>
<li>Controllers listen for, and publish, events. Controllers provide the logic that controls what data is seen and where. Controllers provide the command code to the ViewModel so that the ViewModel is actually reusable.</li>
</ul>
<p>We also noted that the <a href="https://www.codeproject.com/Articles/29051/Introduction-to-Model-Driven-Development-with-Scul" rel="noreferrer">Sculpture code-gen framework</a> implements MVVM and a pattern similar to Prism AND it also makes extensive use of controllers to separate all use-case logic.</p>
<h2>Don't assume controllers are made obsolete by View-models.</h2>
<p><a href="https://web.archive.org/web/20180430230531/http://blog.hitechmagic.com/?page_id=513" rel="noreferrer">I have started a blog on this topic which I will add to as and when I can (archive only as hosting was lost)</a>. There are issues with combining MVCVM with the common navigation systems, as most navigation systems just use Views and VMs, but I will go into that in later articles.</p>
<p>An additional benefit of using an MVCVM model is that <em>only the controller objects need to exist in memory for the life of the application</em> and the controllers contain mainly code and little state data (i.e. tiny memory overhead). This makes for much less memory-intensive apps than solutions where view-models have to be retained and it is ideal for certain types of mobile development (e.g. Windows Mobile using Silverlight/Prism/MEF). This does of course depend on the type of application as you may still need to retain the occasional cached VMs for responsiveness.</p>
<p><em>Note: This post has been edited numerous times, and did not specifically target the narrow question asked, so I have updated the first part to now cover that too. Much of the discussion, in comments below, relates only to ASP.Net and not the broader picture. This post was intended to cover the broader use of MVVM in Silverlight, WPF and ASP.Net and try to discourage people from replacing controllers with ViewModels.</em></p>
|
{
"question_id": 667781,
"question_date": "2009-03-20T20:09:18.777Z",
"question_score": 1415,
"tags": "model-view-controller|mvvm|design-patterns",
"answer_id": 3540895,
"answer_date": "2010-08-22T09:19:15.567Z",
"answer_score": 737
}
|
Please answer the following Stack Overflow question:
Title: What is the preferred Bash shebang ("#!")?
<p>Is there any <code>Bash</code> shebang objectively better than the others for most uses?</p>
<ul>
<li><code>#!/usr/bin/env bash</code></li>
<li><code>#!/bin/bash</code></li>
<li><code>#!/bin/sh</code></li>
<li><code>#!/bin/sh -</code></li>
<li>etc</li>
</ul>
<p>I vaguely recall a long time ago hearing that adding a dash to the end prevents someone passing a command to your script, but can’t find any details on that.</p>
|
<p>You should use <strong><code>#!/usr/bin/env bash</code></strong> for <a href="https://en.wikipedia.org/w/index.php?title=Shebang_(Unix)&oldid=878552871#Portability" rel="noreferrer">portability</a>: different *nixes put <code>bash</code> in different places, and using <code>/usr/bin/env</code> is a workaround to run the first <code>bash</code> found on the <code>PATH</code>. And <strong><a href="https://mywiki.wooledge.org/BashGuide/CommandsAndArguments#Scripts" rel="noreferrer"><code>sh</code> is not <code>bash</code></a></strong>.</p>
|
{
"question_id": 10376206,
"question_date": "2012-04-29T21:37:00.027Z",
"question_score": 1415,
"tags": "bash|shebang",
"answer_id": 10383546,
"answer_date": "2012-04-30T12:14:50.937Z",
"answer_score": 1871
}
|
Please answer the following Stack Overflow question:
Title: How do I check which version of Python is running my script?
<p>How do I check which version of the Python interpreter is running my script?</p>
|
<p>This information is available in the <a href="http://docs.python.org/library/sys.html#sys.version" rel="noreferrer"><code>sys.version</code></a> string in the <a href="http://docs.python.org/library/sys.html" rel="noreferrer"><code>sys</code></a> module:</p>
<pre><code>>>> import sys
</code></pre>
<p>Human readable:</p>
<pre><code>>>> print(sys.version) # parentheses necessary in python 3.
2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)]
</code></pre>
<p>For further processing, use <a href="http://docs.python.org/library/sys.html#sys.version_info" rel="noreferrer"><code>sys.version_info</code></a> or <a href="http://docs.python.org/library/sys.html#sys.hexversion" rel="noreferrer"><code>sys.hexversion</code></a>:</p>
<pre><code>>>> sys.version_info
(2, 5, 2, 'final', 0)
# or
>>> sys.hexversion
34014192
</code></pre>
<p>To ensure a script runs with a minimal version requirement of the Python interpreter add this to your code:</p>
<pre><code>assert sys.version_info >= (2, 5)
</code></pre>
<p>This compares major and minor version information. Add micro (=<code>0</code>, <code>1</code>, etc) and even releaselevel (=<code>'alpha'</code>,<code>'final'</code>, etc) to the tuple as you like. Note however, that it is almost always better to "duck" check if a certain feature is there, and if not, workaround (or bail out). Sometimes features go away in newer releases, being replaced by others.</p>
|
{
"question_id": 1093322,
"question_date": "2009-07-07T16:17:49.703Z",
"question_score": 1414,
"tags": "python|version",
"answer_id": 1093331,
"answer_date": "2009-07-07T16:20:12.490Z",
"answer_score": 1616
}
|
Please answer the following Stack Overflow question:
Title: How to compare arrays in JavaScript?
<p>I'd like to compare two arrays... ideally, efficiently. Nothing fancy, just <code>true</code> if they are identical, and <code>false</code> if not. Not surprisingly, the comparison operator doesn't seem to work.</p>
<pre><code>var a1 = [1,2,3];
var a2 = [1,2,3];
console.log(a1==a2); // Returns false
console.log(JSON.stringify(a1)==JSON.stringify(a2)); // Returns true
</code></pre>
<p>JSON encoding each array does, but is there a faster or "better" way to simply compare arrays without having to iterate through each value?</p>
|
<p>To compare arrays, loop through them and compare every value:</p>
<h2>Comparing arrays:</h2>
<pre><code>// Warn if overriding existing method
if(Array.prototype.equals)
console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l=this.length; i < l; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].equals(array[i]))
return false;
}
else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, "equals", {enumerable: false});
</code></pre>
<h3>Usage:</h3>
<pre><code>[1, 2, [3, 4]].equals([1, 2, [3, 2]]) === false;
[1, "2,3"].equals([1, 2, 3]) === false;
[1, 2, [3, 4]].equals([1, 2, [3, 4]]) === true;
[1, 2, 1, 2].equals([1, 2, 1, 2]) === true;
</code></pre>
<p>You may say "<em>But it is much faster to compare strings - no loops...</em>" well, then you should note there ARE loops. First recursive loop that converts Array to string and second, that compares two strings. So this method <strong>is faster than use of string</strong>.</p>
<p><sub>I believe that larger amounts of data should be always stored in arrays, not in objects. However if you use objects, they can be partially compared too.<br />
<strong>Here's how:</strong></sub></p>
<h2>Comparing objects:</h2>
<p>I've stated above, that two object <strong>instances</strong> will never be equal, even if they contain same data at the moment:</p>
<pre><code>({a:1, foo:"bar", numberOfTheBeast: 666}) == ({a:1, foo:"bar", numberOfTheBeast: 666}) //false
</code></pre>
<p>This has a reason, since there may be, for example <a href="https://stackoverflow.com/a/201471/607407">private variables within objects.</a></p>
<p>However, if you just use object structure to contain data, comparing is still possible:</p>
<pre><code>Object.prototype.equals = function(object2) {
//For the first loop, we only check for types
for (propName in this) {
//Check for inherited methods and properties - like .equals itself
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
//Return false if the return value is different
if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
return false;
}
//Check instance type
else if (typeof this[propName] != typeof object2[propName]) {
//Different types => not equal
return false;
}
}
//Now a deeper check using other objects property names
for(propName in object2) {
//We must check instances anyway, there may be a property that only exists in object2
//I wonder, if remembering the checked values from the first loop would be faster or not
if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
return false;
}
else if (typeof this[propName] != typeof object2[propName]) {
return false;
}
//If the property is inherited, do not check any more (it must be equa if both objects inherit it)
if(!this.hasOwnProperty(propName))
continue;
//Now the detail check and recursion
//This returns the script back to the array comparing
/**REQUIRES Array.equals**/
if (this[propName] instanceof Array && object2[propName] instanceof Array) {
// recurse into the nested arrays
if (!this[propName].equals(object2[propName]))
return false;
}
else if (this[propName] instanceof Object && object2[propName] instanceof Object) {
// recurse into another objects
//console.log("Recursing to compare ", this[propName],"with",object2[propName], " both named \""+propName+"\"");
if (!this[propName].equals(object2[propName]))
return false;
}
//Normal value comparison for strings and numbers
else if(this[propName] != object2[propName]) {
return false;
}
}
//If everything passed, let's say YES
return true;
}
</code></pre>
<p>However, remember that this one is to serve in comparing JSON like data, not class instances and other stuff. If you want to compare more complicated objects, look at <a href="https://stackoverflow.com/a/1144249/607407">this answer and it's super long function</a>.<br />
To make this work with <code>Array.equals</code> you must edit the original function a little bit:</p>
<pre><code>...
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].equals(array[i]))
return false;
}
/**REQUIRES OBJECT COMPARE**/
else if (this[i] instanceof Object && array[i] instanceof Object) {
// recurse into another objects
//console.log("Recursing to compare ", this[propName],"with",object2[propName], " both named \""+propName+"\"");
if (!this[i].equals(array[i]))
return false;
}
else if (this[i] != array[i]) {
...
</code></pre>
<p>I made a <a href="http://jsfiddle.net/Darker/SBtu2/" rel="noreferrer">little test tool for both of the functions</a>.</p>
<h2>Bonus: Nested arrays with <code>indexOf</code> and <code>contains</code></h2>
<p><a href="https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript/14853974?noredirect=1#comment59337127_14853974">Samy Bencherif has prepared</a> useful functions for the case you're searching for a specific object in nested arrays, which are available here: <a href="https://jsfiddle.net/SamyBencherif/8352y6yw/" rel="noreferrer">https://jsfiddle.net/SamyBencherif/8352y6yw/</a></p>
|
{
"question_id": 7837456,
"question_date": "2011-10-20T14:27:57.077Z",
"question_score": 1414,
"tags": "javascript|arrays|json",
"answer_id": 14853974,
"answer_date": "2013-02-13T12:49:05.423Z",
"answer_score": 1036
}
|
Please answer the following Stack Overflow question:
Title: Merge / convert multiple PDF files into one PDF
<p>How could I merge / convert multiple PDF files into one large PDF file?</p>
<p>I tried the following, but the content of the target file was not as expected:</p>
<pre><code>convert file1.pdf file2.pdf merged.pdf
</code></pre>
<p>I need a very simple/basic command line (CLI) solution. Best would be if I could pipe the output of the merge / convert straight into <code>pdf2ps</code> ( as originally attempted in my previously asked question here: <a href="https://stackoverflow.com/questions/2507596/linux-piping-convert-pdf2ps-lp">Linux piping ( convert -> pdf2ps -> lp)</a> ).</p>
|
<p>I'm sorry, I managed to find the answer myself using google and a bit of luck : )</p>
<p>For those interested;</p>
<p>I installed the pdftk (pdf toolkit) on our debian server, and using the following command I achieved desired output:</p>
<pre><code>pdftk file1.pdf file2.pdf cat output output.pdf
</code></pre>
<p>OR </p>
<pre><code>gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=output.pdf file1.pdf file2.pdf file3.pdf ...
</code></pre>
<p>This in turn can be piped directly into pdf2ps.</p>
|
{
"question_id": 2507766,
"question_date": "2010-03-24T12:56:47.203Z",
"question_score": 1412,
"tags": "linux|pdf|merge|command-line-interface",
"answer_id": 2507825,
"answer_date": "2010-03-24T13:06:30.617Z",
"answer_score": 618
}
|
Please answer the following Stack Overflow question:
Title: Using group by on multiple columns
<p>I understand the point of <code>GROUP BY x</code>.</p>
<p>But how does <code>GROUP BY x, y</code> work, and what does it mean?</p>
|
<p><code>Group By X</code> means <strong>put all those with the same value for X in the one group</strong>.</p>
<p><code>Group By X, Y</code> means <strong>put all those with the same values for both X and Y in the one group</strong>.</p>
<p>To illustrate using an example, let's say we have the following table, to do with who is attending what subject at a university:</p>
<pre><code>Table: Subject_Selection
+---------+----------+----------+
| Subject | Semester | Attendee |
+---------+----------+----------+
| ITB001 | 1 | John |
| ITB001 | 1 | Bob |
| ITB001 | 1 | Mickey |
| ITB001 | 2 | Jenny |
| ITB001 | 2 | James |
| MKB114 | 1 | John |
| MKB114 | 1 | Erica |
+---------+----------+----------+
</code></pre>
<p>When you use a <code>group by</code> on the subject column only; say:</p>
<pre><code>select Subject, Count(*)
from Subject_Selection
group by Subject
</code></pre>
<p>You will get something like:</p>
<pre><code>+---------+-------+
| Subject | Count |
+---------+-------+
| ITB001 | 5 |
| MKB114 | 2 |
+---------+-------+
</code></pre>
<p>...because there are 5 entries for ITB001, and 2 for MKB114</p>
<p>If we were to <code>group by</code> two columns:</p>
<pre><code>select Subject, Semester, Count(*)
from Subject_Selection
group by Subject, Semester
</code></pre>
<p>we would get this:</p>
<pre><code>+---------+----------+-------+
| Subject | Semester | Count |
+---------+----------+-------+
| ITB001 | 1 | 3 |
| ITB001 | 2 | 2 |
| MKB114 | 1 | 2 |
+---------+----------+-------+
</code></pre>
<p>This is because, when we group by two columns, it is saying <strong>"Group them so that all of those with the same Subject and Semester are in the same group, and then calculate all the aggregate functions</strong> (Count, Sum, Average, etc.) <strong>for each of those groups"</strong>. In this example, this is demonstrated by the fact that, when we count them, there are <strong>three</strong> people doing ITB001 in semester 1, and <strong>two</strong> doing it in semester 2. Both of the people doing MKB114 are in semester 1, so there is no row for semester 2 (no data fits into the group "MKB114, Semester 2")</p>
<p>Hopefully that makes sense.</p>
|
{
"question_id": 2421388,
"question_date": "2010-03-10T23:11:23.113Z",
"question_score": 1411,
"tags": "sql|group-by|multiple-columns",
"answer_id": 2421441,
"answer_date": "2010-03-10T23:24:01.250Z",
"answer_score": 2613
}
|
Please answer the following Stack Overflow question:
Title: How do I remove the passphrase for the SSH key without having to create a new key?
<p>I set a passphrase when creating a new SSH key on my laptop. But, as I realise now, this is quite painful when you are trying to commit (<a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="noreferrer">Git</a> and <a href="http://en.wikipedia.org/wiki/Apache_Subversion" rel="noreferrer">SVN</a>) to a remote location over SSH many times in an hour.</p>
<p>One way I can think of is, delete my SSH keys and create new. Is there a way to remove the passphrase, while still keeping the same keys?</p>
|
<p>Short answer:</p>
<pre><code>$ ssh-keygen -p
</code></pre>
<p>This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (which can be left blank to have no passphrase).</p>
<hr>
<p>If you would like to do it all on one line without prompts do:</p>
<pre><code>$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]
</code></pre>
<p><strong>Important:</strong> Beware that when executing commands they will typically be logged in your <code>~/.bash_history</code> file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is, therefore, is recommended that you use the first option unless you have a specific reason to do otherwise. </p>
<p>Notice though that you can still use <code>-f keyfile</code> without having to specify <code>-P</code> nor <code>-N</code>, and that the keyfile defaults to <code>~/.ssh/id_rsa</code>, so in many cases, it's not even needed.</p>
<p>You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent.</p>
|
{
"question_id": 112396,
"question_date": "2008-09-21T22:39:02.527Z",
"question_score": 1408,
"tags": "unix|ssh|passwords|openssh|passphrase",
"answer_id": 112409,
"answer_date": "2008-09-21T22:42:09.353Z",
"answer_score": 2559
}
|
Please answer the following Stack Overflow question:
Title: Trigger a button click with JavaScript on the Enter key in a text box
<p>I have one text input and one button (see below). How can I use JavaScript to <strong>trigger the button's click event</strong> when the <kbd>Enter</kbd> key is pressed inside the text box?</p>
<p>There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I <em>only</em> want the <kbd>Enter</kbd> key to click this specific button if it is pressed from within this one text box, nothing else.</p>
<pre><code><input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
</code></pre>
|
<p>In jQuery, the following would work:</p>
<pre><code>$("#id_of_textbox").keyup(function(event) {
if (event.keyCode === 13) {
$("#id_of_button").click();
}
});
</code></pre>
<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>$("#pw").keyup(function(event) {
if (event.keyCode === 13) {
$("#myButton").click();
}
});
$("#myButton").click(function() {
alert("Button code executed.");
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Username:<input id="username" type="text"><br>
Password:&nbsp;<input id="pw" type="password"><br>
<button id="myButton">Submit</button></code></pre>
</div>
</div>
</p>
<p>Or in plain JavaScript, the following would work:</p>
<pre><code>document.getElementById("id_of_textbox")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("id_of_button").click();
}
});
</code></pre>
<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.getElementById("pw")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function buttonCode()
{
alert("Button code executed.");
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Username:<input id="username" type="text"><br>
Password:&nbsp;<input id="pw" type="password"><br>
<button id="myButton" onclick="buttonCode()">Submit</button></code></pre>
</div>
</div>
</p>
|
{
"question_id": 155188,
"question_date": "2008-09-30T21:32:09.577Z",
"question_score": 1407,
"tags": "javascript|button|onclick|onkeydown|onkeypress",
"answer_id": 155263,
"answer_date": "2008-09-30T21:52:16.970Z",
"answer_score": 1508
}
|
Please answer the following Stack Overflow question:
Title: Send HTTP POST request in .NET
<p>How can I make an HTTP <a href="https://en.wikipedia.org/wiki/POST_%28HTTP%29" rel="noreferrer">POST</a> request and send data in the body?</p>
|
<p>There are several ways to perform HTTP <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods" rel="noreferrer">GET</a> and <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods" rel="noreferrer">POST</a> requests:</p>
<hr />
<h2>Method A: HttpClient (Preferred)</h2>
<p>Available in: .NET Framework 4.5+, .NET Standard 1.1+, and .NET Core 1.0+.</p>
<p>It is currently the preferred approach, and is asynchronous and high performance. Use the built-in version in most cases, but for very old platforms there is a <a href="https://www.nuget.org/packages/System.Net.Http" rel="noreferrer">NuGet package</a>.</p>
<pre><code>using System.Net.Http;
</code></pre>
<h3>Setup</h3>
<p><a href="https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/" rel="noreferrer">It is recommended</a> to instantiate one <code>HttpClient</code> for your application's lifetime and share it unless you have a specific reason not to.</p>
<pre><code>private static readonly HttpClient client = new HttpClient();
</code></pre>
<p>See <a href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#what-is-httpclientfactory" rel="noreferrer"><code>HttpClientFactory</code></a> for a <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer">dependency injection</a> solution.</p>
<hr />
<ul>
<li><p>POST</p>
<pre><code> var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
</code></pre>
</li>
<li><p>GET</p>
<pre><code> var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
</code></pre>
</li>
</ul>
<hr />
<h2>Method B: Third-Party Libraries</h2>
<p><em><strong><a href="https://github.com/restsharp/RestSharp" rel="noreferrer">RestSharp</a></strong></em></p>
<ul>
<li><p>POST</p>
<pre><code> var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}");
request.AddParameter("thing1", "Hello");
request.AddParameter("thing2", "world");
request.AddHeader("header", "value");
request.AddFile("file", path);
var response = client.Post(request);
var content = response.Content; // Raw content as string
var response2 = client.Post<Person>(request);
var name = response2.Data.Name;
</code></pre>
</li>
</ul>
<p><em><strong><a href="https://flurl.dev/" rel="noreferrer">Flurl.Http</a></strong></em></p>
<p>It is a newer library sporting a <a href="https://en.wikipedia.org/wiki/Fluent_interface" rel="noreferrer">fluent API</a>, testing helpers, uses HttpClient under the hood, and is portable. It is available via <a href="https://www.nuget.org/packages/Flurl.Http" rel="noreferrer">NuGet</a>.</p>
<pre><code> using Flurl.Http;
</code></pre>
<hr />
<ul>
<li><p>POST</p>
<pre><code> var responseString = await "http://www.example.com/recepticle.aspx"
.PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
.ReceiveString();
</code></pre>
</li>
<li><p><code>GET</code></p>
<pre><code> var responseString = await "http://www.example.com/recepticle.aspx"
.GetStringAsync();
</code></pre>
</li>
</ul>
<hr />
<h2>Method C: HttpWebRequest (not recommended for new work)</h2>
<p>Available in: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+. In .NET Core, it is mostly for compatibility -- it wraps <code>HttpClient</code>, is less performant, and won't get new features.</p>
<pre><code>using System.Net;
using System.Text; // For class Encoding
using System.IO; // For StreamReader
</code></pre>
<hr />
<ul>
<li><p>POST</p>
<pre><code> var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=" + Uri.EscapeDataString("hello");
postData += "&thing2=" + Uri.EscapeDataString("world");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
</code></pre>
</li>
<li><p>GET</p>
<pre><code> var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
</code></pre>
</li>
</ul>
<hr />
<h2>Method D: WebClient (Not recommended for new work)</h2>
<p>This is a wrapper around <code>HttpWebRequest</code>. <a href="https://stackoverflow.com/questions/20530152/deciding-between-httpclient-and-webclient/27737601#27737601">Compare with <code>HttpClient</code></a>.</p>
<p>Available in: .NET Framework 1.1+, NET Standard 2.0+, and .NET Core 2.0+.</p>
<p>In some circumstances (.NET Framework 4.5-4.8), if you need to do a HTTP request synchronously, <code>WebClient</code> can still be used.</p>
<pre><code>using System.Net;
using System.Collections.Specialized;
</code></pre>
<hr />
<ul>
<li><p>POST</p>
<pre><code> using (var client = new WebClient())
{
var values = new NameValueCollection();
values["thing1"] = "hello";
values["thing2"] = "world";
var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);
var responseString = Encoding.Default.GetString(response);
}
</code></pre>
</li>
<li><p>GET</p>
<pre><code> using (var client = new WebClient())
{
var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
}
</code></pre>
</li>
</ul>
|
{
"question_id": 4015324,
"question_date": "2010-10-25T14:05:58.070Z",
"question_score": 1406,
"tags": "c#|.net|post|httpwebrequest|httprequest",
"answer_id": 4015346,
"answer_date": "2010-10-25T14:08:07.163Z",
"answer_score": 2578
}
|
Please answer the following Stack Overflow question:
Title: Custom HTTP headers : naming conventions
<p>Several of our users have asked us to include data relative to their account in the <em>HTTP headers</em> of requests we send them, or even responses they get from our API.
What is the general convention to add custom HTTP headers, in terms of <strong>naming</strong>, <strong>format</strong>... etc.</p>
<p>Also, feel free to post any smart usage of these that you stumbled upon on the web; We're trying to implement this using what's best out there as a target :)</p>
|
<p>The recommendation <strike>is</strike> <strong>was</strong> to start their name with "X-". E.g. <a href="http://en.wikipedia.org/wiki/X-Forwarded-For" rel="noreferrer"><code>X-Forwarded-For</code></a>, <a href="http://en.wikipedia.org/wiki/X-Requested-With" rel="noreferrer"><code>X-Requested-With</code></a>. This is also mentioned in a.o. section 5 of <a href="http://www.ietf.org/rfc/rfc2047.txt" rel="noreferrer">RFC 2047</a>.</p>
<hr />
<p><strong>Update 1</strong>: On June 2011, the first <a href="https://datatracker.ietf.org/doc/html/draft-saintandre-xdash-00" rel="noreferrer">IETF draft</a> was posted to <strong>deprecate</strong> the recommendation of using the "X-" prefix for non-standard headers. The reason is that when non-standard headers prefixed with "X-" become standard, removing the "X-" prefix breaks backwards compatibility, forcing application protocols to support both names (E.g, <code>x-gzip</code> & <code>gzip</code> are now equivalent). So, the official recommendation is to just name them <em>sensibly</em> without the "X-" prefix.</p>
<hr />
<p><strong>Update 2</strong>: On June 2012, the deprecation of recommendation to use the "X-" prefix has become official as <a href="https://www.rfc-editor.org/rfc/rfc6648" rel="noreferrer">RFC 6648</a>. Below are cites of relevance:</p>
<blockquote>
<h3>3. Recommendations for Creators of New Parameters</h3>
<p>...</p>
<ol start="3">
<li>SHOULD NOT prefix their parameter names with "X-" or similar
constructs.</li>
</ol>
</blockquote>
<blockquote>
<h3>4. Recommendations for Protocol Designers</h3>
<p>...</p>
<ol start="4">
<li><p>SHOULD NOT prohibit parameters with an "X-" prefix or similar
constructs from being registered.</p>
</li>
<li><p>MUST NOT stipulate that a parameter with an "X-" prefix or
similar constructs needs to be understood as unstandardized.</p>
</li>
<li><p>MUST NOT stipulate that a parameter without an "X-" prefix or
similar constructs needs to be understood as standardized.</p>
</li>
</ol>
</blockquote>
<p>Note that "SHOULD NOT" ("discouraged") is not the same as "MUST NOT" ("forbidden"), see also <a href="https://www.rfc-editor.org/rfc/rfc2119" rel="noreferrer">RFC 2119</a> for another spec on those keywords. In other words, you can keep using "X-" prefixed headers, but it's not officially recommended anymore and you may definitely not document them as if they are public standard.</p>
<hr />
<p><strong>Summary</strong>:</p>
<ul>
<li>the official recommendation is to just name them <em>sensibly</em> without the "X-" prefix</li>
<li>you can keep using "X-" prefixed headers, but it's not officially recommended anymore and you may definitely not document them as if they are public standard</li>
</ul>
|
{
"question_id": 3561381,
"question_date": "2010-08-24T21:59:38.850Z",
"question_score": 1406,
"tags": "http|http-headers",
"answer_id": 3561399,
"answer_date": "2010-08-24T22:02:52.393Z",
"answer_score": 1492
}
|
Please answer the following Stack Overflow question:
Title: Get the current year in JavaScript
<p>How do I get the current year in JavaScript?</p>
|
<p>Create a <strong><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/Date" rel="noreferrer"><code>new Date()</code></a></strong> object and call <strong><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear" rel="noreferrer"><code>getFullYear()</code></a></strong>:</p>
<pre><code>new Date().getFullYear() // returns the current year
</code></pre>
<hr />
<p><strong>Example usage:</strong> a page footer that always shows the current year:</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.getElementById("year").innerHTML = new Date().getFullYear();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>footer {
text-align: center;
font-family: sans-serif;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
©<span id="year"></span> by Donald Duck
</footer></code></pre>
</div>
</div>
</p>
<p>See also, the <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/Date" rel="noreferrer"><code>Date()</code></a> constructor's <strong><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#static_methods" rel="noreferrer">full list of methods</a></strong>.</p>
|
{
"question_id": 6002254,
"question_date": "2011-05-14T13:53:05.757Z",
"question_score": 1405,
"tags": "javascript|date",
"answer_id": 6002276,
"answer_date": "2011-05-14T13:57:40.143Z",
"answer_score": 2393
}
|
Please answer the following Stack Overflow question:
Title: Find when a file was deleted in Git
<p>I have a Git repository with n commits.</p>
<p>I have a file that I need, and that used to be in the repository, and that I suddenly look for and think "Oh! Where'd that file go?"</p>
<p>Is there a (series of) Git command(s) that will tell me that "file really_needed.txt was deleted at commit n-13"?</p>
<p>In other words, without looking at every individual commit, and knowing that my Git repo has every change of every file, can I quickly find the last commit that HAS that file, so I can get it back?</p>
|
<p>To show the commits that changed a file, even if the file was deleted, run this command:</p>
<pre><code>git log --full-history -- [file path]
</code></pre>
<p>If you want to see only the last commit, which deleted the file, use <code>-1</code> in addition to the command above:</p>
<pre><code>git log --full-history -1 -- [file path]
</code></pre>
<p>See also my article: <a href="http://www.vogella.com/articles/Git/article.html#retrievefiles_finddeletedfile" rel="noreferrer">Which commit deleted a file</a>.</p>
|
{
"question_id": 6839398,
"question_date": "2011-07-27T04:23:45.773Z",
"question_score": 1404,
"tags": "git",
"answer_id": 16635324,
"answer_date": "2013-05-19T13:48:00.157Z",
"answer_score": 1528
}
|
Please answer the following Stack Overflow question:
Title: Why is executing Java code in comments with certain Unicode characters allowed?
<p>The following code produces the output "Hello World!" (no really, try it).</p>
<pre><code>public static void main(String... args) {
// The comment below is not a typo.
// \u000d System.out.println("Hello World!");
}
</code></pre>
<p>The reason for this is that the Java compiler parses the Unicode character <code>\u000d</code> as a new line and gets transformed into:</p>
<pre><code>public static void main(String... args) {
// The comment below is not a typo.
//
System.out.println("Hello World!");
}
</code></pre>
<p>Thus resulting into a comment being "executed".</p>
<p>Since this can be used to "hide" malicious code or whatever an evil programmer can conceive, <strong>why is it allowed in comments</strong>?</p>
<p>Why is this allowed by the Java specification?</p>
|
<p>Unicode decoding takes place before any other lexical translation. The key benefit of this is that it makes it trivial to go back and forth between ASCII and any other encoding. You don't even need to figure out where comments begin and end!</p>
<p>As stated in <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.3">JLS Section 3.3</a> this allows any ASCII based tool to process the source files:</p>
<blockquote>
<p>[...] The Java programming language specifies a standard way of transforming a program written in Unicode into ASCII that changes a program into a form that can be processed by ASCII-based tools. [...]</p>
</blockquote>
<p>This gives a fundamental guarantee for platform independence (independence of supported character sets) which has always been a key goal for the Java platform. </p>
<p>Being able to write any Unicode character anywhere in the file is a neat feature, and especially important in comments, when documenting code in non-latin languages. The fact that it can interfere with the semantics in such subtle ways is just an (unfortunate) side-effect.</p>
<p>There are many gotchas on this theme and <a href="http://www.javapuzzlers.com/"><em>Java Puzzlers</em></a> by Joshua Bloch and Neal Gafter included the following variant:</p>
<blockquote>
<p>Is this a legal Java program? If so, what does it print?</p>
<pre><code>\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020\u0020
\u0063\u006c\u0061\u0073\u0073\u0020\u0055\u0067\u006c\u0079
\u007b\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020
\u0020\u0020\u0020\u0020\u0073\u0074\u0061\u0074\u0069\u0063
\u0076\u006f\u0069\u0064\u0020\u006d\u0061\u0069\u006e\u0028
\u0053\u0074\u0072\u0069\u006e\u0067\u005b\u005d\u0020\u0020
\u0020\u0020\u0020\u0020\u0061\u0072\u0067\u0073\u0029\u007b
\u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074
\u002e\u0070\u0072\u0069\u006e\u0074\u006c\u006e\u0028\u0020
\u0022\u0048\u0065\u006c\u006c\u006f\u0020\u0077\u0022\u002b
\u0022\u006f\u0072\u006c\u0064\u0022\u0029\u003b\u007d\u007d
</code></pre>
</blockquote>
<p>(This program turns out to be a plain "Hello World" program.)</p>
<p>In the solution to the puzzler, they point out the following:</p>
<blockquote>
<p>More seriously, this puzzle serves to reinforce the lessons of the previous three: <strong>Unicode escapes are essential when you need to insert characters that can’t be represented in any other way into your program. Avoid them in all other cases.</strong></p>
</blockquote>
<hr>
<p>Source: <a href="http://programming.guide/java/executing-code-in-comments.html">Java: Executing code in comments?!</a></p>
|
{
"question_id": 30727515,
"question_date": "2015-06-09T09:02:16.973Z",
"question_score": 1404,
"tags": "java|unicode|comments",
"answer_id": 30727799,
"answer_date": "2015-06-09T09:13:50.807Z",
"answer_score": 763
}
|
Please answer the following Stack Overflow question:
Title: How to convert a string to number in TypeScript?
<p>Given a string representation of a number, how can I convert it to <code>number</code> type in TypeScript?</p>
<pre><code>var numberString: string = "1234";
var numberValue: number = /* what should I do with `numberString`? */;
</code></pre>
|
<p><a href="https://stackoverflow.com/questions/1133770/convert-a-string-to-an-integer">Exactly like</a> <a href="https://stackoverflow.com/questions/17106681/parseint-vs-unary-plus-when-to-use-which/17106702#17106702">in JavaScript</a>, you can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt" rel="noreferrer"><code>parseInt</code></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat" rel="noreferrer"><code>parseFloat</code></a> functions, or simply use the unary <code>+</code> operator:</p>
<pre><code>var x = "32";
var y: number = +x;
</code></pre>
<p>All of the mentioned techniques will have correct typing and will correctly parse simple decimal integer strings like <code>"123"</code>, but will behave differently for various other, possibly expected, cases (like <code>"123.45"</code>) and corner cases (like <code>null</code>).</p>
<p><a href="https://i.stack.imgur.com/QNMfI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QNMfI.png" alt="Conversion table"></a>
Table taken from <a href="https://stackoverflow.com/a/17106702/1483676">this answer</a></p>
|
{
"question_id": 14667713,
"question_date": "2013-02-02T23:34:18.517Z",
"question_score": 1403,
"tags": "typescript",
"answer_id": 14668510,
"answer_date": "2013-02-03T01:19:52.857Z",
"answer_score": 2129
}
|
Please answer the following Stack Overflow question:
Title: ignoring any 'bin' directory on a git project
<p>I have a directory structure like this:</p>
<pre><code>.git/
.gitignore
main/
...
tools/
...
...
</code></pre>
<p>Inside main and tools, and any other directory, at any level, there can be a 'bin' directory, which I want to ignore (and I want to ignore everything under it too). I've tried each of these patterns in .gitignore but none of them work:</p>
<pre><code>/**/bin/**/*
/./**/bin/**/*
./**/bin/**/*
**/bin/**/*
*/bin/**/*
bin/**/*
/**/bin/* #and the others with just * at the end too
</code></pre>
<p>Can anyone help me out? The first pattern (the one I think should be working) works just fine if I do this:</p>
<pre><code>/main/**/bin/**/*
</code></pre>
<p>But I don't want to have an entry for every top-level directory and I don't want to have to modify .gitignore every time I add a new one.</p>
<p>This is on Windows using the latest msysgit.</p>
<p>EDIT: <strong>one more thing, there are files and directories that have the substring 'bin' in their names, I don't want those to be ignored :)</strong></p>
|
<p>Before version 1.8.2, <code>**</code> didn't have any special meaning in the <code>.gitignore</code>. As of 1.8.2 git supports <code>**</code> to mean zero or more sub-directories (see <a href="https://github.com/git/git/blob/master/Documentation/RelNotes/1.8.2.txt" rel="noreferrer">release notes</a>).</p>
<p>The way to ignore all directories called bin anywhere below the current level in a directory tree is with a <code>.gitignore</code> file with the pattern:</p>
<pre><code>bin/
</code></pre>
<p>In the <code>man</code> page, there an example of ignoring a directory called <code>foo</code> using an analogous pattern.</p>
<p><strong>Edit:</strong>
If you already have any bin folders in your git index which you no longer wish to track then you need to remove them explicitly. Git won't stop tracking paths that are already being tracked just because they now match a new <code>.gitignore</code> pattern. Execute a folder remove (<strong>rm</strong>) from index only (<strong>--cached</strong>) recursivelly (<strong>-r</strong>). Command line example for root bin folder:</p>
<pre><code>git rm -r --cached bin
</code></pre>
|
{
"question_id": 1470572,
"question_date": "2009-09-24T09:13:51.907Z",
"question_score": 1403,
"tags": "git|gitignore",
"answer_id": 1470664,
"answer_date": "2009-09-24T09:35:38.760Z",
"answer_score": 2058
}
|
Please answer the following Stack Overflow question:
Title: Object comparison in JavaScript
<p>What is the best way to compare objects in JavaScript?</p>
<p>Example:</p>
<pre><code>var user1 = {name : "nerd", org: "dev"};
var user2 = {name : "nerd", org: "dev"};
var eq = user1 == user2;
alert(eq); // gives false
</code></pre>
<p>I know that <strong>two objects are equal if they refer to the exact same object</strong>, but is there a way to check if they have the same attributes' values?</p>
<p>The following way works for me, but is it the only possibility?</p>
<pre><code>var eq = Object.toJSON(user1) == Object.toJSON(user2);
alert(eq); // gives true
</code></pre>
|
<p>Unfortunately there is no perfect way, unless you use <code>_proto_</code> recursively and access all non-enumerable properties, but this works in Firefox only.</p>
<p>So the best I can do is to guess usage scenarios.</p>
<hr>
<h2><strong>1) Fast and limited.</strong></h2>
<p>Works when you have simple JSON-style objects without methods and DOM nodes inside:</p>
<pre><code> JSON.stringify(obj1) === JSON.stringify(obj2)
</code></pre>
<p>The ORDER of the properties IS IMPORTANT, so this method will return false for following objects:</p>
<pre><code> x = {a: 1, b: 2};
y = {b: 2, a: 1};
</code></pre>
<hr>
<h2><strong>2) Slow and more generic.</strong></h2>
<p>Compares objects without digging into prototypes, then compares properties' projections recursively, and also compares constructors.</p>
<p>This is almost correct algorithm:</p>
<pre><code>function deepCompare () {
var i, l, leftChain, rightChain;
function compare2Objects (x, y) {
var p;
// remember that NaN === NaN returns false
// and isNaN(undefined) returns true
if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') {
return true;
}
// Compare primitives and functions.
// Check if both arguments link to the same object.
// Especially useful on the step where we compare prototypes
if (x === y) {
return true;
}
// Works in case when functions are created in constructor.
// Comparing dates is a common scenario. Another built-ins?
// We can even handle functions passed across iframes
if ((typeof x === 'function' && typeof y === 'function') ||
(x instanceof Date && y instanceof Date) ||
(x instanceof RegExp && y instanceof RegExp) ||
(x instanceof String && y instanceof String) ||
(x instanceof Number && y instanceof Number)) {
return x.toString() === y.toString();
}
// At last checking prototypes as good as we can
if (!(x instanceof Object && y instanceof Object)) {
return false;
}
if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) {
return false;
}
if (x.constructor !== y.constructor) {
return false;
}
if (x.prototype !== y.prototype) {
return false;
}
// Check for infinitive linking loops
if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {
return false;
}
// Quick checking of one object being a subset of another.
// todo: cache the structure of arguments[0] for performance
for (p in y) {
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
return false;
}
else if (typeof y[p] !== typeof x[p]) {
return false;
}
}
for (p in x) {
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
return false;
}
else if (typeof y[p] !== typeof x[p]) {
return false;
}
switch (typeof (x[p])) {
case 'object':
case 'function':
leftChain.push(x);
rightChain.push(y);
if (!compare2Objects (x[p], y[p])) {
return false;
}
leftChain.pop();
rightChain.pop();
break;
default:
if (x[p] !== y[p]) {
return false;
}
break;
}
}
return true;
}
if (arguments.length < 1) {
return true; //Die silently? Don't know how to handle such case, please help...
// throw "Need two or more arguments to compare";
}
for (i = 1, l = arguments.length; i < l; i++) {
leftChain = []; //Todo: this can be cached
rightChain = [];
if (!compare2Objects(arguments[0], arguments[i])) {
return false;
}
}
return true;
}
</code></pre>
<p>Known issues (well, they have very low priority, probably you'll never notice them):</p>
<ul>
<li>objects with different prototype structure but same projection</li>
<li>functions may have identical text but refer to different closures</li>
</ul>
<p><strong>Tests:</strong> passes tests are from <em><a href="https://stackoverflow.com/a/16788517/139361">How to determine equality for two JavaScript objects?</a></em>.</p>
|
{
"question_id": 1068834,
"question_date": "2009-07-01T12:18:29.613Z",
"question_score": 1402,
"tags": "javascript|object|comparison|object-comparison",
"answer_id": 1144249,
"answer_date": "2009-07-17T16:08:59.473Z",
"answer_score": 1669
}
|
Please answer the following Stack Overflow question:
Title: Difference between Constructor and ngOnInit
<p>Angular provides life cycle hook <code>ngOnInit</code> by default.</p>
<p>Why should <code>ngOnInit</code> be used, if we already have a <code>constructor</code>?</p>
|
<p>The <code>Constructor</code> is a default method of the class that is executed when the class is instantiated and ensures proper initialisation of fields in the class and its subclasses. Angular, or better Dependency Injector (DI), analyses the constructor parameters and when it creates a new instance by calling <code>new MyClass()</code> it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor like</p>
<pre><code>new MyClass(someArg);
</code></pre>
<p><code>ngOnInit</code> is a life cycle hook called by Angular to indicate that Angular is done creating the component.</p>
<p>We have to import <code>OnInit</code> like this in order to use it (actually implementing <code>OnInit</code> is not mandatory but considered good practice):</p>
<pre><code>import { Component, OnInit } from '@angular/core';
</code></pre>
<p>then to make use of the method <code>OnInit</code>, we have to implement the class like this:</p>
<pre><code>export class App implements OnInit {
constructor() {
// Called first time before the ngOnInit()
}
ngOnInit() {
// Called after the constructor and called after the first ngOnChanges()
}
}
</code></pre>
<blockquote>
<p>Implement this interface to execute custom initialization logic after your directive's data-bound properties have been initialized.
ngOnInit is called right after the directive's data-bound properties have been checked for the first time,
and before any of its children have been checked.
It is invoked only once when the directive is instantiated.</p>
</blockquote>
<p>Mostly we use <code>ngOnInit</code> for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".</p>
<p>So you should use <code>constructor()</code> to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's where/when components' bindings are resolved.</p>
<p>For more information refer here:</p>
<ul>
<li><p><a href="https://angular.io/api/core/OnInit" rel="noreferrer">https://angular.io/api/core/OnInit</a></p>
</li>
<li><p><a href="https://stackoverflow.com/a/35846307/5043867">Angular Component Constructor Vs OnInit</a></p>
</li>
</ul>
<p>Important to note that @Input values are not accessible in the constructor (Thanks to @tim for suggestion in comments)</p>
|
{
"question_id": 35763730,
"question_date": "2016-03-03T05:14:03.667Z",
"question_score": 1402,
"tags": "angular|typescript|ngoninit|angular-lifecycle-hooks",
"answer_id": 35763811,
"answer_date": "2016-03-03T05:20:08.773Z",
"answer_score": 1417
}
|
Please answer the following Stack Overflow question:
Title: Changing git commit message after push (given that no one pulled from remote)
<p>I have made a git commit and subsequent push. I would like to change the commit message. If I understand correctly, this is not advisable because someone might have pulled from the remote repository before I make such changes. What if I know that no one has pulled? </p>
<p>Is there a way to do this?</p>
|
<h3>Changing history</h3>
<p>If it is the most recent commit, you can simply do this:</p>
<pre><code>git commit --amend
</code></pre>
<p>This brings up the editor with the last commit message and lets you edit the message. (You can use <code>-m</code> if you want to wipe out the old message and use a new one.)</p>
<h3>Pushing</h3>
<p>And then when you push, do this:</p>
<pre><code>git push --force-with-lease <repository> <branch>
</code></pre>
<p>Or you can use "+":</p>
<pre><code>git push <repository> +<branch>
</code></pre>
<p>Or you can use <code>--force</code>:</p>
<pre><code>git push --force <repository> <branch>
</code></pre>
<p>Be careful when using these commands.</p>
<ul>
<li><p>If someone else pushed changes to the same branch, you probably want to avoid destroying those changes. The <code>--force-with-lease</code> option is the safest, because it will abort if there are any upstream changes (</p></li>
<li><p>If you don't specify the branch explicitly, Git will use the default push settings. If your default push setting is "matching", then you may destroy changes on several branches at the same time. </p></li>
</ul>
<h3>Pulling / fetching afterwards</h3>
<p>Anyone who already pulled will now get an error message, and they will need to update (assuming they aren't making any changes themselves) by doing something like this:</p>
<pre><code>git fetch origin
git reset --hard origin/master # Loses local commits
</code></pre>
<p>Be careful when using <code>reset --hard</code>. If you have changes to the branch, those changes will be destroyed.</p>
<h3>A note about modifying history</h3>
<p>The destroyed data is really just the old commit message, but <code>--force</code> doesn't know that, and will happily delete other data too. So think of <code>--force</code> as "I want to destroy data, and I know for sure what data is being destroyed." But when the destroyed data is committed, you can often recover old commits from the reflog—the data is actually <em>orphaned</em> instead of destroyed (although orphaned commits are periodically deleted).</p>
<p>If you don't think you're destroying data, then stay away from <code>--force</code>... <a href="https://stackoverflow.com/questions/13036947/10-git-lines-erased-8gb-form-my-pc-how-to-get-them-back/13037141">bad things might happen</a>.</p>
<p>This is why <code>--force-with-lease</code> is somewhat safer.</p>
|
{
"question_id": 8981194,
"question_date": "2012-01-24T01:58:25.293Z",
"question_score": 1398,
"tags": "git|push|commit",
"answer_id": 8981216,
"answer_date": "2012-01-24T02:02:24.590Z",
"answer_score": 1766
}
|
Please answer the following Stack Overflow question:
Title: Can I recover a branch after its deletion in Git?
<p>If I run <code>git branch -d XYZ</code>, is there a way to recover the branch? Is there a way to go back as if I didn't run the delete branch command?</p>
|
<p>Yes, you should be able to do <code>git reflog --no-abbrev</code> and find the SHA1 for the commit at the tip of your deleted branch, then just <code>git checkout [sha]</code>. And once you're at that commit, you can just <code>git checkout -b [branchname]</code> to recreate the branch from there.</p>
<hr />
<p><strong>Credit to @Cascabel for this condensed/one-liner version and @Snowcrash for how to obtain the sha.</strong></p>
<p>If you've just deleted the branch you'll see something like this in your terminal <code>Deleted branch <your-branch> (was <sha>)</code>. Then just use that <code><sha></code> in this one-liner:</p>
<pre><code>git checkout -b <your-branch> <sha>
</code></pre>
|
{
"question_id": 3640764,
"question_date": "2010-09-04T03:25:19.537Z",
"question_score": 1398,
"tags": "git|branch|git-branch",
"answer_id": 3640806,
"answer_date": "2010-09-04T03:43:13.387Z",
"answer_score": 2586
}
|
Please answer the following Stack Overflow question:
Title: Determine whether an array contains a value
<p>I need to determine if a value exists in an array.</p>
<p>I am using the following function:</p>
<pre><code>Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
</code></pre>
<p>The above function always returns false.</p>
<p>The array values and the function call is as below:</p>
<pre><code>arrValues = ["Sam","Great", "Sample", "High"]
alert(arrValues.contains("Sam"));
</code></pre>
|
<pre><code>var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};
</code></pre>
<p>You can use it like this:</p>
<pre><code>var myArray = [0,1,2],
needle = 1,
index = contains.call(myArray, needle); // true
</code></pre>
<p><a href="http://codepen.io/anon/pen/mVRNaJ" rel="noreferrer">CodePen validation/usage</a></p>
|
{
"question_id": 1181575,
"question_date": "2009-07-25T08:18:57.813Z",
"question_score": 1397,
"tags": "javascript|arrays|contains",
"answer_id": 1181586,
"answer_date": "2009-07-25T08:22:43.500Z",
"answer_score": 1015
}
|
Please answer the following Stack Overflow question:
Title: How can I get a list of user accounts using the command line in MySQL?
<p>I'm using the MySQL command-line utility and can navigate through a database. Now I need to see a list of user accounts. How can I do this?</p>
<p>I'm using MySQL version 5.4.1.</p>
|
<p>Use this query:</p>
<pre><code>SELECT User FROM mysql.user;
</code></pre>
<p>Which will output a table like this:</p>
<pre class="lang-none prettyprint-override"><code>+-------+
| User |
+-------+
| root |
+-------+
| user2 |
+-------+
</code></pre>
<p>As Matthew Scharley <a href="https://stackoverflow.com/questions/1135245/how-to-get-a-list-of-mysql-user-accounts/1135251#comment953239_1135251">points out in the comments on this answer</a>, you can group by the <code>User</code> column if you'd only like to see unique usernames.</p>
|
{
"question_id": 1135245,
"question_date": "2009-07-16T03:23:53.637Z",
"question_score": 1397,
"tags": "mysql|command-line|mysql5",
"answer_id": 1135251,
"answer_date": "2009-07-16T03:26:37.250Z",
"answer_score": 1881
}
|
Please answer the following Stack Overflow question:
Title: Convert JavaScript String to be all lower case
<p>How can I convert a JavaScript string value to be in all lower case letters?</p>
<p>Example: <code>"Your Name"</code> to <code>"your name"</code></p>
|
<pre><code>var lowerCaseName = "Your Name".toLowerCase();
</code></pre>
|
{
"question_id": 154862,
"question_date": "2008-09-30T20:22:35.093Z",
"question_score": 1397,
"tags": "javascript|string",
"answer_id": 154891,
"answer_date": "2008-09-30T20:26:19.703Z",
"answer_score": 1808
}
|
Please answer the following Stack Overflow question:
Title: Tab key == 4 spaces and auto-indent after curly braces in Vim
<p>How do I make <a href="http://en.wikipedia.org/wiki/Vi" rel="noreferrer">vi</a>-<a href="http://en.wikipedia.org/wiki/Vim_%28text_editor%29" rel="noreferrer">Vim</a> never use tabs (converting spaces to tabs, bad!), makes the tab key == 4 spaces, and automatically indent code after curly brace blocks like <a href="http://en.wikipedia.org/wiki/Emacs" rel="noreferrer">Emacs</a> does?</p>
<p>Also, how do I save these settings so I never have to input them again?</p>
<p>I've seen other questions related to this, but it always seems to be a little off from what I want.</p>
|
<p>As has been pointed out in a couple of other answers, the preferred method now is NOT to use smartindent, but instead use the following (in your <a href="https://stackoverflow.com/questions/10921441/where-is-my-vimrc-file"><code>.vimrc</code></a>):</p>
<pre><code>filetype plugin indent on
" show existing tab with 4 spaces width
set tabstop=4
" when indenting with '>', use 4 spaces width
set shiftwidth=4
" On pressing tab, insert 4 spaces
set expandtab
</code></pre>
<hr />
<strike>
In your [.vimrc:][1] file:
<pre><code>set smartindent
set tabstop=4
set shiftwidth=4
set expandtab
</code></pre>
<p>The help files take a bit of time to get used to, but the more you read, the better Vim gets:</p>
<pre><code>:help smartindent
</code></pre>
<p>Even better, you can embed these settings in your source for portability:</p>
<pre><code>:help auto-setting
</code></pre>
<p>To see your current settings:</p>
<pre><code>:set all
</code></pre>
<p>As <a href="https://stackoverflow.com/users/18038/graywh">graywh</a> points out in the comments, smartindent has been replaced by cindent which "Works more cleverly", although still mainly for languages with C-like syntax:</p>
<pre><code>:help C-indenting
</code></pre>
</strike>
|
{
"question_id": 234564,
"question_date": "2008-10-24T17:41:47.463Z",
"question_score": 1395,
"tags": "vim|whitespace|indentation|vi|auto-indent",
"answer_id": 234578,
"answer_date": "2008-10-24T17:45:13.557Z",
"answer_score": 2089
}
|
Please answer the following Stack Overflow question:
Title: LINQ's Distinct() on a particular property
<p>I am playing with LINQ to learn about it, but I can't figure out how to use <code>Distinct</code> when I do not have a simple list (a simple list of integers is pretty easy to do, this is not the question). What I if want to use <a href="https://msdn.microsoft.com/library/system.linq.enumerable.distinct%28v=vs.100%29.aspx" rel="noreferrer">Distinct</a> on a list of an Object on <em>one</em> or <em>more</em> properties of the object?</p>
<p>Example: If an object is <code>Person</code>, with Property <code>Id</code>. How can I get all Person and use <code>Distinct</code> on them with the property <code>Id</code> of the object?</p>
<pre><code>Person1: Id=1, Name="Test1"
Person2: Id=1, Name="Test1"
Person3: Id=2, Name="Test2"
</code></pre>
<p>How can I get just <code>Person1</code> and <code>Person3</code>? Is that possible?</p>
<p>If it's not possible with LINQ, what would be the best way to have a list of <code>Person</code> depending on some of its properties in .NET 3.5?</p>
|
<p><strong>EDIT</strong>: This is now part of <a href="https://github.com/morelinq/MoreLINQ" rel="noreferrer">MoreLINQ</a>.</p>
<p>What you need is a "distinct-by" effectively. I don't believe it's part of LINQ as it stands, although it's fairly easy to write:</p>
<pre><code>public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
</code></pre>
<p>So to find the distinct values using just the <code>Id</code> property, you could use:</p>
<pre><code>var query = people.DistinctBy(p => p.Id);
</code></pre>
<p>And to use multiple properties, you can use anonymous types, which implement equality appropriately:</p>
<pre><code>var query = people.DistinctBy(p => new { p.Id, p.Name });
</code></pre>
<p>Untested, but it should work (and it now at least compiles).</p>
<p>It assumes the default comparer for the keys though - if you want to pass in an equality comparer, just pass it on to the <code>HashSet</code> constructor.</p>
|
{
"question_id": 489258,
"question_date": "2009-01-28T20:45:09.357Z",
"question_score": 1393,
"tags": "c#|linq|.net-3.5|distinct",
"answer_id": 489421,
"answer_date": "2009-01-28T21:17:13.163Z",
"answer_score": 1486
}
|
Please answer the following Stack Overflow question:
Title: How can I center an absolutely positioned element in a div?
<p>I want to place a <code>div</code> (with <code>position:absolute;</code>) element in the center of the window. But I'm having problems doing so, because the <strong>width is unknown</strong>.</p>
<p>I tried the following CSS code, but it needs to be adjusted because the <strong>width</strong> is responsive.</p>
<pre><code>.center {
left: 50%;
bottom: 5px;
}
</code></pre>
<p>How can I achieve 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><body>
<div style="position: absolute; left: 50%;">
<div style="position: relative; left: -50%; border: dotted red 1px;">
I am some centered shrink-to-fit content! <br />
tum te tum
</div>
</div>
</body></code></pre>
</div>
</div>
</p>
|
{
"question_id": 1776915,
"question_date": "2009-11-21T21:56:16.713Z",
"question_score": 1392,
"tags": "css|css-position|center|absolute",
"answer_id": 1777282,
"answer_date": "2009-11-22T00:21:32.323Z",
"answer_score": 1508
}
|
Please answer the following Stack Overflow question:
Title: Difference between require, include, require_once and include_once?
<p>In PHP:</p>
<ul>
<li>When should I use <code>require</code> vs. <code>include</code>?</li>
<li>When should I use <code>require_once</code> vs. <code>include_once</code>?</li>
</ul>
|
<p>There are <code>require</code> and <code>include_once</code> as well.</p>
<p>So your question should be... </p>
<ol>
<li>When should I use <code>require</code> vs. <code>include</code>?</li>
<li>When should I use <code>require_once</code> vs. <code>require</code></li>
</ol>
<p>The answer to 1 is described <a href="http://www.w3schools.com/php/php_includes.asp" rel="noreferrer">here</a>.</p>
<blockquote>
<p>The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.</p>
</blockquote>
<p>The answer to 2 can be found <a href="http://php.net/manual/en/function.require-once.php" rel="noreferrer">here</a>.</p>
<blockquote>
<p>The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.</p>
</blockquote>
|
{
"question_id": 2418473,
"question_date": "2010-03-10T16:13:25.127Z",
"question_score": 1389,
"tags": "php|include|require|require-once",
"answer_id": 2418514,
"answer_date": "2010-03-10T16:17:52.327Z",
"answer_score": 1600
}
|
Please answer the following Stack Overflow question:
Title: How to redirect output to a file and stdout
<p>In bash, calling <code>foo</code> would display any output from that command on the stdout.</p>
<p>Calling <code>foo > output</code> would redirect any output from that command to the file specified (in this case 'output').</p>
<p>Is there a way to redirect output to a file <em>and</em> have it display on stdout?</p>
|
<p>The command you want is named <strong><a href="http://www.gnu.org/software/coreutils/manual/html_node/tee-invocation.html" rel="noreferrer"><code>tee</code></a></strong>:</p>
<pre><code>foo | tee output.file
</code></pre>
<p>For example, if you only care about stdout:</p>
<pre><code>ls -a | tee output.file
</code></pre>
<p>If you want to include stderr, do:</p>
<pre><code>program [arguments...] 2>&1 | tee outfile
</code></pre>
<p><code>2>&1</code> redirects channel 2 (stderr/standard error) into channel 1 (stdout/standard output), such that both is written as stdout. It is also directed to the given output file as of the <code>tee</code> command.</p>
<p>Furthermore, if you want to <em>append</em> to the log file, use <code>tee -a</code> as:</p>
<pre><code>program [arguments...] 2>&1 | tee -a outfile
</code></pre>
|
{
"question_id": 418896,
"question_date": "2009-01-07T01:45:42.597Z",
"question_score": 1388,
"tags": "linux|bash|file-io|io|stdout",
"answer_id": 418899,
"answer_date": "2009-01-07T01:48:08.943Z",
"answer_score": 1984
}
|
Please answer the following Stack Overflow question:
Title: How do I remove a single file from the staging area (undo git add)?
<p><strong>Situation:</strong> I have a Git repository with files already in the index. I make changes to several files, open Git and add these files to my staging area with "git add ."</p>
<p><strong>Question:</strong> How do I remove one of those files from the staging area but not remove it from the index or undo the changes to the file itself?</p>
|
<p>If I understand the question correctly, you simply want to "undo" the <code>git add</code> that was done for that file.</p>
<p>If you need to remove a <strong>single file</strong> from the staging area, use</p>
<p><code>git reset HEAD -- <file></code></p>
<p>If you need to remove a <strong>whole directory (folder)</strong> from the staging area, use</p>
<p><code>git reset HEAD -- <directoryName></code></p>
<p>Your modifications will be kept. When you run <code>git status</code> the file will once again show up as modified but not yet staged.</p>
<p>See the <a href="http://schacon.github.com/git/git-reset.html" rel="noreferrer"><code>git reset</code> man page</a> for details.</p>
|
{
"question_id": 1505948,
"question_date": "2009-10-01T19:24:04.720Z",
"question_score": 1388,
"tags": "git|version-control|staging",
"answer_id": 1505968,
"answer_date": "2009-10-01T19:29:08.247Z",
"answer_score": 2104
}
|
Please answer the following Stack Overflow question:
Title: Why there are two ways to unstage a file in Git?
<p>Sometimes git suggests <code>git rm --cached</code> to unstage a file, sometimes <code>git reset HEAD file</code>. When should I use which?</p>
<p>EDIT:</p>
<pre><code>D:\code\gt2>git init
Initialized empty Git repository in D:/code/gt2/.git/
D:\code\gt2>touch a
D:\code\gt2>git status
# On branch master
#
# Initial commit
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# a
nothing added to commit but untracked files present (use "git add" to track)
D:\code\gt2>git add a
D:\code\gt2>git status
# On branch master
#
# Initial commit
#
# Changes to be committed:
# (use "git rm --cached <file>..." to unstage)
#
# new file: a
#
D:\code\gt2>git commit -m a
[master (root-commit) c271e05] a
0 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 a
D:\code\gt2>touch b
D:\code\gt2>git status
# On branch master
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# b
nothing added to commit but untracked files present (use "git add" to track)
D:\code\gt2>git add b
D:\code\gt2>git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# new file: b
#
</code></pre>
|
<p><code>git rm --cached <filePath></code> <strong>does not unstage</strong> a file, it actually <strong>stages the removal of the file(s)</strong> from the repo (assuming it was already committed before) but leaves the file in your working tree (leaving you with an untracked file).</p>
<p><code>git reset -- <filePath></code> will <strong>unstage</strong> any staged changes for the given file(s).</p>
<p>That said, if you used <code>git rm --cached</code> on a new file that is staged, it would basically look like you had just unstaged it since it had never been committed before.</p>
<p><strong>Update git 2.24</strong><br>
In this newer version of git you can use <code>git restore --staged</code> instead of <code>git reset</code>.
See <a href="https://git-scm.com/docs/git-restore" rel="noreferrer">git docs</a>.</p>
|
{
"question_id": 6919121,
"question_date": "2011-08-02T21:50:49.140Z",
"question_score": 1385,
"tags": "git|git-reset|git-rm",
"answer_id": 6919257,
"answer_date": "2011-08-02T22:03:13.717Z",
"answer_score": 2211
}
|
Please answer the following Stack Overflow question:
Title: Relative imports in Python 3
<p>I want to import a function from another file in the same directory.</p>
<p>Usually, one of the following works:</p>
<pre><code>from .mymodule import myfunction
</code></pre>
<pre><code>from mymodule import myfunction
</code></pre>
<p>...but the other one gives me one of these errors:</p>
<pre class="lang-none prettyprint-override"><code>ImportError: attempted relative import with no known parent package
</code></pre>
<pre class="lang-none prettyprint-override"><code>ModuleNotFoundError: No module named 'mymodule'
</code></pre>
<pre class="lang-none prettyprint-override"><code>SystemError: Parent module '' not loaded, cannot perform relative import
</code></pre>
<p>Why is this?</p>
|
<blockquote>
<p>unfortunately, this module needs to be inside the package, and it also
needs to be runnable as a script, sometimes. Any idea how I could
achieve that?</p>
</blockquote>
<p>It's quite common to have a layout like this...</p>
<pre><code>main.py
mypackage/
__init__.py
mymodule.py
myothermodule.py
</code></pre>
<p>...with a <code>mymodule.py</code> like this...</p>
<pre><code>#!/usr/bin/env python3
# Exported function
def as_int(a):
return int(a)
# Test function for module
def _test():
assert as_int('1') == 1
if __name__ == '__main__':
_test()
</code></pre>
<p>...a <code>myothermodule.py</code> like this...</p>
<pre><code>#!/usr/bin/env python3
from .mymodule import as_int
# Exported function
def add(a, b):
return as_int(a) + as_int(b)
# Test function for module
def _test():
assert add('1', '1') == 2
if __name__ == '__main__':
_test()
</code></pre>
<p>...and a <code>main.py</code> like this...</p>
<pre><code>#!/usr/bin/env python3
from mypackage.myothermodule import add
def main():
print(add('1', '1'))
if __name__ == '__main__':
main()
</code></pre>
<p>...which works fine when you run <code>main.py</code> or <code>mypackage/mymodule.py</code>, but fails with <code>mypackage/myothermodule.py</code>, due to the relative import...</p>
<pre><code>from .mymodule import as_int
</code></pre>
<p>The way you're supposed to run it is...</p>
<pre><code>python3 -m mypackage.myothermodule
</code></pre>
<p>...but it's somewhat verbose, and doesn't mix well with a shebang line like <code>#!/usr/bin/env python3</code>.</p>
<p>The simplest fix for this case, assuming the name <code>mymodule</code> is globally unique, would be to avoid using relative imports, and just use...</p>
<pre><code>from mymodule import as_int
</code></pre>
<p>...although, if it's not unique, or your package structure is more complex, you'll need to include the directory containing your package directory in <code>PYTHONPATH</code>, and do it like this...</p>
<pre><code>from mypackage.mymodule import as_int
</code></pre>
<p>...or if you want it to work "out of the box", you can frob the <code>PYTHONPATH</code> in code first with this...</p>
<pre><code>import sys
import os
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(SCRIPT_DIR))
from mypackage.mymodule import as_int
</code></pre>
<p>It's kind of a pain, but there's a clue as to why in <a href="http://mail.python.org/pipermail/python-3000/2007-April/006793.html" rel="noreferrer">an email</a> written by a certain Guido van Rossum...</p>
<blockquote>
<p>I'm -1 on this and on any other proposed twiddlings of the <code>__main__</code>
machinery. The only use case seems to be running scripts that happen
to be living inside a module's directory, which I've always seen as an
antipattern. To make me change my mind you'd have to convince me that
it isn't.</p>
</blockquote>
<p>Whether running scripts inside a package is an antipattern or not is subjective, but personally I find it really useful in a package I have which contains some custom wxPython widgets, so I can run the script for any of the source files to display a <code>wx.Frame</code> containing only that widget for testing purposes.</p>
|
{
"question_id": 16981921,
"question_date": "2013-06-07T10:26:50.187Z",
"question_score": 1385,
"tags": "python|python-3.x|python-import",
"answer_id": 16985066,
"answer_date": "2013-06-07T13:14:23.540Z",
"answer_score": 1043
}
|
Please answer the following Stack Overflow question:
Title: How can I check for an active Internet connection on iOS or macOS?
<p>I would like to check to see if I have an Internet connection on iOS using the <a href="https://en.wikipedia.org/wiki/Cocoa_Touch" rel="noreferrer">Cocoa Touch</a> libraries or on macOS using the <a href="https://en.wikipedia.org/wiki/Cocoa_(API)" rel="noreferrer">Cocoa</a> libraries.</p>
<p>I came up with a way to do this using an <code>NSURL</code>. The way I did it seems a bit unreliable (because even Google could one day be down and relying on a third party seems bad), and while I could check to see for a response from some other websites if Google didn't respond, it does seem wasteful and an unnecessary overhead on my application.</p>
<pre><code>- (BOOL)connectedToInternet {
NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
return ( URLString != NULL ) ? YES : NO;
}
</code></pre>
<p>Is what I have done bad, (not to mention <code>stringWithContentsOfURL</code> is deprecated in iOS 3.0 and macOS 10.4) and if so, what is a better way to accomplish this?</p>
|
<p><strong>Important</strong>: This check should <em>always</em> be performed asynchronously. The majority of answers below are synchronous so be careful otherwise you'll freeze up your app.</p>
<hr />
<h1>Swift</h1>
<ol>
<li><p>Install via CocoaPods or Carthage: <a href="https://github.com/ashleymills/Reachability.swift" rel="noreferrer">https://github.com/ashleymills/Reachability.swift</a></p>
</li>
<li><p>Test reachability via closures</p>
<pre class="lang-swift prettyprint-override"><code>let reachability = Reachability()!
reachability.whenReachable = { reachability in
if reachability.connection == .wifi {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
}
reachability.whenUnreachable = { _ in
print("Not reachable")
}
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
</code></pre>
</li>
</ol>
<hr />
<h1>Objective-C</h1>
<ol>
<li><p>Add <code>SystemConfiguration</code> framework to the project but don't worry about including it anywhere</p>
</li>
<li><p>Add Tony Million's version of <code>Reachability.h</code> and <code>Reachability.m</code> to the project (found here: <a href="https://github.com/tonymillion/Reachability" rel="noreferrer">https://github.com/tonymillion/Reachability</a>)</p>
</li>
<li><p>Update the interface section</p>
<pre class="lang-objectivec prettyprint-override"><code>#import "Reachability.h"
// Add this to the interface in the .m file of your view controller
@interface MyViewController ()
{
Reachability *internetReachableFoo;
}
@end
</code></pre>
</li>
<li><p>Then implement this method in the .m file of your view controller which you can call</p>
<pre class="lang-objectivec prettyprint-override"><code>// Checks if we have an internet connection or not
- (void)testInternetConnection
{
internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];
// Internet is reachable
internetReachableFoo.reachableBlock = ^(Reachability*reach)
{
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Yayyy, we have the interwebs!");
});
};
// Internet is not reachable
internetReachableFoo.unreachableBlock = ^(Reachability*reach)
{
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Someone broke the internet :(");
});
};
[internetReachableFoo startNotifier];
}
</code></pre>
</li>
</ol>
<p><strong>Important Note:</strong> The <code>Reachability</code> class is one of the most used classes in projects so you might run into naming conflicts with other projects. If this happens, you'll have to rename one of the pairs of <code>Reachability.h</code> and <code>Reachability.m</code> files to something else to resolve the issue.</p>
<p><strong>Note:</strong> The domain you use doesn't matter. It's just testing for a gateway to any domain.</p>
|
{
"question_id": 1083701,
"question_date": "2009-07-05T08:45:01.037Z",
"question_score": 1384,
"tags": "ios|macos|cocoa|cocoa-touch|reachability",
"answer_id": 3597085,
"answer_date": "2010-08-29T23:58:19.800Z",
"answer_score": 1310
}
|
Please answer the following Stack Overflow question:
Title: How can I output MySQL query results in CSV format?
<p>Is there an easy way to run a MySQL query from the Linux command line and output the results in <a href="http://en.wikipedia.org/wiki/Comma-separated_values" rel="noreferrer">CSV</a> format?</p>
<p>Here's what I'm doing now:</p>
<pre class="lang-none prettyprint-override"><code>mysql -u uid -ppwd -D dbname << EOQ | sed -e 's/ /,/g' | tee list.csv
select id, concat("\"",name,"\"") as name
from students
EOQ
</code></pre>
<p>It gets messy when there are a lot of columns that need to be surrounded by quotes, or if there are quotes in the results that need to be escaped.</p>
|
<p>From <em><a href="http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/" rel="noreferrer">Save MySQL query results into a text or CSV file</a></em>:</p>
<pre><code>SELECT order_id,product_name,qty
FROM orders
WHERE foo = 'bar'
INTO OUTFILE '/var/lib/mysql-files/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
</code></pre>
<p>Note: That syntax may need to be reordered to</p>
<pre><code>SELECT order_id,product_name,qty
INTO OUTFILE '/var/lib/mysql-files/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM orders
WHERE foo = 'bar';
</code></pre>
<p>in more recent versions of MySQL.</p>
<p>Using this command, columns names will not be exported.</p>
<p>Also note that <code>/var/lib/mysql-files/orders.csv</code> will be on the <em>server</em> that is running MySQL. The user that the MySQL process is running under must have permissions to write to the directory chosen, or the command will fail.</p>
<p>If you want to write output to your local machine from a remote server (especially a hosted or virtualize machine such as <a href="https://en.wikipedia.org/wiki/Heroku" rel="noreferrer">Heroku</a> or <a href="https://en.wikipedia.org/wiki/Amazon_Relational_Database_Service" rel="noreferrer">Amazon RDS</a>), this solution is not suitable.</p>
|
{
"question_id": 356578,
"question_date": "2008-12-10T15:59:51.733Z",
"question_score": 1381,
"tags": "mysql|csv|quotes",
"answer_id": 356605,
"answer_date": "2008-12-10T16:07:55.443Z",
"answer_score": 1961
}
|
Please answer the following Stack Overflow question:
Title: What is the maximum value for an int32?
<p>I can never remember the number. I need a memory rule.</p>
|
<p>It's 2,147,483,647. Easiest way to memorize it is via a tattoo.</p>
|
{
"question_id": 94591,
"question_date": "2008-09-18T17:18:23.720Z",
"question_score": 1379,
"tags": "integer",
"answer_id": 94608,
"answer_date": "2008-09-18T17:20:17.460Z",
"answer_score": 5063
}
|
Please answer the following Stack Overflow question:
Title: Strange OutOfMemory issue while loading an image to a Bitmap object
<p>I have a <code>ListView</code> with a couple of image buttons on each row. When the user clicks the list row, it launches a new activity. I have had to build my own tabs because of an issue with the camera layout. The activity that gets launched for the result is a map. If I click on my button to launch the image preview (load an image off the SD card) the application returns from the activity back to the <code>ListView</code> activity to the result handler to relaunch my new activity which is nothing more than an image widget.</p>
<p>The image preview on the <code>ListView</code> is being done with the cursor and <code>ListAdapter</code>. This makes it pretty simple, but I am not sure how I can put a resized image (I.e. Smaller bit size not pixel as the <code>src</code> for the image button on the fly. So I just resized the image that came off the phone camera.</p>
<p>The issue is that I get an <code>OutOfMemoryError</code> when it tries to go back and re-launch the 2nd activity.</p>
<ul>
<li>Is there a way I can build the list adapter easily row by row, where I can resize on the fly (<em>bitwise</em>)?</li>
</ul>
<p>This would be preferable as I also need to make some changes to the properties of the widgets/elements in each row as I am unable to select a row with the touch screen because of the focus issue. (<em>I can use rollerball.</em>)</p>
<ul>
<li>I know I can do an out of band resize and save my image, but that is not really what I want to do, but some sample code for that would be nice.</li>
</ul>
<p>As soon as I disabled the image on the <code>ListView</code> it worked fine again.</p>
<p>FYI: This is how I was doing it:</p>
<pre class="lang-java prettyprint-override"><code>String[] from = new String[] { DBHelper.KEY_BUSINESSNAME, DBHelper.KEY_ADDRESS,
DBHelper.KEY_CITY, DBHelper.KEY_GPSLONG, DBHelper.KEY_GPSLAT,
DBHelper.KEY_IMAGEFILENAME + ""};
int[] to = new int[] { R.id.businessname, R.id.address, R.id.city, R.id.gpslong,
R.id.gpslat, R.id.imagefilename };
notes = new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
setListAdapter(notes);
</code></pre>
<p>Where <code>R.id.imagefilename</code> is a <code>ButtonImage</code>.</p>
<p>Here is my LogCat:</p>
<pre><code>01-25 05:05:49.877: ERROR/dalvikvm-heap(3896): 6291456-byte external allocation too large for this process.
01-25 05:05:49.877: ERROR/(3896): VM wont let us allocate 6291456 bytes
01-25 05:05:49.877: ERROR/AndroidRuntime(3896): Uncaught handler: thread main exiting due to uncaught exception
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:304)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:149)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:174)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.graphics.drawable.Drawable.createFromPath(Drawable.java:729)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.ImageView.resolveUri(ImageView.java:484)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.ImageView.setImageURI(ImageView.java:281)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.SimpleCursorAdapter.setViewImage(SimpleCursorAdapter.java:183)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.SimpleCursorAdapter.bindView(SimpleCursorAdapter.java:129)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.CursorAdapter.getView(CursorAdapter.java:150)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.AbsListView.obtainView(AbsListView.java:1057)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.ListView.makeAndAddView(ListView.java:1616)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.ListView.fillSpecific(ListView.java:1177)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.ListView.layoutChildren(ListView.java:1454)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.AbsListView.onLayout(AbsListView.java:937)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.view.View.layout(View.java:5611)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1108)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.LinearLayout.onLayout(LinearLayout.java:922)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.view.View.layout(View.java:5611)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.FrameLayout.onLayout(FrameLayout.java:294)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.view.View.layout(View.java:5611)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:999)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.LinearLayout.onLayout(LinearLayout.java:920)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.view.View.layout(View.java:5611)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.FrameLayout.onLayout(FrameLayout.java:294)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.view.View.layout(View.java:5611)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.view.ViewRoot.performTraversals(ViewRoot.java:771)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.view.ViewRoot.handleMessage(ViewRoot.java:1103)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.os.Handler.dispatchMessage(Handler.java:88)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.os.Looper.loop(Looper.java:123)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.app.ActivityThread.main(ActivityThread.java:3742)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at java.lang.reflect.Method.invokeNative(Native Method)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at java.lang.reflect.Method.invoke(Method.java:515)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:497)
01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at dalvik.system.NativeStart.main(Native Method)
01-25 05:10:01.127: ERROR/AndroidRuntime(3943): ERROR: thread attach failed
</code></pre>
<p>I also have a new error when displaying an image:</p>
<pre><code>22:13:18.594: DEBUG/skia(4204): xxxxxxxxxxx jpeg error 20 Improper call to JPEG library in state %d
22:13:18.604: INFO/System.out(4204): resolveUri failed on bad bitmap uri:
22:13:18.694: ERROR/dalvikvm-heap(4204): 6291456-byte external allocation too large for this process.
22:13:18.694: ERROR/(4204): VM won't let us allocate 6291456 bytes
22:13:18.694: DEBUG/skia(4204): xxxxxxxxxxxxxxxxxxxx allocPixelRef failed
</code></pre>
|
<p>The <a href="http://developer.android.com/training/index.html" rel="noreferrer">Android Training</a> class, "<a href="http://developer.android.com/training/displaying-bitmaps/index.html" rel="noreferrer">Displaying Bitmaps Efficiently</a>", offers some great information for understanding and dealing with the exception `java.lang.OutOfMemoryError: bitmap size exceeds VM budget when loading Bitmaps.</p>
<hr />
<h2>Read Bitmap Dimensions and Type</h2>
<p>The <code>BitmapFactory</code> class provides several decoding methods (<code>decodeByteArray()</code>, <code>decodeFile()</code>, <code>decodeResource()</code>, etc.) for creating a <code>Bitmap</code> from various sources. Choose the most appropriate decode method based on your image data source. These methods attempt to allocate memory for the constructed bitmap and therefore can easily result in an <code>OutOfMemory</code> exception. Each type of decode method has additional signatures that let you specify decoding options via the <code>BitmapFactory.Options</code> class. Setting the <code>inJustDecodeBounds</code> property to <code>true</code> while decoding avoids memory allocation, returning <code>null</code> for the bitmap object but setting <code>outWidth</code>, <code>outHeight</code> and <code>outMimeType</code>. This technique allows you to read the dimensions and type of the image data prior to the construction (and memory allocation) of the bitmap.</p>
<pre><code>BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
</code></pre>
<p>To avoid <code>java.lang.OutOfMemory</code> exceptions, check the dimensions of a bitmap before decoding it unless you absolutely trust the source to provide you with predictably sized image data that comfortably fits within the available memory.</p>
<hr />
<h2>Load a scaled-down version into Memory</h2>
<p>Now that the image dimensions are known, they can be used to decide if the full image should be loaded into memory or if a subsampled version should be loaded instead. Here are some factors to consider:</p>
<ul>
<li>Estimated memory usage of loading the full image in memory.</li>
<li>The amount of memory you are willing to commit to loading this image given any other memory requirements of your application.</li>
<li>Dimensions of the target ImageView or UI component that the image is to be loaded into.</li>
<li>Screen size and density of the current device.</li>
</ul>
<p>For example, it’s not worth loading a 1024x768 pixel image into memory if it will eventually be displayed in a 128x96 pixel thumbnail in an <code>ImageView</code>.</p>
<p>To tell the decoder to subsample the image, loading a smaller version into memory, set <code>inSampleSize</code> to <code>true</code> in your <code>BitmapFactory.Options</code> object. For example, an image with resolution 2048x1536 that is decoded with an <code>inSampleSize</code> of 4 produces a bitmap of approximately 512x384. Loading this into memory uses 0.75MB rather than 12MB for the full image (assuming a bitmap configuration of <code>ARGB_8888</code>). Here’s a method to calculate a sample size value that is a power of two based on a target width and height:</p>
<pre><code>public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
</code></pre>
<blockquote>
<p><strong>Note</strong>: A power of two value is calculated because the decoder uses a
final value by rounding down to the nearest power of two, as per the
<code>inSampleSize</code> documentation.</p>
</blockquote>
<p>To use this method, first decode with <code>inJustDecodeBounds</code> set to <code>true, pass the options through and then decode again using the new </code>inSampleSize<code>value and</code>inJustDecodeBounds<code>set to</code>false`:</p>
<pre><code>public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
</code></pre>
<p>This method makes it easy to load a bitmap of arbitrarily large size into an <code>ImageView</code> that displays a 100x100 pixel thumbnail, as shown in the following example code:</p>
<pre><code>mImageView.setImageBitmap(
decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));
</code></pre>
<p>You can follow a similar process to decode bitmaps from other sources, by substituting the appropriate <code>BitmapFactory.decode*</code> method as needed.</p>
|
{
"question_id": 477572,
"question_date": "2009-01-25T11:23:37.957Z",
"question_score": 1378,
"tags": "android|image|bitmap|out-of-memory|android-bitmap",
"answer_id": 10127787,
"answer_date": "2012-04-12T16:31:31.110Z",
"answer_score": 687
}
|
Please answer the following Stack Overflow question:
Title: How do I copy folder with files to another folder in Unix/Linux?
<p>I am having some issues to copy a folder with files in that folder into another folder. Command <code>cp -r</code> doesn't copy files in the folder.</p>
|
<p>The option you're looking for is <code>-R</code>.</p>
<pre><code>cp -R path_to_source path_to_destination/
</code></pre>
<ul>
<li>If <code>destination</code> doesn't exist, it will be created.</li>
<li><code>-R</code> means <code>copy directories recursively</code>. You can also use <code>-r</code> since it's case-insensitive.</li>
<li>To copy <strong>everything inside</strong> the source folder (symlinks, hidden files) without copying the source folder <em>itself</em> use <code>-a</code> flag along with trailing <code>/.</code> in the source (as per <code>@muni764</code>'s / <code>@Anton Krug</code>'s <a href="https://stackoverflow.com/questions/14922562/how-do-i-copy-folder-with-files-to-another-folder-in-unix-linux#comment90054461_14922600">comment</a>):</li>
</ul>
<pre class="lang-bash prettyprint-override"><code>cp -a path_to_source/. path_to_destination/
</code></pre>
|
{
"question_id": 14922562,
"question_date": "2013-02-17T15:16:20.413Z",
"question_score": 1375,
"tags": "linux|cp",
"answer_id": 14922600,
"answer_date": "2013-02-17T15:20:20.803Z",
"answer_score": 2283
}
|
Please answer the following Stack Overflow question:
Title: How do I reformat HTML code using Sublime Text 2?
<p>I've got some poorly-formatted HTML code that I'd like to reformat. Is there a command that will automatically reformat HTML code in Sublime Text 2 so it looks better and is easier to read?</p>
|
<p>You don't need any plugins to do this.
Just select all lines (<kbd>CTRL</kbd>+<kbd>A</kbd>) and then from the menu select Edit → Line → Reindent.
This will work if your file is saved with an extension that contains HTML like <code>.html</code> or <code>.php</code>.</p>
<p>If you do this often, you may find this key mapping useful:</p>
<pre><code>{ "keys": ["ctrl+shift+r"], "command": "reindent" , "args": { "single_line": false } }
</code></pre>
<p>If your file is not saved (e.g. you just pasted in a snippet to a new window), you can manually set the language for indentation by selecting the menu View → Syntax → <code>language of choice</code> before selecting the reindent option.</p>
|
{
"question_id": 8839753,
"question_date": "2012-01-12T17:49:30.247Z",
"question_score": 1373,
"tags": "html|sublimetext2|sublimetext|indentation|reformat",
"answer_id": 10888837,
"answer_date": "2012-06-04T21:47:04.373Z",
"answer_score": 2136
}
|
Please answer the following Stack Overflow question:
Title: Create Generic method constraining T to an Enum
<p>I'm building a function to extend the <code>Enum.Parse</code> concept that</p>
<ul>
<li>Allows a default value to be parsed in case that an Enum value is not found</li>
<li>Is case insensitive</li>
</ul>
<p>So I wrote the following:</p>
<pre><code>public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
</code></pre>
<p>I am getting a Error Constraint cannot be special class <code>System.Enum</code>.</p>
<p>Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the <code>Parse</code> function and pass a type as an attribute, which forces the ugly boxing requirement to your code.</p>
<p><strong>EDIT</strong> All suggestions below have been greatly appreciated, thanks.</p>
<p>Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML)</p>
<pre><code>public static class EnumUtils
{
public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
{
if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
}
</code></pre>
<p><strong>EDIT:</strong> (16th Feb 2015) Christopher Currens has posted <a href="https://stackoverflow.com/a/8086788">a compiler enforced type-safe generic solution in MSIL or F#</a> below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page.</p>
<p><strong>EDIT 2:</strong> (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :)</p>
|
<h2>This feature is finally supported in C# 7.3!</h2>
<p>The following snippet (from <a href="https://github.com/dotnet/samples/blob/3ee82879284e3f4755251fd33c3b3e533f7b3485/snippets/csharp/keywords/GenericWhereConstraints.cs#L180-L190" rel="noreferrer">the dotnet samples</a>) demonstrates how:</p>
<pre><code>public static Dictionary<int, string> EnumNamedValues<T>() where T : System.Enum
{
var result = new Dictionary<int, string>();
var values = Enum.GetValues(typeof(T));
foreach (int item in values)
result.Add(item, Enum.GetName(typeof(T), item));
return result;
}
</code></pre>
<p>Be sure to set your language version in your C# project to version 7.3.</p>
<hr />
<p>Original Answer below:</p>
<p>I'm late to the game, but I took it as a challenge to see how it could be done. It's not possible in C# (or VB.NET, but scroll down for F#), but <em>is possible</em> in MSIL. I wrote this little....thing</p>
<pre><code>// license: http://www.apache.org/licenses/LICENSE-2.0.html
.assembly MyThing{}
.class public abstract sealed MyThing.Thing
extends [mscorlib]System.Object
{
.method public static !!T GetEnumFromString<valuetype .ctor ([mscorlib]System.Enum) T>(string strValue,
!!T defaultValue) cil managed
{
.maxstack 2
.locals init ([0] !!T temp,
[1] !!T return_value,
[2] class [mscorlib]System.Collections.IEnumerator enumerator,
[3] class [mscorlib]System.IDisposable disposer)
// if(string.IsNullOrEmpty(strValue)) return defaultValue;
ldarg strValue
call bool [mscorlib]System.String::IsNullOrEmpty(string)
brfalse.s HASVALUE
br RETURNDEF // return default it empty
// foreach (T item in Enum.GetValues(typeof(T)))
HASVALUE:
// Enum.GetValues.GetEnumerator()
ldtoken !!T
call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
call class [mscorlib]System.Array [mscorlib]System.Enum::GetValues(class [mscorlib]System.Type)
callvirt instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Array::GetEnumerator()
stloc enumerator
.try
{
CONDITION:
ldloc enumerator
callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
brfalse.s LEAVE
STATEMENTS:
// T item = (T)Enumerator.Current
ldloc enumerator
callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()
unbox.any !!T
stloc temp
ldloca.s temp
constrained. !!T
// if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
callvirt instance string [mscorlib]System.Object::ToString()
callvirt instance string [mscorlib]System.String::ToLower()
ldarg strValue
callvirt instance string [mscorlib]System.String::Trim()
callvirt instance string [mscorlib]System.String::ToLower()
callvirt instance bool [mscorlib]System.String::Equals(string)
brfalse.s CONDITION
ldloc temp
stloc return_value
leave.s RETURNVAL
LEAVE:
leave.s RETURNDEF
}
finally
{
// ArrayList's Enumerator may or may not inherit from IDisposable
ldloc enumerator
isinst [mscorlib]System.IDisposable
stloc.s disposer
ldloc.s disposer
ldnull
ceq
brtrue.s LEAVEFINALLY
ldloc.s disposer
callvirt instance void [mscorlib]System.IDisposable::Dispose()
LEAVEFINALLY:
endfinally
}
RETURNDEF:
ldarg defaultValue
stloc return_value
RETURNVAL:
ldloc return_value
ret
}
}
</code></pre>
<p>Which generates a function that <strong>would</strong> look like this, if it were valid C#:</p>
<pre><code>T GetEnumFromString<T>(string valueString, T defaultValue) where T : Enum
</code></pre>
<p>Then with the following C# code:</p>
<pre><code>using MyThing;
// stuff...
private enum MyEnum { Yes, No, Okay }
static void Main(string[] args)
{
Thing.GetEnumFromString("No", MyEnum.Yes); // returns MyEnum.No
Thing.GetEnumFromString("Invalid", MyEnum.Okay); // returns MyEnum.Okay
Thing.GetEnumFromString("AnotherInvalid", 0); // compiler error, not an Enum
}
</code></pre>
<p>Unfortunately, this means having this part of your code written in MSIL instead of C#, with the only added benefit being that you're able to constrain this method by <code>System.Enum</code>. It's also kind of a bummer, because it gets compiled into a separate assembly. However, it doesn't mean you have to deploy it that way.</p>
<p>By removing the line <code>.assembly MyThing{}</code> and invoking ilasm as follows:</p>
<pre><code>ilasm.exe /DLL /OUTPUT=MyThing.netmodule
</code></pre>
<p>you get a netmodule instead of an assembly.</p>
<p>Unfortunately, VS2010 (and earlier, obviously) does not support adding netmodule references, which means you'd have to leave it in 2 separate assemblies when you're debugging. The only way you can add them as part of your assembly would be to run csc.exe yourself using the <code>/addmodule:{files}</code> command line argument. It wouldn't be <em>too</em> painful in an MSBuild script. Of course, if you're brave or stupid, you can run csc yourself manually each time. And it certainly gets more complicated as multiple assemblies need access to it.</p>
<p>So, it CAN be done in .Net. Is it worth the extra effort? Um, well, I guess I'll let you decide on that one.</p>
<hr />
<h3>F# Solution as alternative</h3>
<p>Extra Credit: It turns out that a generic restriction on <code>enum</code> is possible in at least one other .NET language besides MSIL: F#.</p>
<pre class="lang-ml prettyprint-override"><code>type MyThing =
static member GetEnumFromString<'T when 'T :> Enum> str defaultValue: 'T =
/// protect for null (only required in interop with C#)
let str = if isNull str then String.Empty else str
Enum.GetValues(typedefof<'T>)
|> Seq.cast<_>
|> Seq.tryFind(fun v -> String.Compare(v.ToString(), str.Trim(), true) = 0)
|> function Some x -> x | None -> defaultValue
</code></pre>
<p>This one is easier to maintain since it's a well-known language with full Visual Studio IDE support, but you still need a separate project in your solution for it. However, it naturally produces considerably different IL (the code <em>is</em> very different) and it relies on the <code>FSharp.Core</code> library, which, just like any other external library, needs to become part of your distribution.</p>
<p>Here's how you can use it (basically the same as the MSIL solution), and to show that it correctly fails on otherwise synonymous structs:</p>
<pre><code>// works, result is inferred to have type StringComparison
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", StringComparison.Ordinal);
// type restriction is recognized by C#, this fails at compile time
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", 42);
</code></pre>
|
{
"question_id": 79126,
"question_date": "2008-09-17T01:56:19.267Z",
"question_score": 1373,
"tags": "c#|generics|enums|generic-constraints",
"answer_id": 8086788,
"answer_date": "2011-11-10T21:46:36.500Z",
"answer_score": 856
}
|
Please answer the following Stack Overflow question:
Title: Calculate difference between two dates (number of days)?
<p>I see that this question has been answered for <a href="https://stackoverflow.com/questions/1555262/">Java</a>, <a href="https://stackoverflow.com/questions/1036742/">JavaScript</a>, and <a href="https://stackoverflow.com/questions/676824/">PHP</a>, but not C#. So, how might one calculate the number of days between two dates in C#?</p>
|
<p>Assuming <code>StartDate</code> and <code>EndDate</code> are of type <code>DateTime</code>:</p>
<pre><code>(EndDate - StartDate).TotalDays
</code></pre>
|
{
"question_id": 1607336,
"question_date": "2009-10-22T13:47:15.460Z",
"question_score": 1372,
"tags": "c#|date",
"answer_id": 1607352,
"answer_date": "2009-10-22T13:48:58.873Z",
"answer_score": 2467
}
|
Please answer the following Stack Overflow question:
Title: What is the use of "assert" in Python?
<p>What does <code>assert</code> mean? How is it used?</p>
|
<p>The <code>assert</code> statement exists in almost every programming language. It has two main uses:</p>
<ol>
<li><p>It helps detect problems early in your program, where the cause is clear, rather than later when some other operation fails. A type error in Python, for example, can go through several layers of code before actually raising an <code>Exception</code> if not caught early on.</p>
</li>
<li><p>It works as documentation for other developers reading the code, who see the <code>assert</code> and can confidently say that its condition holds from now on.</p>
</li>
</ol>
<p>When you do...</p>
<pre><code>assert condition
</code></pre>
<p>... you're telling the program to test that condition, and immediately trigger an error if the condition is false.</p>
<p>In Python, it's roughly equivalent to this:</p>
<pre><code>if not condition:
raise AssertionError()
</code></pre>
<p>Try it in the Python shell:</p>
<pre><code>>>> assert True # nothing happens
>>> assert False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
</code></pre>
<p>Assertions can include an optional message, and you can disable them when running the interpreter.</p>
<p>To print a message if the assertion fails:</p>
<pre><code>assert False, "Oh no! This assertion failed!"
</code></pre>
<p>Do <strong>not</strong> use parenthesis to call <code>assert</code> like a function. It is a statement. If you do <code>assert(condition, message)</code> you'll be running the <code>assert</code> with a <code>(condition, message)</code> tuple as first parameter.</p>
<p>As for disabling them, when running <code>python</code> in optimized mode, where <code>__debug__</code> is <code>False</code>, assert statements will be ignored. Just pass the <code>-O</code> flag:</p>
<pre><code>python -O script.py
</code></pre>
<p>See <a href="http://docs.python.org/reference/simple_stmts.html#assert" rel="noreferrer">here</a> for the relevant documentation.</p>
|
{
"question_id": 5142418,
"question_date": "2011-02-28T13:11:45.987Z",
"question_score": 1372,
"tags": "python|assert|assertion",
"answer_id": 5142453,
"answer_date": "2011-02-28T13:15:33.593Z",
"answer_score": 1596
}
|
Please answer the following Stack Overflow question:
Title: What should be in my .gitignore for an Android Studio project?
<p>What files should be in my <code>.gitignore</code> for an Android Studio project?</p>
<p>I've seen several examples that all include <code>.iml</code> but IntelliJ docs say that <code>.iml</code> must be included in your source control.</p>
|
<p><strong>Updated to Android Studio 3.0</strong>
Please share missing items in comments.</p>
<p>A late answer but <a href="https://stackoverflow.com/questions/16640566/which-files-shouldnt-be-checked-in-into-version-control-in-android-studio">this</a> alternative answer was not right for us ...</p>
<p>So, here's our gitignore file:</p>
<pre><code>#built application files
*.apk
*.ap_
*.aab
# files for the dex VM
*.dex
# Java class files
*.class
# generated files
bin/
gen/
# Local configuration file (sdk path, etc)
local.properties
# Windows thumbnail db
Thumbs.db
# OSX files
.DS_Store
# Android Studio
*.iml
.idea
#.idea/workspace.xml - remove # and delete .idea if it better suit your needs.
.gradle
build/
.navigation
captures/
output.json
#NDK
obj/
.externalNativeBuild
</code></pre>
<p>Since Android Studio 2.2 and up to 3.0, new projects are created with this gitignore file:</p>
<pre><code>*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
.externalNativeBuild
</code></pre>
<p><strong>Deprecated</strong> - for older project format, add this section to your gitignore file:</p>
<pre><code>
/*/out
/*/*/build
/*/*/production
*.iws
*.ipr
*~
*.swp
</code></pre>
<p>This file should be located in the project's root folder and not inside the project's module folder.</p>
<p><strong>Edit Notes:</strong></p>
<ol>
<li><p>Since version 0.3+ it seems you can commit and push *<strong>.iml</strong> and <strong>build.gradle</strong> files. If your project is based on Gradle: in the new open/import dialog, you should check the <code>"use auto import"</code> checkbox and mark the <code>"use default gradle wrapper (recommended)"</code> radio button. All paths are now relative as @George suggested.</p>
</li>
<li><p>Updated answer according to @128KB <a href="https://github.com/google/iosched/blob/master/.gitignore" rel="noreferrer">attached source</a> and @Skela suggestions</p>
</li>
</ol>
|
{
"question_id": 16736856,
"question_date": "2013-05-24T14:04:16.847Z",
"question_score": 1369,
"tags": "git|android-studio|gitignore",
"answer_id": 17803964,
"answer_date": "2013-07-23T07:29:34.883Z",
"answer_score": 1418
}
|
Please answer the following Stack Overflow question:
Title: How can I know if a branch has been already merged into master?
<p>I have a git repository with multiple branches. </p>
<p>How can I know which branches are already merged into the master branch?</p>
|
<p><code>git branch --merged master</code> lists branches merged into <em>master</em></p>
<p><code>git branch --merged</code> lists branches merged into <em>HEAD</em> (i.e. tip of current branch)</p>
<p><code>git branch --no-merged</code> lists branches that have not been merged</p>
<p>By default this applies to only the local branches. The <code>-a</code> flag will show both local and remote branches, and the <code>-r</code> flag shows only the remote branches.</p>
|
{
"question_id": 226976,
"question_date": "2008-10-22T18:23:03.493Z",
"question_score": 1369,
"tags": "git",
"answer_id": 227026,
"answer_date": "2008-10-22T18:33:09.183Z",
"answer_score": 2124
}
|
Please answer the following Stack Overflow question:
Title: How to manually send HTTP POST requests from Firefox or Chrome browser
<p>I want to test some URLs in a web application I'm working on. For that I would like to manually create HTTP POST requests (meaning I can add whatever parameters I like).</p>
<p>Is there any functionality in Chrome and/or Firefox that I'm missing?</p>
|
<p>I have been making a Chrome app called <a href="https://chrome.google.com/webstore/detail/fhbjgbiflinjbdggehcddcbncdddomop" rel="noreferrer">Postman</a> for this type of stuff. All the other extensions seemed a bit dated so made my own. It also has a bunch of other features which have been helpful for documenting our own API here.</p>
<hr />
<p>Postman now also has <a href="https://www.getpostman.com/" rel="noreferrer"><em>native apps</em></a> (i.e. standalone) for Windows, Mac and Linux! It is more preferable now to use native apps, read more <a href="https://www.getpostman.com/docs/why_native" rel="noreferrer">here</a>.</p>
<hr />
|
{
"question_id": 4797534,
"question_date": "2011-01-25T18:45:15.023Z",
"question_score": 1368,
"tags": "ajax|google-chrome|firefox|browser|http-post",
"answer_id": 9716192,
"answer_date": "2012-03-15T08:32:18.353Z",
"answer_score": 2604
}
|
Please answer the following Stack Overflow question:
Title: How do I combine a background-image and CSS3 gradient on the same element?
<p>How do I use CSS3 gradients for my <code>background-color</code> and then apply a <code>background-image</code> to apply some sort of light transparent texture?</p>
|
<p>Multiple backgrounds!</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: #eb01a5;
background-image: url("IMAGE_URL"); /* fallback */
background-image: url("IMAGE_URL"), linear-gradient(#eb01a5, #d13531); /* W3C */
}</code></pre>
</div>
</div>
</p>
<p>These 2 lines are the fallback for any browser that doesn't do gradients.
See notes for stacking images only IE < 9 below.</p>
<ul>
<li>Line 1 sets a flat background color.</li>
<li>Line 2 sets the background image fallback.</li>
</ul>
<p>The final line sets a background image and gradient for browsers that can handle them.</p>
<ul>
<li>Line 3 is for all relatively modern browsers.</li>
</ul>
<p>Nearly all current browsers have support for multiple background images and css backgrounds. See <a href="http://caniuse.com/#feat=css-gradients" rel="noreferrer">http://caniuse.com/#feat=css-gradients</a> for browser support. For a good post on why you don't need multiple browser prefixes, see <a href="http://codepen.io/thebabydino/full/pjxVWp/" rel="noreferrer">http://codepen.io/thebabydino/full/pjxVWp/</a></p>
<p><strong>Layer Stack</strong></p>
<p>It should be noted that the first defined image will be topmost in the stack. In this case, the image is on TOP of the gradient.</p>
<p>For more information about background layering see <a href="http://www.w3.org/TR/css3-background/#layering" rel="noreferrer">http://www.w3.org/TR/css3-background/#layering</a>.</p>
<p><strong>Stacking images ONLY (no gradients in the declaration) For IE < 9</strong></p>
<p>IE9 and up can stack images this same way. You could use this to create a gradient image for ie9, though personally, I wouldn't. However to be noted when using only images, ie < 9 will ignore the fallback statement and not show any image. This does not happen when a gradient is included. To use a single fallback image in this case I suggest using Paul Irish's wonderful <a href="http://paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/" rel="noreferrer">Conditional HTML element</a> along with your fallback code:</p>
<pre class="lang-css prettyprint-override"><code>.lte9 #target{ background-image: url("IMAGE_URL"); }
</code></pre>
<p><strong>Background position, sizing etc.</strong></p>
<p>Other properties that would apply to a single image may also be comma separated. If only 1 value is supplied, that will be applied to all stacked images including the gradient. <code>background-size: 40px;</code> will constrain both the image and the gradient to 40px height and width. However using <code>background-size: 40px, cover;</code> will make the image 40px and the gradient will cover the element. To only apply a setting to one image, set the default for the other: <code>background-position: 50%, 0 0;</code> or for <a href="http://caniuse.com/#feat=css-initial-value" rel="noreferrer">browsers that support it</a> use <code>initial</code>: <code>background-position: 50%, initial;</code></p>
<p>You may also use the background shorthand, however this removes the fallback color and image.</p>
<pre class="lang-css prettyprint-override"><code>body{
background: url("IMAGE_URL") no-repeat left top, linear-gradient(#eb01a5, #d13531);
}
</code></pre>
<p>The same applies to background-position, background-repeat, etc. </p>
|
{
"question_id": 2504071,
"question_date": "2010-03-23T22:30:53.420Z",
"question_score": 1368,
"tags": "css|background-image|gradient",
"answer_id": 2547064,
"answer_date": "2010-03-30T16:59:59.993Z",
"answer_score": 1748
}
|
Please answer the following Stack Overflow question:
Title: What are these three dots in React doing?
<p>What does the <code>...</code> do in this React (using JSX) code and what is it called?</p>
<pre><code><Modal {...this.props} title='Modal heading' animation={false}>
</code></pre>
|
<p>That's <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax" rel="noreferrer"><em>property spread notation</em></a>. It was added in ES2018 (spread for arrays/iterables was earlier, ES2015), but it's been supported in React projects for a long time via transpilation (as "<a href="https://reactjs.org/docs/jsx-in-depth.html#spread-attributes" rel="noreferrer">JSX spread attributes</a>" even though you could do it elsewhere, too, not just attributes).</p>
<p><code>{...this.props}</code> <em>spreads out</em> the "own" enumerable properties in <code>props</code> as discrete properties on the <code>Modal</code> element you're creating. For instance, if <code>this.props</code> contained <code>a: 1</code> and <code>b: 2</code>, then</p>
<pre><code><Modal {...this.props} title='Modal heading' animation={false}>
</code></pre>
<p>would be the same as</p>
<pre><code><Modal a={this.props.a} b={this.props.b} title='Modal heading' animation={false}>
</code></pre>
<p>But it's dynamic, so whatever "own" properties are in <code>props</code> are included.</p>
<p>Since <code>children</code> is an "own" property in <code>props</code>, spread will include it. So if the component where this appears had child elements, they'll be passed on to <code>Modal</code>. Putting child elements between the opening tag and closing tags is just syntactic sugar — the good kind — for putting a <code>children</code> property in the opening tag. Example:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Example extends React.Component {
render() {
const { className, children } = this.props;
return (
<div className={className}>
{children}
</div>
);
}
}
ReactDOM.render(
[
<Example className="first">
<span>Child in first</span>
</Example>,
<Example className="second" children={<span>Child in second</span>} />
],
document.getElementById("root")
);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.first {
color: green;
}
.second {
color: blue;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code></pre>
</div>
</div>
</p>
<p>Spread notation is handy not only for that use case, but for creating a new object with most (or all) of the properties of an existing object — which comes up a lot when you're updating state, since you can't modify state directly:</p>
<pre><code>this.setState(prevState => {
return {foo: {...prevState.foo, a: "updated"}};
});
</code></pre>
<p>That replaces <code>this.state.foo</code> with a new object with all the same properties as <code>foo</code> except the <code>a</code> property, which becomes <code>"updated"</code>:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const obj = {
foo: {
a: 1,
b: 2,
c: 3
}
};
console.log("original", obj.foo);
// Creates a NEW object and assigns it to `obj.foo`
obj.foo = {...obj.foo, a: "updated"};
console.log("updated", obj.foo);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
max-height: 100% !important;
}</code></pre>
</div>
</div>
</p>
|
{
"question_id": 31048953,
"question_date": "2015-06-25T11:21:52.237Z",
"question_score": 1368,
"tags": "javascript|reactjs|spread-syntax",
"answer_id": 31049016,
"answer_date": "2015-06-25T11:25:12.317Z",
"answer_score": 1520
}
|
Please answer the following Stack Overflow question:
Title: How do I move to end of line in Vim?
<p>I know how to generally move around in command mode, specifically, jumping to lines, etc. But what is the command to jump to the end of the line that I am currently on?</p>
|
<p>Just the <kbd>$</kbd> <em>(dollar sign)</em> key. You can use <kbd>A</kbd> to move to the end of the line and switch to editing mode (Append). To jump the last non-blank character, you can press <kbd>g</kbd> then <kbd>_</kbd> keys.</p>
<p>The opposite of <kbd>A</kbd> is <kbd>I</kbd> (Insert mode at beginning of line), as an aside. Pressing just the <kbd>^</kbd> will place your cursor at the first non-white-space character of the line.</p>
|
{
"question_id": 105721,
"question_date": "2008-09-19T21:19:47.227Z",
"question_score": 1367,
"tags": "vim|editor|keyboard-shortcuts|vi",
"answer_id": 105734,
"answer_date": "2008-09-19T21:20:48.503Z",
"answer_score": 2346
}
|
Please answer the following Stack Overflow question:
Title: Removing multiple files from a Git repo that have already been deleted from disk
<p>I have a Git repo that I have deleted four files from using <code>rm</code> (<strong>not</strong> <code>git rm</code>), and my Git status looks like this:</p>
<pre><code># deleted: file1.txt
# deleted: file2.txt
# deleted: file3.txt
# deleted: file4.txt
</code></pre>
<p>How do I remove these files from Git without having to manually go through and add each file like this:</p>
<pre><code>git rm file1 file2 file3 file4
</code></pre>
<p>Ideally, I'm looking for something that works in the same way that <code>git add .</code> does, if that's possible.</p>
|
<h3>For Git 1.x</h3>
<pre><code>$ git add -u
</code></pre>
<p>This tells git to automatically stage tracked files -- including deleting the previously tracked files. </p>
<h3>For Git 2.0</h3>
<p>To stage your whole working tree:</p>
<pre><code>$ git add -u :/
</code></pre>
<p>To stage just the current path:</p>
<pre><code>$ git add -u .
</code></pre>
|
{
"question_id": 492558,
"question_date": "2009-01-29T17:18:14.777Z",
"question_score": 1367,
"tags": "git|git-commit|git-add|git-rm",
"answer_id": 1402793,
"answer_date": "2009-09-10T00:13:25.730Z",
"answer_score": 2348
}
|
Please answer the following Stack Overflow question:
Title: How to do case insensitive string comparison?
<p>How do I perform case insensitive string comparison in JavaScript?</p>
|
<p>The simplest way to do it (if you're not worried about special Unicode characters) is to call <code>toUpperCase</code>:</p>
<pre><code>var areEqual = string1.toUpperCase() === string2.toUpperCase();
</code></pre>
|
{
"question_id": 2140627,
"question_date": "2010-01-26T16:07:45.427Z",
"question_score": 1366,
"tags": "javascript|string",
"answer_id": 2140644,
"answer_date": "2010-01-26T16:09:23.580Z",
"answer_score": 1439
}
|
Please answer the following Stack Overflow question:
Title: How to force Docker for a clean build of an image
<p>I have build a Docker image from a Docker file using the below command.</p>
<pre><code>$ docker build -t u12_core -f u12_core .
</code></pre>
<p>When I am trying to rebuild it with the same command, it's using the build cache like:</p>
<pre><code>Step 1 : FROM ubuntu:12.04
---> eb965dfb09d2
Step 2 : MAINTAINER Pavan Gupta <[email protected]>
---> Using cache
---> 4354ccf9dcd8
Step 3 : RUN apt-get update
---> Using cache
---> bcbca2fcf204
Step 4 : RUN apt-get install -y openjdk-7-jdk
---> Using cache
---> 103f1a261d44
Step 5 : RUN apt-get install -y openssh-server
---> Using cache
---> dde41f8d0904
Step 6 : RUN apt-get install -y git-core
---> Using cache
---> 9be002f08b6a
Step 7 : RUN apt-get install -y build-essential
---> Using cache
---> a752fd73a698
Step 8 : RUN apt-get install -y logrotate
---> Using cache
---> 93bca09b509d
Step 9 : RUN apt-get install -y lsb-release
---> Using cache
---> fd4d10cf18bc
Step 10 : RUN mkdir /var/run/sshd
---> Using cache
---> 63b4ecc39ff0
Step 11 : RUN echo 'root:root' | chpasswd
---> Using cache
---> 9532e31518a6
Step 12 : RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config
---> Using cache
---> 47d1660bd544
Step 13 : RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
---> Using cache
---> d1f97f1c52f7
Step 14 : RUN wget -O aerospike.tgz 'http://aerospike.com/download/server/latest/artifact/ubuntu12'
---> Using cache
---> bd7dde7a98b9
Step 15 : RUN tar -xvf aerospike.tgz
---> Using cache
---> 54adaa09921f
Step 16 : RUN dpkg -i aerospike-server-community-*/*.deb
---> Using cache
---> 11aba013eea5
Step 17 : EXPOSE 22 3000 3001 3002 3003
---> Using cache
---> e33aaa78a931
Step 18 : CMD /usr/sbin/sshd -D
---> Using cache
---> 25f5fe70fa84
Successfully built 25f5fe70fa84
</code></pre>
<p>The cache shows that aerospike is installed. However, I don't find it inside containers spawn from this image, so I want to rebuild this image without using the cache. How can I force Docker to rebuild a clean image without the cache?</p>
|
<p>There's a <code>--no-cache</code> option:</p>
<pre><code>docker build --no-cache -t u12_core -f u12_core .
</code></pre>
<p>In older versions of Docker you needed to pass <code>--no-cache=true</code>, but this is no longer the case.</p>
|
{
"question_id": 35594987,
"question_date": "2016-02-24T06:37:48.143Z",
"question_score": 1366,
"tags": "docker",
"answer_id": 35595021,
"answer_date": "2016-02-24T06:40:31.277Z",
"answer_score": 2254
}
|
Please answer the following Stack Overflow question:
Title: How do I delete unpushed git commits?
<p>I accidentally committed to the wrong branch.
How do I delete that commit?</p>
|
<p>Delete the most recent commit, keeping the work you've done:</p>
<pre><code>git reset --soft HEAD~1
</code></pre>
<p>Delete the most recent commit, <strong>destroying the work</strong> you've done:</p>
<pre><code>git reset --hard HEAD~1
</code></pre>
|
{
"question_id": 3197413,
"question_date": "2010-07-07T17:47:23.747Z",
"question_score": 1366,
"tags": "git",
"answer_id": 3197432,
"answer_date": "2010-07-07T17:50:19.853Z",
"answer_score": 2623
}
|
Please answer the following Stack Overflow question:
Title: How can I disable ARC for a single file in a project?
<p>I am using ARC successfully in my project. However, I have encountered a few files (e.g., in unit tests and mock objects) where the rules of ARC are a little more fragile right now. I recall hearing that there was a way to disable ARC on a per-file basis, though I have been unable to find this option.</p>
<p>Is this possible? How do I disable ARC on a per-file basis?</p>
|
<p>It is possible to disable ARC for individual files by adding the <code>-fno-objc-arc</code> compiler flag for those files. </p>
<p>You add compiler flags in Targets -> Build Phases -> Compile Sources. You have to double click on the right column of the row under <em>Compiler Flags</em>. You can also add it to multiple files by holding the cmd button to select the files and then pressing enter to bring up the flag edit box. (Note that editing multiple files will overwrite any flags that it may already have.)</p>
<p>I created a sample project that has an example: <a href="https://github.com/jaminguy/NoArc" rel="noreferrer">https://github.com/jaminguy/NoArc</a></p>
<p><img src="https://i.imgur.com/BgteG.png" alt="xcode"></p>
<p>See this answer for more info:
<a href="https://stackoverflow.com/questions/6448874/automatic-reference-counting-for-some-files">Disable Automatic Reference Counting for Some Files</a></p>
|
{
"question_id": 6646052,
"question_date": "2011-07-11T05:21:18.223Z",
"question_score": 1365,
"tags": "objective-c|xcode|automatic-ref-counting|manual-retain-release",
"answer_id": 6658549,
"answer_date": "2011-07-12T01:22:15.520Z",
"answer_score": 2182
}
|
Please answer the following Stack Overflow question:
Title: How can I uninstall npm modules in Node.js?
<p>As commonly known, any npm module can be installed by running a simple command: <code>npm install <module_name></code>.</p>
<p>I have installed a few modules that I do not use any more and I just want to get them off. I have a few questions regarding this:</p>
<ul>
<li><p>Do we have any command or process to uninstall a module from the root (something like <code>npm uninstall <module_name></code>)
or will simply removing the module files do?</p>
</li>
<li><p>How does it affect us if we keep the unused modules?</p>
</li>
</ul>
|
<p>The command is simply <code>npm uninstall <name></code></p>
<p>The Node.js documents <a href="https://npmjs.org/doc/" rel="noreferrer">https://npmjs.org/doc/</a> have all the commands that you need to know with npm.</p>
<p>A local install will be in the <code>node_modules/</code> directory of your application. This won't affect the application if a module remains there with no references to it. </p>
<p>If you're removing a global package, however, any applications referencing it will crash.</p>
<p>Here are different options:</p>
<p><code>npm uninstall <name></code> removes the module from <code>node_modules</code> but does not update <code>package.json</code></p>
<p><code>npm uninstall <name> --save</code> also removes it from <code>dependencies</code>in <code>package.json</code></p>
<p><code>npm uninstall <name> --save-dev</code> also removes it from <code>devDependencies</code> in <code>package.json</code></p>
<p><code>npm uninstall -g <name> --save</code> also removes it globally</p>
|
{
"question_id": 13066532,
"question_date": "2012-10-25T10:23:26.167Z",
"question_score": 1364,
"tags": "node.js|npm",
"answer_id": 13066677,
"answer_date": "2012-10-25T10:33:14.073Z",
"answer_score": 2008
}
|
Please answer the following Stack Overflow question:
Title: How to find the sum of an array of numbers
<p>Given an array <code>[1, 2, 3, 4]</code>, how can I find the sum of its elements? (In this case, the sum would be <code>10</code>.)</p>
<p>I thought <a href="http://api.jquery.com/jquery.each/" rel="noreferrer"><code>$.each</code></a> might be useful, but I'm not sure how to implement it.</p>
|
<h2>Recommended (reduce with default value)</h2>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce" rel="noreferrer">Array.prototype.reduce</a> can be used to iterate through the array, adding the current element value to the sum of the previous element values.</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>console.log(
[1, 2, 3, 4].reduce((a, b) => a + b, 0)
)
console.log(
[].reduce((a, b) => a + b, 0)
)</code></pre>
</div>
</div>
</p>
<h2>Without default value</h2>
<p>You get a TypeError
<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>console.log(
[].reduce((a, b) => a + b)
)</code></pre>
</div>
</div>
</p>
<h2>Prior to ES6's arrow functions</h2>
<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>console.log(
[1,2,3].reduce(function(acc, val) { return acc + val; }, 0)
)
console.log(
[].reduce(function(acc, val) { return acc + val; }, 0)
)</code></pre>
</div>
</div>
</p>
<h2>Non-number inputs</h2>
<p>If non-numbers are possible inputs, you may want to handle that?
<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>console.log(
["hi", 1, 2, "frog"].reduce((a, b) => a + b)
)
let numOr0 = n => isNaN(n) ? 0 : n
console.log(
["hi", 1, 2, "frog"].reduce((a, b) =>
numOr0(a) + numOr0(b))
)</code></pre>
</div>
</div>
</p>
<h2>Non-recommended <em>dangerous</em> eval use</h2>
<p>We can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval" rel="noreferrer">eval</a> to execute a string representation of JavaScript code. Using the Array.prototype.join function to convert the array to a string, we change [1,2,3] into "1+2+3", which evaluates to 6.</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>console.log(
eval([1,2,3].join('+'))
)
//This way is dangerous if the array is built
// from user input as it may be exploited eg:
eval([1,"2;alert('Malicious code!')"].join('+'))</code></pre>
</div>
</div>
</p>
<p>Of course displaying an alert isn't the worst thing that could happen. The only reason I have included this is as an answer Ortund's question as I do not think it was clarified.</p>
|
{
"question_id": 1230233,
"question_date": "2009-08-04T22:29:40.700Z",
"question_score": 1361,
"tags": "javascript|jquery|arrays",
"answer_id": 43363105,
"answer_date": "2017-04-12T07:31:45.860Z",
"answer_score": 1288
}
|
Please answer the following Stack Overflow question:
Title: YYYY-MM-DD format date in shell script
<p>I tried using <code>$(date)</code> in my bash shell script, however, I want the date in <code>YYYY-MM-DD</code> format.<br>
How do I get this?</p>
|
<p>In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external <code>date</code> (usually GNU date).</p>
<p>As such:</p>
<pre><code># put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)T\n' -1
# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1
# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)T\n' -1
# -> current date printed to terminal
</code></pre>
<p>In bash (<4.2): </p>
<pre><code># put current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')
# put current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')
# print current date directly
echo $(date '+%Y-%m-%d')
</code></pre>
<p>Other available date formats can be viewed from the <a href="http://man7.org/linux/man-pages/man1/date.1.html" rel="noreferrer">date man pages</a> (for external non-bash specific command):</p>
<pre><code>man date
</code></pre>
|
{
"question_id": 1401482,
"question_date": "2009-09-09T19:06:56.870Z",
"question_score": 1361,
"tags": "bash|shell|date|strftime",
"answer_id": 1401495,
"answer_date": "2009-09-09T19:08:57.030Z",
"answer_score": 2120
}
|
Please answer the following Stack Overflow question:
Title: How to switch databases in psql?
<p>In MySQL, I used <code>use database_name;</code></p>
<p>What's the <code>psql</code> equivalent?</p>
|
<p>In PostgreSQL, you can use the <a href="https://www.postgresql.org/docs/current/app-psql.html#APP-PSQL-META-COMMANDS" rel="noreferrer"><code>\connect</code></a> meta-command of the client tool psql:</p>
<pre><code>\connect DBNAME
</code></pre>
<p>or in short:</p>
<pre><code>\c DBNAME
</code></pre>
|
{
"question_id": 3949876,
"question_date": "2010-10-16T17:09:34.107Z",
"question_score": 1361,
"tags": "postgresql|psql",
"answer_id": 3949885,
"answer_date": "2010-10-16T17:12:00.967Z",
"answer_score": 2066
}
|
Please answer the following Stack Overflow question:
Title: How can I remove duplicate rows?
<p>I need to remove duplicate rows from a fairly large SQL Server table (i.e. 300,000+ rows).</p>
<p>The rows, of course, will not be perfect duplicates because of the existence of the <code>RowID</code> identity field.</p>
<p><strong>MyTable</strong></p>
<pre><code>RowID int not null identity(1,1) primary key,
Col1 varchar(20) not null,
Col2 varchar(2048) not null,
Col3 tinyint not null
</code></pre>
<p>How can I do this?</p>
|
<p>Assuming no nulls, you <code>GROUP BY</code> the unique columns, and <code>SELECT</code> the <code>MIN (or MAX)</code> RowId as the row to keep. Then, just delete everything that didn't have a row id:</p>
<pre><code>DELETE FROM MyTable
LEFT OUTER JOIN (
SELECT MIN(RowId) as RowId, Col1, Col2, Col3
FROM MyTable
GROUP BY Col1, Col2, Col3
) as KeepRows ON
MyTable.RowId = KeepRows.RowId
WHERE
KeepRows.RowId IS NULL
</code></pre>
<p>In case you have a GUID instead of an integer, you can replace</p>
<pre><code>MIN(RowId)
</code></pre>
<p>with</p>
<pre><code>CONVERT(uniqueidentifier, MIN(CONVERT(char(36), MyGuidColumn)))
</code></pre>
|
{
"question_id": 18932,
"question_date": "2008-08-20T21:51:29.780Z",
"question_score": 1360,
"tags": "sql-server|tsql|duplicates",
"answer_id": 18949,
"answer_date": "2008-08-20T22:00:00.667Z",
"answer_score": 1186
}
|
Please answer the following Stack Overflow question:
Title: Where does npm install packages?
<p>Can someone tell me where can I find the Node.js modules, which I installed using <strong><code>npm</code></strong>?</p>
|
<h1>Global libraries</h1>
<p>You can run <code>npm list -g</code> to see which global libraries are installed and where they're located. Use <code>npm list -g | head -1</code> for truncated output showing just the path. If you want to display only main packages not its sub-packages which installs along with it - you can use - <code>npm list --depth=0</code> which will show all packages and for getting only globally installed packages, just add -g i.e. <code>npm list -g --depth=0</code>.</p>
<p>On Unix systems they are normally placed in <code>/usr/local/lib/node</code> or <code>/usr/local/lib/node_modules</code> when installed globally. If you set the <code>NODE_PATH</code> environment variable to this path, the modules can be found by node.</p>
<p>Windows XP - <code>%USERPROFILE%\AppData\npm\node_modules</code><br>
Windows 7, 8 and 10 - <code>%USERPROFILE%\AppData\Roaming\npm\node_modules</code></p>
<h1>Non-global libraries</h1>
<p>Non-global libraries are installed the <code>node_modules</code> sub folder in the folder you are currently in. </p>
<p>You can run <code>npm list</code> to see the installed non-global libraries for your current location. </p>
<h1>When installing use -g option to install globally</h1>
<p><strong><code>npm install -g pm2</code></strong> - pm2 will be installed globally. It will then typically be found in <code>/usr/local/lib/node_modules</code> (Use <strong><code>npm root -g</code></strong> to check where.)</p>
<p><strong><code>npm install pm2</code></strong> - pm2 will be installed locally. It will then typically be found in the local directory in <code>/node_modules</code></p>
|
{
"question_id": 5926672,
"question_date": "2011-05-08T09:39:20.190Z",
"question_score": 1359,
"tags": "javascript|node.js|location|npm",
"answer_id": 5926706,
"answer_date": "2011-05-08T09:47:01.077Z",
"answer_score": 1494
}
|
Please answer the following Stack Overflow question:
Title: How do I diff the same file between two different commits on the same branch?
<p>In Git, how could I compare the same file between two different commits (not contiguous) on the same branch (master for example)?</p>
<p>I'm searching for a <strong><em>compare</em></strong> feature like the one in <a href="https://en.wikipedia.org/wiki/Microsoft_Visual_SourceSafe" rel="noreferrer">Visual SourceSafe</a> (VSS) or <a href="https://en.wikipedia.org/wiki/Team_Foundation_Server" rel="noreferrer">Team Foundation Server</a> (TFS).<br>
Is it possible in Git?</p>
|
<p>From the <a href="https://www.kernel.org/pub/software/scm/git/docs/git-diff.html" rel="noreferrer" title="Kernel.org version of git-diff manpage"><code>git-diff</code></a> manpage:</p>
<pre><code>git diff [--options] <commit> <commit> [--] [<path>...]
</code></pre>
<p>For instance, to see the difference for a file "main.c" between now and two commits back, here are three equivalent commands:</p>
<pre><code>$ git diff HEAD^^ HEAD main.c
$ git diff HEAD^^..HEAD -- main.c
$ git diff HEAD~2 HEAD -- main.c
</code></pre>
|
{
"question_id": 3338126,
"question_date": "2010-07-26T19:10:24.547Z",
"question_score": 1359,
"tags": "git|git-diff",
"answer_id": 3338145,
"answer_date": "2010-07-26T19:13:13.993Z",
"answer_score": 1714
}
|
Please answer the following Stack Overflow question:
Title: How to align content of a div to the bottom
<p>Say I have the following CSS and HTML 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>#header {
height: 150px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header">
<h1>Header title</h1>
Header content (one or multiple lines)
</div></code></pre>
</div>
</div>
</p>
<p>The header section is fixed height, but the header content may change.</p>
<p>I would like the content of the header to be vertically aligned to the bottom of the header section, so the last line of text "sticks" to the bottom of the header section.</p>
<p>So if there is only one line of text, it would be like:</p>
<pre>
-----------------------------
| Header title
|
|
|
| header content (resulting in one line)
-----------------------------
</pre>
<p>And if there were three lines:</p>
<pre>
-----------------------------
| Header title
|
| header content (which is so
| much stuff that it perfectly
| spans over three lines)
-----------------------------
</pre>
<p>How can this be done in CSS?</p>
|
<p>Relative+absolute positioning is your best bet:</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>#header {
position: relative;
min-height: 150px;
}
#header-content {
position: absolute;
bottom: 0;
left: 0;
}
#header, #header * {
background: rgba(40, 40, 100, 0.25);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header">
<h1>Title</h1>
<div id="header-content">And in the last place, where this might not be the case, they would be of long standing, would have taken deep root, and would not easily be extirpated. The scheme of revising the constitution, in order to correct recent breaches of it, as well as for other purposes, has been actually tried in one of the States.</div>
</div></code></pre>
</div>
</div>
</p>
<p>But you may run into issues with that. When I tried it I had problems with dropdown menus appearing below the content. It's just not pretty.</p>
<p>Honestly, for vertical centering issues and, well, any vertical alignment issues with the items aren't fixed height, it's easier just to use tables.</p>
<p>Example: <a href="https://stackoverflow.com/questions/522928/can-you-do-this-html-layout-without-using-tables">Can you do this HTML layout without using tables?</a></p>
|
{
"question_id": 585945,
"question_date": "2009-02-25T13:15:09.543Z",
"question_score": 1358,
"tags": "html|css|vertical-alignment",
"answer_id": 585965,
"answer_date": "2009-02-25T13:20:01.573Z",
"answer_score": 1481
}
|
Please answer the following Stack Overflow question:
Title: Local Storage vs Cookies
<p>I want to reduce load times on my websites by moving all cookies into local storage since they seem to have the same functionality. Are there any pros/cons (especially performance-wise) in using local storage to replace cookie functionality except for the obvious compatibility issues?</p>
|
<p>Cookies and local storage serve different purposes. Cookies are primarily for reading <strong>server-side</strong>, local storage can only be read by the <strong>client-side</strong>. So the question is, in your app, who needs this data — the client or the server?</p>
<p>If it's your client (your JavaScript), then by all means switch. You're wasting bandwidth by sending all the data in each HTTP header.</p>
<p>If it's your server, local storage isn't so useful because you'd have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.</p>
<p><strong><em>You'll want to leave your session cookie as a cookie either way though.</em></strong></p>
<p>As per the technical difference, and also my understanding:</p>
<ol>
<li><p>Apart from being an old way of saving data, Cookies give you a limit of <strong>4096</strong> bytes (4095, actually) — it's per cookie. Local Storage is as big as <strong>5MB per domain</strong> — <strong><a href="https://stackoverflow.com/questions/2989284/max-size-of-localstorage-values">SO Question</a></strong> also mentions it.</p></li>
<li><p><code>localStorage</code> is an implementation of the <code>Storage</code> Interface. It stores data with <strong>no expiration date</strong>, and gets cleared <strong>only</strong> through JavaScript, or clearing the Browser Cache / Locally Stored Data — unlike cookie expiry.</p></li>
</ol>
|
{
"question_id": 3220660,
"question_date": "2010-07-10T20:02:10.353Z",
"question_score": 1358,
"tags": "html|cookies|browser|local-storage|httprequest",
"answer_id": 3220802,
"answer_date": "2010-07-10T20:54:34.497Z",
"answer_score": 1680
}
|
Please answer the following Stack Overflow question:
Title: How do I create multiline comments in Python?
<p>How do I make multi-line comments? Most languages have block comment symbols like:</p>
<pre><code>/*
*/
</code></pre>
|
<p>You can use triple-quoted strings. When they're not a docstring (the first thing in a class/function/module), they are ignored.</p>
<pre><code>'''
This is a multiline
comment.
'''
</code></pre>
<p>(Make sure to indent the leading <code>'''</code> appropriately to avoid an <code>IndentationError</code>.)</p>
<p><a href="https://en.wikipedia.org/wiki/Guido_van_Rossum" rel="noreferrer">Guido van Rossum</a> (creator of Python) <a href="https://twitter.com/gvanrossum/status/112670605505077248" rel="noreferrer">tweeted this</a> as a "pro tip".</p>
<p>However, Python's style guide, PEP8, <a href="http://www.python.org/dev/peps/pep-0008/#block-comments" rel="noreferrer">favors using consecutive single-line comments</a>, like this:</p>
<pre><code># This is a multiline
# comment.
</code></pre>
<p>...and this is also what you'll find in many projects. Text editors usually have a shortcut to do this easily.</p>
|
{
"question_id": 7696924,
"question_date": "2011-10-08T12:51:13.093Z",
"question_score": 1357,
"tags": "python|comments|documentation",
"answer_id": 7696966,
"answer_date": "2011-10-08T12:58:47.093Z",
"answer_score": 2079
}
|
Please answer the following Stack Overflow question:
Title: Is there a built-in function to print all the current properties and values of an object?
<p>So what I'm looking for here is something like PHP's <a href="http://us2.php.net/print_r" rel="noreferrer">print_r</a> function.</p>
<p>This is so I can debug my scripts by seeing what's the state of the object in question.</p>
|
<p>You are really mixing together two different things.</p>
<p>Use <a href="https://docs.python.org/3/library/functions.html#dir" rel="noreferrer"><code>dir()</code></a>, <a href="https://docs.python.org/3/library/functions.html#vars" rel="noreferrer"><code>vars()</code></a> or the <a href="https://docs.python.org/3/library/inspect.html" rel="noreferrer"><code>inspect</code></a> module to get what you are interested in (I use <code>__builtins__</code> as an example; you can use any object instead).</p>
<pre><code>>>> l = dir(__builtins__)
>>> d = __builtins__.__dict__
</code></pre>
<p>Print that dictionary however fancy you like:</p>
<pre><code>>>> print l
['ArithmeticError', 'AssertionError', 'AttributeError',...
</code></pre>
<p>or</p>
<pre><code>>>> from pprint import pprint
>>> pprint(l)
['ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'DeprecationWarning',
...
>>> pprint(d, indent=2)
{ 'ArithmeticError': <type 'exceptions.ArithmeticError'>,
'AssertionError': <type 'exceptions.AssertionError'>,
'AttributeError': <type 'exceptions.AttributeError'>,
...
'_': [ 'ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'DeprecationWarning',
...
</code></pre>
<p>Pretty printing is also available in the interactive debugger as a command:</p>
<pre><code>(Pdb) pp vars()
{'__builtins__': {'ArithmeticError': <type 'exceptions.ArithmeticError'>,
'AssertionError': <type 'exceptions.AssertionError'>,
'AttributeError': <type 'exceptions.AttributeError'>,
'BaseException': <type 'exceptions.BaseException'>,
'BufferError': <type 'exceptions.BufferError'>,
...
'zip': <built-in function zip>},
'__file__': 'pass.py',
'__name__': '__main__'}
</code></pre>
|
{
"question_id": 192109,
"question_date": "2008-10-10T16:19:27.850Z",
"question_score": 1357,
"tags": "python|debugging|introspection|pretty-print|python-datamodel",
"answer_id": 192365,
"answer_date": "2008-10-10T17:27:06.077Z",
"answer_score": 767
}
|
Please answer the following Stack Overflow question:
Title: How do I sort a dictionary by key?
<p>How do I sort a dictionary by its keys?</p>
<p>Example input:</p>
<pre><code>{2:3, 1:89, 4:5, 3:0}
</code></pre>
<p>Desired output:</p>
<pre><code>{1:89, 2:3, 3:0, 4:5}
</code></pre>
|
<blockquote>
<p><strong>Note:</strong> for Python 3.7+, see <a href="https://stackoverflow.com/a/47017849">this answer</a></p>
</blockquote>
<p>Standard Python dictionaries are unordered (until Python 3.7). Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a <code>dict</code> in a way that would preserve the ordering.</p>
<p>The easiest way is to use <a href="http://docs.python.org/library/collections.html#collections.OrderedDict" rel="noreferrer"><code>OrderedDict</code></a>, which remembers the order in which the elements have been inserted:</p>
<pre><code>In [1]: import collections
In [2]: d = {2:3, 1:89, 4:5, 3:0}
In [3]: od = collections.OrderedDict(sorted(d.items()))
In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
</code></pre>
<p>Never mind the way <code>od</code> is printed out; it'll work as expected:</p>
<pre><code>In [11]: od[1]
Out[11]: 89
In [12]: od[3]
Out[12]: 0
In [13]: for k, v in od.iteritems(): print k, v
....:
1 89
2 3
3 0
4 5
</code></pre>
<h2>Python 3</h2>
<p>For Python 3 users, one needs to use the <code>.items()</code> instead of <code>.iteritems()</code>:</p>
<pre><code>In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5
</code></pre>
|
{
"question_id": 9001509,
"question_date": "2012-01-25T10:54:29.483Z",
"question_score": 1356,
"tags": "python|sorting|dictionary",
"answer_id": 9001529,
"answer_date": "2012-01-25T10:56:30.747Z",
"answer_score": 1224
}
|
Please answer the following Stack Overflow question:
Title: Asynchronous vs synchronous execution. What is the difference?
<p>What is the difference between asynchronous and synchronous execution?</p>
|
<p>When you execute something synchronously, you wait for it to finish before moving on to another task. When you execute something asynchronously, you can move on to another task before it finishes.</p>
<p>In the context of operating systems, this corresponds to executing a process or task on a "thread." A thread is a series of commands (a block of code) that exist as a unit of work. The operating system runs a given thread on a processor core. However, a processor core can only execute a single thread at once. It has no concept of running multiple threads simultaneously. The operating system can provide the illusion of running multiple threads at once by running each thread for a small slice of time (such as 1ms), and continuously switching between threads.</p>
<p>Now, if you introduce multiple processor cores into the mix, then threads CAN execute at the same time. The operating system can allocate time to one thread on the first processor core, then allocate the same block of time to another thread on a different processor core. All of this is about allowing the operating system to manage the completion of your task while you can go on in your code and do other things.</p>
<p>Asynchronous programming is a complicated topic because of the semantics of how things tie together when you can do them at the same time. There are numerous articles and books on the subject; have a look!</p>
|
{
"question_id": 748175,
"question_date": "2009-04-14T15:39:43.320Z",
"question_score": 1356,
"tags": "asynchronous|execution|synchronous",
"answer_id": 748189,
"answer_date": "2009-04-14T15:43:10.160Z",
"answer_score": 1938
}
|
Please answer the following Stack Overflow question:
Title: What characters can be used for up/down triangle (arrow without stem) for display in HTML?
<p>I'm looking for a <strong>HTML</strong> or <strong>ASCII</strong> character which is a triangle pointing up or down so that I can use it as a toggle switch.</p>
<p>I found ↑ (<code>&uarr;</code>), and ↓ (<code>&darr;</code>) - but those have a narrow stem. I'm looking just for the HTML arrow "head".</p>
|
<p>Unicode arrows heads:</p>
<ul>
<li>▲ - U+25B2 BLACK UP-POINTING TRIANGLE</li>
<li>▼ - U+25BC BLACK DOWN-POINTING TRIANGLE</li>
<li>▴ - U+25B4 SMALL BLACK UP-POINTING TRIANGLE</li>
<li>▾ - U+25BE SMALL BLACK DOWN-POINTING TRIANGLE</li>
</ul>
<p>For ▲ and ▼ use <code>&#x25B2;</code> and <code>&#x25BC;</code> respectively if you cannot include Unicode characters directly (use UTF-8!).</p>
<p>Note that the font support for the smaller versions is not as good. Better to use the large versions in smaller font.</p>
<p>More Unicode arrows are at:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Arrow_%28symbol%29#Arrows_in_Unicode" rel="noreferrer">http://en.wikipedia.org/wiki/Arrow_%28symbol%29#Arrows_in_Unicode</a></li>
<li><a href="http://en.wikipedia.org/wiki/Geometric_Shapes" rel="noreferrer">http://en.wikipedia.org/wiki/Geometric_Shapes</a></li>
</ul>
<p>Lastly, these arrows are not ASCII, including ↑ and ↓: they are Unicode.</p>
|
{
"question_id": 2701192,
"question_date": "2010-04-23T18:51:54.080Z",
"question_score": 1355,
"tags": "html|css|unicode|icons|symbols",
"answer_id": 2701226,
"answer_date": "2010-04-23T18:57:18.390Z",
"answer_score": 1738
}
|
Please answer the following Stack Overflow question:
Title: How can I use grep to show just filenames on Linux?
<p>How can I use <a href="https://linux.die.net/man/1/grep" rel="noreferrer">grep</a> to show just file-names (no in-line matches) on Linux?</p>
<p>I am usually using something like:</p>
<pre><code>find . -iname "*php" -exec grep -H myString {} \;
</code></pre>
<p>How can I just get the file-names (with paths), but without the matches? Do I have to use <a href="https://linux.die.net/man/1/xargs" rel="noreferrer">xargs</a>? I didn't see a way to do this on my grep man page.</p>
|
<p>The standard option <code>grep -l</code> (that is a lowercase L) could do this.</p>
<p>From the <a href="http://pubs.opengroup.org/onlinepubs/007908799/xcu/grep.html" rel="noreferrer">Unix standard</a>:</p>
<pre><code>-l
(The letter ell.) Write only the names of files containing selected
lines to standard output. Pathnames are written once per file searched.
If the standard input is searched, a pathname of (standard input) will
be written, in the POSIX locale. In other locales, standard input may be
replaced by something more appropriate in those locales.
</code></pre>
<p>You also do not need <code>-H</code> in this case.</p>
|
{
"question_id": 6637882,
"question_date": "2011-07-09T22:24:53.037Z",
"question_score": 1355,
"tags": "linux|grep",
"answer_id": 6637894,
"answer_date": "2011-07-09T22:26:52.143Z",
"answer_score": 2086
}
|
Please answer the following Stack Overflow question:
Title: Trim string in JavaScript
<p>How do I remove all whitespace from the start and end of the string?</p>
|
<p>All browsers since IE9+ have <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim" rel="noreferrer"><code>trim()</code></a> method for strings:</p>
<pre><code>" \n test \n ".trim(); // returns "test" here
</code></pre>
<p>For those browsers who does not support <code>trim()</code>, you can use this polyfill from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim" rel="noreferrer">MDN</a>:</p>
<pre><code>if (!String.prototype.trim) {
(function() {
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
String.prototype.trim = function() {
return this.replace(rtrim, '');
};
})();
}
</code></pre>
<hr />
<p>That said, if using <code>jQuery</code>, <code>$.trim(str)</code> is also available and handles undefined/null.</p>
<hr />
<p>See this:</p>
<pre><code>String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
String.prototype.ltrim=function(){return this.replace(/^\s+/,'');};
String.prototype.rtrim=function(){return this.replace(/\s+$/,'');};
String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};
</code></pre>
|
{
"question_id": 498970,
"question_date": "2009-01-31T15:12:23.267Z",
"question_score": 1354,
"tags": "javascript|string|trim",
"answer_id": 498995,
"answer_date": "2009-01-31T15:26:30.163Z",
"answer_score": 932
}
|
Please answer the following Stack Overflow question:
Title: window.onload vs $(document).ready()
<p>What are the differences between JavaScript's <a href="https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onload" rel="noreferrer"><code>window.onload</code></a> and jQuery's <a href="https://learn.jquery.com/using-jquery-core/document-ready/" rel="noreferrer"><code>$(document).ready()</code></a> method?</p>
|
<p>The <code>ready</code> event occurs after the HTML document has been loaded, while the <code>onload</code> event occurs later, when all content (e.g. images) also has been loaded.</p>
<p>The <code>onload</code> event is a standard event in the DOM, while the <code>ready</code> event is specific to jQuery. The purpose of the <code>ready</code> event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.</p>
|
{
"question_id": 3698200,
"question_date": "2010-09-13T06:24:52.570Z",
"question_score": 1352,
"tags": "javascript|jquery|dom-events|unobtrusive-javascript",
"answer_id": 3698214,
"answer_date": "2010-09-13T06:28:21.707Z",
"answer_score": 1340
}
|
Please answer the following Stack Overflow question:
Title: JavaScriptSerializer - JSON serialization of enum as string
<p>I have a class that contains an <code>enum</code> property, and upon serializing the object using <code>JavaScriptSerializer</code>, my json result contains the integer value of the enumeration rather than its <code>string</code> "name". Is there a way to get the enum as a <code>string</code> in my json without having to create a custom <code>JavaScriptConverter</code>? Perhaps there's an attribute that I could decorate the <code>enum</code> definition, or object property, with?</p>
<p>As an example:</p>
<pre><code>enum Gender { Male, Female }
class Person
{
int Age { get; set; }
Gender Gender { get; set; }
}
</code></pre>
<p>Desired JSON result:</p>
<pre><code>{ "Age": 35, "Gender": "Male" }
</code></pre>
<p>Ideally looking for answer with built-in .NET framework classes, if not possible alternatives (like Json.net) are welcome.</p>
|
<p>No there is no special attribute you can use. <code>JavaScriptSerializer</code> serializes <code>enums</code> to their numeric values and not their string representation. You would need to use custom serialization to serialize the <code>enum</code> as its name instead of numeric value.</p>
<hr>
<p>If you can use JSON.Net instead of <code>JavaScriptSerializer</code> than see <a href="https://stackoverflow.com/a/2870420/477420">answer on this question</a> provided by <a href="https://stackoverflow.com/users/56829/omer-bokhari">OmerBakhari</a>: JSON.net covers this use case (via the attribute <code>[JsonConverter(typeof(StringEnumConverter))]</code>) and many others not handled by the built in .net serializers. <a href="https://www.newtonsoft.com/json/help/html/JsonNetVsDotNetSerializers.htm" rel="noreferrer">Here is a link comparing features and functionalities of the serializers</a>.</p>
|
{
"question_id": 2441290,
"question_date": "2010-03-14T05:18:56.053Z",
"question_score": 1352,
"tags": "c#|asp.net|json|enums|javascriptserializer",
"answer_id": 2441379,
"answer_date": "2010-03-14T06:21:10.860Z",
"answer_score": 452
}
|
Please answer the following Stack Overflow question:
Title: Which MySQL data type to use for storing boolean values
<p>Since MySQL doesn't seem to have any 'boolean' data type, which data type do you 'abuse' for storing true/false information in MySQL?</p>
<p>Especially in the context of writing and reading from/to a PHP script.</p>
<p>Over time I have used and seen several approaches:</p>
<ul>
<li>tinyint, varchar fields containing the values 0/1,</li>
<li>varchar fields containing the strings '0'/'1' or 'true'/'false'</li>
<li>and finally enum Fields containing the two options 'true'/'false'.</li>
</ul>
<p>None of the above seems optimal. I tend to prefer the tinyint 0/1 variant, since automatic type conversion in PHP gives me boolean values rather simply.</p>
<p>So which data type do you use? Is there a type designed for boolean values which I have overlooked? Do you see any advantages/disadvantages by using one type or another?</p>
|
<p>For MySQL 5.0.3 and higher, you can use <code>BIT</code>. The manual says:</p>
<blockquote>
<p>As of MySQL 5.0.3, the BIT data type is used to store bit-field
values. A type of BIT(M) enables storage of M-bit values. M can range
from 1 to 64.</p>
</blockquote>
<p>Otherwise, according to the MySQL manual you can use <code>BOOL</code> or <code>BOOLEAN</code>, which are at the moment aliases of <a href="http://dev.mysql.com/doc/refman/5.7/en/integer-types.html" rel="noreferrer">tinyint</a>(1):</p>
<blockquote>
<p>Bool, Boolean: These types are synonyms for <a href="http://dev.mysql.com/doc/refman/5.7/en/integer-types.html" rel="noreferrer">TINYINT</a>(1). A value of
zero is considered false. Non-zero
values are considered true.</p>
</blockquote>
<p>MySQL also states that:</p>
<blockquote>
<p>We intend to implement full boolean
type handling, in accordance with
standard SQL, in a future MySQL
release.</p>
</blockquote>
<p>References: <a href="http://dev.mysql.com/doc/refman/5.5/en/numeric-type-overview.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.5/en/numeric-type-overview.html</a></p>
|
{
"question_id": 289727,
"question_date": "2008-11-14T10:36:18.870Z",
"question_score": 1350,
"tags": "mysql|boolean|sqldatatypes",
"answer_id": 289759,
"answer_date": "2008-11-14T10:50:51.943Z",
"answer_score": 1345
}
|
Please answer the following Stack Overflow question:
Title: How to Sort a Multi-dimensional Array by Value
<p>How can I sort this array by the value of the "order" key?</p>
<p>Even though the values are currently sequential, they will not always be.</p>
<pre><code>Array
(
[0] => Array
(
[hashtag] => a7e87329b5eab8578f4f1098a152d6f4
[title] => Flower
[order] => 3
)
[1] => Array
(
[hashtag] => b24ce0cd392a5b0b8dedc66c25213594
[title] => Free
[order] => 2
)
[2] => Array
(
[hashtag] => e7d31fc0602fb2ede144d18cdffd816b
[title] => Ready
[order] => 1
)
)
</code></pre>
|
<p>Try a <a href="http://php.net/manual/en/function.usort.php" rel="noreferrer">usort</a>. If you are still on PHP 5.2 or earlier, you'll have to define a sorting function first:</p>
<pre><code>function sortByOrder($a, $b) {
return $a['order'] - $b['order'];
}
usort($myArray, 'sortByOrder');
</code></pre>
<p>Starting in PHP 5.3, you can use an anonymous function:</p>
<pre><code>usort($myArray, function($a, $b) {
return $a['order'] - $b['order'];
});
</code></pre>
<p>With PHP 7 you can use the <a href="https://stackoverflow.com/a/31298778">spaceship operator</a>:</p>
<pre><code>usort($myArray, function($a, $b) {
return $a['order'] <=> $b['order'];
});
</code></pre>
<p>Finally, in PHP 7.4 you can clean up a bit with an arrow function:</p>
<pre><code>usort($myArray, fn($a, $b) => $a['order'] <=> $b['order']);
</code></pre>
<p>To extend this to multi-dimensional sorting, reference the second/third sorting elements if the first is zero - best explained below. You can also use this for sorting on sub-elements.</p>
<pre><code>usort($myArray, function($a, $b) {
$retval = $a['order'] <=> $b['order'];
if ($retval == 0) {
$retval = $a['suborder'] <=> $b['suborder'];
if ($retval == 0) {
$retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
}
}
return $retval;
});
</code></pre>
<p>If you need to retain key associations, use <code>uasort()</code> - see <a href="http://php.net/manual/en/array.sorting.php" rel="noreferrer">comparison of array sorting functions</a> in the manual.</p>
|
{
"question_id": 2699086,
"question_date": "2010-04-23T13:54:26.653Z",
"question_score": 1348,
"tags": "php|arrays|sorting|multidimensional-array",
"answer_id": 2699159,
"answer_date": "2010-04-23T14:04:55.457Z",
"answer_score": 2026
}
|
Please answer the following Stack Overflow question:
Title: Check if table exists in SQL Server
<p>I would like this to be the ultimate discussion on how to check if a table exists in SQL Server 2000/2005 using SQL Statements.</p>
<p>Here are two possible ways of doing it. Which one is the standard/best way of doing it?</p>
<p>First way:</p>
<pre><code>IF EXISTS (SELECT 1
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME='mytablename')
SELECT 1 AS res ELSE SELECT 0 AS res;
</code></pre>
<p>Second way:</p>
<pre><code>IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL
SELECT 1 AS res ELSE SELECT 0 AS res;
</code></pre>
<p><strong>MySQL</strong> provides the simple</p>
<pre><code>SHOW TABLES LIKE '%tablename%';
</code></pre>
<p>statement. I am looking for something similar.</p>
|
<p>For queries like this it is always best to use an <code>INFORMATION_SCHEMA</code> view. These views are (mostly) standard across many different databases and rarely change from version to version.</p>
<p>To check if a table exists use:</p>
<pre><code>IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
AND TABLE_NAME = 'TheTable'))
BEGIN
--Do Stuff
END
</code></pre>
|
{
"question_id": 167576,
"question_date": "2008-10-03T16:00:33.803Z",
"question_score": 1347,
"tags": "sql-server|tsql|sql-server-2005|sql-server-2000",
"answer_id": 167680,
"answer_date": "2008-10-03T16:17:35.343Z",
"answer_score": 1544
}
|
Please answer the following Stack Overflow question:
Title: How to count lines in a document?
<p>I have lines like these, and I want to know how many lines I actually have...</p>
<pre><code>09:16:39 AM all 2.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 94.00
09:16:40 AM all 5.00 0.00 0.00 4.00 0.00 0.00 0.00 0.00 91.00
09:16:41 AM all 0.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 96.00
09:16:42 AM all 3.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 96.00
09:16:43 AM all 0.00 0.00 1.00 0.00 1.00 0.00 0.00 0.00 98.00
09:16:44 AM all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
09:16:45 AM all 2.00 0.00 6.00 0.00 0.00 0.00 0.00 0.00 92.00
</code></pre>
<p>Is there a way to count them all using linux commands?</p>
|
<p>Use <code>wc</code>:</p>
<pre><code>wc -l <filename>
</code></pre>
<p>This will output the number of lines in <code><filename></code>:</p>
<pre><code>$ wc -l /dir/file.txt
3272485 /dir/file.txt
</code></pre>
<p>Or, to omit the <code><filename></code> from the result use <code>wc -l < <filename></code>:</p>
<pre><code>$ wc -l < /dir/file.txt
3272485
</code></pre>
<p>You can also pipe data to <code>wc</code> as well:</p>
<pre><code>$ cat /dir/file.txt | wc -l
3272485
$ curl yahoo.com --silent | wc -l
63
</code></pre>
|
{
"question_id": 3137094,
"question_date": "2010-06-29T00:31:31.247Z",
"question_score": 1345,
"tags": "linux|bash|command-line|scripting",
"answer_id": 3137099,
"answer_date": "2010-06-29T00:33:38.333Z",
"answer_score": 2453
}
|
Please answer the following Stack Overflow question:
Title: Get a random item from a JavaScript array
<pre><code>var items = Array(523, 3452, 334, 31, ..., 5346);
</code></pre>
<p>How do I get random item from <code>items</code>?</p>
|
<pre><code>var item = items[Math.floor(Math.random()*items.length)];
</code></pre>
|
{
"question_id": 5915096,
"question_date": "2011-05-06T17:47:45.747Z",
"question_score": 1345,
"tags": "javascript|arrays|random",
"answer_id": 5915122,
"answer_date": "2011-05-06T17:50:19.113Z",
"answer_score": 2801
}
|
Please answer the following Stack Overflow question:
Title: Maintain the aspect ratio of a div with CSS
<p>I want to create a <code>div</code> that can change its width/height as the window's width changes.</p>
<p>Are there any CSS3 rules that would allow the height to change according to the width, <strong>while maintaining its aspect ratio</strong>?</p>
<p>I know I can do this via JavaScript, but I would prefer using only CSS.</p>
<p><a href="https://i.stack.imgur.com/1cMfK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1cMfK.png" alt="div keeping aspect ratio according to width of window"></a></p>
|
<p>Just create a wrapper <code><div></code> with a percentage value for <code>padding-bottom</code>, like this:</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>.demoWrapper {
padding: 10px;
background: white;
box-sizing: border-box;
resize: horizontal;
border: 1px dashed;
overflow: auto;
max-width: 100%;
height: calc(100vh - 16px);
}
div {
width: 100%;
padding-bottom: 75%;
background: gold; /** <-- For the demo **/
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="demoWrapper">
<div></div>
</div></code></pre>
</div>
</div>
</p>
<p>It will result in a <code><div></code> with height equal to 75% of the width of its container (a 4:3 aspect ratio).</p>
<p>This relies on the fact that for padding :</p>
<blockquote>
<p>The percentage is calculated with respect to the <strong>width</strong> of the generated box's containing block [...] (source: <a href="http://www.w3.org/TR/2011/REC-CSS2-20110607/box.html#padding-properties" rel="noreferrer">w3.org</a>, emphasis mine)</p>
</blockquote>
<p>Padding-bottom values for other aspect ratios and 100% width :</p>
<pre><code>aspect ratio | padding-bottom value
--------------|----------------------
16:9 | 56.25%
4:3 | 75%
3:2 | 66.66%
8:5 | 62.5%
</code></pre>
<hr />
<p><strong>Placing content in the div :</strong></p>
<p>In order to keep the aspect ratio of the div and prevent its content from stretching it, you need to add an absolutely positioned child and stretch it to the edges of the wrapper with:</p>
<pre class="lang-css prettyprint-override"><code>div.stretchy-wrapper {
position: relative;
}
div.stretchy-wrapper > div {
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
}
</code></pre>
<p><a href="http://dabblet.com/gist/2590942" rel="noreferrer">Here's a <strong>demo</strong></a> and another more in depth <a href="http://jsbin.com/vatuqiyebu/edit" rel="noreferrer">demo</a></p>
|
{
"question_id": 1495407,
"question_date": "2009-09-29T23:11:05.057Z",
"question_score": 1344,
"tags": "html|css|responsive-design|aspect-ratio",
"answer_id": 10441480,
"answer_date": "2012-05-04T01:19:53.813Z",
"answer_score": 1528
}
|
Please answer the following Stack Overflow question:
Title: Removing duplicates in lists
<p>Pretty much I need to write a program to check if a list has any duplicates and if it does it removes them and returns a new list with the items that weren't duplicated/removed. This is what I have but to be honest I do not know what to do.</p>
<pre><code>def remove_duplicates():
t = ['a', 'b', 'c', 'd']
t2 = ['a', 'c', 'd']
for t in t2:
t.append(t.remove())
return t
</code></pre>
|
<p>The common approach to get a unique collection of items is to use a <a href="http://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset" rel="noreferrer"><code>set</code></a>. Sets are <em>unordered</em> collections of <em>distinct</em> objects. To create a set from any iterable, you can simply pass it to the built-in <a href="http://docs.python.org/3/library/functions.html#func-set" rel="noreferrer"><code>set()</code></a> function. If you later need a real list again, you can similarly pass the set to the <a href="http://docs.python.org/3/library/functions.html#func-list" rel="noreferrer"><code>list()</code></a> function.</p>
<p>The following example should cover whatever you are trying to do:</p>
<pre><code>>>> t = [1, 2, 3, 1, 2, 3, 5, 6, 7, 8]
>>> list(set(t))
[1, 2, 3, 5, 6, 7, 8]
>>> s = [1, 2, 3]
>>> list(set(t) - set(s))
[8, 5, 6, 7]
</code></pre>
<p>As you can see from the example result, <em>the original order is not maintained</em>. As mentioned above, sets themselves are unordered collections, so the order is lost. When converting a set back to a list, an arbitrary order is created.</p>
<h3>Maintaining order</h3>
<p>If order is important to you, then you will have to use a different mechanism. A very common solution for this is to rely on <a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict" rel="noreferrer"><code>OrderedDict</code></a> to keep the order of keys during insertion:</p>
<pre><code>>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(t))
[1, 2, 3, 5, 6, 7, 8]
</code></pre>
<p><a href="https://mail.python.org/pipermail/python-dev/2017-December/151283.html" rel="noreferrer">Starting with Python 3.7</a>, the built-in dictionary is guaranteed to maintain the insertion order as well, so you can also use that directly if you are on Python 3.7 or later (or CPython 3.6):</p>
<pre><code>>>> list(dict.fromkeys(t))
[1, 2, 3, 5, 6, 7, 8]
</code></pre>
<p>Note that this may have some overhead of creating a dictionary first, and then creating a list from it. If you don’t actually need to preserve the order, you’re often better off using a set, especially because it gives you a lot more operations to work with. Check out <a href="https://stackoverflow.com/q/480214/216074">this question</a> for more details and alternative ways to preserve the order when removing duplicates.</p>
<hr />
<p>Finally note that both the <code>set</code> as well as the <code>OrderedDict</code>/<code>dict</code> solutions require your items to be <em>hashable</em>. This usually means that they have to be immutable. If you have to deal with items that are not hashable (e.g. list objects), then you will have to use a slow approach in which you will basically have to compare every item with every other item in a nested loop.</p>
|
{
"question_id": 7961363,
"question_date": "2011-11-01T00:45:24.203Z",
"question_score": 1343,
"tags": "python|algorithm|list|duplicates|intersection",
"answer_id": 7961390,
"answer_date": "2011-11-01T00:49:04.907Z",
"answer_score": 2110
}
|
Please answer the following Stack Overflow question:
Title: What are the -Xms and -Xmx parameters when starting JVM?
<p>Please explain the use of the <code>Xms</code> and <code>Xmx</code> parameters in JVMs. What are the default values for them?</p>
|
<p>The flag <code>Xmx</code> specifies the maximum memory allocation pool for a Java Virtual Machine (JVM), while <code>Xms</code> specifies the initial memory allocation pool.</p>
<p>This means that your JVM will be started with <code>Xms</code> amount of memory and will be able to use a maximum of <code>Xmx</code> amount of memory. For example, starting a JVM like below will start it with 256 MB of memory and will allow the process to use up to 2048 MB of memory:</p>
<pre><code>java -Xms256m -Xmx2048m
</code></pre>
<p>The memory flag can also be specified in different sizes, such as kilobytes, megabytes, and so on.</p>
<pre><code>-Xmx1024k
-Xmx512m
-Xmx8g
</code></pre>
<p>The <code>Xms</code> flag has no default value, and <code>Xmx</code> typically has a default value of 256 MB. A common use for these flags is when you encounter a <code>java.lang.OutOfMemoryError</code>.</p>
<p>When using these settings, keep in mind that these settings are for the JVM's <em>heap</em>, and that the JVM can and will use more memory than just the size allocated to the heap. From <a href="http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/garbage_collect.html" rel="noreferrer">Oracle's documentation</a>:</p>
<blockquote>
<p>Note that the JVM uses more memory than just the heap. For example Java methods, thread stacks and native handles are allocated in memory separate from the heap, as well as JVM internal data structures.</p>
</blockquote>
|
{
"question_id": 14763079,
"question_date": "2013-02-07T23:28:20.607Z",
"question_score": 1342,
"tags": "java|memory-management|parameters|jvm",
"answer_id": 14763095,
"answer_date": "2013-02-07T23:29:31.977Z",
"answer_score": 1736
}
|
Please answer the following Stack Overflow question:
Title: How should I ethically approach user password storage for later plaintext retrieval?
<p>As I continue to build more and more websites and web applications I am often asked to store user's passwords in a way that they can be retrieved if/when the user has an issue (either to email a forgotten password link, walk them through over the phone, etc.) When I can I fight bitterly against this practice and I do a lot of ‘extra’ programming to make password resets and administrative assistance possible without storing their actual password.</p>
<p>When I can’t fight it (or can’t win) then I always encode the password in some way so that it, at least, isn’t stored as plaintext in the database—though I am aware that if my DB gets hacked it wouldn't take much for the culprit to crack the passwords, so that makes me uncomfortable.</p>
<p>In a perfect world folks would update passwords frequently and not duplicate them across many different sites—unfortunately I know MANY people that have the same work/home/email/bank password, and have even freely given it to me when they need assistance. I don’t want to be the one responsible for their financial demise if my DB security procedures fail for some reason.</p>
<p>Morally and ethically I feel responsible for protecting what can be, for some users, their livelihood even if they are treating it with much less respect.
I am certain that there are many avenues to approach and arguments to be made for salting hashes and different encoding options, but is there a single ‘best practice’ when you have to store them? In almost all cases I am using PHP and MySQL if that makes any difference in the way I should handle the specifics.</p>
<p><strong>Additional Information for Bounty</strong></p>
<p>I want to clarify that I know this is not something you want to have to do and that in most cases refusal to do so is best. I am, however, not looking for a lecture on the merits of taking this approach I am looking for the best steps to take if you do take this approach.</p>
<p>In a note below I made the point that websites geared largely toward the elderly, mentally challenged, or very young can become confusing for people when they are asked to perform a secure password recovery routine. Though we may find it simple and mundane in those cases some users need the extra assistance of either having a service tech help them into the system or having it emailed/displayed directly to them. </p>
<p>In such systems the attrition rate from these demographics could hobble the application if users were not given this level of access assistance, so please answer with such a setup in mind.</p>
<p><strong>Thanks to Everyone</strong></p>
<p>This has been a fun question with lots of debate and I have enjoyed it. In the end I selected an answer that both retains password security (I will not have to keep plain text or recoverable passwords), but also makes it possible for the user base I specified to log into a system without the major drawbacks I have found from normal password recovery.</p>
<p>As always there were about 5 answers that I would like to have marked as correct for different reasons, but I had to choose the best one--all the rest got a +1. Thanks everyone!</p>
<p>Also, thanks to everyone in the Stack community who voted for this question and/or marked it as a favorite. I take hitting 100 up votes as a compliment and hope that this discussion has helped someone else with the same concern that I had.</p>
|
<p>How about taking another approach or angle at this problem? Ask why the password is required to be in plaintext: if it's so that the user can retrieve the password, then strictly speaking you don't really need to retrieve the password they set (they don't remember what it is anyway), you need to be able to give them a password they <em>can use</em>.</p>
<p>Think about it: if the user needs to retrieve the password, it's because they've forgotten it. In which case a new password is just as good as the old one. But, one of the drawbacks of common password reset mechanisms used today is that the generated passwords produced in a reset operation are generally a bunch of random characters, so they're difficult for the user to simply type in correctly unless they copy-n-paste. That can be a problem for less savvy computer users.</p>
<p>One way around that problem is to provide auto-generated passwords that are more or less natural language text. While natural language strings might not have the entropy that a string of random characters of the same length has, there's nothing that says your auto-generated password needs to have only 8 (or 10 or 12) characters. Get a high-entropy auto-generated passphrase by stringing together several random words (leave a space between them, so they're still recognizable and typeable by anyone who can read). Six random words of varying length are probably easier to type correctly and with confidence than 10 random characters, and they can have a higher entropy as well. For example, the entropy of a 10 character password drawn randomly from uppercase, lowercase, digits and 10 punctuation symbols (for a total of 72 valid symbols) would have an entropy of 61.7 bits. Using a dictionary of 7776 words (as Diceware uses) which could be randomly selected for a six word passphrase, the passphrase would have an entropy of 77.4 bits. See the <a href="http://world.std.com/~reinhold/dicewarefaq.html#calculatingentropy" rel="noreferrer">Diceware FAQ</a> for more info.</p>
<ul>
<li><p>a passphrase with about 77 bits of entropy: "admit prose flare table acute flair"</p></li>
<li><p>a password with about 74 bits of entropy: "K:&$R^tt~qkD"</p></li>
</ul>
<p>I know I'd prefer typing the phrase, and with copy-n-paste, the phrase is no less easy to use that the password either, so no loss there. Of course if your website (or whatever the protected asset is) doesn't need 77 bits of entropy for an auto-generated passphrase, generate fewer words (which I'm sure your users would appreciate).</p>
<p>I understand the arguments that there are password protected assets that really don't have a high level of value, so the breach of a password might not be the end of the world. For example, I probably wouldn't care if 80% of the passwords I use on various websites was breached: all that could happen is a someone spamming or posting under my name for a while. That wouldn't be great, but it's not like they'd be breaking into my bank account. However, given the fact that many people use the same password for their web forum sites as they do for their bank accounts (and probably national security databases), I think it would be best to handle even those 'low-value' passwords as non-recoverable.</p>
|
{
"question_id": 2283937,
"question_date": "2010-02-17T19:54:40.083Z",
"question_score": 1342,
"tags": "security|password-encryption|password-storage",
"answer_id": 2350498,
"answer_date": "2010-02-28T08:16:51.197Z",
"answer_score": 1036
}
|
Please answer the following Stack Overflow question:
Title: Convert JS object to JSON string
<p>If I defined an object in JS with:</p>
<pre><code>var j={"name":"binchen"};
</code></pre>
<p>How can I convert the object to JSON? The output string should be:</p>
<pre><code>'{"name":"binchen"}'
</code></pre>
|
<p>All current browsers have native JSON support built in. So as long as you're not dealing with prehistoric browsers like IE6/7 you can do it just as easily as that:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var j = {
"name": "binchen"
};
console.log(JSON.stringify(j));</code></pre>
</div>
</div>
</p>
|
{
"question_id": 4162749,
"question_date": "2010-11-12T08:20:50.640Z",
"question_score": 1341,
"tags": "javascript|json|string|object",
"answer_id": 4162803,
"answer_date": "2010-11-12T08:31:04.953Z",
"answer_score": 2019
}
|
Please answer the following Stack Overflow question:
Title: Change column type in pandas
<p>I created a DataFrame from a list of lists:</p>
<pre><code>table = [
['a', '1.2', '4.2' ],
['b', '70', '0.03'],
['x', '5', '0' ],
]
df = pd.DataFrame(table)
</code></pre>
<p>How do I convert the columns to specific types? In this case, I want to convert columns 2 and 3 into floats.</p>
<p>Is there a way to specify the types while converting to DataFrame? Or is it better to create the DataFrame first and then loop through the columns to change the type for each column? Ideally I would like to do this in a dynamic way because there can be hundreds of columns, and I don't want to specify exactly which columns are of which type. All I can guarantee is that each column contains values of the same type.</p>
|
<p>You have four main options for converting types in pandas:</p>
<ol>
<li><p><a href="https://pandas.pydata.org/docs/reference/api/pandas.to_numeric.html" rel="noreferrer"><code>to_numeric()</code></a> - provides functionality to safely convert non-numeric types (e.g. strings) to a suitable numeric type. (See also <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html" rel="noreferrer"><code>to_datetime()</code></a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_timedelta.html" rel="noreferrer"><code>to_timedelta()</code></a>.)</p>
</li>
<li><p><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.astype.html" rel="noreferrer"><code>astype()</code></a> - convert (almost) any type to (almost) any other type (even if it's not necessarily sensible to do so). Also allows you to convert to <a href="https://pandas.pydata.org/docs/user_guide/categorical.html" rel="noreferrer">categorial</a> types (very useful).</p>
</li>
<li><p><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.infer_objects.html" rel="noreferrer"><code>infer_objects()</code></a> - a utility method to convert object columns holding Python objects to a pandas type if possible.</p>
</li>
<li><p><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.convert_dtypes.html" rel="noreferrer"><code>convert_dtypes()</code></a> - convert DataFrame columns to the "best possible" dtype that supports <code>pd.NA</code> (pandas' object to indicate a missing value).</p>
</li>
</ol>
<p>Read on for more detailed explanations and usage of each of these methods.</p>
<hr />
<h1>1. <code>to_numeric()</code></h1>
<p>The best way to convert one or more columns of a DataFrame to numeric values is to use <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_numeric.html" rel="noreferrer"><code>pandas.to_numeric()</code></a>.</p>
<p>This function will try to change non-numeric objects (such as strings) into integers or floating-point numbers as appropriate.</p>
<h2>Basic usage</h2>
<p>The input to <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_numeric.html" rel="noreferrer"><code>to_numeric()</code></a> is a Series or a single column of a DataFrame.</p>
<pre><code>>>> s = pd.Series(["8", 6, "7.5", 3, "0.9"]) # mixed string and numeric values
>>> s
0 8
1 6
2 7.5
3 3
4 0.9
dtype: object
>>> pd.to_numeric(s) # convert everything to float values
0 8.0
1 6.0
2 7.5
3 3.0
4 0.9
dtype: float64
</code></pre>
<p>As you can see, a new Series is returned. Remember to assign this output to a variable or column name to continue using it:</p>
<pre><code># convert Series
my_series = pd.to_numeric(my_series)
# convert column "a" of a DataFrame
df["a"] = pd.to_numeric(df["a"])
</code></pre>
<p>You can also use it to convert multiple columns of a DataFrame via the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="noreferrer"><code>apply()</code></a> method:</p>
<pre><code># convert all columns of DataFrame
df = df.apply(pd.to_numeric) # convert all columns of DataFrame
# convert just columns "a" and "b"
df[["a", "b"]] = df[["a", "b"]].apply(pd.to_numeric)
</code></pre>
<p>As long as your values can all be converted, that's probably all you need.</p>
<h2>Error handling</h2>
<p>But what if some values can't be converted to a numeric type?</p>
<p><a href="https://pandas.pydata.org/docs/reference/api/pandas.to_numeric.html" rel="noreferrer"><code>to_numeric()</code></a> also takes an <code>errors</code> keyword argument that allows you to force non-numeric values to be <code>NaN</code>, or simply ignore columns containing these values.</p>
<p>Here's an example using a Series of strings <code>s</code> which has the object dtype:</p>
<pre><code>>>> s = pd.Series(['1', '2', '4.7', 'pandas', '10'])
>>> s
0 1
1 2
2 4.7
3 pandas
4 10
dtype: object
</code></pre>
<p>The default behaviour is to raise if it can't convert a value. In this case, it can't cope with the string 'pandas':</p>
<pre><code>>>> pd.to_numeric(s) # or pd.to_numeric(s, errors='raise')
ValueError: Unable to parse string
</code></pre>
<p>Rather than fail, we might want 'pandas' to be considered a missing/bad numeric value. We can coerce invalid values to <code>NaN</code> as follows using the <code>errors</code> keyword argument:</p>
<pre><code>>>> pd.to_numeric(s, errors='coerce')
0 1.0
1 2.0
2 4.7
3 NaN
4 10.0
dtype: float64
</code></pre>
<p>The third option for <code>errors</code> is just to ignore the operation if an invalid value is encountered:</p>
<pre><code>>>> pd.to_numeric(s, errors='ignore')
# the original Series is returned untouched
</code></pre>
<p>This last option is particularly useful for converting your entire DataFrame, but don't know which of our columns can be converted reliably to a numeric type. In that case, just write:</p>
<pre><code>df.apply(pd.to_numeric, errors='ignore')
</code></pre>
<p>The function will be applied to each column of the DataFrame. Columns that can be converted to a numeric type will be converted, while columns that cannot (e.g. they contain non-digit strings or dates) will be left alone.</p>
<h2>Downcasting</h2>
<p>By default, conversion with <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_numeric.html" rel="noreferrer"><code>to_numeric()</code></a> will give you either an <code>int64</code> or <code>float64</code> dtype (or whatever integer width is native to your platform).</p>
<p>That's usually what you want, but what if you wanted to save some memory and use a more compact dtype, like <code>float32</code>, or <code>int8</code>?</p>
<p><a href="https://pandas.pydata.org/docs/reference/api/pandas.to_numeric.html" rel="noreferrer"><code>to_numeric()</code></a> gives you the option to downcast to either <code>'integer'</code>, <code>'signed'</code>, <code>'unsigned'</code>, <code>'float'</code>. Here's an example for a simple series <code>s</code> of integer type:</p>
<pre><code>>>> s = pd.Series([1, 2, -7])
>>> s
0 1
1 2
2 -7
dtype: int64
</code></pre>
<p>Downcasting to <code>'integer'</code> uses the smallest possible integer that can hold the values:</p>
<pre><code>>>> pd.to_numeric(s, downcast='integer')
0 1
1 2
2 -7
dtype: int8
</code></pre>
<p>Downcasting to <code>'float'</code> similarly picks a smaller than normal floating type:</p>
<pre><code>>>> pd.to_numeric(s, downcast='float')
0 1.0
1 2.0
2 -7.0
dtype: float32
</code></pre>
<hr />
<h1>2. <code>astype()</code></h1>
<p>The <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.astype.html" rel="noreferrer"><code>astype()</code></a> method enables you to be explicit about the dtype you want your DataFrame or Series to have. It's very versatile in that you can try and go from one type to any other.</p>
<h2>Basic usage</h2>
<p>Just pick a type: you can use a NumPy dtype (e.g. <code>np.int16</code>), some Python types (e.g. bool), or pandas-specific types (like the categorical dtype).</p>
<p>Call the method on the object you want to convert and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.astype.html" rel="noreferrer"><code>astype()</code></a> will try and convert it for you:</p>
<pre><code># convert all DataFrame columns to the int64 dtype
df = df.astype(int)
# convert column "a" to int64 dtype and "b" to complex type
df = df.astype({"a": int, "b": complex})
# convert Series to float16 type
s = s.astype(np.float16)
# convert Series to Python strings
s = s.astype(str)
# convert Series to categorical type - see docs for more details
s = s.astype('category')
</code></pre>
<p>Notice I said "try" - if <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.astype.html" rel="noreferrer"><code>astype()</code></a> does not know how to convert a value in the Series or DataFrame, it will raise an error. For example, if you have a <code>NaN</code> or <code>inf</code> value you'll get an error trying to convert it to an integer.</p>
<p>As of pandas 0.20.0, this error can be suppressed by passing <code>errors='ignore'</code>. Your original object will be returned untouched.</p>
<h2>Be careful</h2>
<p><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.astype.html" rel="noreferrer"><code>astype()</code></a> is powerful, but it will sometimes convert values "incorrectly". For example:</p>
<pre><code>>>> s = pd.Series([1, 2, -7])
>>> s
0 1
1 2
2 -7
dtype: int64
</code></pre>
<p>These are small integers, so how about converting to an unsigned 8-bit type to save memory?</p>
<pre><code>>>> s.astype(np.uint8)
0 1
1 2
2 249
dtype: uint8
</code></pre>
<p>The conversion worked, but the -7 was wrapped round to become 249 (i.e. 2<sup>8</sup> - 7)!</p>
<p>Trying to downcast using <code>pd.to_numeric(s, downcast='unsigned')</code> instead could help prevent this error.</p>
<hr />
<h1>3. <code>infer_objects()</code></h1>
<p>Version 0.21.0 of pandas introduced the method <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.infer_objects.html" rel="noreferrer"><code>infer_objects()</code></a> for converting columns of a DataFrame that have an object datatype to a more specific type (soft conversions).</p>
<p>For example, here's a DataFrame with two columns of object type. One holds actual integers and the other holds strings representing integers:</p>
<pre><code>>>> df = pd.DataFrame({'a': [7, 1, 5], 'b': ['3','2','1']}, dtype='object')
>>> df.dtypes
a object
b object
dtype: object
</code></pre>
<p>Using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.infer_objects.html" rel="noreferrer"><code>infer_objects()</code></a>, you can change the type of column 'a' to int64:</p>
<pre><code>>>> df = df.infer_objects()
>>> df.dtypes
a int64
b object
dtype: object
</code></pre>
<p>Column 'b' has been left alone since its values were strings, not integers. If you wanted to force both columns to an integer type, you could use <code>df.astype(int)</code> instead.</p>
<hr />
<h1>4. <code>convert_dtypes()</code></h1>
<p>Version 1.0 and above includes a method <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.convert_dtypes.html" rel="noreferrer"><code>convert_dtypes()</code></a> to convert Series and DataFrame columns to the best possible dtype that supports the <code>pd.NA</code> missing value.</p>
<p>Here "best possible" means the type most suited to hold the values. For example, this a pandas integer type, if all of the values are integers (or missing values): an object column of Python integer objects are converted to <code>Int64</code>, a column of NumPy <code>int32</code> values, will become the pandas dtype <code>Int32</code>.</p>
<p>With our <code>object</code> DataFrame <code>df</code>, we get the following result:</p>
<pre><code>>>> df.convert_dtypes().dtypes
a Int64
b string
dtype: object
</code></pre>
<p>Since column 'a' held integer values, it was converted to the <code>Int64</code> type (which is capable of holding missing values, unlike <code>int64</code>).</p>
<p>Column 'b' contained string objects, so was changed to pandas' <code>string</code> dtype.</p>
<p>By default, this method will infer the type from object values in each column. We can change this by passing <code>infer_objects=False</code>:</p>
<pre><code>>>> df.convert_dtypes(infer_objects=False).dtypes
a object
b string
dtype: object
</code></pre>
<p>Now column 'a' remained an object column: pandas knows it can be described as an 'integer' column (internally it ran <a href="https://github.com/pandas-dev/pandas/blob/6b2d0260c818e62052eaf535767f3a8c4b446c69/pandas/_libs/lib.pyx#L1188-L1434" rel="noreferrer"><code>infer_dtype</code></a>) but didn't infer exactly what dtype of integer it should have so did not convert it. Column 'b' was again converted to 'string' dtype as it was recognised as holding 'string' values.</p>
|
{
"question_id": 15891038,
"question_date": "2013-04-08T23:53:30.657Z",
"question_score": 1340,
"tags": "python|pandas|dataframe|types|casting",
"answer_id": 28648923,
"answer_date": "2015-02-21T17:37:02.897Z",
"answer_score": 2214
}
|
Please answer the following Stack Overflow question:
Title: How to compare a local Git branch with its remote branch
<p>How can I see the <code>diff</code> between a local branch and a remote branch?</p>
|
<p>To update remote-tracking branches, you need to type <code>git fetch</code> first and then:</p>
<pre><code>git diff <mainbranch_path> <remotebranch_path>
</code></pre>
<p>You can <code>git branch -a</code> to list all branches (local and remote) and then choose the branch name from the list (just remove <code>remotes/</code> from the remote branch name.</p>
<p>Example: <code>git diff main origin/main</code> (where "main" is the local main branch and "origin/main" is a remote, namely the origin and main branch.)</p>
|
{
"question_id": 1800783,
"question_date": "2009-11-25T23:58:17.360Z",
"question_score": 1340,
"tags": "git|diff",
"answer_id": 1800787,
"answer_date": "2009-11-25T23:59:18.903Z",
"answer_score": 787
}
|
Please answer the following Stack Overflow question:
Title: What is the difference between visibility:hidden and display:none?
<p>The CSS rules <code>visibility:hidden</code> and <code>display:none</code> both result in the element not being visible. Are these synonyms?</p>
|
<p><code>display:none</code> means that the tag in question will not appear on the page at all (although you can still interact with it through the dom). There will be no space allocated for it between the other tags. </p>
<p><code>visibility:hidden</code> means that unlike <code>display:none</code>, the tag is not visible, but space is allocated for it on the page. The tag is rendered, it just isn't seen on the page.</p>
<p>For example:</p>
<pre><code>test | <span style="[style-tag-value]">Appropriate style in this tag</span> | test
</code></pre>
<p>Replacing <code>[style-tag-value]</code> with <code>display:none</code> results in:</p>
<pre><code>test | | test
</code></pre>
<p>Replacing <code>[style-tag-value]</code> with <code>visibility:hidden</code> results in:</p>
<pre><code>test | | test
</code></pre>
|
{
"question_id": 133051,
"question_date": "2008-09-25T12:37:47.617Z",
"question_score": 1340,
"tags": "css|visibility",
"answer_id": 133064,
"answer_date": "2008-09-25T12:40:05.647Z",
"answer_score": 1647
}
|
Please answer the following Stack Overflow question:
Title: How can I create a two dimensional array in JavaScript?
<p>I have been reading online and some places say it isn't possible, some say it is and then give an example and others refute the example, etc. </p>
<ol>
<li><p>How do I declare a 2 dimensional array in JavaScript? (assuming it's possible) </p></li>
<li><p>How would I access its members? (<code>myArray[0][1]</code> or <code>myArray[0,1]</code>?)</p></li>
</ol>
|
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let items = [
[1, 2],
[3, 4],
[5, 6]
];
console.log(items[0][0]); // 1
console.log(items[0][1]); // 2
console.log(items[1][0]); // 3
console.log(items[1][1]); // 4
console.log(items);</code></pre>
</div>
</div>
</p>
|
{
"question_id": 966225,
"question_date": "2009-06-08T18:24:54.130Z",
"question_score": 1339,
"tags": "javascript|arrays|multidimensional-array",
"answer_id": 966234,
"answer_date": "2009-06-08T18:27:28.803Z",
"answer_score": 1385
}
|
Please answer the following Stack Overflow question:
Title: What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?
<p>What is the difference between the <code>remap</code>, <code>noremap</code>, <code>nnoremap</code> and <code>vnoremap</code> mapping commands in Vim?</p>
|
<p><code>remap</code> is an <strong>option</strong> that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are <strong>mapping commands</strong>, described below:</p>
<p><code>:map</code> and <code>:noremap</code> are <strong>recursive</strong> and <strong>non-recursive</strong> versions of the various mapping commands. For example, if we run:</p>
<pre><code>:map j gg (moves cursor to first line)
:map Q j (moves cursor to first line)
:noremap W j (moves cursor down one line)
</code></pre>
<p>Then:</p>
<ul>
<li><code>j</code> will be mapped to <code>gg</code>.</li>
<li><code>Q</code> will <em>also</em> be mapped to <code>gg</code>, because <code>j</code> will be expanded for the recursive mapping.</li>
<li><code>W</code> will be mapped to <code>j</code> (and not to <code>gg</code>) because <code>j</code> will not be expanded for the non-recursive mapping.</li>
</ul>
<p>Now remember that Vim is a <strong>modal editor</strong>. It has a <strong>normal</strong> mode, <strong>visual</strong> mode and other modes.</p>
<p>For each of these sets of mappings, there is a <a href="http://vim.wikia.com/wiki/Mapping_keys_in_Vim_-_Tutorial_%28Part_1%29#Creating_keymaps" rel="noreferrer">mapping</a> that works in normal, visual, select and operator modes (<code>:map</code> and <code>:noremap</code>), one that works in normal mode (<code>:nmap</code> and <code>:nnoremap</code>), one in visual mode (<code>:vmap</code> and <code>:vnoremap</code>) and so on.</p>
<p>For more guidance on this, see:</p>
<pre><code>:help :map
:help :noremap
:help recursive_mapping
:help :map-modes
</code></pre>
|
{
"question_id": 3776117,
"question_date": "2010-09-23T07:13:30.917Z",
"question_score": 1338,
"tags": "vim|mapping|command",
"answer_id": 3776182,
"answer_date": "2010-09-23T07:24:15.540Z",
"answer_score": 1932
}
|
Please answer the following Stack Overflow question:
Title: Git merge hotfix branch into feature branch
<p>Let’s say we have the following situation in Git:</p>
<ol>
<li><p>A created repository:</p>
<pre><code>mkdir GitTest2
cd GitTest2
git init
</code></pre></li>
<li><p>Some modifications in the master take place and get committed:</p>
<pre><code>echo "On Master" > file
git commit -a -m "Initial commit"
</code></pre></li>
<li><p>Feature1 branched off master and some work is done:</p>
<pre><code>git branch feature1
git checkout feature1
echo "Feature1" > featureFile
git commit -a -m "Commit for feature1"
</code></pre></li>
<li><p>Meanwhile, a bug is discovered in the master-code and a hotfix-branch is established:</p>
<pre><code>git checkout master
git branch hotfix1
git checkout hotfix1
</code></pre></li>
<li><p>The bug is fixed in the hotfix branch and merged back into the master (perhaps after a pull request/code review):</p>
<pre><code>echo "Bugfix" > bugfixFile
git commit -a -m "Bugfix Commit"
git checkout master
git merge --no-ff hotfix1
</code></pre></li>
<li><p>Development on feature1 continues:</p>
<pre><code>git checkout feature1
</code></pre></li>
</ol>
<p>Say I need the hotfix in my feature branch, maybe because the bug also occurs there. How can I achieve this without duplicating the commits into my feature branch?</p>
<p>I want to prevent to get two new commits on my feature branch which have no relation to the feature implementation. This especially seems important for me if I use pull requests: All these commits will also be included in the pull request and have to be reviewed although this has already been done (as the hotfix is already in the master).</p>
<p>I can not do a <code>git merge master --ff-only</code>: "fatal: Not possible to fast-forward, aborting.", but I am not sure if this helped me.</p>
|
<p>How do we merge the master branch into the feature branch? Easy:</p>
<pre><code>git checkout feature1
git merge master
</code></pre>
<p>There is no point in forcing a fast forward merge here, as it cannot be done. You committed both into the feature branch and the master branch. Fast forward is impossible now.</p>
<p>Have a look at <a href="https://github.com/nvie/gitflow" rel="noreferrer">GitFlow</a>. It is a branching model for git that can be followed, and you unconsciously already did. It also is an extension to Git which adds some commands for the new workflow steps that do things automatically which you would otherwise need to do manually.</p>
<p>So what did you do right in your workflow? You have two branches to work with, your feature1 branch is basically the "develop" branch in the GitFlow model.</p>
<p>You created a hotfix branch from master and merged it back. And now you are stuck.</p>
<p>The GitFlow model asks you to merge the hotfix also to the development branch, which is "feature1" in your case.</p>
<p>So the real answer would be:</p>
<pre><code>git checkout feature1
git merge --no-ff hotfix1
</code></pre>
<p>This adds all the changes that were made inside the hotfix to the feature branch, but <em>only</em> those changes. They might conflict with other development changes in the branch, but they will not conflict with the master branch should you merge the feature branch back to master eventually.</p>
<p>Be very careful with rebasing. Only rebase if the changes you did stayed local to your repository, e.g. you did not push any branches to some other repository. Rebasing is a great tool for you to arrange your local commits into a useful order before pushing it out into the world, but rebasing afterwards will mess up things for the git beginners like you.</p>
|
{
"question_id": 16955980,
"question_date": "2013-06-06T07:18:57.723Z",
"question_score": 1337,
"tags": "git|git-branch|git-merge|git-flow|feature-branch",
"answer_id": 16957483,
"answer_date": "2013-06-06T08:42:35.777Z",
"answer_score": 1615
}
|
Please answer the following Stack Overflow question:
Title: How and when to use ‘async’ and ‘await’
<p>From my understanding one of the main things that <a href="https://docs.microsoft.com/en-us/dotnet/csharp/async" rel="noreferrer"><code>async</code> and <code>await</code></a> do is to make code easy to write and read - but is using them equal to spawning background threads to perform long duration logic?</p>
<p>I'm currently trying out the most basic example. I've added some comments inline. Can you clarify it for me?</p>
<pre><code>// I don't understand why this method must be marked as `async`.
private async void button1_Click(object sender, EventArgs e)
{
Task<int> access = DoSomethingAsync();
// task independent stuff here
// this line is reached after the 5 seconds sleep from
// DoSomethingAsync() method. Shouldn't it be reached immediately?
int a = 1;
// from my understanding the waiting should be done here.
int x = await access;
}
async Task<int> DoSomethingAsync()
{
// is this executed on a background thread?
System.Threading.Thread.Sleep(5000);
return 1;
}
</code></pre>
|
<p>When using <code>async</code> and <code>await</code> the compiler generates a state machine in the background.</p>
<p>Here's an example on which I hope I can explain some of the high-level details that are going on:</p>
<pre><code>public async Task MyMethodAsync()
{
Task<int> longRunningTask = LongRunningOperationAsync();
// independent work which doesn't need the result of LongRunningOperationAsync can be done here
//and now we call await on the task
int result = await longRunningTask;
//use the result
Console.WriteLine(result);
}
public async Task<int> LongRunningOperationAsync() // assume we return an int from this long running operation
{
await Task.Delay(1000); // 1 second delay
return 1;
}
</code></pre>
<p>OK, so what happens here:</p>
<ol>
<li><p><code>Task<int> longRunningTask = LongRunningOperationAsync();</code> starts executing <code>LongRunningOperation</code></p>
</li>
<li><p>Independent work is done on let's assume the Main Thread (Thread ID = 1) then <code>await longRunningTask</code> is reached.</p>
<p>Now, if the <code>longRunningTask</code> hasn't finished and it is still running, <code>MyMethodAsync()</code> will return to its calling method, thus the main thread doesn't get blocked. When the <code>longRunningTask</code> is done then a thread from the ThreadPool (can be any thread) will return to <code>MyMethodAsync()</code> in its previous context and continue execution (in this case printing the result to the console).</p>
</li>
</ol>
<p>A second case would be that the <code>longRunningTask</code> has already finished its execution and the result is available. When reaching the <code>await longRunningTask</code> we already have the result so the code will continue executing on the very same thread. (in this case printing result to console). Of course this is not the case for the above example, where there's a <code>Task.Delay(1000)</code> involved.</p>
|
{
"question_id": 14455293,
"question_date": "2013-01-22T09:29:58.633Z",
"question_score": 1337,
"tags": "c#|.net|asynchronous|async-await",
"answer_id": 19985988,
"answer_date": "2013-11-14T18:55:19.103Z",
"answer_score": 924
}
|
Please answer the following Stack Overflow question:
Title: Best way to convert string to bytes in Python 3?
<p><a href="https://stackoverflow.com/questions/5471158/typeerror-str-does-not-support-the-buffer-interface">TypeError: 'str' does not support the buffer interface</a> suggests two possible methods to convert a string to bytes:</p>
<pre><code>b = bytes(mystring, 'utf-8')
b = mystring.encode('utf-8')
</code></pre>
<p>Which method is more Pythonic?</p>
|
<p>If you look at the docs for <code>bytes</code>, it points you to <a href="https://docs.python.org/3/library/functions.html#func-bytearray" rel="noreferrer"><code>bytearray</code></a>:</p>
<blockquote>
<p>bytearray([source[, encoding[, errors]]])</p>
<p>Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods.</p>
<p>The optional source parameter can be used to initialize the array in a few different ways:</p>
<p><strong>If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().</strong></p>
<p><strong>If it is an integer, the array will have that size and will be initialized with null bytes.</strong></p>
<p><strong>If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.</strong></p>
<p><strong>If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.</strong></p>
<p><strong>Without an argument, an array of size 0 is created.</strong></p>
</blockquote>
<p>So <code>bytes</code> can do much more than just encode a string. It's Pythonic that it would allow you to call the constructor with any type of source parameter that makes sense.</p>
<p>For encoding a string, I think that <code>some_string.encode(encoding)</code> is more Pythonic than using the constructor, because it is the most self documenting -- "take this string and encode it with this encoding" is clearer than <code>bytes(some_string, encoding)</code> -- there is no explicit verb when you use the constructor.</p>
<p>I checked the Python source. If you pass a unicode string to <code>bytes</code> using CPython, it calls <a href="http://hg.python.org/cpython/file/5a12416890c0/Objects/unicodeobject.c#l2328" rel="noreferrer">PyUnicode_AsEncodedString</a>, which is the implementation of <code>encode</code>; so you're just skipping a level of indirection if you call <code>encode</code> yourself.</p>
<p>Also, see Serdalis' comment -- <code>unicode_string.encode(encoding)</code> is also more Pythonic because its inverse is <code>byte_string.decode(encoding)</code> and symmetry is nice.</p>
|
{
"question_id": 7585435,
"question_date": "2011-09-28T15:14:07.873Z",
"question_score": 1336,
"tags": "python|string|character-encoding|python-3.x",
"answer_id": 7585619,
"answer_date": "2011-09-28T15:27:58.583Z",
"answer_score": 806
}
|
Please answer the following Stack Overflow question:
Title: "Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
<p>I'm running a PHP script and continue to receive errors like:</p>
<blockquote>
<p>Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on line 10</p>
<p>Notice: Undefined index: my_index C:\wamp\www\mypath\index.php on line 11</p>
<p>Warning: Undefined array key "my_index" in C:\wamp\www\mypath\index.php on line 11</p>
</blockquote>
<p>Line 10 and 11 looks like this:</p>
<pre><code>echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];
</code></pre>
<p>What is the meaning of these error messages?</p>
<p>Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.</p>
<p>How do I fix them?</p>
<hr/>
<blockquote>
<p><sub><strong>This is a General Reference question</strong> for people to link to as duplicate, instead of having to explain the issue over and over again. I feel this is necessary because most real-world answers on this issue are very specific. </sub></p>
<p><sub>Related Meta discussion:</sub></p>
<ul>
<li><sub><a href="https://meta.stackexchange.com/questions/62258/what-can-be-done-about-repetitive-questions">What can be done about repetitive questions?</a></sub></li>
<li><sub><a href="https://meta.stackexchange.com/questions/63762/do-reference-questions-make-sense">Do “reference questions” make sense?</a></sub></li>
</ul>
</blockquote>
|
<h1>Notice / Warning: Undefined variable</h1>
<p>From the vast wisdom of the <a href="http://php.net/manual/en/language.variables.basics.php#example-112" rel="noreferrer">PHP Manual</a>:</p>
<blockquote>
<p>Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major <a href="http://www.php.net/manual/en/security.globals.php" rel="noreferrer">security risk</a> with <a href="http://www.php.net/manual/en/ini.core.php#ini.register-globals" rel="noreferrer">register_globals</a> turned on. <a href="http://www.php.net/manual/en/errorfunc.constants.php#errorfunc.constants.errorlevels.e-notice" rel="noreferrer">E_NOTICE</a> level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. <a href="http://www.php.net/manual/en/function.isset.php" rel="noreferrer">isset()</a> language construct can be used to detect if a variable has been already initialized. Additionally and more ideal is the solution of <a href="http://php.net/manual/en/function.empty.php" rel="noreferrer">empty()</a> since it does not generate a warning or error message if the variable is not initialized.</p>
</blockquote>
<p>From <a href="http://php.net/manual/en/function.empty.php" rel="noreferrer">PHP documentation</a>:</p>
<blockquote>
<p>No warning is generated if the variable does not exist. That means
<strong>empty()</strong> is essentially the concise equivalent to <strong>!isset($var) || $var
== false</strong>.</p>
</blockquote>
<p>This means that you could use only <code>empty()</code> to determine if the variable is set, and in addition it checks the variable against the following, <code>0</code>, <code>0.0</code>, <code>""</code>, <code>"0"</code>, <code>null</code>, <code>false</code> or <code>[]</code>.</p>
<p>Example:</p>
<pre><code>$o = [];
@$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
array_walk($var, function($v) {
echo (!isset($v) || $v == false) ? 'true ' : 'false';
echo ' ' . (empty($v) ? 'true' : 'false');
echo "\n";
});
</code></pre>
<p>Test the above snippet in the <a href="https://3v4l.org/5Wvgj" rel="noreferrer">3v4l.org online PHP editor</a></p>
<p>Although PHP does not require a variable declaration, it does recommend it in order to avoid some security vulnerabilities or bugs where one would forget to give a value to a variable that will be used later in the script. What PHP does in the case of undeclared variables is issue a very low level error, <code>E_NOTICE</code>, one that is not even reported by default, but the Manual <a href="http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting" rel="noreferrer">advises to allow</a> during development.</p>
<p>Ways to deal with the issue:</p>
<ol>
<li><p><strong>Recommended:</strong> Declare your variables, for example when you try to append a string to an undefined variable. Or use <a href="http://www.php.net/manual/en/function.isset.php" rel="noreferrer"><code>isset()</code></a> / <a href="http://php.net/manual/en/function.empty.php" rel="noreferrer"><code>!empty()</code></a> to check if they are declared before referencing them, as in:</p>
<pre><code>//Initializing variable
$value = ""; //Initialization value; Examples
//"" When you want to append stuff later
//0 When you want to add numbers later
//isset()
$value = isset($_POST['value']) ? $_POST['value'] : '';
//empty()
$value = !empty($_POST['value']) ? $_POST['value'] : '';
</code></pre>
</li>
</ol>
<p>This has become much cleaner as of PHP 7.0, now you can use the <a href="https://wiki.php.net/rfc/isset_ternary" rel="noreferrer">null coalesce operator</a>:</p>
<pre><code> // Null coalesce operator - No need to explicitly initialize the variable.
$value = $_POST['value'] ?? '';
</code></pre>
<ol start="2">
<li><p>Set a <a href="http://www.php.net/manual/en/function.set-error-handler.php" rel="noreferrer">custom error handler</a> for E_NOTICE and redirect the messages away from the standard output (maybe to a log file):</p>
<pre><code>set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)
</code></pre>
</li>
<li><p>Disable E_NOTICE from reporting. A quick way to exclude just <code>E_NOTICE</code> is:</p>
<pre><code>error_reporting( error_reporting() & ~E_NOTICE )
</code></pre>
</li>
<li><p>Suppress the error with the <a href="http://php.net/manual/en/language.operators.errorcontrol.php" rel="noreferrer">@ operator</a>.</p>
</li>
</ol>
<p><strong>Note:</strong> It's strongly recommended to implement just point 1.</p>
<h1>Notice: Undefined index / Undefined offset / Warning: Undefined array key</h1>
<p>This notice/warning appears when you (or PHP) try to access an undefined index of an array.</p>
<p>Ways to deal with the issue:</p>
<ol>
<li><p>Check if the index exists before you access it. For this you can use <a href="http://php.net/manual/en/function.isset.php" rel="noreferrer"><code>isset()</code></a> or <a href="http://php.net/manual/en/function.array-key-exists.php" rel="noreferrer"><code>array_key_exists()</code></a>:</p>
<pre><code>//isset()
$value = isset($array['my_index']) ? $array['my_index'] : '';
//array_key_exists()
$value = array_key_exists('my_index', $array) ? $array['my_index'] : '';
</code></pre>
</li>
<li><p>The language construct <a href="http://php.net/manual/en/function.list.php" rel="noreferrer"><code>list()</code></a> may generate this when it attempts to access an array index that does not exist:</p>
<pre><code>list($a, $b) = array(0 => 'a');
//or
list($one, $two) = explode(',', 'test string');
</code></pre>
</li>
</ol>
<p>Two variables are used to access two array elements, however there is only one array element, index <code>0</code>, so this will generate:</p>
<blockquote>
<p>Notice: Undefined offset: 1</p>
</blockquote>
<p>#<code>$_POST</code> / <code>$_GET</code> / <code>$_SESSION</code> variable</p>
<p>The notices above appear often when working with <code>$_POST</code>, <code>$_GET</code> or <code>$_SESSION</code>. For <code>$_POST</code> and <code>$_GET</code> you just have to check if the index exists or not before you use them. For <code>$_SESSION</code> you have to make sure you have the session started with <a href="http://php.net/manual/en/function.session-start.php" rel="noreferrer"><code>session_start()</code></a> and that the index also exists.</p>
<p>Also note that all 3 variables are <a href="http://php.net/manual/en/language.variables.superglobals.php" rel="noreferrer">superglobals</a> and are uppercase.</p>
<p>Related:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/12778634#12778634">Notice: Undefined variable</a></li>
<li><a href="https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/12770836#12770836">Notice: Undefined Index</a></li>
</ul>
|
{
"question_id": 4261133,
"question_date": "2010-11-23T21:26:54.170Z",
"question_score": 1336,
"tags": "php|arrays|variables|warnings|undefined-index",
"answer_id": 4261200,
"answer_date": "2010-11-23T21:36:14.763Z",
"answer_score": 1190
}
|
Please answer the following Stack Overflow question:
Title: How to check if element is visible after scrolling?
<p>I'm loading elements via AJAX. Some of them are only visible if you scroll down the page. Is there any way I can know if an element is now in the visible part of the page?</p>
|
<p>This should do the trick:</p>
<pre><code>function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
</code></pre>
<p><strong>Simple Utility Function</strong>
This will allow you to call a utility function that accepts the element you're looking for and if you want the element to be fully in view or partially.</p>
<pre><code>function Utils() {
}
Utils.prototype = {
constructor: Utils,
isElementInView: function (element, fullyInView) {
var pageTop = $(window).scrollTop();
var pageBottom = pageTop + $(window).height();
var elementTop = $(element).offset().top;
var elementBottom = elementTop + $(element).height();
if (fullyInView === true) {
return ((pageTop < elementTop) && (pageBottom > elementBottom));
} else {
return ((elementTop <= pageBottom) && (elementBottom >= pageTop));
}
}
};
var Utils = new Utils();
</code></pre>
<p><strong>Usage</strong></p>
<pre><code>var isElementInView = Utils.isElementInView($('#flyout-left-container'), false);
if (isElementInView) {
console.log('in view');
} else {
console.log('out of view');
}
</code></pre>
|
{
"question_id": 487073,
"question_date": "2009-01-28T10:00:55.303Z",
"question_score": 1336,
"tags": "javascript|jquery|scroll",
"answer_id": 488073,
"answer_date": "2009-01-28T15:36:57.170Z",
"answer_score": 1327
}
|
Please answer the following Stack Overflow question:
Title: How can I pass arguments to a batch file?
<p>I need to pass an ID and a password to a batch file at the time of running rather than hardcoding them into the file.</p>
<p>Here's what the command line looks like:</p>
<pre><code>test.cmd admin P@55w0rd > test-log.txt
</code></pre>
|
<p>Here's how I did it:</p>
<pre><code>@fake-command /u %1 /p %2
</code></pre>
<p>Here's what the command looks like:</p>
<pre><code>test.cmd admin P@55w0rd > test-log.txt
</code></pre>
<p>The <code>%1</code> applies to the first parameter the <code>%2</code> (and here's the tricky part) applies to the second. You can have up to 9 parameters passed in this way.</p>
|
{
"question_id": 26551,
"question_date": "2008-08-25T18:14:18.437Z",
"question_score": 1335,
"tags": "batch-file|arguments",
"answer_id": 92057,
"answer_date": "2008-09-18T12:26:52.253Z",
"answer_score": 342
}
|
Please answer the following Stack Overflow question:
Title: Undo git pull, how to bring repos to old state
<p>Is there any way to revert or undo git pull so that my source/repos will come to old state that was before doing git pull ?
I want to do this because it merged some files which I didn't want to do so, but only merge other remaining files. So, I want to get those files back, is that possible?</p>
<p>EDIT: I want to undo git merge for clarification.
After seeing some answers, I did this </p>
<pre><code>git reflog
bb3139b... HEAD@{0}: pull : Fast forward
01b34fa... HEAD@{1}: clone: from ...name...
</code></pre>
<p>Now, what should I do ? Doing <code>git reset --hard</code> is OK ? I don't want to screw it again, so asking for detailed steps ? </p>
|
<p>Running <code>git pull</code> performs the following tasks, in order:</p>
<ol>
<li><code>git fetch</code> </li>
<li><code>git merge</code></li>
</ol>
<p>The merge step combines branches that have been setup to be merged in your config. You want to undo the <strong>merge</strong> step, but probably not the <strong>fetch</strong> (doesn't make a lot of sense and shouldn't be necessary). </p>
<p>To undo the <strong>merge</strong>, use <code>git reset --hard</code> to reset the local repository to a previous state; use <a href="http://www.kernel.org/pub/software/scm/git/docs/git-reflog.html" rel="noreferrer">git-reflog</a> to find the SHA-1 of the previous state and then reset to it.</p>
<p><strong>Warning</strong></p>
<p>The commands listed in this section remove all uncommitted changes, potentially leading to a loss of work:</p>
<pre><code>git reset --hard
</code></pre>
<p>Alternatively, reset to a particular point in time, such as:</p>
<pre><code>git reset --hard master@{"10 minutes ago"}
</code></pre>
|
{
"question_id": 1223354,
"question_date": "2009-08-03T16:42:51.997Z",
"question_score": 1335,
"tags": "git|version-control|git-merge",
"answer_id": 1223385,
"answer_date": "2009-08-03T16:47:27.030Z",
"answer_score": 1914
}
|
Please answer the following Stack Overflow question:
Title: How do I trim whitespace from a string?
<p>How do I remove leading and trailing whitespace from a string in Python?</p>
<pre><code>" Hello world " --> "Hello world"
" Hello world" --> "Hello world"
"Hello world " --> "Hello world"
"Hello world" --> "Hello world"
</code></pre>
|
<p>To remove all whitespace surrounding a string, use <a href="https://docs.python.org/library/stdtypes.html#str.strip" rel="noreferrer"><code>.strip()</code></a>. Examples:</p>
<pre><code>>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> ' Hello '.strip() # ALL consecutive spaces at both ends removed
'Hello'
</code></pre>
<p>Note that <a href="https://docs.python.org/library/stdtypes.html#str.strip" rel="noreferrer"><code>str.strip()</code></a> removes all whitespace characters, including tabs and newlines. To remove only spaces, specify the specific character to remove as an argument to <code>strip</code>:</p>
<pre><code>>>> " Hello\n ".strip(" ")
'Hello\n'
</code></pre>
<hr />
<p>To remove only one space at most:</p>
<pre><code>def strip_one_space(s):
if s.endswith(" "): s = s[:-1]
if s.startswith(" "): s = s[1:]
return s
>>> strip_one_space(" Hello ")
' Hello'
</code></pre>
|
{
"question_id": 761804,
"question_date": "2009-04-17T19:16:06.860Z",
"question_score": 1335,
"tags": "python|string|trim",
"answer_id": 761825,
"answer_date": "2009-04-17T19:21:29.607Z",
"answer_score": 1960
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.