input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: How do I see all foreign keys to a table or column?
<p>In MySQL, how do I get a list of all foreign key constraints pointing to a particular table? a particular column? This is the same thing as <a href="https://stackoverflow.com/questions/85978/query-a-tables-foreign-key-relationships">this Oracle question</a>, but for MySQL.</p> | <p><strong>For a Table:</strong></p>
<pre><code>SELECT
TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_SCHEMA = '<database>' AND
REFERENCED_TABLE_NAME = '<table>';
</code></pre>
<p><strong>For a Column:</strong></p>
<pre><code>SELECT
TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_SCHEMA = '<database>' AND
REFERENCED_TABLE_NAME = '<table>' AND
REFERENCED_COLUMN_NAME = '<column>';
</code></pre>
<p>Basically, we changed REFERENCED_TABLE_NAME with REFERENCED_COLUMN_NAME in the where clause.</p> | {
"question_id": 201621,
"question_date": "2008-10-14T15:18:49.127Z",
"question_score": 707,
"tags": "mysql|foreign-keys|innodb",
"answer_id": 201678,
"answer_date": "2008-10-14T15:35:13.617Z",
"answer_score": 985
} |
Please answer the following Stack Overflow question:
Title: How to atomically delete keys matching a pattern using Redis
<p>In my Redis DB I have a number of <code>prefix:<numeric_id></code> hashes.</p>
<p>Sometimes I want to purge them all atomically. How do I do this without using some distributed locking mechanism?</p> | <p>Starting with redis 2.6.0, you can run lua scripts, which execute atomically. I have never written one, but I think it would look something like this</p>
<pre><code>EVAL "return redis.call('del', unpack(redis.call('keys', ARGV[1])))" 0 prefix:[YOUR_PREFIX e.g delete_me_*]
</code></pre>
<blockquote>
<p><strong>Warning</strong>: As the <a href="https://redis.io/commands/keys" rel="noreferrer">Redis document</a> says, because of performance maters, <code>keys</code>
command should not use for regular operations in production, this
command is intended for debugging and special operations. <a href="https://redis.io/commands/keys" rel="noreferrer">read
more</a></p>
</blockquote>
<p>See the <a href="http://redis.io/commands/eval" rel="noreferrer">EVAL documentation</a>.</p> | {
"question_id": 4006324,
"question_date": "2010-10-23T22:04:27.493Z",
"question_score": 707,
"tags": "redis",
"answer_id": 16974060,
"answer_date": "2013-06-06T23:47:53.097Z",
"answer_score": 478
} |
Please answer the following Stack Overflow question:
Title: How do I prepend to a short python list?
<p><code>list.append()</code> appends to the end of a list. <a href="http://mail.python.org/pipermail/tutor/2005-March/036803.html" rel="noreferrer">This explains</a> that <code>list.prepend()</code> does not exist due to performance concerns for large lists. For a short list, how do I prepend a value?</p> | <p>The <code>s.insert(0, x)</code> form is the most common.</p>
<p>Whenever you see it though, it may be time to consider using a <a href="http://docs.python.org/library/collections.html#collections.deque" rel="noreferrer">collections.deque</a> instead of a list. Prepending to a deque runs in constant time. Prepending to a list runs in linear time.</p> | {
"question_id": 8537916,
"question_date": "2011-12-16T17:30:01.267Z",
"question_score": 707,
"tags": "python|list|prepend",
"answer_id": 8538295,
"answer_date": "2011-12-16T18:08:26.647Z",
"answer_score": 995
} |
Please answer the following Stack Overflow question:
Title: How do I write standard error to a file while using "tee" with a pipe?
<p>I know how to use <code>tee</code> to write the output (<a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29" rel="noreferrer">standard output</a>) of <code>aaa.sh</code> to <code>bbb.out</code>, while still displaying it in the terminal:</p>
<pre class="lang-none prettyprint-override"><code>./aaa.sh | tee bbb.out
</code></pre>
<p>How would I now also write <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)" rel="noreferrer">standard error</a> to a file named <code>ccc.out</code>, while still having it displayed?</p> | <p>I'm assuming you want to still see standard error and standard output on the terminal. You could go for <a href="https://stackoverflow.com/questions/692000/how-do-i-write-standard-error-to-a-file-while-using-tee-with-a-pipe/692009#692009">Josh Kelley's answer</a>, but I find keeping a <code>tail</code> around in the background which outputs your log file very hackish and cludgy. Notice how you need to keep an extra <a href="https://en.wikipedia.org/wiki/File_descriptor" rel="noreferrer">file descriptor</a> and do cleanup afterward by killing it and technically should be doing that in a <code>trap '...' EXIT</code>.</p>
<p>There is a better way to do this, and you've already discovered it: <code>tee</code>.</p>
<p>Only, instead of just using it for your standard output, have a tee for standard output and one for standard error. How will you accomplish this? Process substitution and file redirection:</p>
<pre><code>command > >(tee -a stdout.log) 2> >(tee -a stderr.log >&2)
</code></pre>
<p>Let's split it up and explain:</p>
<pre><code>> >(..)
</code></pre>
<p><code>>(...)</code> (process substitution) creates a FIFO and lets <code>tee</code> listen on it. Then, it uses <code>></code> (file redirection) to redirect the standard output of <code>command</code> to the FIFO that your first <code>tee</code> is listening on.</p>
<p>The same thing for the second:</p>
<pre><code>2> >(tee -a stderr.log >&2)
</code></pre>
<p>We use process substitution again to make a <code>tee</code> process that reads from standard input and dumps it into <code>stderr.log</code>. <code>tee</code> outputs its input back on standard output, but since its input is our standard error, we want to redirect <code>tee</code>'s standard output to our standard error again. Then we use file redirection to redirect <code>command</code>'s standard error to the FIFO's input (<code>tee</code>'s standard input).</p>
<p>See <em><a href="http://mywiki.wooledge.org/BashGuide/InputAndOutput" rel="noreferrer">Input And Output</a></em></p>
<p>Process substitution is one of those really lovely things you get as a bonus of choosing Bash as your shell as opposed to <code>sh</code> (POSIX or Bourne).</p>
<hr />
<p>In <code>sh</code>, you'd have to do things manually:</p>
<pre><code>out="${TMPDIR:-/tmp}/out.$$" err="${TMPDIR:-/tmp}/err.$$"
mkfifo "$out" "$err"
trap 'rm "$out" "$err"' EXIT
tee -a stdout.log < "$out" &
tee -a stderr.log < "$err" >&2 &
command >"$out" 2>"$err"
</code></pre> | {
"question_id": 692000,
"question_date": "2009-03-28T01:53:04.557Z",
"question_score": 707,
"tags": "linux|bash|unix|tee",
"answer_id": 692407,
"answer_date": "2009-03-28T07:54:59.473Z",
"answer_score": 963
} |
Please answer the following Stack Overflow question:
Title: This action could not be completed. Try Again (-22421)
<p>I am trying to upload an <strong>Apple TV</strong> App to the App Store for testing purposes, but I got the issue:</p>
<blockquote>
<p>This Action could not be completed. Try Again (-22421)</p>
</blockquote>
<p>as in the below image:</p>
<p><a href="https://i.stack.imgur.com/eV1e7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eV1e7.png" alt="enter image description here" /></a></p>
<p>So what can I do?</p> | <p>This happens because Apple's servers may not be working correctly. Just wait and try later or next time. It will work for sure eventually.</p> | {
"question_id": 35429801,
"question_date": "2016-02-16T10:21:09.613Z",
"question_score": 707,
"tags": "ios|xcode|app-store-connect",
"answer_id": 35663309,
"answer_date": "2016-02-26T23:02:24.807Z",
"answer_score": 769
} |
Please answer the following Stack Overflow question:
Title: How to make a background 20% transparent on Android
<p>How do I make the background of a <code>Textview</code> about 20% transparent (not fully transparent), where there is a color in the background (i.e. white)?</p> | <p>Make the color have 80% in the alpha channel. For example, for red use <code>#CCFF0000</code>:</p>
<pre><code><TextView
...
android:background="#CCFF0000" />
</code></pre>
<p>In the example, <code>CC</code> is the hexadecimal number for <code>255 * 0.8 = 204</code>. Note that the first two hexadecimal digits are for the alpha channel. The format is <code>#AARRGGBB</code>, where <code>AA</code> is the alpha channel, <code>RR</code> is the red channel, <code>GG</code> is the green channel and <code>BB</code> is the blue channel.</p>
<p>I'm assuming that 20% transparent means 80% opaque. If you meant the other way, instead of <code>CC</code> use <code>33</code> which is the hexadecimal for <code>255 * 0.2 = 51</code>.</p>
<p>In order to calculate the proper value for an alpha transparency value you can follow this procedure:</p>
<ol>
<li>Given a transparency percentage, for example 20%, you know the opaque percentage value is 80% (this is <code>100-20=80</code>)</li>
<li>The range for the alpha channel is 8 bits (<code>2^8=256</code>), meaning the range goes from 0 to 255.</li>
<li>Project the opaque percentage into the alpha range, that is, multiply the range (255) by the percentage. In this example <code>255 * 0.8 = 204</code>. Round to the nearest integer if needed.</li>
<li>Convert the value obtained in 3., which is in base 10, to hexadecimal (base 16). You can use Google for this or any calculator. Using Google, type "204 to hexa" and it will give you the hexadecimal value. In this case it is <code>0xCC</code>.</li>
<li>Prepend the value obtained in 4. to the desired color. For example, for red, which is <code>FF0000</code>, you will have <code>CCFF0000</code>.</li>
</ol>
<p>You can take a look at the <a href="http://developer.android.com/guide/topics/resources/more-resources.html#Color" rel="noreferrer">Android documentation for colors</a>.</p> | {
"question_id": 11285961,
"question_date": "2012-07-01T22:01:29.190Z",
"question_score": 706,
"tags": "android|transparency|textview",
"answer_id": 11286013,
"answer_date": "2012-07-01T22:09:26.437Z",
"answer_score": 1111
} |
Please answer the following Stack Overflow question:
Title: How to append to a file in Node?
<p>I am trying to <em>append</em> a string to a log file. However writeFile will erase the content each time before writing the string.</p>
<pre><code>fs.writeFile('log.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
}); // => message.txt erased, contains only 'Hello Node'
</code></pre>
<p>Any idea how to do this the easy way?</p> | <p>For occasional appends, you can use <code>appendFile</code>, which creates a new file handle each time it's called:</p>
<p><a href="https://nodejs.org/api/fs.html#fs_fs_appendfile_file_data_options_callback" rel="noreferrer">Asynchronously</a>:</p>
<pre><code>const fs = require('fs');
fs.appendFile('message.txt', 'data to append', function (err) {
if (err) throw err;
console.log('Saved!');
});
</code></pre>
<p><a href="https://nodejs.org/api/fs.html#fs_fs_appendfilesync_file_data_options" rel="noreferrer">Synchronously</a>:</p>
<pre><code>const fs = require('fs');
fs.appendFileSync('message.txt', 'data to append');
</code></pre>
<p>But if you append repeatedly to the same file, it's much better to <a href="https://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node/43370201#43370201">reuse the file handle</a>.</p> | {
"question_id": 3459476,
"question_date": "2010-08-11T14:37:31.633Z",
"question_score": 706,
"tags": "javascript|node.js|fs|appendfile",
"answer_id": 11267583,
"answer_date": "2012-06-29T19:06:56.090Z",
"answer_score": 1080
} |
Please answer the following Stack Overflow question:
Title: npm check and update package if needed
<p>We need to integrate Karma test runner into TeamCity and for that I'd like to give sys-engineers small script (powershell or whatever) that would:</p>
<ol>
<li><p>pick up desired version number from some config file (I guess I can put it as a comment right in the <code>karma.conf.js</code>)</p></li>
<li><p>check if the defined version of karma runner installed in npm's global repo</p></li>
<li><p>if it's not, or the installed version is older than desired: pick up and install right version</p></li>
<li><p>run it: <code>karma start .\Scripts-Tests\karma.conf.js --reporters teamcity --single-run</code></p></li>
</ol>
<p>So my real question is: "how can one check in a script, if desired version of package installed?". Should you do the check, or it's safe to just call <code>npm -g install</code> everytime?</p>
<p><em>I don't want to always check and install the latest available version, because other config values may become incompatible</em></p> | <p>To check if any module in a project is 'old':</p>
<pre><code>npm outdated
</code></pre>
<p>'<a href="https://docs.npmjs.com/cli/outdated" rel="noreferrer">outdated</a>' will check every module defined in <code>package.json</code> and see if there is a newer version in the NPM registry.</p>
<p>For example, say <code>xml2js 0.2.6</code> (located in <code>node_modules</code> in the current project) is outdated because a newer version exists (0.2.7). You would see:</p>
<pre><code>[email protected] node_modules/xml2js current=0.2.6
</code></pre>
<p>To <a href="https://docs.npmjs.com/cli/update" rel="noreferrer">update</a> all dependencies, if you are confident this is desirable:</p>
<pre><code>npm update
</code></pre>
<p>Or, to update a single dependency such as <code>xml2js</code>:</p>
<pre><code>npm update xml2js
</code></pre>
<p>To update <code>package.json</code> version numbers, append the <code>--save</code> flag:</p>
<pre><code>npm update --save
</code></pre> | {
"question_id": 16525430,
"question_date": "2013-05-13T15:12:22.030Z",
"question_score": 706,
"tags": "node.js|teamcity|npm|karma-runner",
"answer_id": 16532884,
"answer_date": "2013-05-13T23:40:46.637Z",
"answer_score": 965
} |
Please answer the following Stack Overflow question:
Title: Move an array element from one array position to another
<p>I'm having a hard time figuring out how to move an element of an array. For example, given the following:</p>
<pre><code>var array = [ 'a', 'b', 'c', 'd', 'e'];
</code></pre>
<p>How can I write a function to move the element <code>'d'</code> to the left of <code>'b'</code> ?</p>
<p>Or <code>'a'</code> to the right of <code>'c'</code>?</p>
<p>After moving the elements, the indexes of the rest of the elements should be updated. The resulting array would be:</p>
<pre><code>array = ['a', 'd', 'b', 'c', 'e']
</code></pre>
<p>This seems like it should be pretty simple, but I can't wrap my head around it.</p> | <p>If you'd like a version on npm, <a href="https://www.npmjs.com/package/array-move" rel="noreferrer">array-move</a> is the closest to this answer, although it's not the same implementation. See its usage section for more details. The previous version of this answer (that modified Array.prototype.move) can be found on npm at <a href="https://www.npmjs.com/package/array.prototype.move" rel="noreferrer">array.prototype.move</a>.</p>
<hr>
<p>I had fairly good success with this function:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function array_move(arr, old_index, new_index) {
if (new_index >= arr.length) {
var k = new_index - arr.length + 1;
while (k--) {
arr.push(undefined);
}
}
arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
return arr; // for testing
};
// returns [2, 1, 3]
console.log(array_move([1, 2, 3], 0, 1)); </code></pre>
</div>
</div>
</p>
<p>Note that the last <code>return</code> is simply for testing purposes: <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice" rel="noreferrer"><code>splice</code></a> performs operations on the array in-place, so a return is not necessary. By extension, this <code>move</code> is an in-place operation. If you want to avoid that and return a copy, use <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/slice" rel="noreferrer"><code>slice</code></a>.</p>
<p>Stepping through the code:</p>
<ol>
<li>If <code>new_index</code> is greater than the length of the array, we want (I presume) to pad the array properly with new <code>undefined</code>s. This little snippet handles this by pushing <code>undefined</code> on the array until we have the proper length.</li>
<li>Then, in <code>arr.splice(old_index, 1)[0]</code>, we splice out the old element. <code>splice</code> returns the element that was spliced out, but it's in an array. In our above example, this was <code>[1]</code>. So we take the first index of that array to get the raw <code>1</code> there.</li>
<li>Then we use <code>splice</code> to insert this element in the new_index's place. Since we padded the array above if <code>new_index > arr.length</code>, it will probably appear in the right place, unless they've done something strange like pass in a negative number. </li>
</ol>
<p>A fancier version to account for negative indices: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function array_move(arr, old_index, new_index) {
while (old_index < 0) {
old_index += arr.length;
}
while (new_index < 0) {
new_index += arr.length;
}
if (new_index >= arr.length) {
var k = new_index - arr.length + 1;
while (k--) {
arr.push(undefined);
}
}
arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
return arr; // for testing purposes
};
// returns [1, 3, 2]
console.log(array_move([1, 2, 3], -1, -2));</code></pre>
</div>
</div>
</p>
<p>Which should account for things like <code>array_move([1, 2, 3], -1, -2)</code> properly (move the last element to the second to last place). Result for that should be <code>[1, 3, 2]</code>. </p>
<p>Either way, in your original question, you would do <code>array_move(arr, 0, 2)</code> for <code>a</code> after <code>c</code>. For <code>d</code> before <code>b</code>, you would do <code>array_move(arr, 3, 1)</code>.</p> | {
"question_id": 5306680,
"question_date": "2011-03-15T01:57:45.877Z",
"question_score": 706,
"tags": "javascript|arrays",
"answer_id": 5306832,
"answer_date": "2011-03-15T02:23:38.860Z",
"answer_score": 840
} |
Please answer the following Stack Overflow question:
Title: Revert to a commit by a SHA hash in Git?
<p>I'm not clear on how <code>git revert</code> works. For example, I want to revert to a commit six commits behind the head, reverting all the changes in the intermediary commits in between.</p>
<p>Say its <a href="http://en.wikipedia.org/wiki/SHA-1" rel="noreferrer">SHA</a> hash is <code>56e05fced214c44a37759efa2dfc25a65d8ae98d</code>. Then why can't I just do something like:</p>
<pre><code>git revert 56e05fced214c44a37759efa2dfc25a65d8ae98d
</code></pre> | <p>If you want to commit on top of the current HEAD with the exact state at a different commit, undoing all the intermediate commits, then you can use <code>reset</code> to create the correct state of the index to make the commit.</p>
<pre class="lang-bash prettyprint-override"><code># Reset the index and working tree to the desired tree
# Ensure you have no uncommitted changes that you want to keep
git reset --hard 56e05fced
# Move the branch pointer back to the previous HEAD
git reset --soft "HEAD@{1}"
git commit -m "Revert to 56e05fced"
</code></pre> | {
"question_id": 1895059,
"question_date": "2009-12-12T23:34:39.977Z",
"question_score": 706,
"tags": "git",
"answer_id": 1895095,
"answer_date": "2009-12-12T23:51:36.277Z",
"answer_score": 1291
} |
Please answer the following Stack Overflow question:
Title: How to store Node.js deployment settings/configuration files?
<p>I have been working on a few Node apps, and I've been looking for a good pattern of storing deployment-related settings. In the Django world (where I come from), the common practise would be to have a <code>settings.py</code> file containing the standard settings (timezone, etc), and then a <code>local_settings.py</code> for deployment specific settings, ie. what database to talk to, what memcache socket, e-mail address for the admins and so on.</p>
<p>I have been looking for similar patterns for Node. Just a config file would be nice, so it does not have to be jammed in with everything else in <code>app.js</code>, but I find it important to have a way to have server-specific configuration in a file that is not in source control. The same app could well be deployed across different servers with wildly different settings, and having to deal with merge conflicts and all that is not my idea of fun.</p>
<p>So is there some kind of framework/tool for this, or does everyone just hack something together themselves?</p> | <p>Much later, I found a pretty good Node.js module for managing configuration: <a href="https://github.com/flatiron/nconf">nconf</a>.</p>
<p>A simple example:</p>
<pre><code>var nconf = require('nconf');
// First consider commandline arguments and environment variables, respectively.
nconf.argv().env();
// Then load configuration from a designated file.
nconf.file({ file: 'config.json' });
// Provide default values for settings not provided above.
nconf.defaults({
'http': {
'port': 1337
}
});
// Once this is in place, you can just use nconf.get to get your settings.
// So this would configure `myApp` to listen on port 1337 if the port
// has not been overridden by any of the three configuration inputs
// mentioned above.
myApp.listen(nconf.get('http:port'));
</code></pre>
<p>It also supports storing settings in <a href="http://redis.io/">Redis</a>, writing configuration files, and has a fairly solid API, and is also backed by one of the more well-respected Node.js shops, <a href="http://nodejitsu.com/">Nodejitsu</a>, as part of the <a href="http://flatironjs.org/">Flatiron</a> framework initiative, so it should be fairly future-proof. </p>
<p>Check out <a href="https://github.com/flatiron/nconf">nconf at Github</a>.</p> | {
"question_id": 5869216,
"question_date": "2011-05-03T12:09:07.720Z",
"question_score": 706,
"tags": "node.js|configuration-files",
"answer_id": 8563528,
"answer_date": "2011-12-19T15:28:46.607Z",
"answer_score": 217
} |
Please answer the following Stack Overflow question:
Title: What's the difference between Cache-Control: max-age=0 and no-cache?
<p>The header <code>Cache-Control: max-age=0</code> implies that the content is considered stale (and must be re-fetched) immediately, which is in effect the same thing as <code>Cache-Control: no-cache</code>.</p> | <p>I had this same question, and found some info in my searches (your question came up as one of the results). Here's what I determined...</p>
<p>There are two sides to the <code>Cache-Control</code> header. One side is where it can be sent by the web server (aka. "origin server"). The other side is where it can be sent by the browser (aka. "user agent").</p>
<hr>
<h2>When sent by the origin server</h2>
<p>I believe <code>max-age=0</code> simply tells caches (and user agents) the response is stale from the get-go and so they <strong>SHOULD</strong> revalidate the response (eg. with the <code>If-Not-Modified</code> header) before using a cached copy, whereas, <code>no-cache</code> tells them they <strong>MUST</strong> revalidate before using a cached copy. From <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.1" rel="noreferrer">14.9.1 What is Cacheable</a>:</p>
<blockquote>
<p><strong>no-cache</strong></p>
<p>...a cache MUST NOT use the response
to satisfy a subsequent request
without successful revalidation with
the origin server. This allows an
origin server to prevent caching even
by caches that have been configured to
return stale responses to client
requests.</p>
</blockquote>
<p>In other words, caches may sometimes choose to use a stale response (although I believe they have to then add a <code>Warning</code> header), but <code>no-cache</code> says they're not allowed to use a stale response no matter what. Maybe you'd want the <strong>SHOULD</strong>-revalidate behavior when baseball stats are generated in a page, but you'd want the <strong>MUST</strong>-revalidate behavior when you've generated the response to an e-commerce purchase.</p>
<p>Although you're correct in your comment when you say <code>no-cache</code> is not supposed to prevent storage, it might actually be another difference when using <code>no-cache</code>. I came across a page, <a href="https://web.archive.org/web/20140811162719/http://palizine.plynt.com/issues/2008Jul/cache-control-attributes/" rel="noreferrer">Cache Control Directives Demystified</a>, that says (I can't vouch for its correctness):</p>
<blockquote>
<p>In practice, IE and Firefox have
started treating the no-cache
directive as if it instructs the
browser not to even cache the page.
We started observing this behavior
about a year ago. We suspect that
this change was prompted by the
widespread (and incorrect) use of this
directive to prevent caching.</p>
<p>...</p>
<p>Notice that of late, "cache-control:
no-cache" has also started behaving
like the "no-store" directive.</p>
</blockquote>
<p>As an aside, it appears to me that <code>Cache-Control: max-age=0, must-revalidate</code> should basically mean the same thing as <code>Cache-Control: no-cache</code>. So maybe that's a way to get the <strong>MUST</strong>-revalidate behavior of <code>no-cache</code>, while avoiding the apparent migration of <code>no-cache</code> to doing the same thing as <code>no-store</code> (ie. no caching whatsoever)?</p>
<hr>
<h2>When sent by the user agent</h2>
<p>I believe <a href="https://stackoverflow.com/a/1046987">shahkalpesh's answer</a> applies to the user agent side. You can also look at <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.2.6" rel="noreferrer">13.2.6 Disambiguating Multiple Responses</a>.</p>
<p>If a user agent sends a request with <code>Cache-Control: max-age=0</code> (aka. "end-to-end revalidation"), then each cache along the way will revalidate its cache entry (eg. with the <code>If-Not-Modified</code> header) all the way to the origin server. If the reply is then 304 (Not Modified), the cached entity can be used.</p>
<p>On the other hand, sending a request with <code>Cache-Control: no-cache</code> (aka. "end-to-end reload") doesn't revalidate and the server <strong>MUST NOT</strong> use a cached copy when responding.</p> | {
"question_id": 1046966,
"question_date": "2009-06-26T01:34:40.320Z",
"question_score": 706,
"tags": "http|caching|http-headers|browser-cache|cache-control",
"answer_id": 1383359,
"answer_date": "2009-09-05T13:43:33.693Z",
"answer_score": 649
} |
Please answer the following Stack Overflow question:
Title: What is an idiomatic way of representing enums in Go?
<p>I'm trying to represent a simplified chromosome, which consists of N bases, each of which can only be one of <code>{A, C, T, G}</code>.</p>
<p>I'd like to formalize the constraints with an enum, but I'm wondering what the most idiomatic way of emulating an enum is in Go.</p> | <p>Quoting from the language specs:<a href="http://golang.org/ref/spec#Iota">Iota</a></p>
<blockquote>
<p>Within a constant declaration, the predeclared identifier iota represents successive untyped integer constants. It is reset to 0 whenever the reserved word const appears in the source and increments after each ConstSpec. It can be used to construct a set of related constants:</p>
</blockquote>
<pre><code>const ( // iota is reset to 0
c0 = iota // c0 == 0
c1 = iota // c1 == 1
c2 = iota // c2 == 2
)
const (
a = 1 << iota // a == 1 (iota has been reset)
b = 1 << iota // b == 2
c = 1 << iota // c == 4
)
const (
u = iota * 42 // u == 0 (untyped integer constant)
v float64 = iota * 42 // v == 42.0 (float64 constant)
w = iota * 42 // w == 84 (untyped integer constant)
)
const x = iota // x == 0 (iota has been reset)
const y = iota // y == 0 (iota has been reset)
</code></pre>
<blockquote>
<p>Within an ExpressionList, the value of each iota is the same because it is only incremented after each ConstSpec:</p>
</blockquote>
<pre><code>const (
bit0, mask0 = 1 << iota, 1<<iota - 1 // bit0 == 1, mask0 == 0
bit1, mask1 // bit1 == 2, mask1 == 1
_, _ // skips iota == 2
bit3, mask3 // bit3 == 8, mask3 == 7
)
</code></pre>
<blockquote>
<p>This last example exploits the implicit repetition of the last non-empty expression list.</p>
</blockquote>
<hr>
<p>So your code might be like</p>
<pre><code>const (
A = iota
C
T
G
)
</code></pre>
<p>or</p>
<pre><code>type Base int
const (
A Base = iota
C
T
G
)
</code></pre>
<p>if you want bases to be a separate type from int.</p> | {
"question_id": 14426366,
"question_date": "2013-01-20T16:07:22.017Z",
"question_score": 706,
"tags": "enums|go|genetics",
"answer_id": 14426447,
"answer_date": "2013-01-20T16:15:09.460Z",
"answer_score": 839
} |
Please answer the following Stack Overflow question:
Title: How do I ignore files in Subversion?
<p>How do I ignore files in Subversion?</p>
<p>Also, how do I find files which are not under version control?</p> | <p>(This answer has been updated to match SVN 1.8 and 1.9's behaviour)</p>
<p>You have 2 questions:</p>
<h1>Marking files as ignored:</h1>
<p>By "ignored file" I mean the file won't appear in lists even as "unversioned": your SVN client will pretend the file doesn't exist at all in the filesystem.</p>
<p>Ignored files are specified by a "file pattern". The syntax and format of file patterns is explained in SVN's online documentation: <a href="http://svnbook.red-bean.com/nightly/en/svn.advanced.props.special.ignore.html" rel="noreferrer">http://svnbook.red-bean.com/nightly/en/svn.advanced.props.special.ignore.html</a> "File Patterns in Subversion".</p>
<p>Subversion, as of version 1.8 (June 2013) and later, supports 3 different ways of specifying file patterns. Here's a summary with examples:</p>
<h2>1 - Runtime Configuration Area - <code>global-ignores</code> option:</h2>
<ul>
<li>This is a <strong>client-side only</strong> setting, so your <code>global-ignores</code> list won't be shared by other users, and it applies to all repos you checkout onto your computer.</li>
<li>This setting is defined in your Runtime Configuration Area file:
<ul>
<li>Windows (file-based) - <code>C:\Users\{you}\AppData\Roaming\Subversion\config</code></li>
<li>Windows (registry-based) - <code>Software\Tigris.org\Subversion\Config\Miscellany\global-ignores</code> in both <code>HKLM</code> and <code>HKCU</code>.</li>
<li>Linux/Unix - <code>~/.subversion/config</code></li>
</ul></li>
</ul>
<h2>2 - The <code>svn:ignore</code> property, which is set on directories (not files):</h2>
<ul>
<li>This is stored within the repo, so other users will have the same ignore files. Similar to how <code>.gitignore</code> works.</li>
<li><code>svn:ignore</code> is applied to directories and is non-recursive or inherited. Any file or <em>immediate</em> subdirectory of the parent directory that matches the File Pattern will be excluded.</li>
<li><p>While SVN 1.8 adds the concept of "inherited properties", the <code>svn:ignore</code> property itself is ignored in non-immediate descendant directories:</p>
<pre><code>cd ~/myRepoRoot # Open an existing repo.
echo "foo" > "ignoreThis.txt" # Create a file called "ignoreThis.txt".
svn status # Check to see if the file is ignored or not.
> ? ./ignoreThis.txt
> 1 unversioned file # ...it is NOT currently ignored.
svn propset svn:ignore "ignoreThis.txt" . # Apply the svn:ignore property to the "myRepoRoot" directory.
svn status
> 0 unversioned files # ...but now the file is ignored!
cd subdirectory # now open a subdirectory.
echo "foo" > "ignoreThis.txt" # create another file named "ignoreThis.txt".
svn status
> ? ./subdirectory/ignoreThis.txt # ...and is is NOT ignored!
> 1 unversioned file
</code></pre>
<p>(So the file <code>./subdirectory/ignoreThis</code> is not ignored, even though "<code>ignoreThis.txt</code>" is applied on the <code>.</code> repo root).</p></li>
<li><p>Therefore, to apply an ignore list recursively you must use <code>svn propset svn:ignore <filePattern> . --recursive</code>.</p>
<ul>
<li>This will create a copy of the property on every subdirectory.</li>
<li>If the <code><filePattern></code> value is different in a child directory then the child's value completely overrides the parents, so there is no "additive" effect.</li>
<li>So if you change the <code><filePattern></code> on the root <code>.</code>, then you must change it with <code>--recursive</code> to overwrite it on the child and descendant directories.</li>
</ul></li>
<li><p>I note that the command-line syntax is counter-intuitive.</p>
<ul>
<li>I started-off assuming that you would ignore a file in SVN by typing something like <code>svn ignore pathToFileToIgnore.txt</code> however this is not how SVN's ignore feature works.</li>
</ul></li>
</ul>
<h2>3- The <code>svn:global-ignores</code> property. Requires SVN 1.8 (June 2013):</h2>
<ul>
<li>This is similar to <code>svn:ignore</code>, except it makes use of SVN 1.8's "inherited properties" feature.</li>
<li>Compare to <code>svn:ignore</code>, the file pattern is automatically applied in every descendant directory (not just immediate children).
<ul>
<li>This means that is unnecessary to set <code>svn:global-ignores</code> with the <code>--recursive</code> flag, as inherited ignore file patterns are automatically applied as they're inherited.</li>
</ul></li>
<li><p>Running the same set of commands as in the previous example, but using <code>svn:global-ignores</code> instead:</p>
<pre><code>cd ~/myRepoRoot # Open an existing repo
echo "foo" > "ignoreThis.txt" # Create a file called "ignoreThis.txt"
svn status # Check to see if the file is ignored or not
> ? ./ignoreThis.txt
> 1 unversioned file # ...it is NOT currently ignored
svn propset svn:global-ignores "ignoreThis.txt" .
svn status
> 0 unversioned files # ...but now the file is ignored!
cd subdirectory # now open a subdirectory
echo "foo" > "ignoreThis.txt" # create another file named "ignoreThis.txt"
svn status
> 0 unversioned files # the file is ignored here too!
</code></pre></li>
</ul>
<h2>For TortoiseSVN users:</h2>
<p>This whole arrangement was confusing for me, because TortoiseSVN's terminology (as used in their Windows Explorer menu system) was initially misleading to me - I was unsure what the significance of the Ignore menu's "Add recursively", "Add *" and "Add " options. I hope this post explains how the Ignore feature ties-in to the SVN Properties feature. That said, I suggest using the command-line to set ignored files so you get a feel for how it works instead of using the GUI, and only using the GUI to manipulate properties after you're comfortable with the command-line.</p>
<h1>Listing files that are ignored:</h1>
<p>The command <code>svn status</code> will hide ignored files (that is, files that match an RGA <code>global-ignores</code> pattern, or match an immediate parent directory's <code>svn:ignore</code> pattern or match any ancesor directory's <code>svn:global-ignores</code> pattern.</p>
<p>Use the <code>--no-ignore</code> option to see those files listed. Ignored files have a status of <code>I</code>, then pipe the output to <code>grep</code> to only show lines starting with "I".</p>
<p>The command is:</p>
<pre><code>svn status --no-ignore | grep "^I"
</code></pre>
<p>For example:</p>
<pre><code>svn status
> ? foo # An unversioned file
> M modifiedFile.txt # A versioned file that has been modified
svn status --no-ignore
> ? foo # An unversioned file
> I ignoreThis.txt # A file matching an svn:ignore pattern
> M modifiedFile.txt # A versioned file that has been modified
svn status --no-ignore | grep "^I"
> I ignoreThis.txt # A file matching an svn:ignore pattern
</code></pre>
<p>ta-da!</p> | {
"question_id": 86049,
"question_date": "2008-09-17T18:15:55.807Z",
"question_score": 705,
"tags": "svn|command",
"answer_id": 86052,
"answer_date": "2008-09-17T18:16:07.227Z",
"answer_score": 792
} |
Please answer the following Stack Overflow question:
Title: List of remotes for a Git repository?
<p>I have a Git repository. This repository has multiple remote repositories (I think). How can I get a list of the remote repositories that belong to said repository?</p>
<p>Like <code>git list --remotes</code> or something like that?</p> | <p>You can get a list of any configured remote URLs with the command <code>git remote -v</code>.</p>
<p>This will give you something like the following:</p>
<pre><code>base /home/***/htdocs/base (fetch)
base /home/***/htdocs/base (push)
origin [email protected]:*** (fetch)
origin [email protected]:*** (push)
</code></pre> | {
"question_id": 10183724,
"question_date": "2012-04-17T00:58:00.883Z",
"question_score": 705,
"tags": "git",
"answer_id": 10183740,
"answer_date": "2012-04-17T01:01:02.380Z",
"answer_score": 997
} |
Please answer the following Stack Overflow question:
Title: What's the @ in front of a string in C#?
<p>This is a .NET question for C# (or possibly VB.net), but I am trying to figure out what's the difference between the following declarations:</p>
<pre><code>string hello = "hello";
</code></pre>
<p>vs. </p>
<pre><code>string hello_alias = @"hello";
</code></pre>
<p>Printing out on the console makes no difference, the length properties are the same. </p> | <p>It marks the string as a <a href="http://csharpindepth.com/Articles/General/Strings.aspx" rel="noreferrer">verbatim string literal</a> - anything in the string that would normally be interpreted as an <a href="http://en.wikipedia.org/wiki/Escape_sequence" rel="noreferrer">escape sequence</a> is ignored.</p>
<p>So <code>"C:\\Users\\Rich"</code> is the same as <code>@"C:\Users\Rich"</code></p>
<p>There is one exception: an escape sequence is needed for the double quote. To escape a double quote, you need to put two double quotes in a row. For instance, <code>@""""</code> evaluates to <code>"</code>. </p> | {
"question_id": 556133,
"question_date": "2009-02-17T09:54:17.500Z",
"question_score": 705,
"tags": "c#|.net|string|verbatim-string",
"answer_id": 556142,
"answer_date": "2009-02-17T09:57:31.890Z",
"answer_score": 888
} |
Please answer the following Stack Overflow question:
Title: How do I create a URL shortener?
<p>I want to create a URL shortener service where you can write a long URL into an input field and the service shortens the URL to "<code>http://www.example.org/abcdef</code>".</p>
<p>Instead of "<code>abcdef</code>" there can be any other string with six characters containing <code>a-z, A-Z and 0-9</code>. That makes 56~57 billion possible strings.</p>
<p>My approach:</p>
<p>I have a database table with three columns:</p>
<ol>
<li>id, integer, auto-increment</li>
<li>long, string, the long URL the user entered</li>
<li>short, string, the shortened URL (or just the six characters)</li>
</ol>
<p>I would then insert the long URL into the table. Then I would select the auto-increment value for "<code>id</code>" and build a hash of it. This hash should then be inserted as "<code>short</code>". But what sort of hash should I build? Hash algorithms like MD5 create too long strings. I don't use these algorithms, I think. A self-built algorithm will work, too.</p>
<p>My idea:</p>
<p>For "<code>http://www.google.de/</code>" I get the auto-increment id <code>239472</code>. Then I do the following steps:</p>
<pre><code>short = '';
if divisible by 2, add "a"+the result to short
if divisible by 3, add "b"+the result to short
... until I have divisors for a-z and A-Z.
</code></pre>
<p>That could be repeated until the number isn't divisible any more. Do you think this is a good approach? Do you have a better idea?</p>
<blockquote>
<p><sub><em>Due to the ongoing interest in this topic, I've <a href="https://github.com/delight-im/ShortURL" rel="noreferrer">published an efficient solution to GitHub</a>, with implementations for <a href="https://github.com/delight-im/ShortURL/blob/master/JavaScript/ShortURL.js" rel="noreferrer">JavaScript</a>, <a href="https://github.com/delight-im/ShortURL/blob/master/PHP/ShortURL.php" rel="noreferrer">PHP</a>, <a href="https://github.com/delight-im/ShortURL/blob/master/Python/shorturl.py" rel="noreferrer">Python</a> and <a href="https://github.com/delight-im/ShortURL/blob/master/Java/ShortURL.java" rel="noreferrer">Java</a>. Add your solutions if you like :)</em> </sub></p>
</blockquote> | <p>I would continue your "convert number to string" approach. However, you will realize that your proposed algorithm fails if your ID is a <em>prime and greater than 52</em>.</p>
<h3>Theoretical background</h3>
<p>You need a <a href="http://en.wikipedia.org/wiki/Bijection" rel="noreferrer">Bijective Function</a> <em>f</em>. This is necessary so that you can find a inverse function <em>g('abc') = 123</em> for your <em>f(123) = 'abc'</em> function. This means:</p>
<ul>
<li>There must be no <em>x1, x2 (with x1 ≠ x2)</em> that will make <em>f(x1) = f(x2)</em>,</li>
<li>and for every <em>y</em> you must be able to find an <em>x</em> so that <em>f(x) = y</em>.</li>
</ul>
<h3>How to convert the ID to a shortened URL</h3>
<ol>
<li>Think of an alphabet we want to use. In your case, that's <code>[a-zA-Z0-9]</code>. It contains <em>62 letters</em>.</li>
<li><p>Take an auto-generated, unique numerical key (the auto-incremented <code>id</code> of a MySQL table for example).</p>
<p>For this example, I will use 125<sub>10</sub> (125 with a base of 10).</p></li>
<li><p>Now you have to convert 125<sub>10</sub> to X<sub>62</sub> (base 62).</p>
<p>125<sub>10</sub> = 2×62<sup>1</sup> + 1×62<sup>0</sup> = <code>[2,1]</code></p>
<p>This requires the use of integer division and modulo. A pseudo-code example:</p>
<pre><code>digits = []
while num > 0
remainder = modulo(num, 62)
digits.push(remainder)
num = divide(num, 62)
digits = digits.reverse
</code></pre>
<p>Now map the <em>indices 2 and 1</em> to your alphabet. This is how your mapping (with an array for example) could look like:</p>
<pre><code>0 → a
1 → b
...
25 → z
...
52 → 0
61 → 9
</code></pre>
<p>With 2 → c and 1 → b, you will receive cb<sub>62</sub> as the shortened URL.</p>
<pre><code>http://shor.ty/cb
</code></pre></li>
</ol>
<h3>How to resolve a shortened URL to the initial ID</h3>
<p>The reverse is even easier. You just do a reverse lookup in your alphabet.</p>
<ol>
<li><p>e9a<sub>62</sub> will be resolved to "4th, 61st, and 0th letter in the alphabet".</p>
<p>e9a<sub>62</sub> = <code>[4,61,0]</code> = 4×62<sup>2</sup> + 61×62<sup>1</sup> + 0×62<sup>0</sup> = 19158<sub>10</sub></p></li>
<li><p>Now find your database-record with <code>WHERE id = 19158</code> and do the redirect.</p></li>
</ol>
<h3>Example implementations (provided by commenters)</h3>
<ul>
<li><a href="https://gist.github.com/jaytaylor/a11fadf61a869ade0dfe568606b216c8#file-base64-url-shortener-poc-cpp" rel="noreferrer">C++</a></li>
<li><a href="https://gist.github.com/778542" rel="noreferrer">Python</a></li>
<li><a href="https://gist.github.com/1073996" rel="noreferrer">Ruby</a></li>
<li><a href="https://gist.github.com/4626401" rel="noreferrer">Haskell</a></li>
<li><a href="https://gist.github.com/9554733" rel="noreferrer">C#</a></li>
<li><a href="https://gist.github.com/1158171" rel="noreferrer">CoffeeScript</a></li>
<li><a href="https://metacpan.org/pod/Short::URL" rel="noreferrer">Perl</a></li>
</ul> | {
"question_id": 742013,
"question_date": "2009-04-12T16:29:15.603Z",
"question_score": 705,
"tags": "algorithm|url",
"answer_id": 742047,
"answer_date": "2009-04-12T16:50:21.747Z",
"answer_score": 865
} |
Please answer the following Stack Overflow question:
Title: Eclipse HotKey: how to switch between tabs?
<p>How can I switch between opened windows in Eclipse? There is <kbd>Ctrl</kbd>+<kbd>F6</kbd>, but it's asking me which one I want, but I want switch it like tabs in browser or window in operating system (<kbd>Cmd</kbd>/<kbd>Win</kbd>+<kbd>Tab</kbd>) without file-selection from the list. How to do this easy thing in Eclipse?</p>
<p>I've tried to assign hotkey for events:</p>
<ul>
<li>forward</li>
<li>forward history</li>
<li>next page</li>
</ul>
<p>but it doesn't work the way I want.</p> | <ul>
<li><kbd>CTRL</kbd>+<kbd>E</kbd> (for a list of editor)</li>
<li><kbd>CTRL</kbd>+<kbd>F6</kbd> (for switching to the next editor through a list)<br>
You can assign another shortcut to the 'Next Editor' key.</li>
</ul>
<p>are the two official shortcuts, but they both involve a list being displayed.</p>
<p><kbd>CTRL</kbd>+<kbd>Page Up</kbd> / <kbd>CTRL</kbd>+<kbd>Page Down</kbd> can cycle through editors without displaying a list. </p>
<p>What is interesting with that last set of shortcuts is:<br>
<strong>they are not listed in the Eclipse Keys shortcuts to be defined.</strong><br>
They may be inherited from the multipage editor, making them an <strong>OS specific shortcut</strong>.</p>
<hr>
<p>Regarding shortcuts on Mac OS (OSX), <a href="https://stackoverflow.com/users/139010/m-ll">Matt Ball</a> complained in Sept. 2011 to not being able to remap <kbd>CTRL</kbd>+<kbd>Page Up</kbd>/<kbd>CTRL</kbd>+<kbd>Page Down</kbd>:</p>
<blockquote>
<p>It drives me nuts to not be able to flip through open tabs as I can in pretty much every other tabbed program in OS X (<kbd>⌘</kbd>-<kbd>Left</kbd> and <kbd>⌘</kbd>-<kbd>Right</kbd>). </p>
</blockquote>
<p>Well, in March 2012, <a href="https://stackoverflow.com/users/486930/arthur">Arthur</a> replied:</p>
<blockquote>
<p>, I've just downloaded the latest version of Eclipse (3.7+). I've been able to bind "Previous/Next tab" to (<kbd>⌘</kbd>-<kbd>Left</kbd> and <kbd>⌘</kbd>-<kbd>Right</kbd>) when in Editor, which I'm pretty sure I couldn't do before.<br>
So I guess they heard you.<br>
It works just as you expect, tabs going from left to right and vice-versa, not on a history basis or some nonsense like that.</p>
</blockquote>
<p><a href="https://stackoverflow.com/users/139010/m-ll">Matt Ball</a> confirms:</p>
<blockquote>
<p>oh wow, selecting <strong>"Editing Java Source" actually worked</strong>!<br>
Now, unfortunately this means that I'm SOL if I nav into a non-Java file (JSP, XML, JS, etc.).<br>
<strong>The fix for this is to "copy command" for this pair, and select all the "whens" that I want</strong>.<br>
So far it's at least working beautifully for Java and JSP files.<br>
This is a major PITA to set up, but it's just a one-time thing.</p>
</blockquote>
<p>His <a href="https://gist.github.com/2022533" rel="noreferrer">exported preferences are available here</a> for you to try.<br>
Once imported, you should see, for all the relevant types of document:</p>
<p><img src="https://i.stack.imgur.com/4WQwQ.png" alt="Mac Os key bindings"></p> | {
"question_id": 2332330,
"question_date": "2010-02-25T07:21:30.153Z",
"question_score": 705,
"tags": "eclipse|tabs|hotkeys",
"answer_id": 2332440,
"answer_date": "2010-02-25T07:48:18.180Z",
"answer_score": 939
} |
Please answer the following Stack Overflow question:
Title: When should I write the keyword 'inline' for a function/method?
<p>When should I write the keyword <code>inline</code> for a function/method in C++?</p>
<p>After seeing some answers, some related questions:</p>
<ul>
<li><p>When should I <strong>not</strong> write the keyword 'inline' for a function/method in C++?</p></li>
<li><p>When will the compiler not know when to make a function/method 'inline'?</p></li>
<li><p>Does it matter if an application is <strong>multithreaded</strong> when one writes 'inline' for a function/method?</p></li>
</ul> | <p>Oh man, one of my pet peeves.</p>
<p><code>inline</code> is more like <code>static</code> or <code>extern</code> than a directive telling the compiler to inline your functions. <code>extern</code>, <code>static</code>, <code>inline</code> are linkage directives, used almost exclusively by the linker, not the compiler.</p>
<p>It is said that <code>inline</code> hints to the compiler that you think the function should be inlined. That may have been true in 1998, but a decade later the compiler needs no such hints. Not to mention humans are usually wrong when it comes to optimizing code, so most compilers flat out ignore the 'hint'.</p>
<ul>
<li><p><strong><code>static</code></strong> - the variable/function name cannot be used in other translation units. Linker needs to make sure it doesn't accidentally use a statically defined variable/function from another translation unit.</p></li>
<li><p><strong><code>extern</code></strong> - use this variable/function name in this translation unit but don't complain if it isn't defined. The linker will sort it out and make sure all the code that tried to use some extern symbol has its address.</p></li>
<li><p><strong><code>inline</code></strong> - this function will be defined in multiple translation units, don't worry about it. The linker needs to make sure all translation units use a single instance of the variable/function.</p></li>
</ul>
<p><strong>Note:</strong> Generally, declaring templates <code>inline</code> is pointless, as they have the linkage semantics of <code>inline</code> already. However, explicit specialization and instantiation of templates <a href="https://stackoverflow.com/a/10536588/183120">require <code>inline</code></a> to be used.</p>
<hr>
<p>Specific answers to your questions:</p>
<ul>
<li><blockquote>
<p>When should I write the keyword 'inline' for a function/method in C++?</p>
</blockquote>
<p>Only when you want the function to be defined in a header. More exactly only when the function's definition can show up in multiple translation units. It's a good idea to define small (as in one liner) functions in the header file as it gives the compiler more information to work with while optimizing your code. It also increases compilation time.</p></li>
<li><blockquote>
<p>When should I not write the keyword 'inline' for a function/method in C++?</p>
</blockquote>
<p>Don't add inline just because you think your code will run faster if the compiler inlines it.</p></li>
<li><blockquote>
<p>When will the compiler not know when to make a function/method 'inline'?</p>
</blockquote>
<p>Generally, the compiler will be able to do this better than you. However, the compiler doesn't have the option to inline code if it doesn't have the function definition. In maximally optimized code usually all <code>private</code> methods are inlined whether you ask for it or not.</p>
<p>As an aside to prevent inlining in GCC, use <code>__attribute__(( noinline ))</code>, and in Visual Studio, use <code>__declspec(noinline)</code>.</p></li>
<li><blockquote>
<p>Does it matter if an application is multithreaded when one writes 'inline' for a function/method?</p>
</blockquote>
<p>Multithreading doesn't affect inlining in any way.</p></li>
</ul> | {
"question_id": 1759300,
"question_date": "2009-11-18T21:46:00.627Z",
"question_score": 705,
"tags": "c++|inline|one-definition-rule",
"answer_id": 1759575,
"answer_date": "2009-11-18T22:22:25.740Z",
"answer_score": 1102
} |
Please answer the following Stack Overflow question:
Title: Comments in .gitignore?
<p>Can you write comments in a <code>.gitignore</code> file?</p>
<p>If so, should the line be preceded with a <code>#</code> or some other indicator?</p> | <p>Yes, you may put comments in there. They however must start at the beginning of a line.</p>
<p>cf. <a href="http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files">http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files</a></p>
<blockquote>
<p>The rules for the patterns you can put in the .gitignore file are as follows:<br>
- Blank lines or lines starting with # are ignored.<br>
[…]</p>
</blockquote>
<p>The comment character is <code>#</code>, example:</p>
<pre><code># no .a files
*.a
</code></pre> | {
"question_id": 8865848,
"question_date": "2012-01-14T22:25:04.100Z",
"question_score": 705,
"tags": "git|comments|gitignore",
"answer_id": 8865858,
"answer_date": "2012-01-14T22:26:55.487Z",
"answer_score": 861
} |
Please answer the following Stack Overflow question:
Title: How To Auto-Format / Indent XML/HTML in Notepad++
<p>Is there a way to re-indent a block of code? I'm looking for something similar to <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>F</kbd> in Eclipse (Auto-Format/Indent).</p>
<p>To be clear,</p>
<ul>
<li>I already know how to format XML <em>outside</em> of Notepad++ (Eclipse works fine, as mentioned) so I don't need a bunch of links to other XML-formatting tools. </li>
<li>I'm specifically working with XML and HTML.</li>
<li>Ideally, there's a keybinding as convenient as the one in Eclipse, so I don't have to break my workflow.</li>
</ul>
<p>I already know about NppAutoIndent - it won't work, as I'm working with XML, HTML and CSS.</p> | <p>Since I upgraded to 6.3.2, I use <code>XML Tools</code>.</p>
<ul>
<li>install XML Tools via the Plugin Admin (Plugins → Plugins Admin... Then search for "XML Tools", check its box and click the "Install" button).</li>
<li>use the shortcut <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Shift</kbd>+<kbd>B</kbd> (<em>or</em>
menu → Plugins → XML Tools → Pretty Print)</li>
</ul>
<p><a href="https://i.stack.imgur.com/bp1DO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bp1DO.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/6APie.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6APie.png" alt="enter image description here" /></a></p>
<p>In older versions:
menu → TextFX → HTML Tidy → Tidy: Reindent XML.</p> | {
"question_id": 7117949,
"question_date": "2011-08-19T06:50:52.363Z",
"question_score": 704,
"tags": "html|xml|notepad++|auto-indent|autoformatting",
"answer_id": 8786249,
"answer_date": "2012-01-09T09:29:43.500Z",
"answer_score": 959
} |
Please answer the following Stack Overflow question:
Title: Append integer to beginning of list in Python
<p>How do I prepend an integer to the beginning of a list?</p>
<pre><code>[1, 2, 3] ⟶ [42, 1, 2, 3]
</code></pre> | <pre><code>>>> x = 42
>>> xs = [1, 2, 3]
>>> xs.insert(0, x)
>>> xs
[42, 1, 2, 3]
</code></pre>
<p>How it works:</p>
<p><code>list.insert(index, value)</code></p>
<p>Insert an item at a given position. The first argument is the index of the element before which to insert, so <code>xs.insert(0, x)</code> inserts at the front of the list, and <code>xs.insert(len(xs), x)</code> is equivalent to <code>xs.append(x)</code>. Negative values are treated as being relative to the end of the list.</p> | {
"question_id": 17911091,
"question_date": "2013-07-28T17:54:33.540Z",
"question_score": 704,
"tags": "python|list|prepend",
"answer_id": 17911209,
"answer_date": "2013-07-28T18:07:05.063Z",
"answer_score": 1136
} |
Please answer the following Stack Overflow question:
Title: How can I get the concatenation of two lists in Python without modifying either one?
<p>In Python, the only way I can find to concatenate two lists is <code>list.extend</code>, which modifies the first list. Is there any concatenation function that returns its result without modifying its arguments?</p> | <p>Yes: <code>list1 + list2</code>. This gives a new list that is the concatenation of <code>list1</code> and <code>list2</code>.</p> | {
"question_id": 4344017,
"question_date": "2010-12-03T09:16:30.073Z",
"question_score": 704,
"tags": "python|concatenation|sequence|list-manipulation",
"answer_id": 4344029,
"answer_date": "2010-12-03T09:17:48.827Z",
"answer_score": 1150
} |
Please answer the following Stack Overflow question:
Title: How do I split a string with multiple separators in JavaScript?
<p>How do I split a string with multiple separators in JavaScript?</p>
<p>I'm trying to split on both <em>commas</em> and <em>spaces</em>, but AFAIK JavaScript's <code>split()</code> function only supports one separator.</p> | <p>Pass in a regexp as the parameter:</p>
<pre><code>js> "Hello awesome, world!".split(/[\s,]+/)
Hello,awesome,world!
</code></pre>
<p><strong>Edited to add:</strong></p>
<p>You can get the last element by selecting the length of the array minus 1:</p>
<pre><code>>>> bits = "Hello awesome, world!".split(/[\s,]+/)
["Hello", "awesome", "world!"]
>>> bit = bits[bits.length - 1]
"world!"
</code></pre>
<p>... and if the pattern doesn't match:</p>
<pre><code>>>> bits = "Hello awesome, world!".split(/foo/)
["Hello awesome, world!"]
>>> bits[bits.length - 1]
"Hello awesome, world!"
</code></pre> | {
"question_id": 650022,
"question_date": "2009-03-16T11:25:52.623Z",
"question_score": 704,
"tags": "javascript|regex|split",
"answer_id": 650037,
"answer_date": "2009-03-16T11:30:45.590Z",
"answer_score": 925
} |
Please answer the following Stack Overflow question:
Title: How to iterate over the keys and values with ng-repeat in AngularJS?
<p>In my controller, I have data like:
<code>$scope.object = data</code></p>
<p>Now this data is the dictionary with keys and values from <code>json</code>.</p>
<p>I can access the attribute with <code>object.name</code> in the template. Is there any way that I can iterate over the keys as well and display them in table like</p>
<p><code><tr><td> {{key}} </td> <td> data.key </td></code></p>
<p>The data is like this</p>
<pre><code>{
"id": 2,
"project": "wewe2012",
"date": "2013-02-26",
"description": "ewew",
"eet_no": "ewew",
}
</code></pre> | <p>How about:</p>
<pre class="lang-html prettyprint-override"><code><table>
<tr ng-repeat="(key, value) in data">
<td> {{key}} </td> <td> {{ value }} </td>
</tr>
</table>
</code></pre>
<p>This method is listed in the docs: <a href="https://docs.angularjs.org/api/ng/directive/ngRepeat" rel="noreferrer">https://docs.angularjs.org/api/ng/directive/ngRepeat</a></p> | {
"question_id": 15127834,
"question_date": "2013-02-28T04:57:45.827Z",
"question_score": 704,
"tags": "angularjs|angularjs-ng-repeat",
"answer_id": 15127934,
"answer_date": "2013-02-28T05:07:41.970Z",
"answer_score": 1447
} |
Please answer the following Stack Overflow question:
Title: What is the best way to remove accents (normalize) in a Python unicode string?
<p>I have a Unicode string in Python, and I would like to remove all the accents (diacritics).</p>
<p>I found on the web an elegant way to do this (in Java):</p>
<ol>
<li>convert the Unicode string to its <em><strong>long normalized form</strong></em> (with a separate character for letters and diacritics)</li>
<li>remove all the characters whose Unicode type is "diacritic".</li>
</ol>
<p>Do I need to install a library such as pyICU or is this possible with just the Python standard library? And what about python 3?</p>
<p>Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.</p> | <p>How about this:</p>
<pre><code>import unicodedata
def strip_accents(s):
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
</code></pre>
<p>This works on greek letters, too:</p>
<pre><code>>>> strip_accents(u"A \u00c0 \u0394 \u038E")
u'A A \u0394 \u03a5'
>>>
</code></pre>
<p>The <a href="http://www.unicode.org/reports/tr44/#GC_Values_Table" rel="noreferrer">character category</a> "Mn" stands for <code>Nonspacing_Mark</code>, which is similar to unicodedata.combining in MiniQuark's answer (I didn't think of unicodedata.combining, but it is probably the better solution, because it's more explicit).</p>
<p>And keep in mind, these manipulations may significantly alter the meaning of the text. Accents, Umlauts etc. are not "decoration".</p> | {
"question_id": 517923,
"question_date": "2009-02-05T21:10:40.760Z",
"question_score": 704,
"tags": "python|python-3.x|unicode|python-2.x|diacritics",
"answer_id": 518232,
"answer_date": "2009-02-05T22:17:22.780Z",
"answer_score": 367
} |
Please answer the following Stack Overflow question:
Title: How is a tag different from a branch in Git? Which should I use, here?
<p>I am having some difficulty understanding how to use <em>tags</em> versus <em>branches</em> in <a href="/questions/tagged/git" class="post-tag" title="show questions tagged 'git'" rel="tag">git</a>.</p>
<p>I just moved the current version of our code from <a href="/questions/tagged/cvs" class="post-tag" title="show questions tagged 'cvs'" rel="tag">cvs</a> to <a href="/questions/tagged/git" class="post-tag" title="show questions tagged 'git'" rel="tag">git</a>, and now I'm going to be working on a subset of that code for a particular feature. A few other developers will be working on this as well, but not all developers in our group are going to care about this feature. Should I be creating a branch or a tag? In what situations should I be using one versus the other?</p> | <p>A <strong>tag</strong> represents a version of a particular branch at a moment in time. A <strong>branch</strong> represents a separate thread of development that may run concurrently with other development efforts on the same code base. Changes to a branch may eventually be merged back into another branch to unify them.</p>
<p>Usually you'll <strong>tag</strong> a particular version so that you can recreate it, e.g., <em>this is the version we shipped to XYZ Corp</em>. A <strong>branch</strong> is more of a strategy to provide on-going updates on a particular version of the code while continuing to do development on it. You'll make a branch of the delivered version, continue development on the main line, but make bug fixes to the branch that represents the delivered version. Eventually, you'll merge these bug fixes back into the main line. Often you'll use both branching and tagging together. You'll have various tags that may apply both to the main line and its branches marking particular versions (those delivered to customers, for instance) along each branch that you may want to recreate -- for delivery, bug diagnosis, etc.</p>
<p>It's actually more complicated than this -- or as complicated as you want to make it -- but these examples should give you an idea of the differences.</p> | {
"question_id": 1457103,
"question_date": "2009-09-21T21:55:15.797Z",
"question_score": 704,
"tags": "git|version-control|branch|git-branch|git-tag",
"answer_id": 1457136,
"answer_date": "2009-09-21T22:03:52.940Z",
"answer_score": 587
} |
Please answer the following Stack Overflow question:
Title: Multiple cases in switch statement
<p>Is there a way to fall through multiple case statements without stating <code>case value:</code> repeatedly?</p>
<p>I know this works:</p>
<pre><code>switch (value)
{
case 1:
case 2:
case 3:
// Do some stuff
break;
case 4:
case 5:
case 6:
// Do some different stuff
break;
default:
// Default stuff
break;
}
</code></pre>
<p>but I'd like to do something like this:</p>
<pre><code>switch (value)
{
case 1,2,3:
// Do something
break;
case 4,5,6:
// Do something
break;
default:
// Do the Default
break;
}
</code></pre>
<p>Is this syntax I'm thinking of from a different language, or am I missing something?</p> | <p>There is no syntax in C++ nor C# for the second method you mentioned. </p>
<p>There's nothing wrong with your first method. If however you have very big ranges, just use a series of if statements.</p> | {
"question_id": 68578,
"question_date": "2008-09-16T01:34:41.277Z",
"question_score": 703,
"tags": "c#|switch-statement",
"answer_id": 68611,
"answer_date": "2008-09-16T01:40:32.557Z",
"answer_score": 362
} |
Please answer the following Stack Overflow question:
Title: Read a file one line at a time in node.js?
<p>I am trying to read a large file one line at a time. I found <a href="http://www.quora.com/What-is-the-best-way-to-read-a-file-line-by-line-in-node-js" rel="noreferrer">a question on Quora</a> that dealt with the subject but I'm missing some connections to make the whole thing fit together.</p>
<pre><code> var Lazy=require("lazy");
new Lazy(process.stdin)
.lines
.forEach(
function(line) {
console.log(line.toString());
}
);
process.stdin.resume();
</code></pre>
<p>The bit that I'd like to figure out is how I might read one line at a time from a file instead of STDIN as in this sample.</p>
<p>I tried: </p>
<pre><code> fs.open('./VeryBigFile.csv', 'r', '0666', Process);
function Process(err, fd) {
if (err) throw err;
// DO lazy read
}
</code></pre>
<p>but it's not working. I know that in a pinch I could fall back to using something like PHP, but I would like to figure this out. </p>
<p>I don't think the other answer would work as the file is much larger than the server I'm running it on has memory for. </p> | <p>Since Node.js v0.12 and as of Node.js v4.0.0, there is a stable <a href="https://nodejs.org/api/readline.html" rel="noreferrer">readline</a> core module. Here's the easiest way to read lines from a file, without any external modules:</p>
<pre class="lang-js prettyprint-override"><code>const fs = require('fs');
const readline = require('readline');
async function processLineByLine() {
const fileStream = fs.createReadStream('input.txt');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.
for await (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
}
}
processLineByLine();
</code></pre>
<p>Or alternatively:</p>
<pre><code>var lineReader = require('readline').createInterface({
input: require('fs').createReadStream('file.in')
});
lineReader.on('line', function (line) {
console.log('Line from file:', line);
});
</code></pre>
<p>The last line is read correctly (as of Node v0.12 or later), even if there is no final <code>\n</code>.</p>
<p><strong>UPDATE</strong>: this example has been <a href="https://nodejs.org/api/readline.html#readline_example_read_file_stream_line_by_line" rel="noreferrer">added to Node's API official documentation</a>.</p> | {
"question_id": 6156501,
"question_date": "2011-05-27T18:49:48.010Z",
"question_score": 703,
"tags": "javascript|node.js|file-io|lazy-evaluation",
"answer_id": 32599033,
"answer_date": "2015-09-16T02:59:40.020Z",
"answer_score": 1038
} |
Please answer the following Stack Overflow question:
Title: Does Python have “private” variables in classes?
<p>I'm coming from the Java world and reading Bruce Eckels' <em>Python 3 Patterns, Recipes and Idioms</em>. </p>
<p>While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there. </p>
<p>So for example:</p>
<pre><code>class Simple:
def __init__(self, s):
print("inside the simple constructor")
self.s = s
def show(self):
print(self.s)
def showMsg(self, msg):
print(msg + ':', self.show())
</code></pre>
<p>If that’s true, then any object of class <code>Simple</code> can just change the value of variable <code>s</code> outside of the class. </p>
<p>For example: </p>
<pre><code>if __name__ == "__main__":
x = Simple("constructor argument")
x.s = "test15" # this changes the value
x.show()
x.showMsg("A message")
</code></pre>
<p>In Java, we have been taught about public/private/protected variables. Those keywords make sense because at times you want variables in a class to which no one outside the class has access to. </p>
<p>Why is that not required in Python?</p> | <p>It's cultural. In Python, you don't write to other classes' instance or class variables. In Java, nothing prevents you from doing the same if you <em>really</em> want to - after all, you can always edit the source of the class itself to achieve the same effect. Python drops that pretence of security and encourages programmers to be responsible. In practice, this works very nicely.</p>
<p>If you want to emulate private variables for some reason, you can always use the <code>__</code> prefix from <a href="https://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables" rel="noreferrer">PEP 8</a>. Python mangles the names of variables like <code>__foo</code> so that they're not easily visible to code outside the class that contains them (although you <em>can</em> get around it if you're determined enough, just like you <em>can</em> get around Java's protections if you work at it).</p>
<p>By the same convention, the <code>_</code> prefix means <strong>stay away even if you're not technically prevented from doing so</strong>. You don't play around with another class's variables that look like <code>__foo</code> or <code>_bar</code>.</p> | {
"question_id": 1641219,
"question_date": "2009-10-29T01:54:18.923Z",
"question_score": 703,
"tags": "python|class|private",
"answer_id": 1641236,
"answer_date": "2009-10-29T02:01:29.063Z",
"answer_score": 1112
} |
Please answer the following Stack Overflow question:
Title: Difference between rake db:migrate db:reset and db:schema:load
<p>The difference between <code>rake db:migrate</code> and <code>rake db:reset</code> is pretty clear to me. The thing which I don't understand is how <code>rake db:schema:load</code> is different from the former two.</p>
<p>Just to be sure that I am on the same page:</p>
<ul>
<li><code>rake db:migrate</code> - Runs the migrations which haven't been run yet.</li>
<li><code>rake db:reset</code> - Clears the database (presumably does a <code>rake db:drop</code> + <code>rake db:create</code> + <code>rake db:migrate</code>) and runs migration on a fresh database.</li>
</ul> | <ul>
<li><p><strong>db:migrate</strong> runs (single) migrations that have not run yet.</p>
</li>
<li><p><strong>db:create</strong> creates the database</p>
</li>
<li><p><strong>db:drop</strong> deletes the database</p>
</li>
<li><p><strong>db:schema:load</strong> creates tables and columns within the existing database following schema.rb. This will delete existing data.</p>
</li>
<li><p><strong>db:setup</strong> does db:create, db:schema:load, db:seed</p>
</li>
<li><p><strong>db:reset</strong> does db:drop, db:setup</p>
</li>
<li><p><strong>db:migrate:reset</strong> does db:drop, db:create, db:migrate</p>
</li>
</ul>
<p>Typically, you would use db:migrate after having made changes to the schema via new migration files (this makes sense only if there is already data in the database). db:schema:load is used when you setup a new instance of your app.</p>
<hr />
<h2>For rails 3.2.12:</h2>
<p>I just checked the source and the dependencies are like this now:</p>
<ul>
<li><p><strong>db:create</strong> creates the database for the current env</p>
</li>
<li><p><strong>db:create:all</strong> creates the databases for all envs</p>
</li>
<li><p><strong>db:drop</strong> drops the database for the current env</p>
</li>
<li><p><strong>db:drop:all</strong> drops the databases for all envs</p>
</li>
<li><p><strong>db:migrate</strong> runs migrations for the current env that have not run yet</p>
</li>
<li><p><strong>db:migrate:up</strong> runs one specific migration</p>
</li>
<li><p><strong>db:migrate:down</strong> rolls back one specific migration</p>
</li>
<li><p><strong>db:migrate:status</strong> shows current migration status</p>
</li>
<li><p><strong>db:rollback</strong> rolls back the last migration</p>
</li>
<li><p><strong>db:forward</strong> advances the current schema version to the next one</p>
</li>
<li><p><strong>db:seed</strong> (only) runs the db/seed.rb file</p>
</li>
<li><p><strong>db:schema:load</strong> loads the schema into the current env's database</p>
</li>
<li><p><strong>db:schema:dump</strong> dumps the current env's schema (and seems to create the db as well)</p>
</li>
<li><p><strong>db:setup</strong> runs db:create db:schema:load db:seed</p>
</li>
<li><p><strong>db:reset</strong> runs db:drop db:setup</p>
</li>
<li><p><strong>db:migrate:redo</strong> runs (db:migrate:down db:migrate:up) or (db:rollback db:migrate) depending on the specified migration</p>
</li>
<li><p><strong>db:migrate:reset</strong> runs db:drop db:create db:migrate</p>
</li>
</ul>
<p>For further information please have a look at <a href="https://github.com/rails/rails/blob/v3.2.12/activerecord/lib/active_record/railties/databases.rake" rel="noreferrer">https://github.com/rails/rails/blob/v3.2.12/activerecord/lib/active_record/railties/databases.rake</a> (for Rails 3.2.x) and <a href="https://github.com/rails/rails/blob/v4.0.5/activerecord/lib/active_record/railties/databases.rake" rel="noreferrer">https://github.com/rails/rails/blob/v4.0.5/activerecord/lib/active_record/railties/databases.rake</a> (for Rails 4.0.x)</p> | {
"question_id": 10301794,
"question_date": "2012-04-24T16:11:32.397Z",
"question_score": 703,
"tags": "ruby-on-rails|ruby|database|rake",
"answer_id": 10302357,
"answer_date": "2012-04-24T16:48:46.120Z",
"answer_score": 1476
} |
Please answer the following Stack Overflow question:
Title: Is there a way to detect if a browser window is not currently active?
<p>I have JavaScript that is doing activity periodically. When the user is not looking at the site (i.e., the window or tab does not have focus), it'd be nice to not run.</p>
<p>Is there a way to do this using JavaScript?</p>
<p>My reference point: Gmail Chat plays a sound if the window you're using isn't active. </p> | <p>Since originally writing this answer, a new specification has reached <em>recommendation</em> status thanks to the W3C. The <a href="http://www.w3.org/TR/page-visibility/" rel="noreferrer">Page Visibility API</a> (on <a href="https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API" rel="noreferrer">MDN</a>) now allows us to more accurately detect when a page is hidden to the user.</p>
<pre><code>document.addEventListener("visibilitychange", onchange);
</code></pre>
<p>Current browser support:</p>
<ul>
<li>Chrome 13+</li>
<li>Internet Explorer 10+</li>
<li>Firefox 10+</li>
<li>Opera 12.10+ <sup>[<a href="https://dev.opera.com/blog/page-visibility-api-support-in-opera-12-10/" rel="noreferrer">read notes</a>]</sup></li>
</ul>
<p>The following code falls back to the less reliable blur/focus method in incompatible browsers:</p>
<pre><code>(function() {
var hidden = "hidden";
// Standards:
if (hidden in document)
document.addEventListener("visibilitychange", onchange);
else if ((hidden = "mozHidden") in document)
document.addEventListener("mozvisibilitychange", onchange);
else if ((hidden = "webkitHidden") in document)
document.addEventListener("webkitvisibilitychange", onchange);
else if ((hidden = "msHidden") in document)
document.addEventListener("msvisibilitychange", onchange);
// IE 9 and lower:
else if ("onfocusin" in document)
document.onfocusin = document.onfocusout = onchange;
// All others:
else
window.onpageshow = window.onpagehide
= window.onfocus = window.onblur = onchange;
function onchange (evt) {
var v = "visible", h = "hidden",
evtMap = {
focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
};
evt = evt || window.event;
if (evt.type in evtMap)
document.body.className = evtMap[evt.type];
else
document.body.className = this[hidden] ? "hidden" : "visible";
}
// set the initial state (but only if browser supports the Page Visibility API)
if( document[hidden] !== undefined )
onchange({type: document[hidden] ? "blur" : "focus"});
})();
</code></pre>
<p><code>onfocusin</code> and <code>onfocusout</code> are <a href="http://www.thefutureoftheweb.com/blog/detect-browser-window-focus" rel="noreferrer">required for IE 9 and lower</a>, while all others make use of <code>onfocus</code> and <code>onblur</code>, except for iOS, which uses <code>onpageshow</code> and <code>onpagehide</code>.</p> | {
"question_id": 1060008,
"question_date": "2009-06-29T19:20:00.777Z",
"question_score": 703,
"tags": "javascript|browser|focus|window",
"answer_id": 1060034,
"answer_date": "2009-06-29T19:26:07.473Z",
"answer_score": 790
} |
Please answer the following Stack Overflow question:
Title: Embedding DLLs in a compiled executable
<p>Is it possible to embed a pre-existing DLL into a compiled C# executable (so that you only have one file to distribute)? If it is possible, how would one go about doing it?</p>
<p>Normally, I'm cool with just leaving the DLLs outside and having the setup program handle everything, but there have been a couple of people at work who have asked me this and I honestly don't know.</p> | <p>I highly recommend to use <a href="https://github.com/Fody/Costura" rel="noreferrer">Costura.Fody</a> - by far the best and easiest way to embed resources in your assembly. It's available as NuGet package.</p>
<pre><code>Install-Package Costura.Fody
</code></pre>
<p>After adding it to the project, it will automatically embed all references that are copied to the output directory into your <em>main</em> assembly. You might want to clean the embedded files by adding a target to your project:</p>
<pre><code>Install-CleanReferencesTarget
</code></pre>
<p>You'll also be able to specify whether to include the pdb's, exclude certain assemblies, or extracting the assemblies on the fly. As far as I know, also unmanaged assemblies are supported.</p>
<p><strong>Update</strong></p>
<p>Currently, some people are trying to add <a href="https://github.com/Fody/Fody/issues/206" rel="noreferrer">support for DNX</a>.</p>
<p><strong>Update 2</strong></p>
<p>For the lastest Fody version, you will need to have MSBuild 16 (so Visual Studio 2019). Fody version 4.2.1 will do MSBuild 15. (reference: <a href="https://stackoverflow.com/questions/55795625/fody-is-only-supported-on-msbuild-16-and-above-current-version-15">Fody is only supported on MSBuild 16 and above. Current version: 15</a>)</p> | {
"question_id": 189549,
"question_date": "2008-10-09T23:11:54.007Z",
"question_score": 702,
"tags": "c#|.net|dll|merge|linker",
"answer_id": 20306095,
"answer_date": "2013-11-30T21:53:21.077Z",
"answer_score": 826
} |
Please answer the following Stack Overflow question:
Title: How to get a subset of a javascript object's properties
<p>Say I have an object:</p>
<pre><code>elmo = {
color: 'red',
annoying: true,
height: 'unknown',
meta: { one: '1', two: '2'}
};
</code></pre>
<p>I want to make a new object with a subset of its properties.</p>
<pre><code> // pseudo code
subset = elmo.slice('color', 'height')
//=> { color: 'red', height: 'unknown' }
</code></pre>
<p>How may I achieve this?</p> | <p>Using Object Destructuring and Property Shorthand</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const object = { a: 5, b: 6, c: 7 };
const picked = (({ a, c }) => ({ a, c }))(object);
console.log(picked); // { a: 5, c: 7 }</code></pre>
</div>
</div>
</p>
<hr>
<p>From Philipp Kewisch:</p>
<blockquote>
<p>This is really just an anonymous function being called instantly. All of this can be found on the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" rel="noreferrer">Destructuring Assignment</a> page on MDN. Here is an expanded form</p>
</blockquote>
<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 unwrap = ({a, c}) => ({a, c});
let unwrap2 = function({a, c}) { return { a, c }; };
let picked = unwrap({ a: 5, b: 6, c: 7 });
let picked2 = unwrap2({a: 5, b: 6, c: 7})
console.log(picked)
console.log(picked2)</code></pre>
</div>
</div>
</p> | {
"question_id": 17781472,
"question_date": "2013-07-22T06:47:20.590Z",
"question_score": 702,
"tags": "javascript|object",
"answer_id": 39333479,
"answer_date": "2016-09-05T15:12:31.693Z",
"answer_score": 1075
} |
Please answer the following Stack Overflow question:
Title: Why are static variables considered evil?
<p>I am a Java programmer who is new to the corporate world. Recently I've developed an application using <a href="http://en.wikipedia.org/wiki/Groovy_%28programming_language%29" rel="noreferrer">Groovy</a> and Java. All through the code I wrote used quite a good number of statics. I was asked by the senior technical lot to cut down on the number of statics used. I've googled about the same, and I find that many programmers are fairly against using static variables.</p>
<p>I find static variables more convenient to use. And I presume that they are efficient too (please correct me if I am wrong), because if I had to make 10,000 calls to a function within a class, I would be glad to make the method static and use a straightforward <code>Class.methodCall()</code> on it instead of cluttering the memory with 10,000 instances of the class, right?</p>
<p>Moreover statics reduce the inter-dependencies on the other parts of the code. They can act as perfect state holders. Adding to this I find that statics are widely implemented in some languages like <a href="https://en.wikipedia.org/wiki/Smalltalk" rel="noreferrer">Smalltalk</a> and <a href="http://en.wikipedia.org/wiki/Scala_%28programming_language%29" rel="noreferrer">Scala</a>. So why is this opposition to statics prevalent among programmers (especially in the world of Java)?</p>
<p>PS: please do correct me if my assumptions about statics are wrong.</p> | <p>Static variables represent global state. That's hard to reason about and hard to test: if I create a new instance of an object, I can reason about its new state within tests. If I use code which is using static variables, it could be in any state - and anything could be modifying it.</p>
<p>I could go on for quite a while, but the bigger concept to think about is that the tighter the scope of something, the easier it is to reason about. We're good at thinking about small things, but it's hard to reason about the state of a million line system if there's no modularity. This applies to all sorts of things, by the way - not just static variables.</p> | {
"question_id": 7026507,
"question_date": "2011-08-11T13:14:37.463Z",
"question_score": 702,
"tags": "java|static",
"answer_id": 7026563,
"answer_date": "2011-08-11T13:18:22.020Z",
"answer_score": 763
} |
Please answer the following Stack Overflow question:
Title: Can code that is valid in both C and C++ produce different behavior when compiled in each language?
<p>C and C++ have many differences, and not all valid C code is valid C++ code.<br>
(By "valid" I mean standard code with defined behavior, i.e. not implementation-specific/undefined/etc.)</p>
<p>Is there any scenario in which a piece of code valid in both C and C++ would produce <em>different</em> behavior when compiled with a standard compiler in each language?</p>
<p>To make it a reasonable/useful comparison (I'm trying to learn something practically useful, not to try to find obvious loopholes in the question), let's assume:</p>
<ul>
<li>Nothing preprocessor-related (which means no hacks with <code>#ifdef __cplusplus</code>, pragmas, etc.) </li>
<li>Anything implementation-defined is the same in both languages (e.g. numeric limits, etc.)</li>
<li>We're comparing reasonably recent versions of each standard (e.g. say, C++98 and C90 or later)<br>
If the versions matter, then please mention which versions of each produce different behavior.</li>
</ul> | <p>The following, valid in C and C++, is going to (most likely) result in different values in <code>i</code> in C and C++:</p>
<pre><code>int i = sizeof('a');
</code></pre>
<p>See <a href="https://stackoverflow.com/questions/2172943/size-of-character-a-in-c-c">Size of character ('a') in C/C++</a> for an explanation of the difference.</p>
<p>Another one from <a href="http://david.tribble.com/text/cdiffs.htm" rel="noreferrer">this article</a>:</p>
<pre><code>#include <stdio.h>
int sz = 80;
int main(void)
{
struct sz { char c; };
int val = sizeof(sz); // sizeof(int) in C,
// sizeof(struct sz) in C++
printf("%d\n", val);
return 0;
}
</code></pre> | {
"question_id": 12887700,
"question_date": "2012-10-14T23:54:26.223Z",
"question_score": 702,
"tags": "c++|c",
"answer_id": 12887719,
"answer_date": "2012-10-14T23:57:11.920Z",
"answer_score": 409
} |
Please answer the following Stack Overflow question:
Title: How to get current route
<p>The current docs only talk about getting route params, not the actual route segments.</p>
<p>For example, if i want to find the parent of current route, how is that possible?</p> | <p>The new V3 router has a url property.</p>
<pre><code>this.router.url === '/login'
</code></pre> | {
"question_id": 34597835,
"question_date": "2016-01-04T18:51:28.163Z",
"question_score": 701,
"tags": "angular|angular2-routing",
"answer_id": 37909349,
"answer_date": "2016-06-19T16:22:49.170Z",
"answer_score": 780
} |
Please answer the following Stack Overflow question:
Title: How to calculate number of days between two given dates
<p>If I have two dates (ex. <code>'8/18/2008'</code> and <code>'9/26/2008'</code>), what is the best way to get the number of days between these two dates?</p> | <p>If you have two date objects, you can just subtract them, which computes a <a href="https://docs.python.org/3/library/datetime.html#datetime.timedelta" rel="noreferrer"><code>timedelta</code></a> object.</p>
<pre><code>from datetime import date
d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d1 - d0
print(delta.days)
</code></pre>
<p>The relevant section of the docs:
<a href="https://docs.python.org/library/datetime.html" rel="noreferrer">https://docs.python.org/library/datetime.html</a>.</p>
<p>See <a href="https://stackoverflow.com/a/8258465">this answer</a> for another example.</p> | {
"question_id": 151199,
"question_date": "2008-09-29T23:36:25.977Z",
"question_score": 701,
"tags": "python|date|datetime",
"answer_id": 151211,
"answer_date": "2008-09-29T23:41:22.830Z",
"answer_score": 1096
} |
Please answer the following Stack Overflow question:
Title: How can I select an element in a component template?
<p>Does anybody know how to get hold of an element defined in a component template? Polymer makes it really easy with the <code>$</code> and <code>$$</code>.</p>
<p>I was just wondering how to go about it in Angular.</p>
<p>Take the example from the tutorial:</p>
<pre><code>import {Component} from '@angular/core';
@Component({
selector:'display',
template:`
<input #myname (input)="updateName(myname.value)"/>
<p>My name : {{myName}}</p>
`
})
export class DisplayComponent {
myName: string = "Aman";
updateName(input: String) {
this.myName = input;
}
}
</code></pre>
<p>How do I catch hold or get a reference of the <code>p</code> or <code>input</code> element from within the class definition?</p> | <p>Instead of injecting <code>ElementRef</code> and using <code>querySelector</code> or similar from there, a declarative way can be used instead to access elements in the view directly:</p>
<pre class="lang-html prettyprint-override"><code><input #myname>
</code></pre>
<pre class="lang-ts prettyprint-override"><code>@ViewChild('myname') input;
</code></pre>
<p>element</p>
<pre class="lang-ts prettyprint-override"><code>ngAfterViewInit() {
console.log(this.input.nativeElement.value);
}
</code></pre>
<p><a href="https://stackblitz.com/edit/angular-ftvwwq" rel="noreferrer"><strong>StackBlitz example</strong></a></p>
<ul>
<li><a href="https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html" rel="noreferrer">@ViewChild()</a> supports directive or component type as parameter, or the name (string) of a template variable. </li>
<li><a href="https://angular.io/docs/ts/latest/api/core/index/ViewChildren-decorator.html" rel="noreferrer">@ViewChildren()</a> also supports a list of names as comma separated list (currently no spaces allowed <code>@ViewChildren('var1,var2,var3')</code>). </li>
<li><a href="https://angular.io/docs/ts/latest/api/core/index/ContentChild-decorator.html" rel="noreferrer">@ContentChild()</a> and <a href="https://angular.io/docs/ts/latest/api/core/index/ContentChildren-decorator.html" rel="noreferrer">@ContentChildren()</a> do the same but in the light DOM (<code><ng-content></code> projected elements).</li>
</ul>
<p><strong>descendants</strong></p>
<p><code>@ContentChildren()</code> is the only one that allows to also query for descendants </p>
<pre class="lang-ts prettyprint-override"><code>@ContentChildren(SomeTypeOrVarName, {descendants: true}) someField;
</code></pre>
<p><strike>
<code>{descendants: true}</code> should be the default but is not in 2.0.0 final and it's <a href="https://github.com/angular/angular/issues/11645#issuecomment-247650618" rel="noreferrer">considered a bug</a>
</strike><br>
This was fixed in 2.0.1</p>
<p><strong>read</strong></p>
<p>If there are a component and directives the <code>read</code> parameter allows to specify which instance should be returned.</p>
<p>For example <code>ViewContainerRef</code> that is required by dynamically created components instead of the default <code>ElementRef</code></p>
<pre class="lang-ts prettyprint-override"><code>@ViewChild('myname', { read: ViewContainerRef }) target;
</code></pre>
<p><strong>subscribe changes</strong></p>
<p>Even though view children are only set when <code>ngAfterViewInit()</code> is called and content children are only set when <code>ngAfterContentInit()</code> is called, if you want to subscribe to changes of the query result, it should be done in <code>ngOnInit()</code></p>
<p><a href="https://github.com/angular/angular/issues/9689#issuecomment-229247134" rel="noreferrer">https://github.com/angular/angular/issues/9689#issuecomment-229247134</a></p>
<pre class="lang-ts prettyprint-override"><code>@ViewChildren(SomeType) viewChildren;
@ContentChildren(SomeType) contentChildren;
ngOnInit() {
this.viewChildren.changes.subscribe(changes => console.log(changes));
this.contentChildren.changes.subscribe(changes => console.log(changes));
}
</code></pre>
<p><strong>direct DOM access</strong></p>
<p>can only query DOM elements, but not components or directive instances:</p>
<pre class="lang-ts prettyprint-override"><code>export class MyComponent {
constructor(private elRef:ElementRef) {}
ngAfterViewInit() {
var div = this.elRef.nativeElement.querySelector('div');
console.log(div);
}
// for transcluded content
ngAfterContentInit() {
var div = this.elRef.nativeElement.querySelector('div');
console.log(div);
}
}
</code></pre>
<p><strong>get arbitrary projected content</strong></p>
<p>See <a href="https://stackoverflow.com/questions/40737037/access-transcluded-content/40737143#40737143">Access transcluded content</a></p> | {
"question_id": 32693061,
"question_date": "2015-09-21T10:34:45.943Z",
"question_score": 701,
"tags": "angular|typescript|angular-components",
"answer_id": 35209681,
"answer_date": "2016-02-04T19:17:58.300Z",
"answer_score": 1202
} |
Please answer the following Stack Overflow question:
Title: Solutions for INSERT OR UPDATE on SQL Server
<p>Assume a table structure of <code>MyTable(KEY, datafield1, datafield2...)</code>.</p>
<p>Often I want to either update an existing record, or insert a new record if it doesn't exist.</p>
<p>Essentially:</p>
<pre><code>IF (key exists)
run update command
ELSE
run insert command
</code></pre>
<p>What's the best performing way to write this?</p> | <p>don't forget about transactions. Performance is good, but simple (IF EXISTS..) approach is very dangerous.<br>
When multiple threads will try to perform Insert-or-update you can easily
get primary key violation.</p>
<p>Solutions provided by @Beau Crawford & @Esteban show general idea but error-prone.</p>
<p>To avoid deadlocks and PK violations you can use something like this: </p>
<pre><code>begin tran
if exists (select * from table with (updlock,serializable) where key = @key)
begin
update table set ...
where key = @key
end
else
begin
insert into table (key, ...)
values (@key, ...)
end
commit tran
</code></pre>
<p>or</p>
<pre><code>begin tran
update table with (serializable) set ...
where key = @key
if @@rowcount = 0
begin
insert into table (key, ...) values (@key,..)
end
commit tran
</code></pre> | {
"question_id": 108403,
"question_date": "2008-09-20T15:00:47.833Z",
"question_score": 701,
"tags": "sql|sql-server|database|insert|upsert",
"answer_id": 108420,
"answer_date": "2008-09-20T15:06:11.063Z",
"answer_score": 430
} |
Please answer the following Stack Overflow question:
Title: How to convert an int value to string in Go?
<pre><code>i := 123
s := string(i)
</code></pre>
<p>s is 'E', but what I want is "123"</p>
<p>Please tell me how can I get "123".</p>
<p>And in Java, I can do in this way: </p>
<pre><code>String s = "ab" + "c" // s is "abc"
</code></pre>
<p>how can I <code>concat</code> two strings in Go?</p> | <p>Use the <a href="http://golang.org/pkg/strconv/#Itoa" rel="noreferrer"><code>strconv</code></a> package's <code>Itoa</code> function.</p>
<p>For example:</p>
<pre><code>package main
import (
"strconv"
"fmt"
)
func main() {
t := strconv.Itoa(123)
fmt.Println(t)
}
</code></pre>
<p>You can concat strings simply by <code>+</code>'ing them, or by using the <code>Join</code> function of the <a href="http://golang.org/pkg/strings/#Join" rel="noreferrer"><code>strings</code></a> package.</p> | {
"question_id": 10105935,
"question_date": "2012-04-11T12:30:35.930Z",
"question_score": 701,
"tags": "string|go|int|converters",
"answer_id": 10105983,
"answer_date": "2012-04-11T12:33:55.287Z",
"answer_score": 1086
} |
Please answer the following Stack Overflow question:
Title: Filter dict to contain only certain keys?
<p>I've got a <code>dict</code> that has a whole bunch of entries. I'm only interested in a select few of them. Is there an easy way to prune all the other ones out?</p> | <p>Constructing a new dict: </p>
<pre><code>dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys }
</code></pre>
<p>Uses dictionary comprehension. </p>
<p>If you use a version which lacks them (ie Python 2.6 and earlier), make it <code>dict((your_key, old_dict[your_key]) for ...)</code>. It's the same, though uglier.</p>
<p>Note that this, unlike jnnnnn's version, has stable performance (depends only on number of your_keys) for <code>old_dict</code>s of any size. Both in terms of speed and memory. Since this is a generator expression, it processes one item at a time, and it doesn't looks through all items of old_dict.</p>
<p>Removing everything in-place:</p>
<pre><code>unwanted = set(keys) - set(your_dict)
for unwanted_key in unwanted: del your_dict[unwanted_key]
</code></pre> | {
"question_id": 3420122,
"question_date": "2010-08-06T00:08:36.730Z",
"question_score": 701,
"tags": "python|dictionary",
"answer_id": 3420156,
"answer_date": "2010-08-06T00:22:21.580Z",
"answer_score": 891
} |
Please answer the following Stack Overflow question:
Title: What techniques can be used to define a class in JavaScript, and what are their trade-offs?
<p>I prefer to use OOP in large scale projects like the one I'm working on right now. I need to create several classes in JavaScript but, if I'm not mistaken, there are at least a couple of ways to go about doing that. What would be the syntax and why would it be done in that way?</p>
<p>I would like to avoid using third-party libraries - at least at first.<br>
Looking for other answers, I found the article <em><a href="http://www.webreference.com/js/column79/" rel="noreferrer">Object-Oriented Programming with JavaScript, Part I: Inheritance - Doc JavaScript</a></em> that discusses object-oriented programming in JavaScript. Is there a better way to do inheritance? </p> | <p>Here's the way to do it without using any external libraries:</p>
<pre><code>// Define a class like this
function Person(name, gender){
// Add object properties like this
this.name = name;
this.gender = gender;
}
// Add methods like this. All Person objects will be able to invoke this
Person.prototype.speak = function(){
alert("Howdy, my name is" + this.name);
};
// Instantiate new objects with 'new'
var person = new Person("Bob", "M");
// Invoke methods like this
person.speak(); // alerts "Howdy, my name is Bob"
</code></pre>
<p>Now the real answer is a whole lot more complex than that. For instance, there is no such thing as classes in JavaScript. JavaScript uses a <code>prototype</code>-based inheritance scheme. </p>
<p>In addition, there are numerous popular JavaScript libraries that have their own style of approximating class-like functionality in JavaScript. You'll want to check out at least <a href="http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework" rel="noreferrer">Prototype</a> and <a href="http://en.wikipedia.org/wiki/JQuery" rel="noreferrer">jQuery</a>. </p>
<p>Deciding which of these is the "best" is a great way to start a holy war on Stack Overflow. If you're embarking on a larger JavaScript-heavy project, it's definitely worth learning a popular library and doing it their way. I'm a Prototype guy, but Stack Overflow seems to lean towards jQuery.</p>
<p>As far as there being only "one way to do it", without any dependencies on external libraries, the way I wrote is pretty much it. </p> | {
"question_id": 387707,
"question_date": "2008-12-22T23:07:04.047Z",
"question_score": 701,
"tags": "javascript|oop|class",
"answer_id": 387733,
"answer_date": "2008-12-22T23:16:04.293Z",
"answer_score": 752
} |
Please answer the following Stack Overflow question:
Title: How do search engines deal with AngularJS applications?
<p>I see two issues with AngularJS application regarding search engines and SEO:</p>
<p>1) What happens with custom tags? Do search engines ignore the whole content within those tags? i.e. suppose I have</p>
<pre><code><custom>
<h1>Hey, this title is important</h1>
</custom>
</code></pre>
<p>would <code><h1></code> be indexed despite being inside custom tags?</p>
<p><br></p>
<p>2) Is there a way to avoid search engines of indexing {{}} binds literally? i.e.</p>
<pre><code><h2>{{title}}</h2>
</code></pre>
<p>I know I could do something like</p>
<pre><code><h2 ng-bind="title"></h2>
</code></pre>
<p>but what if I want to actually let the crawler "see" the title? Is server-side rendering the only solution?</p> | <p><strong>Update May 2014</strong></p>
<p>Google crawlers <a href="http://googlewebmastercentral.blogspot.no/2014/05/understanding-web-pages-better.html">now executes javascript</a> - you can use the <a href="https://www.google.com/webmasters/tools/home">Google Webmaster Tools</a> to better understand how your sites are rendered by Google. </p>
<p><strong>Original answer</strong><br>
If you want to optimize your app for search engines there is unfortunately no way around serving a pre-rendered version to the crawler. You can read more about Google's recommendations for ajax and javascript-heavy sites <a href="https://developers.google.com/webmasters/ajax-crawling/docs/html-snapshot">here</a>.</p>
<p>If this is an option I'd recommend reading <a href="http://www.yearofmoo.com/2012/11/angularjs-and-seo.html">this article</a> about how to do SEO for Angular with server-side rendering. </p>
<p>I’m not sure what the crawler does when it encounters custom tags.</p> | {
"question_id": 13499040,
"question_date": "2012-11-21T17:44:48.300Z",
"question_score": 701,
"tags": "html|angularjs|seo|search-engine|google-search",
"answer_id": 13521668,
"answer_date": "2012-11-23T00:17:30.597Z",
"answer_score": 406
} |
Please answer the following Stack Overflow question:
Title: Git: How to squash all commits on branch
<p>I make new branch from <code>master</code> with: </p>
<pre><code>git checkout -b testbranch
</code></pre>
<p>I make 20 commits into it.</p>
<p>Now I want to squash those 20 commits. I do that with:</p>
<pre><code>git rebase -i HEAD~20
</code></pre>
<p>What about if I don't know how many commits? Is there any way to do something like:</p>
<pre><code>git rebase -i all on this branch
</code></pre> | <p>Another way to squash all your commits is to reset the index to master:</p>
<pre class="lang-bash prettyprint-override"><code>git checkout yourBranch
git reset $(git merge-base master $(git branch --show-current))
git add -A
git commit -m "one commit on yourBranch"
</code></pre>
<p>This isn't perfect as it implies you know from which branch "yourBranch" is coming from.<br />
Note: finding that origin branch isn't <a href="https://stackoverflow.com/a/9898110/6309">easy/possible with Git</a> (the <a href="https://stackoverflow.com/a/2255638/6309">visual way is often the easiest</a>, as <a href="https://stackoverflow.com/a/4991675/6309">seen here</a>).</p>
<p>Note: <code>git branch --show-current</code> has been <a href="https://stackoverflow.com/a/55088865/6309">introduced with Git 2.22 (Q2 2019)</a>.</p>
<hr />
<p>EDIT: you will need to use <code>git push --force</code></p>
<hr />
<p><a href="https://stackoverflow.com/users/1466235/karlotcha-hoa">Karlotcha Hoa</a> adds in <a href="https://stackoverflow.com/questions/25356810/git-how-to-squash-all-commits-on-branch/25357146?noredirect=1#comment90323165_25357146">the comments</a>:</p>
<blockquote>
<p>For the reset, you can do</p>
<pre><code>git reset $(git merge-base master $(git rev-parse --abbrev-ref HEAD))
</code></pre>
<p>[That] automatically uses the branch you are currently on.<br />
And if you use that, <strong>you can also use an alias, as the command doesn't rely on the branch name</strong>.</p>
</blockquote>
<hr />
<p><a href="https://stackoverflow.com/users/4319676/sschoof">sschoof</a> adds in <a href="https://stackoverflow.com/questions/25356810/git-how-to-squash-all-commits-on-branch/25357146#comment125966782_25357146">the comments</a>:</p>
<blockquote>
<p>Since my default branch is called <code>main</code> and my search had multi times brought me here:<br />
To copy it for my next time</p>
<pre><code>git reset $(git merge-base main $(git rev-parse --abbrev-ref HEAD))
</code></pre>
</blockquote> | {
"question_id": 25356810,
"question_date": "2014-08-18T05:25:39.520Z",
"question_score": 700,
"tags": "git|version-control",
"answer_id": 25357146,
"answer_date": "2014-08-18T05:59:47.643Z",
"answer_score": 881
} |
Please answer the following Stack Overflow question:
Title: Cocoa Autolayout: content hugging vs content compression resistance priority
<p>I can't find a clear answer on Apple documentation regarding Cocoa Autolayout about the difference between content hugging and compression resistance. </p>
<p>Can somebody explain their usages and difference ? </p> | <p>A quick summary of the concepts:</p>
<ul>
<li>Hugging => content does not want to grow</li>
<li>Compression Resistance => content does not want to shrink</li>
</ul>
<p>Example:</p>
<p>Say you've got a button like this:</p>
<pre><code>[ Click Me ]
</code></pre>
<p>and you've pinned the edges to a larger superview with priority 500.</p>
<p>Then, if Hugging priority > 500 it'll look like this:</p>
<pre><code>[Click Me]
</code></pre>
<p>If Hugging priority < 500 it'll look like this:</p>
<pre><code>[ Click Me ]
</code></pre>
<p>If the superview now shrinks then, if the Compression Resistance priority > 500, it'll look like this</p>
<pre><code>[Click Me]
</code></pre>
<p>Else if Compression Resistance priority < 500, it could look like this:</p>
<pre><code>[Cli..]
</code></pre>
<p>If it doesn't work like this then you've probably got some other constraints going on that are messing up your good work!</p>
<p>E.g. you could have it pinned to the superview with priority 1000.
Or you could have a width priority. If so, this can be helpful:</p>
<p>Editor > Size to Fit Content</p> | {
"question_id": 15850417,
"question_date": "2013-04-06T11:34:44.553Z",
"question_score": 700,
"tags": "cocoa|autolayout",
"answer_id": 16281229,
"answer_date": "2013-04-29T14:29:25.980Z",
"answer_score": 1383
} |
Please answer the following Stack Overflow question:
Title: JavaScript window resize event
<p>How can I hook into a browser window resize event?</p>
<p>There's <a href="https://stackoverflow.com/questions/599288/cross-browser-window-resize-event-javascript-jquery">a jQuery way of listening for resize events</a> but I would prefer not to bring it into my project for just this one requirement.</p> | <p>Best practice is to attach to the resize event.</p>
<pre class="lang-js prettyprint-override"><code>window.addEventListener('resize', function(event) {
...
}, true);
</code></pre>
<p>jQuery is just wrapping the standard <code>resize</code> DOM event, eg.</p>
<pre class="lang-js prettyprint-override"><code>window.onresize = function(event) {
...
};
</code></pre>
<p>jQuery <em>may</em> do some work to ensure that the resize event gets fired consistently in all browsers, but I'm not sure if any of the browsers differ, but I'd encourage you to test in Firefox, Safari, and IE.</p> | {
"question_id": 641857,
"question_date": "2009-03-13T08:50:23.120Z",
"question_score": 699,
"tags": "javascript|window-resize",
"answer_id": 641874,
"answer_date": "2009-03-13T08:58:05.363Z",
"answer_score": 744
} |
Please answer the following Stack Overflow question:
Title: How to start new activity on button click
<p>In an Android application, how do you start a new activity (GUI) when a button in another activity is clicked, and how do you pass data between these two activities?</p> | <p>Easy.</p>
<pre><code>Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
</code></pre>
<p>Extras are retrieved on the other side via:</p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.
}
</code></pre>
<p>Don't forget to add your new activity in the AndroidManifest.xml:</p>
<pre><code><activity android:label="@string/app_name" android:name="NextActivity"/>
</code></pre> | {
"question_id": 4186021,
"question_date": "2010-11-15T15:43:36.590Z",
"question_score": 699,
"tags": "android|android-intent|android-activity|android-button|android-lifecycle",
"answer_id": 4186097,
"answer_date": "2010-11-15T15:51:23.870Z",
"answer_score": 1247
} |
Please answer the following Stack Overflow question:
Title: Targeting only Firefox with CSS
<p>Using conditional comments it is easy to target Internet Explorer with browser-specific CSS rules:</p>
<pre><code><!--[if IE 6]>
...include IE6-specific stylesheet here...
<![endif]-->
</code></pre>
<p>Sometimes it is the Gecko engine (Firefox) that misbehaves. <strong>What would be best way to target only Firefox with your CSS rules and not a single other browser?</strong> That is, not only should Internet Explorer ignore the Firefox-only rules, but also WebKit and Opera should.</p>
<p><strong>Note:</strong> I'm looking for a 'clean' solution. Using a JavaScript browser sniffer to add a 'firefox' class to my HTML does not qualify as clean in my opinion. I would rather like to see something that depends on browser capabilities, much like conditional comments are only 'special' to IE…</p> | <p>OK, I've found it. This is probably the cleanest and easiest solution out there and does not rely on JavaScript being turned on.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>@-moz-document url-prefix() {
h1 {
color: red;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>This should be red in FF</h1></code></pre>
</div>
</div>
</p>
<p>It's based on yet another Mozilla specific CSS extension. There's a whole list for these CSS extensions right here: <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Mozilla_Extensions" rel="noreferrer">Mozilla CSS Extensions</a>.</p> | {
"question_id": 952861,
"question_date": "2009-06-04T20:19:09.543Z",
"question_score": 699,
"tags": "css|firefox|css-hack",
"answer_id": 953491,
"answer_date": "2009-06-04T22:43:32.870Z",
"answer_score": 1398
} |
Please answer the following Stack Overflow question:
Title: Set ImageView width and height programmatically?
<p>How can I set an <code>ImageView</code>'s width and height programmatically?</p> | <p>It may be too late but for the sake of others who have the same problem, to set the height of the <code>ImageView</code>:</p>
<pre><code>imageView.getLayoutParams().height = 20;
</code></pre>
<p><strong>Important.</strong> If you're setting the height after the layout has already been 'laid out', make sure you also call:</p>
<pre><code>imageView.requestLayout();
</code></pre> | {
"question_id": 3144940,
"question_date": "2010-06-29T21:36:28.527Z",
"question_score": 699,
"tags": "java|android|android-emulator|android-widget",
"answer_id": 5257851,
"answer_date": "2011-03-10T09:45:10.353Z",
"answer_score": 1215
} |
Please answer the following Stack Overflow question:
Title: Preloading images with jQuery
<p>I'm looking for a quick and easy way to preload images with JavaScript. I'm using jQuery if that's important.</p>
<p>I saw this here (<a href="http://nettuts.com/tutorials/javascript-ajax/the-definitive-guide-to-creating-a-practical-jquery-plugin/" rel="noreferrer">http://nettuts.com...</a>):</p>
<pre><code>function complexLoad(config, fileNames) {
for (var x = 0; x < fileNames.length; x++) {
$("<img>").attr({
id: fileNames[x],
src: config.imgDir + fileNames[x] + config.imgFormat,
title: "The " + fileNames[x] + " nebula"
}).appendTo("#" + config.imgContainer).css({ display: "none" });
}
};
</code></pre>
<p>But, it looks a bit over-the-top for what I want!</p>
<p>I know there are jQuery plugins out there that do this but they all seem a bit big (in size); I just need a quick, easy and short way of preloading images!</p> | <p>Quick <em>and</em> easy:</p>
<pre><code>function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);
</code></pre>
<p>Or, if you want a jQuery plugin:</p>
<pre><code>$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
$(['img1.jpg','img2.jpg','img3.jpg']).preload();
</code></pre> | {
"question_id": 476679,
"question_date": "2009-01-24T21:25:54.747Z",
"question_score": 699,
"tags": "javascript|jquery",
"answer_id": 476681,
"answer_date": "2009-01-24T21:28:26.537Z",
"answer_score": 979
} |
Please answer the following Stack Overflow question:
Title: How do I create a new Git branch from an old commit?
<blockquote>
<p><strong>Possible Duplicate / a more recent/less clear question</strong> <br/>
<a href="http://stackoverflow.com/questions/2816715/branch-from-a-previous-commit-using-git">Branch from a previous commit using Git</a></p>
</blockquote>
<p>I have a Git branch called <code>jzbranch</code> and have an old commit id: <code>a9c146a09505837ec03b</code>.</p>
<p>How do I create a new branch, <code>justin</code>, from the information listed above?</p> | <pre><code>git checkout -b NEW_BRANCH_NAME COMMIT_ID
</code></pre>
<p>This will create a new branch called 'NEW_BRANCH_NAME' and check it out.</p>
<p>("check out" means "to switch to the branch")</p>
<pre><code>git branch NEW_BRANCH_NAME COMMIT_ID
</code></pre>
<p>This just creates the new branch without checking it out.</p>
<hr />
<p><a href="https://stackoverflow.com/questions/7167645/how-do-i-create-a-new-git-branch-from-an-old-commit#comment39807482_7167659">in the comments many people seem to prefer doing this in two steps</a>. here's how to do so in two steps:</p>
<pre><code>git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
</code></pre> | {
"question_id": 7167645,
"question_date": "2011-08-23T21:15:40.080Z",
"question_score": 699,
"tags": "git|branch|commit",
"answer_id": 7167659,
"answer_date": "2011-08-23T21:16:44.453Z",
"answer_score": 1248
} |
Please answer the following Stack Overflow question:
Title: How do I see which version of Swift I'm using?
<p>I just created a new Swift project within Xcode. I am wondering which version of Swift it's using. </p>
<p>How can I see, in Xcode or the terminal, what version of Swift I am using inside my project?</p> | <p>Project build settings have a block 'Swift Compiler - Languages', which stores information about Swift Language Version in key-value format. It will show you all available (supported) Swift Language Version for your Xcode and active version also by a tick mark.</p>
<blockquote>
<p>Project ► (Select Your Project Target) ► Build Settings ► (Type
'swift_version' in the Search bar) Swift Compiler Language ► Swift Language
Version ► Click on Language list to open it (and there will be a tick mark on any one of list-item, that will be current swift version).</p>
</blockquote>
<p>Look at this snapshot, for easy understanding:</p>
<p><a href="https://i.stack.imgur.com/gKkGp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gKkGp.png" alt="xcode with described areas highlighted" /></a></p>
<hr />
<p>With help of following code, programmatically you can find Swift version supported by your project.</p>
<pre><code>#if swift(>=5.7)
print("Hello, Swift 5.7")
#elseif swift(>=5.6)
print("Hello, Swift 5.6")
#elseif swift(>=5.5)
print("Hello, Swift 5.5")
#elseif swift(>=5.4)
print("Hello, Swift 5.4")
#elseif swift(>=5.3)
print("Hello, Swift 5.3")
#elseif swift(>=5.2)
print("Hello, Swift 5.2")
#elseif swift(>=5.1)
print("Hello, Swift 5.1")
#elseif swift(>=5.0)
print("Hello, Swift 5.0")
#elseif swift(>=4.2)
print("Hello, Swift 4.2")
#elseif swift(>=4.1)
print("Hello, Swift 4.1")
#elseif swift(>=4.0)
print("Hello, Swift 4.0")
#elseif swift(>=3.2)
print("Hello, Swift 3.2")
#elseif swift(>=3.0)
print("Hello, Swift 3.0")
#elseif swift(>=2.2)
print("Hello, Swift 2.2")
#elseif swift(>=2.1)
print("Hello, Swift 2.1")
#elseif swift(>=2.0)
print("Hello, Swift 2.0")
#elseif swift(>=1.2)
print("Hello, Swift 1.2")
#elseif swift(>=1.1)
print("Hello, Swift 1.1")
#elseif swift(>=1.0)
print("Hello, Swift 1.0")
#endif
</code></pre>
<p>Here is result using Playground (with <a href="https://stackoverflow.com/questions/44390162/download-install-xcode-10-version-without-premium-developer-account?noredirect=1&lq=1">Xcode 11.x</a>)</p>
<p><a href="https://i.stack.imgur.com/pNCnC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pNCnC.png" alt="enter image description here" /></a></p> | {
"question_id": 30790188,
"question_date": "2015-06-11T19:52:21.977Z",
"question_score": 699,
"tags": "swift|xcode|terminal",
"answer_id": 46080904,
"answer_date": "2017-09-06T17:10:55.620Z",
"answer_score": 550
} |
Please answer the following Stack Overflow question:
Title: Authentication versus Authorization
<p>What's the difference in context of web applications? I see the abbreviation "auth" a lot. Does it stand for <strong>auth</strong>-entication or <strong>auth</strong>-orization? Or is it both?</p> | <blockquote>
<p><strong>Authentication</strong> is the process of ascertaining that somebody really is who they claim to be.</p>
<p><strong>Authorization</strong> refers to rules that determine who is allowed to do what. E.g. Adam may be authorized to create and delete databases,
while Usama is only authorised to read.</p>
</blockquote>
<p>The two concepts are completely orthogonal and independent, but <em>both</em> are central to security design, and the failure to get either one correct opens up the avenue to compromise.</p>
<p>In terms of web apps, very crudely speaking, authentication is when you check login credentials to see if you recognize a user as logged in, and authorization is when you look up in your access control whether you allow the user to view, edit, delete or create content.</p> | {
"question_id": 6556522,
"question_date": "2011-07-02T10:44:19.630Z",
"question_score": 699,
"tags": "security|authorization|authentication",
"answer_id": 6556548,
"answer_date": "2011-07-02T10:49:55.043Z",
"answer_score": 935
} |
Please answer the following Stack Overflow question:
Title: Divide a number by 3 without using *, /, +, -, % operators
<p>How would you divide a number by 3 without using <code>*</code>, <code>/</code>, <code>+</code>, <code>-</code>, <code>%</code>, operators?</p>
<p>The number may be signed or unsigned.</p> | <p>This is a <a href="http://web.archive.org/web/20121103111129/http://forums.hscripts.com/viewtopic.php?f=13&t=1358" rel="noreferrer">simple function</a> which performs the desired operation. But it requires the <code>+</code> operator, so all you have left to do is to add the values with bit-operators:</p>
<pre><code>// replaces the + operator
int add(int x, int y)
{
while (x) {
int t = (x & y) << 1;
y ^= x;
x = t;
}
return y;
}
int divideby3(int num)
{
int sum = 0;
while (num > 3) {
sum = add(num >> 2, sum);
num = add(num >> 2, num & 3);
}
if (num == 3)
sum = add(sum, 1);
return sum;
}
</code></pre>
<p>As Jim commented this works, because:</p>
<ul>
<li><code>n = 4 * a + b</code></li>
<li><code>n / 3 = a + (a + b) / 3</code> </li>
<li><p>So <code>sum += a</code>, <code>n = a + b</code>, and iterate </p></li>
<li><p>When <code>a == 0 (n < 4)</code>, <code>sum += floor(n / 3);</code> i.e. 1, <code>if n == 3, else 0</code></p></li>
</ul> | {
"question_id": 11694546,
"question_date": "2012-07-27T19:34:31.463Z",
"question_score": 699,
"tags": "c|math|division|divide",
"answer_id": 11694778,
"answer_date": "2012-07-27T19:51:47.083Z",
"answer_score": 553
} |
Please answer the following Stack Overflow question:
Title: Java: convert List<String> to a join()d String
<p>JavaScript has <code>Array.join()</code></p>
<pre><code>js>["Bill","Bob","Steve"].join(" and ")
Bill and Bob and Steve
</code></pre>
<p>Does Java have anything like this? I know I can cobble something up myself with <code>StringBuilder</code>:</p>
<pre><code>static public String join(List<String> list, String conjunction)
{
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String item : list)
{
if (first)
first = false;
else
sb.append(conjunction);
sb.append(item);
}
return sb.toString();
}
</code></pre>
<p>.. but there's no point in doing this if something like it is already part of the JDK.</p> | <h1><code>String.join</code></h1>
<p>With Java 8 you can do this without any third party library.</p>
<p>If you want to join a Collection of Strings you can use the <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-" rel="noreferrer"><code>String.join</code>()</a> method:</p>
<pre><code>List<String> list = Arrays.asList("foo", "bar", "baz");
String joined = String.join(" and ", list); // "foo and bar and baz"
</code></pre>
<h1><code>Collectors.joining</code></h1>
<p>If you have a Collection with another type than String you can use the Stream API with the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#joining-java.lang.CharSequence-" rel="noreferrer">joining Collector</a>:</p>
<pre><code>List<Person> list = Arrays.asList(
new Person("John", "Smith"),
new Person("Anna", "Martinez"),
new Person("Paul", "Watson ")
);
String joinedFirstNames = list.stream()
.map(Person::getFirstName)
.collect(Collectors.joining(", ")); // "John, Anna, Paul"
</code></pre>
<p>The <a href="http://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html" rel="noreferrer"><code>StringJoiner</code></a> class may also be useful.</p> | {
"question_id": 1751844,
"question_date": "2009-11-17T21:15:14.877Z",
"question_score": 698,
"tags": "java|string|list",
"answer_id": 22577565,
"answer_date": "2014-03-22T12:25:00.897Z",
"answer_score": 903
} |
Please answer the following Stack Overflow question:
Title: Find MongoDB records where array field is not empty
<p>All of my records have a field called "pictures". This field is an array of strings.</p>
<p>I now want the newest 10 records where this array IS NOT empty.</p>
<p>I've googled around, but strangely enough I haven't found much on this.
I've read into the $where option, but I was wondering how slow that is to native functions, and if there is a better solution.</p>
<p>And even then, that does not work:</p>
<pre class="lang-js prettyprint-override"><code>ME.find({$where: 'this.pictures.length > 0'}).sort('-created').limit(10).execFind()
</code></pre>
<p>Returns nothing. Leaving <code>this.pictures</code> without the length bit does work, but then it also returns empty records, of course.</p> | <p>If you also have documents that don't have the key, you can use:</p>
<pre><code>ME.find({ pictures: { $exists: true, $not: {$size: 0} } })
</code></pre>
<p>MongoDB doesn't use indexes if <code>$size</code> is involved, so here is a better solution:</p>
<pre><code>ME.find({ pictures: { $exists: true, $ne: [] } })
</code></pre>
<p>If your property can have invalid values (like <code>null</code> <code>boolean</code> or others) , then you an add an additional check <a href="https://docs.mongodb.com/manual/reference/operator/query/type/" rel="noreferrer">using <code>$types</code></a> as proposed <a href="https://stackoverflow.com/a/52465830/968799">in this answer</a>:</p>
<p>With mongo >= 3.2:</p>
<pre><code>ME.find({ pictures: { $exists: true, $type: 'array', $ne: [] } })
</code></pre>
<p>With mongo < 3.2:</p>
<pre><code>ME.find({ pictures: { $exists: true, $type: 4, $ne: [] } })
</code></pre>
<p>Since the MongoDB 2.6 release, you can compare with the operator <code>$gt</code>, but this could lead to unexpected results (you can find a detailed explanation <a href="https://stackoverflow.com/questions/14789684/find-mongodb-records-where-array-field-is-not-empty/42601244#42601244">in this answer</a>):</p>
<pre><code>ME.find({ pictures: { $gt: [] } })
</code></pre> | {
"question_id": 14789684,
"question_date": "2013-02-09T15:39:06.643Z",
"question_score": 698,
"tags": "mongodb|mongoose",
"answer_id": 25142571,
"answer_date": "2014-08-05T15:24:27.547Z",
"answer_score": 1217
} |
Please answer the following Stack Overflow question:
Title: How to add screenshot to READMEs in github repository?
<p>Is it possible to place a screenshot in README file in a GitHub repository? What's the syntax?</p> | <p>If you use Markdown (README.md):</p>
<p>Provided that you have the image in your repo, you can use a relative URL: </p>
<pre><code>
</code></pre>
<p>If you need to embed an image that's hosted elsewhere, you can use a full URL</p>
<pre><code>
</code></pre>
<p>GitHub recommend that you use <strong>relative links</strong> with the <code>?raw=true</code> parameter to ensure forked repos point correctly.</p>
<p>The <code>raw=true</code> parameter is there in order to ensure the image you link to, will be rendered as is. That means that only the image will be linked to, not the whole GitHub interface for that respective file. See <a href="https://stackoverflow.com/questions/10189356/how-to-add-screenshot-to-readmes-in-github-repository/10189374?noredirect=1#comment94874283_10189374">this comment</a> for more details.</p>
<p>Check out an example: <a href="https://raw.github.com/altercation/solarized/master/README.md" rel="noreferrer">https://raw.github.com/altercation/solarized/master/README.md</a></p>
<p>If you use SVGs then you'll need to set the sanitize attribute to <code>true</code> as well: <code>?raw=true&sanitize=true</code>. (Thanks @EliSherer)</p>
<p>Also, the documentation on relative links in README files: <a href="https://help.github.com/articles/relative-links-in-readmes" rel="noreferrer">https://help.github.com/articles/relative-links-in-readmes</a></p>
<p>And of course the markdown docs: <a href="http://daringfireball.net/projects/markdown/syntax" rel="noreferrer">http://daringfireball.net/projects/markdown/syntax</a></p>
<p>Additionally, if you create a new branch <code>screenshots</code> to store the images you can avoid them being in the <code>master</code> working tree</p>
<p>You can then embed them using:</p>
<pre><code>
</code></pre> | {
"question_id": 10189356,
"question_date": "2012-04-17T10:20:27.427Z",
"question_score": 698,
"tags": "github|markdown",
"answer_id": 10189374,
"answer_date": "2012-04-17T10:22:08.547Z",
"answer_score": 963
} |
Please answer the following Stack Overflow question:
Title: Difference of keywords 'typename' and 'class' in templates?
<p>For templates I have seen both declarations:</p>
<pre><code>template < typename T >
template < class T >
</code></pre>
<p>What's the difference? </p>
<p>And what exactly do those keywords mean in the following example (taken from the German Wikipedia article about templates)?</p>
<pre><code>template < template < typename, typename > class Container, typename Type >
class Example
{
Container< Type, std::allocator < Type > > baz;
};
</code></pre> | <p><code>typename</code> and <code>class</code> are interchangeable in the basic case of specifying a template:</p>
<pre><code>template<class T>
class Foo
{
};
</code></pre>
<p>and</p>
<pre><code>template<typename T>
class Foo
{
};
</code></pre>
<p>are equivalent.</p>
<p>Having said that, there are specific cases where there is a difference between <code>typename</code> and <code>class</code>.</p>
<p>The first one is in the case of dependent types. <code>typename</code> is used to declare when you are referencing a nested type that depends on another template parameter, such as the <code>typedef</code> in this example:</p>
<pre><code>template<typename param_t>
class Foo
{
typedef typename param_t::baz sub_t;
};
</code></pre>
<p>The second one you actually show in your question, though you might not realize it:</p>
<pre><code>template < template < typename, typename > class Container, typename Type >
</code></pre>
<p>When specifying a <strong>template template</strong>, the <code>class</code> keyword MUST be used as above -- it is <strong>not</strong> interchangeable with <code>typename</code> in this case <em>(note: since C++17 both keywords are allowed in this case)</em>.</p>
<p>You also must use <code>class</code> when explicitly instantiating a template:</p>
<pre><code>template class Foo<int>;
</code></pre>
<p>I'm sure that there are other cases that I've missed, but the bottom line is: these two keywords are not equivalent, and these are some common cases where you need to use one or the other.</p> | {
"question_id": 2023977,
"question_date": "2010-01-07T21:59:41.047Z",
"question_score": 698,
"tags": "c++|templates|keyword",
"answer_id": 2024173,
"answer_date": "2010-01-07T22:30:34.170Z",
"answer_score": 574
} |
Please answer the following Stack Overflow question:
Title: Convert list to array in Java
<p>How can I convert a <code>List</code> to an <code>Array</code> in Java?</p>
<p>Check the code below:</p>
<pre><code>ArrayList<Tienda> tiendas;
List<Tienda> tiendasList;
tiendas = new ArrayList<Tienda>();
Resources res = this.getBaseContext().getResources();
XMLParser saxparser = new XMLParser(marca,res);
tiendasList = saxparser.parse(marca,res);
tiendas = tiendasList.toArray();
this.adaptador = new adaptadorMarca(this, R.layout.filamarca, tiendas);
setListAdapter(this.adaptador);
</code></pre>
<p>I need to populate the array <code>tiendas</code> with the values of <code>tiendasList</code>.</p> | <p>Either:</p>
<pre><code>Foo[] array = list.toArray(new Foo[0]);
</code></pre>
<p>or:</p>
<pre><code>Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array
</code></pre>
<hr>
<p>Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way:</p>
<pre><code>List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);
</code></pre>
<hr>
<h2>Update:</h2>
<p>It is recommended now to use <code>list.toArray(new Foo[0]);</code>, not <code>list.toArray(new Foo[list.size()]);</code>.</p>
<p><em>From JetBrains Intellij Idea inspection:</em></p>
<blockquote>
<p>There are two styles to convert a collection to an array: either using
a pre-sized array (like <b>c.toArray(new String[c.size()])</b>) or
using an empty array (like <b>c.toArray(new String[0])</b>. <p> In
older Java versions using pre-sized array was recommended, as the
reflection call which is necessary to create an array of proper size
was quite slow. However since late updates of OpenJDK 6 this call
was intrinsified, making the performance of the empty array version
the same and sometimes even better, compared to the pre-sized
version. Also passing pre-sized array is dangerous for a concurrent or
synchronized collection as a data race is possible between the
<b>size</b> and <b>toArray</b> call which may result in extra nulls
at the end of the array, if the collection was concurrently shrunk
during the operation. </p> <p> This inspection allows to follow the
uniform style: either using an empty array (which is recommended in
modern Java) or using a pre-sized array (which might be faster in
older Java versions or non-HotSpot based JVMs). </p></p>
</blockquote> | {
"question_id": 9572795,
"question_date": "2012-03-05T19:37:28.803Z",
"question_score": 697,
"tags": "java|arrays|list|arraylist",
"answer_id": 9572820,
"answer_date": "2012-03-05T19:39:39.307Z",
"answer_score": 1364
} |
Please answer the following Stack Overflow question:
Title: Read whole ASCII file into C++ std::string
<p>I need to read a whole file into memory and place it in a C++ <code>std::string</code>.</p>
<p>If I were to read it into a <code>char[]</code>, the answer would be very simple:</p>
<pre><code>std::ifstream t;
int length;
t.open("file.txt"); // open input file
t.seekg(0, std::ios::end); // go to the end
length = t.tellg(); // report location (this is the length)
t.seekg(0, std::ios::beg); // go back to the beginning
buffer = new char[length]; // allocate memory for a buffer of appropriate dimension
t.read(buffer, length); // read the whole file into the buffer
t.close(); // close file handle
// ... Do stuff with buffer here ...
</code></pre>
<p>Now, I want to do the exact same thing, but using a <code>std::string</code> instead of a <code>char[]</code>. I want to avoid loops, i.e. I <strong>don't</strong> want to:</p>
<pre><code>std::ifstream t;
t.open("file.txt");
std::string buffer;
std::string line;
while(t){
std::getline(t, line);
// ... Append line to buffer and go on
}
t.close()
</code></pre>
<p>Any ideas?</p> | <p><strong>Update:</strong> Turns out that this method, while following STL idioms well, is actually surprisingly inefficient! Don't do this with large files. (See: <a href="http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html" rel="noreferrer">http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html</a>)</p>
<p>You can make a streambuf iterator out of the file and initialize the string with it:</p>
<pre><code>#include <string>
#include <fstream>
#include <streambuf>
std::ifstream t("file.txt");
std::string str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
</code></pre>
<p>Not sure where you're getting the <code>t.open("file.txt", "r")</code> syntax from. As far as I know that's not a method that <code>std::ifstream</code> has. It looks like you've confused it with C's <code>fopen</code>.</p>
<p><strong>Edit:</strong> Also note the extra parentheses around the first argument to the string constructor. <em>These are essential</em>. They prevent the problem known as the "<a href="http://web.archive.org/web/20110426155617/http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=439" rel="noreferrer">most vexing parse</a>", which in this case won't actually give you a compile error like it usually does, but will give you interesting (read: wrong) results.</p>
<p>Following KeithB's point in the comments, here's a way to do it that allocates all the memory up front (rather than relying on the string class's automatic reallocation):</p>
<pre><code>#include <string>
#include <fstream>
#include <streambuf>
std::ifstream t("file.txt");
std::string str;
t.seekg(0, std::ios::end);
str.reserve(t.tellg());
t.seekg(0, std::ios::beg);
str.assign((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
</code></pre> | {
"question_id": 2602013,
"question_date": "2010-04-08T17:19:49.340Z",
"question_score": 697,
"tags": "c++|string|caching|file-io|standard-library",
"answer_id": 2602060,
"answer_date": "2010-04-08T17:23:38.680Z",
"answer_score": 597
} |
Please answer the following Stack Overflow question:
Title: What's the best way to convert a number to a string in JavaScript?
<p>What's the "best" way to convert a number to a string (in terms of speed advantage, clarity advantage, memory advantage, etc) ?</p>
<p>Some examples:</p>
<ol>
<li><p><code>String(n)</code></p></li>
<li><p><code>n.toString()</code></p></li>
<li><p><code>""+n</code></p></li>
<li><p><code>n+""</code></p></li>
</ol> | <p>like this:</p>
<pre><code>var foo = 45;
var bar = '' + foo;
</code></pre>
<p>Actually, even though I typically do it like this for simple convenience, over 1,000s of iterations it appears <strong>for raw speed there is an advantage for <code>.toString()</code></strong></p>
<p>See Performance tests here (not by me, but found when I went to write my own):
<a href="http://jsben.ch/#/ghQYR">http://jsben.ch/#/ghQYR</a></p>
<p>Fastest based on the JSPerf test above: <code>str = num.toString();</code></p>
<p><em>It should be noted</em> that the difference in speed is not overly significant when you consider that it can do the conversion any way <strong>1 Million times in 0.1 seconds</strong>.</p>
<p><strong>Update:</strong> The speed seems to differ greatly by browser. In Chrome <code>num + ''</code> seems to be fastest based on this test <a href="http://jsben.ch/#/ghQYR">http://jsben.ch/#/ghQYR</a></p>
<p><strong>Update 2:</strong> Again based on my test above it should be noted that Firefox 20.0.1 executes the <code>.toString()</code> about 100 times slower than the <code>'' + num</code> sample.</p> | {
"question_id": 5765398,
"question_date": "2011-04-23T16:25:32.643Z",
"question_score": 697,
"tags": "javascript|string|performance|coding-style|numbers",
"answer_id": 5765401,
"answer_date": "2011-04-23T16:26:47.850Z",
"answer_score": 696
} |
Please answer the following Stack Overflow question:
Title: Various ways to remove local Git changes
<p>I just cloned a git repository and checked out a branch. I worked on it, and then decided to remove all my local changes, as I wanted the original copy.</p>
<p>In short, I had to do the following two commands to remove my local changes</p>
<pre><code>git checkout .
git clean -f
</code></pre>
<p><strong>My question is,</strong></p>
<p>(1) Is this the correct approach in getting rid of local changes, or else please let me know the correct approach.</p>
<p>(2) when do we use <code>git reset --hard</code> as i am able to reset even without this command</p>
<p>Thanks</p>
<p><strong>*Solution : Major Edit(s): 03/26 : *</strong>
Replaced many of vague terms with git specific terminology
[tracked/untracked/staged/unstaged]</p>
<p>There could be only three categories of files when we make local changes:</p>
<blockquote>
<p>Type 1. Staged Tracked files</p>
<p>Type 2. Unstaged Tracked files</p>
<p>Type 3. Unstaged UnTracked files a.k.a UnTracked files</p>
</blockquote>
<ul>
<li>Staged - Those that are moved to staging area/ Added to index</li>
<li>Tracked - modified files</li>
<li>UnTracked - new files. Always unstaged. If staged, that means they are tracked.</li>
</ul>
<p><strong>What each commands do:</strong></p>
<ol>
<li><p><code>git checkout .</code> - Removes Unstaged Tracked files ONLY [Type 2]</p></li>
<li><p><code>git clean -f</code> - Removes Unstaged UnTracked files ONLY [Type 3]</p></li>
<li><p><code>git reset --hard</code> - Removes Staged Tracked and UnStaged Tracked files ONLY[Type 1, Type 2]</p></li>
<li><p><code>git stash -u</code> - Removes all changes [Type 1, Type 2, Type 3]</p></li>
</ol>
<p><strong>Conclusion:</strong></p>
<p>It's clear that we can use either </p>
<pre><code>(1) combination of `git clean -f` and `git reset --hard`
</code></pre>
<p>OR</p>
<pre><code>(2) `git stash -u`
</code></pre>
<p>to achieve the desired result.</p>
<p>Note: Stashing, as the word means 'Store (something) safely and secretly in a specified place.' This can always be retrieved using <code>git stash pop</code>.
So choosing between the above two options is developer's call.</p>
<p>Thank you Christoph and Frederik Schøning.</p>
<p><strong>Edit: 03/27</strong></p>
<p>I thought it's worth putting the '<em>beware</em>' note to <code>git clean -f</code></p>
<p><code>git clean -f</code></p>
<p>There is no going back. Use <code>-n</code> or <code>--dry-run</code> to preview the damage you'll do.</p>
<p>If you want to also remove directories, run <code>git clean -f -d</code></p>
<p>If you just want to remove ignored files, run <code>git clean -f -X</code></p>
<p>If you want to remove ignored as well as non-ignored files, run <code>git clean -f -x</code></p>
<p>reference : more on <code>git clean</code> : <a href="https://stackoverflow.com/questions/61212/removing-untracked-files-from-your-git-working-copy?rq=1">How to remove local (untracked) files from the current Git working tree?</a></p>
<p><strong>Edit: 05/20/15</strong></p>
<p><em>Discarding all local commits on this branch</em> [Removing local commits]</p>
<p>In order to discard all local commits on this branch, to make the local branch identical
to the "upstream" of this branch, simply run <code>git reset --hard @{u}</code></p>
<p>Reference: <a href="http://sethrobertson.github.io/GitFixUm/fixup.html" rel="noreferrer">http://sethrobertson.github.io/GitFixUm/fixup.html</a></p>
<p>or do <code>git reset --hard origin/master</code> [if local branch is <code>master</code>]</p>
<p><strong>Note: 06/12/2015</strong>
This is <strong>not</strong> a duplicate of the other SO question that's marked as duplicate. This question address how to remove local GIT changes [remove a file added, remove changes added to existing file etc and the various approaches; Where in the other SO thread only address how to remove local commit. If you added a file, and you want to remove that alone, then the other SO thread doesn't discuss about it. Hence this is not a duplicate of the other one]</p>
<p><strong>Edit: 06/23/15</strong></p>
<p>How to revert a commit already pushed to a remote repository?</p>
<pre><code>$ git revert ab12cd15
</code></pre>
<p><strong>Edit: 09/01/2015</strong></p>
<p>Delete a previous commit from local branch and remote branch</p>
<p>Case: You just commited a change to your local branch and immediately pushed to the remote branch,
Suddenly realized , Oh no! I dont need this change. Now do what?</p>
<p><code>git reset --hard HEAD~1</code> [for deleting that commit from local branch]</p>
<p><code>git push origin HEAD --force</code> [both the commands must be executed. For deleting from remote branch]</p>
<p>Whats the branch ? Its the currently checked out branch.</p>
<p><strong>Edit 09/08/2015</strong> - Remove local git <strong>merge</strong>:</p>
<p>I am on <code>master</code> branch and merged <code>master</code> branch with a newly working branch <code>phase2</code></p>
<pre><code>$ git status
# On branch master
$ git merge phase2
$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 8 commits.
</code></pre>
<p>Q: How to get rid of this merge?
Tried <code>git reset --hard</code> and <code>git clean -d -f</code>
Both didn't work.</p>
<p>The only thing that <strong>worked</strong> are any of the below ones:</p>
<pre><code>$ git reset --hard origin/master
</code></pre>
<p>or</p>
<pre><code>$ git reset --hard HEAD~8
</code></pre>
<p>or</p>
<p><code>$ git reset --hard 9a88396f51e2a068bb7</code> [sha commit code - this is the one that was present before all your merge commits happened]</p> | <p>It all depends on exactly what you are trying to undo/revert. Start out by reading <a href="https://stackoverflow.com/questions/1146973/how-do-i-revert-all-local-changes-in-a-git-managed-project-to-previous-state">the post in Ube's link</a>. But to attempt an answer:</p>
<p><strong>Hard reset</strong></p>
<pre><code>git reset --hard [HEAD]
</code></pre>
<p><em>completely remove all staged and unstaged changes to tracked files.</em></p>
<p>I find myself often using hard resetting, when I'm like "just undo everything like if I had done a complete re-clone from the remote". In your case, where you just want your repo pristine, this would work.</p>
<p><strong>Clean</strong></p>
<pre><code>git clean [-f]
</code></pre>
<p><em>Remove files that are not tracked.</em></p>
<p>For removing temporary files, but keep staged and unstaged changes to already tracked files. Most times, I would probably end up making an ignore-rule instead of repeatedly cleaning - e.g. for the bin/obj folders in a C# project, which you would usually want to exclude from your repo to save space, or something like that.</p>
<p>The -f (force) option will also remove files, that are not tracked <em>and</em> are also being ignored by git though ignore-rule. In the case above, with an ignore-rule to never track the bin/obj folders, even though these folders are being ignored by git, using the force-option will remove them from your file system. I've sporadically seen a use for this, e.g. when scripting deployment, and you want to clean your code before deploying, zipping or whatever.</p>
<p>Git clean will not touch files, that are already being tracked.</p>
<p><strong>Checkout "dot"</strong></p>
<pre><code>git checkout .
</code></pre>
<p>I had actually never seen this notation before reading your post. I'm having a hard time finding documentation for this (maybe someone can help), but from playing around a bit, it looks like it means:</p>
<p><em>"undo all changes in my working tree".</em></p>
<p>I.e. undo unstaged changes in tracked files. It apparently doesn't touch staged changes and leaves untracked files alone.</p>
<p><strong>Stashing</strong></p>
<p>Some answers mention stashing. As the wording implies, you would probably use stashing when you are in the middle of something (not ready for a commit), and you have to temporarily switch branches or somehow work on another state of your code, later to return to your "messy desk". I don't see this applies to your question, but it's definitely handy.</p>
<p><strong>To sum up</strong></p>
<p>Generally, if you are confident you have committed and maybe pushed to a remote important changes, if you are just playing around or the like, using <code>git reset --hard HEAD</code> followed by <code>git clean -f</code> will definitively cleanse your code to the state, it would be in, had it just been cloned and checked out from a branch. It's really important to emphasize, that the resetting will also remove staged, but uncommitted changes. <strong>It will wipe everything that has not been committed</strong> (except untracked files, in which case, use <em>clean</em>).</p>
<p>All the other commands are there to facilitate more complex scenarios, where a granularity of "undoing stuff" is needed :)</p>
<p>I feel, your question #1 is covered, but lastly, to conclude on #2: the reason you never found the need to use <code>git reset --hard</code> was that you had never staged anything. Had you staged a change, neither <code>git checkout .</code> nor <code>git clean -f</code> would have reverted that.</p>
<p>Hope this covers.</p> | {
"question_id": 22620393,
"question_date": "2014-03-24T20:54:39.417Z",
"question_score": 697,
"tags": "git|git-bash",
"answer_id": 22621464,
"answer_date": "2014-03-24T21:57:47.710Z",
"answer_score": 549
} |
Please answer the following Stack Overflow question:
Title: Learning to write a compiler
<p><em>Preferred languages</em>: C/C++, Java, and Ruby.</p>
<p>I am looking for some helpful books/tutorials on how to write your own compiler simply for educational purposes. I am most familiar with C/C++, Java, and Ruby, so I prefer resources that involve one of those three, but any good resource is acceptable.</p> | <h2>Big List of Resources:</h2>
<ul>
<li><a href="http://www.cs.indiana.edu/%7Edyb/pubs/nano-jfp.pdf" rel="noreferrer">A Nanopass Framework for Compiler Education</a> ¶</li>
<li><a href="http://www.amazon.com/gp/offer-listing/1558603204?tag=thecompilerconne&camp=14573&creative=327641&linkCode=am1&creativeASIN=1558603204&adid=1ZQWN5FGBA1JM6MNQ2ZV&" rel="noreferrer">Advanced Compiler Design and Implementation</a> $</li>
<li><a href="http://scheme2006.cs.uchicago.edu/11-ghuloum.pdf" rel="noreferrer">An Incremental Approach to Compiler Construction</a> ¶</li>
<li><a href="http://javadude.com/articles/antlr3xtut" rel="noreferrer">ANTLR 3.x Video Tutorial</a></li>
<li><a href="http://www.diku.dk/%7Etorbenm/Basics/" rel="noreferrer">Basics of Compiler Design</a></li>
<li><a href="http://web.archive.org/web/20160731061607/http://www.onlamp.com/pub/a/onlamp/2004/04/15/parrot_compiler_construction.html" rel="noreferrer">Building a Parrot Compiler</a></li>
<li><a href="http://www.cs.man.ac.uk/%7Epjj/farrell/compmain.html" rel="noreferrer">Compiler Basics</a></li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/0201403536" rel="noreferrer" rel="nofollow noreferrer">Compiler Construction</a> $</li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/0442275366" rel="noreferrer" rel="nofollow noreferrer">Compiler Design and Construction</a> $</li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/0805321667" rel="noreferrer" rel="nofollow noreferrer">Crafting a Compiler with C</a> $</li>
<li><a href="http://craftinginterpreters.com/" rel="noreferrer">Crafting Interpreters</a></li>
<li>[Compiler Design in C] <a href="http://www.holub.com/software/compiler.design.in.c.html" rel="noreferrer">12</a> ¶</li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/0321486811" rel="noreferrer" rel="nofollow noreferrer">Compilers: Principles, Techniques, and Tools</a> $ — aka <a href="http://en.wikipedia.org/wiki/Compilers:_Principles%2C_Techniques%2C_and_Tools" rel="noreferrer">"The Dragon Book"</a>; widely considered "the book" for compiler writing.</li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/012088478X" rel="noreferrer" rel="nofollow noreferrer">Engineering a Compiler</a> $</li>
<li><a href="http://www.cs.indiana.edu/eopl/" rel="noreferrer">Essentials of Programming Languages</a></li>
<li><a href="http://flipcode.com/archives/articles.shtml" rel="noreferrer">Flipcode Article Archive</a> (look for "Implementing A Scripting Engine by Jan Niestadt")</li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/1931841578" rel="noreferrer" rel="nofollow noreferrer">Game Scripting Mastery</a> $</li>
<li><a href="http://www.codeproject.com/KB/recipes/B32Machine1/VMCS.pdf" rel="noreferrer">How to build a virtual machine from scratch in C#</a> ¶</li>
<li><a href="http://research.microsoft.com/%7Esimonpj/papers/pj-lester-book/" rel="noreferrer">Implementing Functional Languages</a></li>
<li><a href="http://www1.digitalgrammars.com/ipl-book/" rel="noreferrer">Implementing Programming Languages (with BNFC)</a></li>
<li><a href="http://www.codeproject.com/KB/recipes/programminglanguagetoools.aspx" rel="noreferrer">Implementing Programming Languages using C# 4.0</a></li>
<li><a href="http://en.wikipedia.org/wiki/Interpreter_pattern" rel="noreferrer">Interpreter pattern</a> (described in <a href="https://rads.stackoverflow.com/amzn/click/com/0201633612" rel="noreferrer" rel="nofollow noreferrer">Design Patterns</a> $) specifies a way to evaluate sentences in a language</li>
<li><a href="http://pragprog.com/titles/tpdsl/language-implementation-patterns" rel="noreferrer">Language Implementation Patterns: Create Your Own Domain-Specific and General Programming Languages</a> $</li>
<li><a href="http://compilers.iecc.com/crenshaw/" rel="noreferrer">Let's Build a Compiler</a> by Jack Crenshaw — The <a href="http://www.stack.nl/%7Emarcov/compiler.pdf" rel="noreferrer">PDF</a> ¶ version (examples are in Pascal, but the information is generally applicable)</li>
<li><a href="http://books.google.com/books?id=Id9cYsIdjIwC&lpg=PP1&ots=IxFkFWJ-8V&dq=%22linkers%20and%20loaders%22&pg=PA215#v=onepage&q=%22linkers%20and%20loaders%22&f=false" rel="noreferrer">Linkers and Loaders</a> $ (Google Books)</li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/0521562473" rel="noreferrer" rel="nofollow noreferrer">Lisp in Small Pieces (LiSP)</a> $</li>
<li><a href="http://llvm.org/docs/tutorial/" rel="noreferrer">LLVM Tutorial</a></li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/0521607647" rel="noreferrer" rel="nofollow noreferrer">Modern Compiler Implementation in ML</a> $ — There is a <a href="https://rads.stackoverflow.com/amzn/click/com/052182060X" rel="noreferrer" rel="nofollow noreferrer">Java</a> $ and <a href="https://rads.stackoverflow.com/amzn/click/com/0521607655" rel="noreferrer" rel="nofollow noreferrer">C</a> $ version as well - widely considered a very good book</li>
<li><a href="http://www.amazon.com/gp/offer-listing/013630740X?tag=thecompilerconne&camp=14573&creative=327641&linkCode=am1&creativeASIN=013630740X&adid=0JPMVBRNCAN6PDKGYSXX&" rel="noreferrer">Object-Oriented Compiler Construction</a> $</li>
<li><a href="http://www.dickgrune.com/Books/PTAPG_1st_Edition/" rel="noreferrer">Parsing Techniques - A Practical Guide</a></li>
<li><a href="http://www-old.oberon.ethz.ch/WirthPubl/ProjectOberon.pdf" rel="noreferrer">Project Oberon</a> ¶ - Look at chapter 13</li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/0137302673" rel="noreferrer" rel="nofollow noreferrer">Programming a Personal Computer</a> $</li>
<li><a href="http://www.cs.brown.edu/%7Esk/Publications/Books/ProgLangs/" rel="noreferrer">Programing Languages: Application and Interpretation</a></li>
<li><a href="http://repository.readscheme.org/ftp/papers/ai-lab-pubs/AITR-474.pdf" rel="noreferrer">Rabbit: A Compiler for Scheme</a>¶</li>
<li><a href="http://web.archive.org/web/20141221110345/http://cm.bell-labs.com/who/ken/trust.html" rel="noreferrer">Reflections on Trusting Trust</a> — A quick guide</li>
<li><a href="http://msdn.microsoft.com/en-us/magazine/cc136756.aspx" rel="noreferrer">Roll Your Own Compiler for the .NET framework</a> — A quick tutorial from MSDN</li>
<li><a href="http://mitpress.mit.edu/sicp/" rel="noreferrer">Structure and Interpretation of Computer Programs</a></li>
<li><a href="http://www.cis.upenn.edu/%7Ebcpierce/tapl/" rel="noreferrer">Types and Programming Languages</a></li>
<li><a href="http://prog21.dadgum.com/30.html" rel="noreferrer">Want to Write a Compiler?</a> - a quick guide</li>
<li><a href="http://www.hokstad.com/writing-a-compiler-in-ruby-bottom-up-step-1.html" rel="noreferrer">Writing a Compiler in Ruby Bottom Up</a></li>
<li><a href="https://bernsteinbear.com/blog/compiling-a-lisp-0/" rel="noreferrer">Compiling a Lisp</a> — compile directly to x86-64</li>
</ul>
<p>Legend:</p>
<ul>
<li>¶ Link to a PDF file</li>
<li>$ Link to a printed book</li>
</ul> | {
"question_id": 1669,
"question_date": "2008-08-04T22:46:36.900Z",
"question_score": 697,
"tags": "compiler-construction|language-agnostic",
"answer_id": 1672,
"answer_date": "2008-08-04T22:52:00.650Z",
"answer_score": 1182
} |
Please answer the following Stack Overflow question:
Title: Get the current language in device
<p>How can we get the current language selected in the Android device?</p> | <p>If you want to get the selected language of your device, this might help you:</p>
<pre><code>Locale.getDefault().getDisplayLanguage();
</code></pre>
<p>You can use <code>Locale.getDefault().getLanguage();</code> to get the usual language code (e.g. "de", "en")</p> | {
"question_id": 4212320,
"question_date": "2010-11-18T06:49:18.150Z",
"question_score": 696,
"tags": "android|localization",
"answer_id": 4212417,
"answer_date": "2010-11-18T07:07:12.280Z",
"answer_score": 930
} |
Please answer the following Stack Overflow question:
Title: What is the difference between using constructor vs getInitialState in React / React Native?
<p>I've seen both used interchangeably. </p>
<p>What are the main use cases for both? Are there advantages / disadvantages? Is one a better practice?</p> | <p>The two approaches are not interchangeable. You should initialize state in the constructor when using ES6 classes, and define the <code>getInitialState</code> method when using <code>React.createClass</code>.</p>
<p><a href="https://facebook.github.io/react/docs/reusable-components.html#es6-classes" rel="noreferrer">See the official React doc on the subject of ES6 classes</a>.</p>
<pre class="lang-js prettyprint-override"><code>class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { /* initial state */ };
}
}
</code></pre>
<p>is equivalent to </p>
<pre class="lang-js prettyprint-override"><code>var MyComponent = React.createClass({
getInitialState() {
return { /* initial state */ };
},
});
</code></pre> | {
"question_id": 30668326,
"question_date": "2015-06-05T13:53:36.897Z",
"question_score": 696,
"tags": "reactjs|react-native|constructor",
"answer_id": 30668609,
"answer_date": "2015-06-05T14:06:19.033Z",
"answer_score": 977
} |
Please answer the following Stack Overflow question:
Title: What is the runtime performance cost of a Docker container?
<p>I'd like to comprehensively understand the run-time performance cost of a Docker container. I've found references to <a href="https://stackoverflow.com/questions/21691540/how-to-optimize-performance-for-a-docker-container/21707838#21707838">networking anecdotally being ~100µs slower</a>.</p>
<p>I've also found references to the run-time cost being "negligible" and "close to zero" but I'd like to know more precisely what those costs are. Ideally I'd like to know what Docker is abstracting with a performance cost and things that are abstracted without a performance cost. Networking, CPU, memory, etc.</p>
<p>Furthermore, if there are abstraction costs, are there ways to get around the abstraction cost. For example, perhaps I can mount a disk directly vs. virtually in Docker.</p> | <p>An excellent 2014 IBM research paper “<a href="http://domino.research.ibm.com/library/cyberdig.nsf/papers/0929052195DD819C85257D2300681E7B/$File/rc25482.pdf" rel="noreferrer">An Updated Performance Comparison of Virtual Machines and Linux Containers</a>” by Felter et al. provides a comparison between bare metal, KVM, and Docker containers. The general result is: <strong>Docker is nearly identical to native performance and faster than KVM in every category.</strong></p>
<p>The exception to this is Docker’s NAT — if you use port mapping (e.g., <code>docker run -p 8080:8080</code>), then you can expect a minor hit in latency, as shown below. However, you can now use the host network stack (e.g., <code>docker run --net=host</code>) when launching a Docker container, which will perform identically to the Native column (as shown in the Redis latency results lower down). </p>
<p><img src="https://i.stack.imgur.com/4yRh1m.png" alt="Docker NAT overhead"></p>
<p>They also ran latency tests on a few specific services, such as Redis. You can see that above 20 client threads, highest latency overhead goes Docker NAT, then KVM, then a rough tie between Docker host/native. </p>
<p><img src="https://i.stack.imgur.com/9RH9lm.png" alt="Docker Redis Latency Overhead"></p>
<p>Just because it’s a really useful paper, here are some other figures. Please download it for full access. </p>
<p>Taking a look at Disk I/O:</p>
<p><img src="https://i.stack.imgur.com/2Ftytm.png" alt="Docker vs. KVM vs. Native I/O Performance"></p>
<p>Now looking at CPU overhead: </p>
<p><img src="https://i.stack.imgur.com/wZZH6m.png" alt="Docker CPU Overhead"></p>
<p>Now some examples of memory (read the paper for details, memory can be extra tricky):</p>
<p><img src="https://i.stack.imgur.com/aHPVkm.png" alt="Docker Memory Comparison"></p> | {
"question_id": 21889053,
"question_date": "2014-02-19T18:19:45.670Z",
"question_score": 696,
"tags": "linux|docker|performance|virtual-machine|containerd",
"answer_id": 26149994,
"answer_date": "2014-10-01T20:26:14.203Z",
"answer_score": 624
} |
Please answer the following Stack Overflow question:
Title: Is it safe to expose Firebase apiKey to the public?
<p>The <a href="https://firebase.google.com/docs/web/setup#add_firebase_to_your_app" rel="noreferrer">Firebase Web-App guide</a> states I should put the given <code>apiKey</code> in my Html to initialize Firebase:</p>
<pre class="lang-html prettyprint-override"><code>// TODO: Replace with your project's customized code snippet
<script src="https://www.gstatic.com/firebasejs/3.0.2/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: '<your-api-key>',
authDomain: '<your-auth-domain>',
databaseURL: '<your-database-url>',
storageBucket: '<your-storage-bucket>'
};
firebase.initializeApp(config);
</script>
</code></pre>
<p>By doing so, the <code>apiKey</code> is exposed to every visitor.</p>
<p>What is the <strong>purpose of that key</strong> and is it really <strong>meant to be public</strong>?</p> | <p>The <code>apiKey</code> in this configuration snippet just identifies your Firebase project on the Google servers. It is not a security risk for someone to know it. In fact, it is necessary for them to know it, in order for them to interact with your Firebase project. This same configuration data is also included in every iOS and Android app that uses Firebase as its backend.</p>
<p>In that sense it is very similar to the database URL that identifies the back-end database associated with your project in the same snippet: <code>https://<app-id>.firebaseio.com</code>. See this question on why this is not a security risk: <a href="https://stackoverflow.com/questions/35418143/how-to-restrict-firebase-data-modification">How to restrict Firebase data modification?</a>, including the use of Firebase's server side security rules to ensure only authorized users can access the backend services.</p>
<p>If you want to learn how to secure all data access to your Firebase backend services is authorized, read up on the documentation on <a href="https://firebase.google.com/docs/rules" rel="noreferrer">Firebase security rules</a>. These rules control access to file storage and database access, and are enforced on the Firebase servers. So no matter if it's <em>your</em> code, or somebody else's code that uses you configuration data, it can only do what the security rules allow it to do.</p>
<p>For another explanation of what Firebase uses these values for, and for which of them you <em>can</em> set quotas, see the Firebase documentation on <a href="https://firebase.google.com/docs/projects/api-keys" rel="noreferrer">using and managing API keys</a>.</p>
<hr />
<p>If you'd like to reduce the risk of committing this configuration data to version control, consider using the <a href="https://firebase.google.com/docs/hosting/reserved-urls#sdk_auto-configuration" rel="noreferrer">SDK auto-configuration of Firebase Hosting</a>. While the keys will still end up in the browser in the same format, they won't be hard-coded into your code anymore with that.</p>
<hr />
<p><strong>Update</strong> (May 2021): Thanks to the new feature called <a href="https://firebase.google.com/docs/app-check" rel="noreferrer">Firebase App Check</a>, it is now actually possible to limit access to the backend services in your Firebase project to only those coming from iOS, Android and Web apps that are registered in that specific project.</p>
<p>You'll typically want to combine this with the user authentication based security described above, so that you have another shield against abusive users that <em>do</em> use your app.</p>
<p>By combining App Check with security rules you have both broad protection against abuse, and fine gained control over what data each user can access, while still allowing direct access to the database from your client-side application code.</p> | {
"question_id": 37482366,
"question_date": "2016-05-27T11:30:20.687Z",
"question_score": 696,
"tags": "javascript|firebase",
"answer_id": 37484053,
"answer_date": "2016-05-27T12:51:37.990Z",
"answer_score": 784
} |
Please answer the following Stack Overflow question:
Title: Run a Docker image as a container
<p>After building a Docker image from a <code>dockerfile</code>, I see the image was built successfully, but what do I do with it? Shouldn't i be able to run it as a container?</p> | <p>The specific way to run it depends on whether you gave the image a tag/name or not.</p>
<pre><code>$ docker images
REPOSITORY TAG ID CREATED SIZE
ubuntu 12.04 8dbd9e392a96 4 months ago 131.5 MB (virtual 131.5 MB)
</code></pre>
<p>With a name (let's use <em>Ubuntu</em>):</p>
<pre><code>$ docker run -i -t ubuntu:12.04 /bin/bash
</code></pre>
<p>Without a name, just using the ID:</p>
<pre><code>$ docker run -i -t 8dbd9e392a96 /bin/bash
</code></pre>
<p>Please see <em><a href="https://docs.docker.com/engine/reference/run/" rel="noreferrer">Docker run reference</a></em> for more information.</p> | {
"question_id": 18497688,
"question_date": "2013-08-28T20:34:51.897Z",
"question_score": 695,
"tags": "docker|docker-image",
"answer_id": 18498313,
"answer_date": "2013-08-28T21:14:50.127Z",
"answer_score": 981
} |
Please answer the following Stack Overflow question:
Title: How do I remove objects from a JavaScript associative array?
<p>Suppose I have this code:</p>
<pre><code>var myArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;
</code></pre>
<p>Now if I wanted to remove "lastname"?....is there some equivalent of
<code>myArray["lastname"].remove()</code>?</p>
<p>(I need the element gone because the number of elements is important and I want to keep things clean.)</p> | <p>Objects in JavaScript can be thought of as associative arrays, mapping keys (properties) to values.</p>
<p>To remove a property from an object in JavaScript you use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete" rel="noreferrer"><code>delete</code></a> operator:</p>
<pre><code>const o = { lastName: 'foo' }
o.hasOwnProperty('lastName') // true
delete o['lastName']
o.hasOwnProperty('lastName') // false
</code></pre>
<p>Note that when <code>delete</code> is applied to an index property of an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" rel="noreferrer"><code>Array</code></a>, you will create a <a href="https://2ality.com/2012/06/dense-arrays.html" rel="noreferrer">sparsely populated array</a> (ie. an array with a missing index).</p>
<p>When working with instances of <code>Array</code>, if you do not want to create a sparsely populated array - and you usually don't - then you should use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice" rel="noreferrer"><code>Array#splice</code></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop" rel="noreferrer"><code>Array#pop</code></a>.</p>
<p>Note that the <code>delete</code> operator in JavaScript does not directly free memory. Its purpose is to remove properties from objects. Of course, if a property being deleted holds the only remaining reference to an object <code>o</code>, then <code>o</code> will subsequently be garbage collected in the normal way.</p>
<p>Using the <code>delete</code> operator can affect JavaScript engines' ability to <a href="http://www.html5rocks.com/en/tutorials/speed/v8/" rel="noreferrer">optimise</a> <a href="http://www.smashingmagazine.com/2012/11/writing-fast-memory-efficient-javascript/" rel="noreferrer">code</a>.</p> | {
"question_id": 346021,
"question_date": "2008-12-06T06:44:05.723Z",
"question_score": 695,
"tags": "javascript|arrays|associative-array|associative",
"answer_id": 346022,
"answer_date": "2008-12-06T06:46:34.767Z",
"answer_score": 1241
} |
Please answer the following Stack Overflow question:
Title: jQuery: Get selected element tag name
<p>Is there an easy way to get a tag name?</p>
<p>For example, if I am given <code>$('a')</code> into a function, I want to get <code>'a'</code>.</p> | <p>You can call <code>.prop("tagName")</code>. Examples:</p>
<pre><code>jQuery("<a>").prop("tagName"); //==> "A"
jQuery("<h1>").prop("tagName"); //==> "H1"
jQuery("<coolTagName999>").prop("tagName"); //==> "COOLTAGNAME999"
</code></pre>
<p><br>
If writing out <code>.prop("tagName")</code> is tedious, you can create a custom function like so:</p>
<pre><code>jQuery.fn.tagName = function() {
return this.prop("tagName");
};
</code></pre>
<p>Examples:</p>
<pre><code>jQuery("<a>").tagName(); //==> "A"
jQuery("<h1>").tagName(); //==> "H1"
jQuery("<coolTagName999>").tagName(); //==> "COOLTAGNAME999"
</code></pre>
<p><br>
Note that tag names are, by convention, returned <b>CAPITALIZED</b>. If you want the returned tag name to be all lowercase, you can edit the custom function like so:</p>
<pre><code>jQuery.fn.tagNameLowerCase = function() {
return this.prop("tagName").toLowerCase();
};
</code></pre>
<p>Examples:</p>
<pre><code>jQuery("<a>").tagNameLowerCase(); //==> "a"
jQuery("<h1>").tagNameLowerCase(); //==> "h1"
jQuery("<coolTagName999>").tagNameLowerCase(); //==> "cooltagname999"
</code></pre> | {
"question_id": 5347357,
"question_date": "2011-03-18T02:20:23.157Z",
"question_score": 695,
"tags": "javascript|html|jquery|css|htmlelements",
"answer_id": 5347371,
"answer_date": "2011-03-18T02:22:41.257Z",
"answer_score": 1115
} |
Please answer the following Stack Overflow question:
Title: How can I make git show a list of the files that are being tracked?
<p>Using command line git, how can I make git show a list of the files that are being tracked in the repository?</p> | <p>If you want to list all the files currently being tracked under the branch <code>master</code>, you could use this command:</p>
<pre><code>git ls-tree -r master --name-only
</code></pre>
<p>If you want a list of files that ever existed (i.e. including deleted files):</p>
<pre><code>git log --pretty=format: --name-only --diff-filter=A | sort - | sed '/^$/d'
</code></pre> | {
"question_id": 15606955,
"question_date": "2013-03-25T03:04:06.263Z",
"question_score": 695,
"tags": "git",
"answer_id": 15606995,
"answer_date": "2013-03-25T03:09:47.250Z",
"answer_score": 823
} |
Please answer the following Stack Overflow question:
Title: Version vs build in Xcode
<p>I have an app that I developed with Xcode 3 and recently started editing with Xcode 4. In the target summary I have the iOS application target form with fields: identifier, version, build, devices, and deployment target. The version field is blank and the build field is 3.4.0 (which matches the version of the app from when I was still editing with Xcode 3).</p>
<p><strong>My questions are:</strong> </p>
<ol>
<li><p>What is the difference between the version and build fields?</p></li>
<li><p>Why was the version field blank after I upgraded to Xcode 4?</p></li>
</ol> | <p>Apple sort of rearranged/repurposed the fields. </p>
<p>Going forward, if you look on the Info tab for your Application Target, you should use the "Bundle versions string, short" as your Version (e.g., 3.4.0) and "Bundle version" as your Build (e.g., 500 or 1A500). If you don't see them both, you can add them. Those will map to the proper Version and Build textboxes on the Summary tab; they are the same values.</p>
<p>When viewing the Info tab, if you right-click and select <strong>Show Raw Keys/Values</strong>, you'll see the actual names are <code>CFBundleShortVersionString</code> (Version) and <code>CFBundleVersion</code> (Build).</p>
<p>The Version is usually used how you appear to have been using it with Xcode 3. I'm not sure on what level you're asking about the Version/Build difference, so I'll answer it philosophically.</p>
<p>There are all sorts of schemes, but a popular one is:</p>
<p>{MajorVersion}.{MinorVersion}.{Revision}</p>
<ul>
<li><strong>Major version</strong> - Major changes, redesigns, and functionality
changes</li>
<li><strong>Minor version</strong> - Minor improvements, additions to functionality</li>
<li><strong>Revision</strong> - A patch number for bug-fixes</li>
</ul>
<p>Then the Build is used separately to indicate the total number of builds for a release or for the entire product lifetime.</p>
<p>Many developers start the Build number at 0, and every time they build they increase the number by one, increasing forever. In my projects, I have a script that automatically increases the build number every time I build. See instructions for that below.</p>
<ul>
<li>Release 1.0.0 might be build 542. It took 542 builds to get to a
1.0.0 release.</li>
<li>Release 1.0.1 might be build 578.</li>
<li>Release 1.1.0 might be build 694.</li>
<li>Release 2.0.0 might be build 949.</li>
</ul>
<p>Other developers, including Apple, have a Build number comprised of a major version + minor version + number of builds for the release. These are the actual software version numbers, as opposed to the values used for marketing.</p>
<p>If you go to <strong>Xcode</strong> menu > <strong>About Xcode</strong>, you'll see the Version and Build numbers. If you hit the <strong>More Info...</strong> button you'll see a bunch of different versions. Since the <strong>More Info...</strong> button was removed in Xcode 5, this information is also available from the <strong>Software > Developer</strong> section of the <strong>System Information</strong> app, available by opening <strong>Apple</strong> menu > <strong>About This Mac</strong> > <strong>System Report...</strong>.</p>
<p>For example, Xcode 4.2 (4C139). Marketing version 4.2 is Build major version 4, Build minor version C, and Build number 139. The next release (presumably 4.3) will likely be Build release 4D, and the Build number will start over at 0 and increment from there.</p>
<p>The iPhone Simulator Version/Build numbers are the same way, as are iPhones, Macs, etc.</p>
<ul>
<li>3.2: (7W367a)</li>
<li>4.0: (8A400)</li>
<li>4.1: (8B117)</li>
<li>4.2: (8C134)</li>
<li>4.3: (8H7)</li>
</ul>
<p><strong>Update</strong>: By request, here are the steps to create a script that runs each time you build your app in Xcode to read the Build number, increment it, and write it back to the app's <code>{App}-Info.plist</code> file. There are optional, additional steps if you want to write your version/build numbers to your <code>Settings.bundle/Root*.plist</code> file(s).</p>
<p>This is extended from the how-to article <a href="http://davedelong.com/blog/2009/04/15/incrementing-build-numbers-xcode" rel="noreferrer">here</a>.</p>
<p>In Xcode 4.2 - 5.0:</p>
<ol>
<li>Load your Xcode project.</li>
<li>In the left hand pane, click on your project at the very top of the hierarchy. This will load the project settings editor.</li>
<li>On the left-hand side of the center window pane, click on your app under the <strong>TARGETS</strong> heading. You will need to configure this setup for each project target.</li>
<li>Select the <strong>Build Phases</strong> tab.</li>
<li><ul>
<li>In Xcode 4, at the bottom right, click the <strong>Add Build Phase</strong> button and select <strong>Add Run Script</strong>.</li>
<li>In Xcode 5, select <strong>Editor</strong> menu > <strong>Add Build Phase</strong> > <strong>Add Run Script Build Phase</strong>.</li>
</ul></li>
<li>Drag-and-drop the new <strong>Run Script</strong> phase to move it to just before the <strong>Copy Bundle Resources</strong> phase (when the app-info.plist file will be bundled with your app).</li>
<li>In the new <strong>Run Script</strong> phase, set <strong>Shell</strong>: <code>/bin/bash</code>.</li>
<li><p>Copy and paste the following into the script area for integer build numbers:</p>
<pre><code>buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"
</code></pre>
<p>As @Bdebeez pointed out, the <a href="https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/agvtool.1.html" rel="noreferrer">Apple Generic Versioning Tool</a> (<code>agvtool</code>) is also available. If you prefer to use it instead, then there are a couple things to change first:</p>
<ul>
<li>Select the <strong>Build Settings</strong> tab.</li>
<li>Under the <strong>Versioning</strong> section, set the <strong>Current Project Version</strong> to the initial build number you want to use, e.g., <strong>1</strong>.</li>
<li>Back on the <strong>Build Phases</strong> tab, drag-and-drop your <strong>Run Script</strong> phase after the <strong>Copy Bundle Resources</strong> phase to avoid a race condition when trying to both build and update the source file that includes your build number. </li>
</ul>
<p><strong>Note that with the <code>agvtool</code> method you may still periodically get failed/canceled builds with no errors. For this reason, I don't recommend using <code>agvtool</code> with this script.</strong></p>
<p>Nevertheless, in your <strong>Run Script</strong> phase, you can use the following script:</p>
<pre><code>"${DEVELOPER_BIN_DIR}/agvtool" next-version -all
</code></pre>
<p>The <code>next-version</code> argument increments the build number (<code>bump</code> is also an alias for the same thing), and <code>-all</code> updates <code>Info.plist</code> with the new build number.</p></li>
<li><p>And if you have a Settings bundle where you show the Version and Build, you can add the following to the end of the script to update the version and build. <em>Note: Change the <code>PreferenceSpecifiers</code> values to match your settings. <code>PreferenceSpecifiers:2</code> means look at the item at index 2 under the <code>PreferenceSpecifiers</code> array in your plist file, so for a 0-based index, that's the 3rd preference setting in the array.</em></p>
<pre><code>productVersion=$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "$INFOPLIST_FILE")
/usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:2:DefaultValue $buildNumber" Settings.bundle/Root.plist
/usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:1:DefaultValue $productVersion" Settings.bundle/Root.plist
</code></pre>
<p>If you're using <code>agvtool</code> instead of reading the <code>Info.plist</code> directly, you can add the following to your script instead:</p>
<pre><code>buildNumber=$("${DEVELOPER_BIN_DIR}/agvtool" what-version -terse)
productVersion=$("${DEVELOPER_BIN_DIR}/agvtool" what-marketing-version -terse1)
/usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:2:DefaultValue $buildNumber" Settings.bundle/Root.plist
/usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:1:DefaultValue $productVersion" Settings.bundle/Root.plist
</code></pre></li>
<li><p>And if you have a universal app for iPad & iPhone, then you can also set the settings for the iPhone file:</p>
<pre><code>/usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:2:DefaultValue $buildNumber" Settings.bundle/Root~iphone.plist
/usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:1:DefaultValue $productVersion" Settings.bundle/Root~iphone.plist
</code></pre></li>
</ol> | {
"question_id": 6851660,
"question_date": "2011-07-27T21:48:15.987Z",
"question_score": 695,
"tags": "ios|xcode",
"answer_id": 6965086,
"answer_date": "2011-08-06T05:55:34.320Z",
"answer_score": 1272
} |
Please answer the following Stack Overflow question:
Title: How to solve "The specified service has been marked for deletion" error
<p>I try to remove a Windows Service with <code>sc delete <service name></code>, and encounter the following error:</p>
<blockquote>
<p>[SC] DeleteService FAILED 1072:</p>
<p>The specified service has been marked for deletion.</p>
</blockquote>
<p>What I've already done:</p>
<ul>
<li><p>Stopped the service, obviously. The <code>sc queryex "<service name>"</code> gives the following result:</p>
<pre><code>SERVICE_NAME: Stub service
TYPE : 10 WIN32_OWN_PROCESS
STATE : 1 STOPPED
WIN32_EXIT_CODE : 1067 (0x42b)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
PID : 0
FLAGS :
</code></pre></li>
<li><p><a href="https://stackoverflow.com/a/8529760/240613">Ensured that Microsoft Management Console is closed</a> (<code>taskkill /F /IM mmc.exe</code>),</p></li>
<li><p><a href="https://stackoverflow.com/a/18467128/240613">Ensured that Event Viewer is closed</a>,</p></li>
<li><p><a href="https://stackoverflow.com/a/2804099/240613">Removed the key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<service name> from the registry</a>.</p>
<p>Due to this removal, <code>services.msc</code> still shows the service (with a name, but no status or startup type), but the description is “<Failed to Read Description. Error Code: 2 >”. When attempting to view the properties, “The system cannot find the file specified.” is shown five times.</p></li>
</ul>
<p>The problem persists.</p>
<p>What is the next step?</p> | <p>There may be several causes which lead to the service being stuck in “marked for deletion”.</p>
<ol>
<li><p><a href="http://blog.cyotec.com/2011/05/specified-service-has-been-marked-for.html" rel="noreferrer">SysInternals' Process Explorer is opened</a>. Closing it should lead to automatic removal of the service.</p></li>
<li><p><a href="https://stackoverflow.com/questions/20561990/how-to-solve-the-specified-service-has-been-marked-for-deletion-error/21310096#comment32672750_20565337">Task Manager is opened</a>.</p></li>
<li><p><a href="https://stackoverflow.com/a/8529760/240613">Microsoft Management Console (MMC) is opened</a>. To ensure all instances are closed, run <code>taskkill /F /IM mmc.exe</code>.</p></li>
<li><p><a href="https://stackoverflow.com/a/21310096/240613">Services console is opened</a>. This is the same as the previous point, since Services console is hosted by MMC.</p></li>
<li><p><a href="https://stackoverflow.com/a/18467128/240613">Event Viewer is opened</a>. Again, this is the same as the third point.</p></li>
<li><p><a href="https://stackoverflow.com/a/2804099/240613">The key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\{service name} exists</a>.</p></li>
<li><p><a href="https://stackoverflow.com/a/28632820/240613">Someone else is logged into the server</a> and has one of the previously mentioned applications opened.</p></li>
<li><p>An instance of Visual Studio <em>used to debug the service</em> is open.</p></li>
</ol> | {
"question_id": 20561990,
"question_date": "2013-12-13T08:20:42.427Z",
"question_score": 694,
"tags": "windows-services",
"answer_id": 20565337,
"answer_date": "2013-12-13T11:23:48.633Z",
"answer_score": 1476
} |
Please answer the following Stack Overflow question:
Title: Select <a> which href ends with some string
<p>Is it possible using <a href="https://jquery.com/" rel="noreferrer">jQuery</a> to select all <code><a></code> links which href ends with "ABC"?</p>
<p>For example, if I want to find this link <code><a href="http://server/page.aspx?id=ABC"></code></p> | <pre><code> $('a[href$="ABC"]')...
</code></pre>
<p>Selector documentation can be found at <a href="http://docs.jquery.com/Selectors" rel="noreferrer">http://docs.jquery.com/Selectors</a></p>
<p>For attributes:</p>
<pre><code>= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")
</code></pre> | {
"question_id": 303956,
"question_date": "2008-11-20T00:23:58.913Z",
"question_score": 694,
"tags": "jquery|string|anchor|href",
"answer_id": 303961,
"answer_date": "2008-11-20T00:26:13.230Z",
"answer_score": 1616
} |
Please answer the following Stack Overflow question:
Title: How to detect if JavaScript is disabled?
<p>There was a post this morning asking about how many people disable JavaScript. Then I began to wonder what techniques might be used to determine if the user has it disabled. </p>
<p>Does anyone know of some short/simple ways to detect if JavaScript is disabled? My intention is to give a warning that the site is not able to function properly without the browser having JS enabled. </p>
<p>Eventually I would want to redirect them to content that is able to work in the absence of JS, but I need this detection as a placeholder to start.</p> | <p>I assume you're trying to decide whether or not to deliver JavaScript-enhanced content. The best implementations degrade cleanly, so that the site will still operate without JavaScript. I also assume that you mean <a href="https://www.seguetech.com/client-server-side-code/" rel="nofollow noreferrer" title="'Client-Side vs. Server-Side Code: What’s the Difference?'">server-side</a> detection, rather than using the <a href="https://www.w3.org/TR/html52/semantics-scripting.html#the-noscript-element" rel="nofollow noreferrer" title="WC3 Recommendation: The <noscript> element (HTML 5.2)"><code><noscript></code></a> element for an unexplained reason.</p>
<p>There is no good way to perform server-side JavaScript detection. As an alternative it is possible to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie" rel="nofollow noreferrer" title="MDN: Document.cookie">set a cookie using JavaScript</a>, and then test for that cookie using server-side scripting upon subsequent page views. However this would be unsuitable for deciding what content to deliver, as it would not distinguish visitors without the cookie from new visitors or from visitors who did not accept the JavaScript set cookie.</p> | {
"question_id": 121203,
"question_date": "2008-09-23T14:07:12.740Z",
"question_score": 694,
"tags": "javascript|html|code-snippets",
"answer_id": 121259,
"answer_date": "2008-09-23T14:16:38.053Z",
"answer_score": 302
} |
Please answer the following Stack Overflow question:
Title: Sending Email in Android using JavaMail API without using the default/built-in app
<p>I am trying to create a mail sending application in Android. </p>
<p>If I use: </p>
<pre><code>Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
</code></pre>
<p>This will launch the built-in Android application; I'm trying to send the mail on button click directly <strong>without</strong> using this application.</p> | <p>Send e-mail in Android using the JavaMail API using Gmail authentication.</p>
<h3>Steps to create a sample Project:</h3>
<p><strong>MailSenderActivity.java:</strong></p>
<pre><code>public class MailSenderActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button send = (Button) this.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
GMailSender sender = new GMailSender("[email protected]", "password");
sender.sendMail("This is Subject",
"This is Body",
"[email protected]",
"[email protected]");
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
});
}
}
</code></pre>
<p><strong>GMailSender.java:</strong></p>
<pre><code>public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new com.provider.JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
try{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}catch(Exception e){
}
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
</code></pre>
<p><strong>JSSEProvider.java:</strong></p>
<pre><code>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Alexander Y. Kleymenov
* @version $Revision$
*/
import java.security.AccessController;
import java.security.Provider;
public final class JSSEProvider extends Provider {
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
</code></pre>
<p>ADD 3 jars found in the following link to your Android Project</p>
<ul>
<li><a href="https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/javamail-android/mail.jar" rel="noreferrer">mail.jar</a></li>
<li><a href="https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/javamail-android/activation.jar" rel="noreferrer">activation.jar</a></li>
<li><a href="https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/javamail-android/additionnal.jar" rel="noreferrer">additional.jar</a></li>
</ul>
<p><a href="https://stackoverflow.com/a/6859020/28557">Click here - How to add External Jars</a></p>
<p>And don't forget to add this line in your manifest:</p>
<pre><code><uses-permission android:name="android.permission.INTERNET" />
</code></pre>
<p><strong>Just click below link to change account access for less secure apps</strong>
<a href="https://www.google.com/settings/security/lesssecureapps" rel="noreferrer">https://www.google.com/settings/security/lesssecureapps</a></p>
<p>Run the project and check your recipient mail account for the mail.
Cheers!</p>
<p>P.S. And don't forget that you cannot do network operation from any Activity in android.
Hence it is recommended to use <code>AsyncTask</code> or <code>IntentService</code> to avoid network on main thread exception.</p>
<p>Jar files: <a href="https://code.google.com/archive/p/javamail-android/" rel="noreferrer">https://code.google.com/archive/p/javamail-android/</a></p> | {
"question_id": 2020088,
"question_date": "2010-01-07T12:04:43.637Z",
"question_score": 694,
"tags": "java|android|email|android-intent|jakarta-mail",
"answer_id": 2033124,
"answer_date": "2010-01-09T11:03:30.570Z",
"answer_score": 783
} |
Please answer the following Stack Overflow question:
Title: Android Studio Error "Android Gradle plugin requires Java 11 to run. You are currently using Java 1.8"
<p>I downloaded the newest Android Studio, and I wanted to run the Android Jetpack Compose Project, but when I ran it, I got the error:</p>
<pre class="lang-none prettyprint-override"><code>> Failed to apply plugin 'com.android.internal.application'.
> Android Gradle plugin requires Java 11 to run. You are currently using Java 1.8.
You can try some of the following options:
- changing the IDE settings.
- changing the JAVA_HOME environment variable.
- changing `org.gradle.java.home` in `gradle.properties`.
</code></pre>
<p>I already downloaded Java 11 and added Java 11 in <em>gradle.properties</em>.</p>
<pre class="lang-none prettyprint-override"><code>org.gradle.java.home=/Library/Java/JavaVirtualMachines/jdk-11.0.10.jdk/Contents/Home
</code></pre>
<p>The JAVA_HOME shows Java 11, but when I run, it doesn't work -
<code>/Library/Java/JavaVirtualMachines/jdk-11.0.10.jdk/Contents/Home</code></p>
<p>How should I do?</p>
<p>My Android Studio version</p>
<p><a href="https://i.stack.imgur.com/VLFU2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VLFU2.png" alt="Enter image description here" /></a></p>
<p>My Java version</p>
<pre class="lang-none prettyprint-override"><code>java 11.0.10 2021-01-19 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.10+8-LTS-162)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.10+8-LTS-162, mixed mode)
</code></pre>
<p>My <em>gradle-wrapper.properties</em></p>
<pre class="lang-none prettyprint-override"><code>distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.2-bin.zip
</code></pre>
<p><em>build.gradle</em> classpath</p>
<pre class="lang-none prettyprint-override"><code>classpath "com.android.tools.build:gradle:7.0.0-alpha13"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.31"
</code></pre>
<p>File <em>build.gradle</em></p>
<pre class="lang-none prettyprint-override"><code>plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdk 30
defaultConfig {
applicationId "com.example.testandroid3"
minSdk 21
targetSdk 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = "11"
useIR = true
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion compose_version
kotlinCompilerVersion '1.4.31'
}
}
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(11))
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.0'
implementation 'androidx.activity:activity-compose:1.3.0-alpha02'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
}
</code></pre> | <p>Make sure that your Gradle is using the proper JDK.
Try running <code>./gradlew --version</code> in your project's directory. The output should be something like this:</p>
<pre class="lang-none prettyprint-override"><code>Gradle 7.0-rc-2
------------------------------------------------------------
Build time: 2021-04-01 21:26:39 UTC
Revision: 912a3368b654b71250dfc925a20d620393
Kotlin: 1.4.31
Groovy: 3.0.7
Ant: Apache Ant(TM) version 1.10.9 compiled on September 27 2020
JVM: 11.0.10 (Ubuntu 11.0.10+9-Ubuntu-0ubuntu1.20.10)
OS: Linux 5.11.4-051104-generic amd64
</code></pre>
<p>If the JVM points to version 1.8 then you should change it in settings. You can find it in <em>Preferences</em> → <em>Build, Execution, Deployment</em> → <em>Build Tools</em> → <em>Gradle</em> → *Gradle JDK.</p>
<p><a href="https://i.stack.imgur.com/eumlW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eumlW.png" alt="Enter image description here" /></a></p> | {
"question_id": 66980512,
"question_date": "2021-04-07T06:17:01.410Z",
"question_score": 694,
"tags": "android|android-studio|gradle|android-gradle-plugin",
"answer_id": 67002271,
"answer_date": "2021-04-08T10:38:59.127Z",
"answer_score": 1150
} |
Please answer the following Stack Overflow question:
Title: Can I create links with 'target="_blank"' in Markdown?
<p>Is there a way to create a link in Markdown that opens in a new window? If not, what syntax do you recommend to do this? I'll add it to the markdown compiler I use. I think it should be an option.</p> | <p>As far as the Markdown syntax is concerned, if you want to get that detailed, you'll just have to use HTML.</p>
<pre><code><a href="http://example.com/" target="_blank">Hello, world!</a>
</code></pre>
<p>Most Markdown engines I've seen allow plain old HTML, just for situations like this where a generic text markup system just won't cut it. (The StackOverflow engine, for example.) They then run the entire output through an HTML whitelist filter, regardless, since even a Markdown-only document can easily contain XSS attacks. As such, if you or your users want to create <code>_blank</code> links, then they probably still can.</p>
<p>If that's a feature you're going to be using often, it might make sense to create your own syntax, but it's generally not a vital feature. If I want to launch that link in a new window, I'll ctrl-click it myself, thanks.</p> | {
"question_id": 4425198,
"question_date": "2010-12-13T01:33:05.087Z",
"question_score": 694,
"tags": "html|hyperlink|markdown|target|new-window",
"answer_id": 4425223,
"answer_date": "2010-12-13T01:40:35.647Z",
"answer_score": 526
} |
Please answer the following Stack Overflow question:
Title: Stylesheet not loaded because of MIME-type
<p>I'm working on a website that uses <code>gulp</code> to compile and browser sync to keep the browser synchronised with my changes.</p>
<p>The gulp task compiles everything properly, but on the website, I'm unable to see any style, and the console shows this error message:</p>
<blockquote>
<p>Refused to apply style from
'<a href="http://localhost:3000/assets/styles/custom-style.css" rel="noreferrer">http://localhost:3000/assets/styles/custom-style.css</a>' because its
MIME type ('text/html') is not a supported stylesheet MIME type, and
strict MIME checking is enabled.</p>
</blockquote>
<p>Now, I don't really understand why this happens.</p>
<p>The HTML includes the file like this (which I am pretty sure is correct):</p>
<pre><code><link rel="stylesheet" type="text/css" href="assets/styles/custom-style.css"/>
</code></pre>
<p>And the stylesheet is a merge between Bootstrap & font-awesome styles for now (nothing custom yet).</p>
<p>The path is correct as well, as this is the folder structure:</p>
<pre><code>index.html
assets
|-styles
|-custom-style.css
</code></pre>
<p>But I keep getting the error.</p>
<p>What could it be? Is this something (maybe a setting?) for gulp/browsersync maybe?</p> | <p>The issue, I think, was with a CSS library starting with comments.</p>
<p>While in development, I do not minify files and I don't remove comments. This meant that the stylesheet started with some comments, causing it to be seen as something different from CSS.</p>
<p>Removing the library and putting it into a vendor file (which is ALWAYS minified without comments) solved the issue.</p>
<p>Again, I'm not 100% sure this is a fix, but it's still a win for me as it works as expected now.</p> | {
"question_id": 48248832,
"question_date": "2018-01-14T10:52:40.917Z",
"question_score": 693,
"tags": "html|css|gulp|mime-types|browser-sync",
"answer_id": 48270432,
"answer_date": "2018-01-15T20:46:08.220Z",
"answer_score": 177
} |
Please answer the following Stack Overflow question:
Title: Changing the tick frequency on the x or y axis
<p>I am trying to fix how python plots my data.
Say:</p>
<pre><code>x = [0,5,9,10,15]
y = [0,1,2,3,4]
matplotlib.pyplot.plot(x,y)
matplotlib.pyplot.show()
</code></pre>
<p>The x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?</p> | <p>You could explicitly set where you want to tick marks with <code>plt.xticks</code>:</p>
<pre><code>plt.xticks(np.arange(min(x), max(x)+1, 1.0))
</code></pre>
<hr>
<p>For example,</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
plt.show()
</code></pre>
<hr>
<p>(<code>np.arange</code> was used rather than Python's <code>range</code> function just in case <code>min(x)</code> and <code>max(x)</code> are floats instead of ints.) </p>
<hr>
<p>The <code>plt.plot</code> (or <code>ax.plot</code>) function will automatically set default <code>x</code> and <code>y</code> limits. If you wish to keep those limits, and just change the stepsize of the tick marks, then you could use <code>ax.get_xlim()</code> to discover what limits Matplotlib has already set. </p>
<pre><code>start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, stepsize))
</code></pre>
<p>The default tick formatter should do a decent job rounding the tick values to a sensible number of significant digits. However, if you wish to have more control over the format, you can define your own formatter. For example,</p>
<pre><code>ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
</code></pre>
<p>Here's a runnable example:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, 0.712123))
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
plt.show()
</code></pre> | {
"question_id": 12608788,
"question_date": "2012-09-26T19:12:53.957Z",
"question_score": 693,
"tags": "python|matplotlib|plot|axes|xticks",
"answer_id": 12608937,
"answer_date": "2012-09-26T19:24:08.597Z",
"answer_score": 835
} |
Please answer the following Stack Overflow question:
Title: What is the { get; set; } syntax in C#?
<p>I am learning ASP.NET MVC and I can read English documents, but I don't really understand what is happening in this code:</p>
<pre><code>public class Genre
{
public string Name { get; set; }
}
</code></pre>
<p>What does this mean: <code>{ get; set; }</code>?</p> | <p>It's a so-called auto property, and is essentially a shorthand for the following (similar code will be generated by the compiler):</p>
<pre><code>private string name;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
</code></pre> | {
"question_id": 5096926,
"question_date": "2011-02-23T20:49:47.047Z",
"question_score": 693,
"tags": "c#",
"answer_id": 5096967,
"answer_date": "2011-02-23T20:53:12.647Z",
"answer_score": 663
} |
Please answer the following Stack Overflow question:
Title: Any way to declare an array in-line?
<p>Let's say I have a method m() that takes an array of Strings as an argument. Is there a way I can just declare this array in-line when I make the call? i.e. Instead of:</p>
<pre><code>String[] strs = {"blah", "hey", "yo"};
m(strs);
</code></pre>
<p>Can I just replace this with one line, and avoid declaring a named variable that I'm never going to use?</p> | <pre><code>m(new String[]{"blah", "hey", "yo"});
</code></pre> | {
"question_id": 1154008,
"question_date": "2009-07-20T14:44:51.117Z",
"question_score": 693,
"tags": "java|arrays",
"answer_id": 1154027,
"answer_date": "2009-07-20T14:48:18.773Z",
"answer_score": 1062
} |
Please answer the following Stack Overflow question:
Title: What is a reasonable code coverage % for unit tests (and why)?
<p>If you were to mandate a minimum percentage code-coverage for unit tests, perhaps even as a requirement for committing to a repository, what would it be?</p>
<p>Please explain how you arrived at your answer (since if all you did was pick a number, then I could have done that all by myself ;)</p> | <p>This prose by Alberto Savoia answers precisely that question (in a nicely entertaining manner at that!):</p>
<p><a href="http://www.artima.com/forums/flat.jsp?forum=106&thread=204677" rel="noreferrer">http://www.artima.com/forums/flat.jsp?forum=106&thread=204677</a></p>
<blockquote>
<p><strong>Testivus On Test Coverage</strong></p>
<p>Early one morning, a programmer asked
the great master:</p>
<p>“I am ready to write some unit tests. What code coverage should I aim
for?”</p>
<p>The great master replied:</p>
<p>“Don’t worry about coverage, just write some good tests.”</p>
<p>The programmer smiled, bowed, and
left.</p>
<p>...</p>
<p>Later that day, a second programmer
asked the same question.</p>
<p>The great master pointed at a pot of
boiling water and said:</p>
<p>“How many grains of rice should I put in that pot?”</p>
<p>The programmer, looking puzzled,
replied:</p>
<p>“How can I possibly tell you? It depends on how many people you need to
feed, how hungry they are, what other
food you are serving, how much rice
you have available, and so on.”</p>
<p>“Exactly,” said the great master.</p>
<p>The second programmer smiled, bowed,
and left.</p>
<p>...</p>
<p>Toward the end of the day, a third
programmer came and asked the same
question about code coverage.</p>
<p>“Eighty percent and no less!” Replied the master in a stern voice,
pounding his fist on the table.</p>
<p>The third programmer smiled, bowed,
and left.</p>
<p>...</p>
<p>After this last reply, a young
apprentice approached the great
master:</p>
<p>“Great master, today I overheard you answer the same question about
code coverage with three different
answers. Why?”</p>
<p>The great master stood up from his
chair:</p>
<p>“Come get some fresh tea with me and let’s talk about it.”</p>
<p>After they filled their cups with
smoking hot green tea, the great
master began to answer:</p>
<p>“The first programmer is new and just getting started with testing.
Right now he has a lot of code and no
tests. He has a long way to go;
focusing on code coverage at this time
would be depressing and quite useless.
He’s better off just getting used to
writing and running some tests. He can
worry about coverage later.”</p>
<p>“The second programmer, on the other hand, is quite experience both
at programming and testing. When I
replied by asking her how many grains
of rice I should put in a pot, I
helped her realize that the amount of
testing necessary depends on a number
of factors, and she knows those
factors better than I do – it’s her
code after all. There is no single,
simple, answer, and she’s smart enough
to handle the truth and work with
that.”</p>
<p>“I see,” said the young apprentice,
“but if there is no single simple
answer, then why did you answer the
third programmer ‘Eighty percent and
no less’?”</p>
<p>The great master laughed so hard and
loud that his belly, evidence that he
drank more than just green tea,
flopped up and down.</p>
<p>“The third programmer wants only simple answers – even when there are
no simple answers … and then does not
follow them anyway.”</p>
<p>The young apprentice and the grizzled
great master finished drinking their
tea in contemplative silence.</p>
</blockquote> | {
"question_id": 90002,
"question_date": "2008-09-18T04:25:40.303Z",
"question_score": 693,
"tags": "unit-testing|code-coverage|code-metrics",
"answer_id": 90021,
"answer_date": "2008-09-18T04:30:10.230Z",
"answer_score": 1572
} |
Please answer the following Stack Overflow question:
Title: How can I convert a std::string to int?
<p>I want to convert a string to an int and I don't mean ASCII codes.</p>
<p>For a quick run-down, we are passed in an equation as a string. We are to break it down, format it correctly and solve the linear equations. Now, in saying that, I'm not able to convert a string to an int.</p>
<p>I know that the string will be in either the format (-5) or (25) etc. so it's definitely an int. But how do we extract that from a string?</p>
<p>One way I was thinking is running a for/while loop through the string, check for a digit, extract all the digits after that and then look to see if there was a leading '-', if there is, multiply the int by -1.</p>
<p>It seems a bit over complicated for such a small problem though. Any ideas?</p> | <p>In C++11 there are some nice new convert functions from <code>std::string</code> to a number type.</p>
<p>So instead of </p>
<pre><code>atoi( str.c_str() )
</code></pre>
<p>you can use</p>
<pre><code>std::stoi( str )
</code></pre>
<p>where <code>str</code> is your number as <code>std::string</code>.</p>
<p>There are version for all flavours of numbers:
<code>long stol(string)</code>, <code>float stof(string)</code>, <code>double stod(string)</code>,...
see <a href="http://en.cppreference.com/w/cpp/string/basic_string/stol">http://en.cppreference.com/w/cpp/string/basic_string/stol</a></p> | {
"question_id": 7663709,
"question_date": "2011-10-05T15:23:45.227Z",
"question_score": 692,
"tags": "c++|string|integer",
"answer_id": 7664227,
"answer_date": "2011-10-05T15:59:32.813Z",
"answer_score": 1023
} |
Please answer the following Stack Overflow question:
Title: How do I remove/delete a virtualenv?
<p>I created an environment with the following command: <code>virtualenv venv --distribute</code></p>
<p>I cannot remove it with the following command: <code>rmvirtualenv venv</code> -
<strong>This is part of <a href="http://virtualenvwrapper.readthedocs.io/en/latest/command_ref.html#rmvirtualenv" rel="noreferrer">virtualenvwrapper</a> as mentioned in <a href="https://stackoverflow.com/a/18624789/452708">answer below for virtualenvwrapper</a></strong></p>
<p>I do an <code>ls</code>on my current directory and I still see venv</p>
<p>The only way I can remove it seems to be: <code>sudo rm -rf venv</code></p>
<p>Note that the environment is not active. I'm running Ubuntu 11.10. Any ideas? I've tried rebooting my system to no avail.</p> | <blockquote>
<p>"<em>The only way I can remove it seems to be: <code>sudo rm -rf venv</code></em>"</p>
</blockquote>
<p>That's it! There is no command for deleting your virtual environment. Simply deactivate it and rid your application of its artifacts by recursively removing it.</p>
<p>Note that this is the same regardless of what kind of virtual environment you are using. <code>virtualenv</code>, <code>venv</code>, Anaconda environment, <code>pyenv</code>, <code>pipenv</code> are all based the same principle here.</p> | {
"question_id": 11005457,
"question_date": "2012-06-12T21:54:54.767Z",
"question_score": 692,
"tags": "python-3.x|virtualenvwrapper|python-venv|virtual-environment|virtualenv-commands",
"answer_id": 11005505,
"answer_date": "2012-06-12T21:58:56.483Z",
"answer_score": 665
} |
Please answer the following Stack Overflow question:
Title: Remove last item from array
<p>I have the following array.</p>
<pre><code>var arr = [1,0,2];
</code></pre>
<p>I would like to remove the last element i.e. 2.</p>
<p>I used <code>arr.slice(-1);</code> but it doesn't remove the value.</p> | <p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice" rel="noreferrer">splice(startPosition, deleteCount)</a></p>
<pre><code>array.splice(-1)
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = ['abc','def','ghi','123'];
var removed = array.splice(-1); //last item
console.log( 'array:', array );
console.log( 'removed:', removed );</code></pre>
</div>
</div>
</p> | {
"question_id": 19544452,
"question_date": "2013-10-23T14:24:49.830Z",
"question_score": 692,
"tags": "javascript|arrays|slice",
"answer_id": 19544478,
"answer_date": "2013-10-23T14:25:42.623Z",
"answer_score": 693
} |
Please answer the following Stack Overflow question:
Title: Remove CSS class from element with JavaScript (no jQuery)
<p>Could anyone let me know how to remove a class on an element using JavaScript only?
Please do not give me an answer with jQuery as I can't use it, and I don't know anything about it.</p> | <p>The right and standard way to do it is using <code>classList</code>. It is now <a href="http://caniuse.com/#search=classList" rel="noreferrer">widely supported in the latest version of most modern browsers</a>:</p>
<pre><code>ELEMENT.classList.remove("CLASS_NAME");
</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>remove.onclick = () => {
const el = document.querySelector('#el');
el.classList.remove("red");
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red {
background: red
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='el' class="red"> Test</div>
<button id='remove'>Remove Class</button></code></pre>
</div>
</div>
</p>
<p>Documentation: <a href="https://developer.mozilla.org/en/DOM/element.classList" rel="noreferrer">https://developer.mozilla.org/en/DOM/element.classList</a></p> | {
"question_id": 2155737,
"question_date": "2010-01-28T15:43:04.287Z",
"question_score": 692,
"tags": "javascript|html|css",
"answer_id": 2156090,
"answer_date": "2010-01-28T16:29:55.983Z",
"answer_score": 1078
} |
Please answer the following Stack Overflow question:
Title: How do I bind to list of checkbox values with AngularJS?
<p>I have a few checkboxes:</p>
<pre><code><input type='checkbox' value="apple" checked>
<input type='checkbox' value="orange">
<input type='checkbox' value="pear" checked>
<input type='checkbox' value="naartjie">
</code></pre>
<p>That I would like to bind to a list in my controller such that whenever a checkbox is changed the controller maintains a list of all the checked values, for example, <code>['apple', 'pear']</code>.</p>
<p>ng-model seems to only be able to bind the value of one single checkbox to a variable in the controller.</p>
<p>Is there another way to do it so that I can bind the four checkboxes to a list in the controller?</p> | <p>There are two ways to approach this problem. Either use a simple array or an array of objects. Each solution has it pros and cons. Below you'll find one for each case.</p>
<hr>
<h3>With a simple array as input data</h3>
<p>The HTML could look like:</p>
<pre><code><label ng-repeat="fruitName in fruits">
<input
type="checkbox"
name="selectedFruits[]"
value="{{fruitName}}"
ng-checked="selection.indexOf(fruitName) > -1"
ng-click="toggleSelection(fruitName)"
> {{fruitName}}
</label>
</code></pre>
<p>And the appropriate controller code would be:</p>
<pre><code>app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) {
// Fruits
$scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];
// Selected fruits
$scope.selection = ['apple', 'pear'];
// Toggle selection for a given fruit by name
$scope.toggleSelection = function toggleSelection(fruitName) {
var idx = $scope.selection.indexOf(fruitName);
// Is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// Is newly selected
else {
$scope.selection.push(fruitName);
}
};
}]);
</code></pre>
<p><strong>Pros</strong>: Simple data structure and toggling by name is easy to handle</p>
<p><strong>Cons</strong>: Add/remove is cumbersome as two lists (the input and selection) have to be managed</p>
<hr>
<h3>With an object array as input data</h3>
<p>The HTML could look like:</p>
<pre><code><label ng-repeat="fruit in fruits">
<!--
- Use `value="{{fruit.name}}"` to give the input a real value, in case the form gets submitted
traditionally
- Use `ng-checked="fruit.selected"` to have the checkbox checked based on some angular expression
(no two-way-data-binding)
- Use `ng-model="fruit.selected"` to utilize two-way-data-binding. Note that `.selected`
is arbitrary. The property name could be anything and will be created on the object if not present.
-->
<input
type="checkbox"
name="selectedFruits[]"
value="{{fruit.name}}"
ng-model="fruit.selected"
> {{fruit.name}}
</label>
</code></pre>
<p>And the appropriate controller code would be:</p>
<pre><code>app.controller('ObjectArrayCtrl', ['$scope', 'filterFilter', function ObjectArrayCtrl($scope, filterFilter) {
// Fruits
$scope.fruits = [
{ name: 'apple', selected: true },
{ name: 'orange', selected: false },
{ name: 'pear', selected: true },
{ name: 'naartjie', selected: false }
];
// Selected fruits
$scope.selection = [];
// Helper method to get selected fruits
$scope.selectedFruits = function selectedFruits() {
return filterFilter($scope.fruits, { selected: true });
};
// Watch fruits for changes
$scope.$watch('fruits|filter:{selected:true}', function (nv) {
$scope.selection = nv.map(function (fruit) {
return fruit.name;
});
}, true);
}]);
</code></pre>
<p><strong>Pros</strong>: Add/remove is very easy</p>
<p><strong>Cons</strong>: Somewhat more complex data structure and toggling by name is cumbersome or requires a helper method</p>
<hr>
<p><strong>Demo</strong>: <a href="http://jsbin.com/ImAqUC/1/" rel="noreferrer">http://jsbin.com/ImAqUC/1/</a></p> | {
"question_id": 14514461,
"question_date": "2013-01-25T02:36:46.960Z",
"question_score": 692,
"tags": "javascript|angularjs",
"answer_id": 14520103,
"answer_date": "2013-01-25T10:40:07.570Z",
"answer_score": 951
} |
Please answer the following Stack Overflow question:
Title: What does the Java assert keyword do, and when should it be used?
<p>What are some <strong>real life examples</strong> to understand the key role of assertions?</p> | <p><a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.10" rel="noreferrer">Assertions</a> (by way of the <strong>assert</strong> keyword) were added in Java 1.4. They are used to verify the correctness of an invariant in the code. They should never be triggered in production code, and are indicative of a bug or misuse of a code path. They can be activated at run-time by way of the <code>-ea</code> option on the <code>java</code> command, but are not turned on by default.</p>
<p>An example:</p>
<pre><code>public Foo acquireFoo(int id) {
Foo result = null;
if (id > 50) {
result = fooService.read(id);
} else {
result = new Foo(id);
}
assert result != null;
return result;
}
</code></pre> | {
"question_id": 2758224,
"question_date": "2010-05-03T13:11:56.183Z",
"question_score": 692,
"tags": "java|assertions",
"answer_id": 2758645,
"answer_date": "2010-05-03T14:14:52.603Z",
"answer_score": 471
} |
Please answer the following Stack Overflow question:
Title: Return a default value if a dictionary key is not available
<p>I need a way to get a dictionary value if its key exists, or simply return <code>None</code>, if it does not.</p>
<p>However, Python raises a <code>KeyError</code> exception if you search for a key that does not exist. I know that I can check for the key, but I am looking for something more explicit. Is there a way to just return <code>None</code> if the key does not exist?</p> | <p>You can use <a href="http://docs.python.org/library/stdtypes.html#dict.get" rel="noreferrer"><code>dict.get()</code></a></p>
<pre><code>value = d.get(key)
</code></pre>
<p>which will return <code>None</code> if <code>key is not in d</code>. You can also provide a different default value that will be returned instead of <code>None</code>:</p>
<pre><code>value = d.get(key, "empty")
</code></pre> | {
"question_id": 6130768,
"question_date": "2011-05-25T20:49:52.057Z",
"question_score": 692,
"tags": "python|dictionary|key|nonetype",
"answer_id": 6130800,
"answer_date": "2011-05-25T20:52:32.417Z",
"answer_score": 1157
} |
Please answer the following Stack Overflow question:
Title: Managing CSS Explosion
<p>I have been heavily relying on CSS for a website that I am working on. Right now, all the CSS styles are being applied on a per tag basis, and so now I am trying to move it to more of an external styling to help with any future changes.</p>
<p>But now the problem is that I have noticed I am getting a "CSS Explosion". It is becoming difficult for me to decide how to best organize and abstract data within the CSS file.</p>
<p>I am using a large number of <code>div</code> tags within the website, moving from a heavily table-based website. So I'm getting a lot of CSS selectors that look like this:</p>
<pre class="lang-css prettyprint-override"><code>div.title {
background-color: blue;
color: white;
text-align: center;
}
div.footer {
/* Styles Here */
}
div.body {
/* Styles Here */
}
/* And many more */
</code></pre>
<p>It's not too bad yet, but as I am a beginner, I was wondering if recommendations could be made on how best to organize the various parts of a CSS file. I don't want to have a separate CSS attribute for every element on my website, and I always want the CSS file to be fairly intuitive and easy to read.</p>
<p>My ultimate goal is to make it easy to use the CSS files and demonstrate their power to increase the speed of web development. This way, other individuals that may work on this site in the future will also get into the practice of using good coding practices, rather than having to pick it up the way I did.</p> | <p>This is a very good question. Everywhere I look, CSS files tend to get out of control after a while—especially, but not only, when working in a team.</p>
<p>The following are the rules I myself am trying to adhere to (not that I always manage to.)</p>
<ul>
<li><p><strong>Refactor early, refactor often.</strong> Frequently clean up CSS files, fuse together multiple definitions of the same class. Remove obsolete definitions <em>immediately</em>.</p></li>
<li><p>When adding CSS during fixing bugs, leave a comment as to what the change does ("This is to make sure the box is left aligned in IE < 7")</p></li>
<li><p>Avoid redundancies, e.g. defining the same thing in <code>.classname</code> and <code>.classname:hover</code>.</p></li>
<li><p>Use comments <code>/** Head **/</code> to build a clear structure.</p></li>
<li><p>Use a prettifier tool that helps maintain a constant style. I use <a href="http://www.polystyle.com/" rel="noreferrer"><strong>Polystyle</strong></a>, with which I'm quite happy (costs $15 but is money well spent). There are free ones around as well (e.g. <a href="http://www.codebeautifier.com/" rel="noreferrer"><strong>Code Beautifier</strong></a> based on <a href="http://csstidy.sourceforge.net/" rel="noreferrer"><strong>CSS Tidy</strong></a>, an open-source tool).</p></li>
<li><p>Build sensible classes. See below for a few notes on this.</p></li>
<li><p>Use semantics, avoid DIV soup - use <code><ul></code>s for menus, for example. </p></li>
<li><p>Define everything on as low a level as possible (e.g. a default font family, colour and size in the <code>body</code>) and use <code>inherit</code> where possible</p></li>
<li><p>If you have very complex CSS, maybe a CSS pre-compiler helps. I'm planning to look into <a href="http://docs.xcss.sygnal.com/" rel="noreferrer"><strong>xCSS</strong></a> for the very same reason soon. There are several others around.</p></li>
<li><p>If working in a team, highlight the necessity of quality and standards for CSS files as well. Everybody's big on coding standards in their programming language(s), but there is little awareness that this is necessary for CSS too.</p></li>
<li><p>If working in a team, <em>do</em> consider using Version Control. It makes things that much easier to track, and editing conflicts that much easier to solve. It's really worth it, even if you're "just" into HTML and CSS.</p></li>
<li><p>Do not work with <code>!important</code>. Not only because IE =< 7 can't deal with it. In a complex structure, the use of <code>!important</code> is often tempting to change a behaviour whose source can't be found, but it's <em>poison</em> for long-term maintenance.</p></li>
</ul>
<p><strong>Building sensible classes</strong></p>
<p>This is how I like to build sensible classes. </p>
<p>I apply global settings first:</p>
<pre><code>body { font-family: .... font-size ... color ... }
a { text-decoration: none; }
</code></pre>
<p>Then, I identify the main sections of the page's layout—e.g. the top area, the menu, the content, and the footer. <strong>If I wrote good markup, these areas will be identical to the HTML structure.</strong> </p>
<p>Then, I start building CSS classes, specifying as much ancestry as possible as long as it is sensible, and grouping related classes as closely as possible.</p>
<pre><code>div.content ul.table_of_contents
div.content ul.table_of_contents li
div.content ul.table_of_contents li h1
div.content ul.table_of_contents li h2
div.content ul.table_of_contents li span.pagenumber
</code></pre>
<p>Think of the whole CSS structure as a <em>tree</em> with increasingly specific definitions the further away from the root you are. You want to keep the number of classes as low as possible, and you want to repeat yourself as seldom as possible.</p>
<p>For example, let's say you have three levels of navigational menus.
These three menus look different, but they also share certain characteristics. For example, they are all <code><ul></code>, they all have the same font size, and the items are all next to each other (as opposed to the default rendering of an <code>ul</code>). Also, none of the menus has any bullet points (<code>list-style-type</code>).</p>
<p>First, define the <em>common</em> characteristics in a class named <code>menu</code>:</p>
<pre><code>div.navi ul.menu { display: ...; list-style-type: none; list-style-image: none; }
div.navi ul.menu li { float: left }
</code></pre>
<p>then, define the specific characteristics of each of the three menus. Level 1 is 40 pixels tall; levels 2 and 3, 20 pixels.</p>
<p><strong>Note:</strong> you could also use multiple classes for this but Internet Explorer 6 <a href="https://stackoverflow.com/questions/312022/use-double-classes-in-ie6-css"><strong>has problems with multiple classes</strong></a>, so this example uses <code>id</code>s.</p>
<pre class="lang-css prettyprint-override"><code>div.navi ul.menu#level1 { height: 40px; }
div.navi ul.menu#level2 { height: 20px; }
div.navi ul.menu#level3 { height: 16px; }
</code></pre>
<p>The markup for the menu will look like this:</p>
<pre><code><ul id="level1" class="menu"><li> ...... </li></ul>
<ul id="level2" class="menu"><li> ...... </li></ul>
<ul id="level3" class="menu"><li> ...... </li></ul>
</code></pre>
<p>If you have semantically similar elements on the page—like these three menus—try to work out the commonalities first and put them into a class; then, work out the specific properties and apply them to classes, or, if you have to support Internet Explorer 6, ID's.</p>
<p><strong>Miscellaneous HTML tips</strong></p>
<blockquote>
<p>If you add these semantics to your HTML output, designers can later customize the look of web sites and/or apps using pure CSS, which is a great advantage and time-saver.</p>
</blockquote>
<ul>
<li><p>If possible, give every page's body a unique class: <code><body class='contactpage'></code> this makes it very easy to add page-specific tweaks to the style sheet: </p>
<pre><code>body.contactpage div.container ul.mainmenu li { color: green }
</code></pre></li>
<li><p>When building menus automatically, add as much CSS context as possible to allow extensive styling later. For example:</p>
<pre><code><ul class="mainmenu">
<li class="item_first item_active item_1"> First item </li>
<li class="item_2"> Second item </li>
<li class="item_3"> Third item </li>
<li class="item_last item_4"> Fourth item </li>
</ul>
</code></pre>
<p>This way, every menu item can be accessed for styling according to its semantic context: Whether it's the first or last item in the list; Whether it's the currently active item; and by number.</p></li>
</ul>
<blockquote>
<p><strong>Note</strong> that this assigning of multiple classes as outlined in the example above <a href="https://stackoverflow.com/questions/312022/use-double-classes-in-ie6-css"><strong>does not work properly in IE6</strong></a>. There is a <a href="http://code.google.com/p/ie7-js/" rel="noreferrer"><strong>workaround</strong></a> to make IE6 able to deal with multiple classes. If the workaround is not an option, you will have to set the class that is most important to you (item number, active or first/last), or resort to using IDs.</p>
</blockquote> | {
"question_id": 2253110,
"question_date": "2010-02-12T16:03:34.813Z",
"question_score": 692,
"tags": "css|organization",
"answer_id": 2253189,
"answer_date": "2010-02-12T16:12:32.740Z",
"answer_score": 571
} |
Please answer the following Stack Overflow question:
Title: How to urlencode a querystring in Python?
<p>I am trying to urlencode this string before I submit. </p>
<pre><code>queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"];
</code></pre> | <p>You need to pass your parameters into <a href="http://docs.python.org/2/library/urllib.html#urllib.urlencode" rel="noreferrer"><code>urlencode()</code></a> as either a mapping (dict), or a sequence of 2-tuples, like:</p>
<pre><code>>>> import urllib
>>> f = { 'eventName' : 'myEvent', 'eventDescription' : 'cool event'}
>>> urllib.urlencode(f)
'eventName=myEvent&eventDescription=cool+event'
</code></pre>
<p><strong>Python 3 or above</strong></p>
<p>Use <a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode" rel="noreferrer"><code>urllib.parse.urlencode</code></a>:</p>
<pre><code>>>> urllib.parse.urlencode(f)
eventName=myEvent&eventDescription=cool+event
</code></pre>
<p>Note that this does <em>not</em> do url encoding in the commonly used sense (look at the output). For that use <a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote_plus" rel="noreferrer"><code>urllib.parse.quote_plus</code></a>.</p> | {
"question_id": 5607551,
"question_date": "2011-04-09T20:07:12.780Z",
"question_score": 691,
"tags": "python|urllib|urlencode",
"answer_id": 5607708,
"answer_date": "2011-04-09T20:30:21.633Z",
"answer_score": 687
} |
Please answer the following Stack Overflow question:
Title: What is the difference between char, nchar, varchar, and nvarchar in SQL Server?
<p>What is meant by <code>nvarchar</code>?</p>
<p>What is the difference between <code>char</code>, <code>nchar</code>, <code>varchar</code>, and <code>nvarchar</code> in SQL Server?</p> | <p>Just to clear up... or sum up...</p>
<ul>
<li><strong><code>nchar</code></strong> and <strong><code>nvarchar</code></strong> can store <strong>Unicode</strong> characters.</li>
<li><strong><code>char</code></strong> and <strong><code>varchar</code></strong> <strong>cannot store Unicode</strong> characters.</li>
<li><strong><code>char</code></strong> and <strong><code>nchar</code></strong> are <strong>fixed-length</strong> which will <strong>reserve storage space</strong> for number of characters you specify even if you don't use up all that space.</li>
<li><strong><code>varchar</code></strong> and <strong><code>nvarchar</code></strong> are <strong>variable-length</strong> which will only use up spaces for the characters you store. It <strong>will not reserve storage like <code>char</code> or <code>nchar</code></strong>.</li>
</ul>
<p><code>nchar</code> and <code>nvarchar</code> will take up twice as much storage space, so it may be wise to use them only if you need <em>Unicode</em> support.</p> | {
"question_id": 176514,
"question_date": "2008-10-06T22:47:33.480Z",
"question_score": 691,
"tags": "sql-server|varchar",
"answer_id": 176565,
"answer_date": "2008-10-06T23:02:33.887Z",
"answer_score": 952
} |
Please answer the following Stack Overflow question:
Title: Remove a fixed prefix/suffix from a string in Bash
<p>In my <code>bash</code> script I have a string and its prefix/suffix. I need to remove the prefix/suffix from the original string.</p>
<p>For example, let's say I have the following values:</p>
<pre><code>string="hello-world"
prefix="hell"
suffix="ld"
</code></pre>
<p>How do I get to the following result?</p>
<pre><code>result="o-wor"
</code></pre> | <pre><code>$ prefix="hell"
$ suffix="ld"
$ string="hello-world"
$ foo=${string#"$prefix"}
$ foo=${foo%"$suffix"}
$ echo "${foo}"
o-wor
</code></pre>
<p>This is documented in the <a href="https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html" rel="noreferrer">Shell Parameter Expansion</a> section of the manual:</p>
<blockquote>
<p><code>${parameter#word}</code><br />
<code>${parameter##word}</code></p>
<p>The word is expanded to produce a pattern and matched according to the rules described below (see <a href="https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html" rel="noreferrer">Pattern Matching</a>). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the <code>#</code> case) or the longest matching pattern (the <code>##</code> case) deleted. […]</p>
<p><code>${parameter%word}</code><br />
<code>${parameter%%word}</code></p>
<p>The word is expanded to produce a pattern and matched according to the rules described below (see <a href="https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html" rel="noreferrer">Pattern Matching</a>). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the <code>%</code> case) or the longest matching pattern (the <code>%%</code> case) deleted. […]</p>
</blockquote> | {
"question_id": 16623835,
"question_date": "2013-05-18T11:37:50.667Z",
"question_score": 691,
"tags": "bash|replace|pattern-matching|string-interpolation",
"answer_id": 16623897,
"answer_date": "2013-05-18T11:43:59.300Z",
"answer_score": 1062
} |
Please answer the following Stack Overflow question:
Title: How to write a bash script that takes optional input arguments?
<p>I want my script to be able to take an optional input, </p>
<p>e.g. currently my script is </p>
<pre><code>#!/bin/bash
somecommand foo
</code></pre>
<p>but I would like it to say:</p>
<pre><code>#!/bin/bash
somecommand [ if $1 exists, $1, else, foo ]
</code></pre> | <p>You could use the default-value syntax:</p>
<pre><code>somecommand ${1:-foo}
</code></pre>
<p>The above will, as described in <a href="http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion" rel="noreferrer">Bash Reference Manual - 3.5.3 Shell Parameter Expansion</a> [emphasis mine]:</p>
<blockquote>
<p>If parameter is unset <em>or null</em>, the expansion of word is substituted. Otherwise, the value of parameter is substituted.</p>
</blockquote>
<p>If you only want to substitute a default value if the parameter is unset (but not if it's null, e.g. not if it's an empty string), use this syntax instead:</p>
<pre><code>somecommand ${1-foo}
</code></pre>
<p>Again from <a href="http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion" rel="noreferrer">Bash Reference Manual - 3.5.3 Shell Parameter Expansion</a>:</p>
<blockquote>
<p>Omitting the colon results in a test only for a parameter that is unset. Put another way, if the colon is included, the operator tests for both parameter’s existence and that its value is not null; if the colon is omitted, the operator tests only for existence.</p>
</blockquote> | {
"question_id": 9332802,
"question_date": "2012-02-17T17:32:52.960Z",
"question_score": 691,
"tags": "bash|arguments|parameter-passing",
"answer_id": 9333006,
"answer_date": "2012-02-17T17:50:19.917Z",
"answer_score": 985
} |
Please answer the following Stack Overflow question:
Title: @selector() in Swift?
<p>I'm trying to create an <code>NSTimer</code> in <code>Swift</code> but I'm having some trouble.</p>
<pre><code>NSTimer(timeInterval: 1, target: self, selector: test(), userInfo: nil, repeats: true)
</code></pre>
<p><em><code>test()</code> is a function in the same class.</em></p>
<hr>
<p>I get an error in the editor: </p>
<blockquote>
<p>Could not find an overload for 'init' that accepts the supplied
arguments</p>
</blockquote>
<p>When I change <code>selector: test()</code> to <code>selector: nil</code> the error disappears.</p>
<p>I've tried:</p>
<ul>
<li><code>selector: test()</code></li>
<li><code>selector: test</code></li>
<li><code>selector: Selector(test())</code></li>
</ul>
<p>But nothing works and I can't find a solution in the references.</p> | <p>Swift <em>itself</em> doesn't use selectors — several design patterns that in Objective-C make use of selectors work differently in Swift. (For example, use optional chaining on protocol types or <code>is</code>/<code>as</code> tests instead of <code>respondsToSelector:</code>, and use closures wherever you can instead of <code>performSelector:</code> for better type/memory safety.)</p>
<p>But there are still a number of important ObjC-based APIs that use selectors, including timers and the target/action pattern. Swift provides the <code>Selector</code> type for working with these. (Swift automatically uses this in place of ObjC's <code>SEL</code> type.)</p>
<h3>In Swift 2.2 (Xcode 7.3) and later (including Swift 3 / Xcode 8 and Swift 4 / Xcode 9):</h3>
<p>You can construct a <code>Selector</code> from a Swift function type using the <code>#selector</code> expression.</p>
<pre><code>let timer = Timer(timeInterval: 1, target: object,
selector: #selector(MyClass.test),
userInfo: nil, repeats: false)
button.addTarget(object, action: #selector(MyClass.buttonTapped),
for: .touchUpInside)
view.perform(#selector(UIView.insertSubview(_:aboveSubview:)),
with: button, with: otherButton)
</code></pre>
<p>The great thing about this approach? A function reference is checked by the Swift compiler, so you can use the <code>#selector</code> expression only with class/method pairs that actually exist and are eligible for use as selectors (see "Selector availability" below). You're also free to make your function reference only as specific as you need, as per <a href="https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html#//apple_ref/doc/uid/TP40014097-CH32-ID400" rel="noreferrer">the Swift 2.2+ rules for function-type naming</a>.</p>
<p>(This is actually an improvement over ObjC's <code>@selector()</code> directive, because the compiler's <code>-Wundeclared-selector</code> check verifies only that the named selector exists. The Swift function reference you pass to <code>#selector</code> checks existence, membership in a class, and type signature.)</p>
<p>There are a couple of extra caveats for the function references you pass to the <code>#selector</code> expression:</p>
<ul>
<li>Multiple functions with the same base name can be differentiated by their parameter labels using the aforementioned <a href="https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html#//apple_ref/doc/uid/TP40014097-CH32-ID400" rel="noreferrer">syntax for function references</a> (e.g. <code>insertSubview(_:at:)</code> vs <code>insertSubview(_:aboveSubview:)</code>). But if a function has no parameters, the only way to disambiguate it is to use an <code>as</code> cast with the function's type signature (e.g. <code>foo as () -> ()</code> vs <code>foo(_:)</code>).</li>
<li>There's a special syntax for property getter/setter pairs in Swift 3.0+. For example, given a <code>var foo: Int</code>, you can use <code>#selector(getter: MyClass.foo)</code> or <code>#selector(setter: MyClass.foo)</code>.</li>
</ul>
<h3>General notes:</h3>
<p><strong>Cases where <code>#selector</code> doesn't work, and naming:</strong> Sometimes you don't have a function reference to make a selector with (for example, with methods dynamically registered in the ObjC runtime). In that case, you can construct a <code>Selector</code> from a string: e.g. <code>Selector("dynamicMethod:")</code> — though you lose the compiler's validity checking. When you do that, you need to follow ObjC naming rules, including colons (<code>:</code>) for each parameter.</p>
<p><strong>Selector availability:</strong> The method referenced by the selector must be exposed to the ObjC runtime. In Swift 4, every method exposed to ObjC must have its declaration prefaced with the <code>@objc</code> attribute. (In previous versions you got that attribute for free in some cases, but now you have to explicitly declare it.)</p>
<p>Remember that <code>private</code> symbols aren't exposed to the runtime, too — your method needs to have at least <code>internal</code> visibility.</p>
<p><strong>Key paths:</strong> These are related to but not quite the same as selectors. There's a special syntax for these in Swift 3, too: e.g. <code>chris.valueForKeyPath(#keyPath(Person.friends.firstName))</code>. See <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0062-objc-keypaths.md" rel="noreferrer">SE-0062</a> for details. And even more <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0161-key-paths.md" rel="noreferrer"><code>KeyPath</code> stuff in Swift 4</a>, so make sure you're using the right KeyPath-based API instead of selectors if appropriate.</p>
<p>You can read more about selectors under <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html#//apple_ref/doc/uid/TP40014216-CH4-XID_26" rel="noreferrer">Interacting with Objective-C APIs</a> in <em>Using Swift with Cocoa and Objective-C</em>.</p>
<p><sup><strong>Note:</strong> Before Swift 2.2, <code>Selector</code> conformed to <code>StringLiteralConvertible</code>, so you might find old code where bare strings are passed to APIs that take selectors. You'll want to run "Convert to Current Swift Syntax" in Xcode to get those using <code>#selector</code>.</sup></p> | {
"question_id": 24007650,
"question_date": "2014-06-03T05:21:43.033Z",
"question_score": 691,
"tags": "swift|selector|nstimer",
"answer_id": 24007718,
"answer_date": "2014-06-03T05:27:11.183Z",
"answer_score": 960
} |
Please answer the following Stack Overflow question:
Title: When to use cla(), clf() or close() for clearing a plot in matplotlib?
<p>Matplotlib offers these functions:</p>
<pre><code>cla() # Clear axis
clf() # Clear figure
close() # Close a figure window
</code></pre>
<p>When should I use each function and what exactly does it do?</p> | <p>They all do different things, since matplotlib uses a hierarchical order in which a figure window contains a figure which may consist of many axes. Additionally, there are functions from the pyplot interface and there are methods on the <code>Figure</code> class. I will discuss both cases below.</p>
<h2>pyplot interface</h2>
<p><code>pyplot</code> is a module that collects a couple of functions that allow matplotlib to be used in a functional manner. I here assume that <code>pyplot</code> has been imported as <code>import matplotlib.pyplot as plt</code>.
In this case, there are three different commands that remove stuff:</p>
<p>See <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.html" rel="noreferrer"><code>matplotlib.pyplot</code></a> Functions:</p>
<ul>
<li><strong><a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.cla.html#matplotlib.pyplot.cla" rel="noreferrer"><code>plt.cla()</code></a> clears an axis</strong>, i.e. the currently active axis in the current figure. It leaves the other axes untouched.</li>
<li><strong><a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.clf.html#matplotlib.pyplot.clf" rel="noreferrer"><code>plt.clf()</code></a> clears the entire current figure with all its axes</strong>, but leaves the window opened, such that it may be reused for other plots.</li>
<li><strong><a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.close.html#matplotlib.pyplot.close" rel="noreferrer"><code>plt.close()</code></a> closes a window</strong>, which will be the current window, if not specified otherwise.</li>
</ul>
<p>Which functions suits you best depends thus on your use-case.</p>
<p>The <code>close()</code> function furthermore allows one to specify which window should be closed. The argument can either be a number or name given to a window when it was created using <code>figure(number_or_name)</code> or it can be a figure instance <code>fig</code> obtained, i.e., using<code>fig = figure()</code>. If no argument is given to <code>close()</code>, the currently active window will be closed. Furthermore, there is the syntax <code>close('all')</code>, which closes all figures.</p>
<h2>methods of the Figure class</h2>
<p>Additionally, the <code>Figure</code> class provides methods for clearing figures.
I'll assume in the following that <code>fig</code> is an instance of a <code>Figure</code>:</p>
<p><a href="https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.clf" rel="noreferrer"><code>fig.clf()</code> clears the entire figure</a>. This call is equivalent to <code>plt.clf()</code> only if <code>fig</code> is the current figure.</p>
<p><code>fig.clear()</code> is a synonym for <code>fig.clf()</code></p>
<p>Note that even <code>del fig</code> will not close the associated figure window. As far as I know the only way to close a figure window is using <code>plt.close(fig)</code> as described above.</p> | {
"question_id": 8213522,
"question_date": "2011-11-21T14:38:03.013Z",
"question_score": 690,
"tags": "python|matplotlib|plot",
"answer_id": 8228808,
"answer_date": "2011-11-22T14:54:33.910Z",
"answer_score": 868
} |
Please answer the following Stack Overflow question:
Title: RedirectToAction with parameter
<p>I have an action I call from an anchor thusly, <code>Site/Controller/Action/ID</code> where <code>ID</code> is an <code>int</code>.</p>
<p>Later on I need to redirect to this same Action from a Controller.</p>
<p>Is there a clever way to do this? Currently I'm stashing <code>ID</code> in tempdata, but when you
hit f5 to refresh the page again after going back, the tempdata is gone and the page crashes.</p> | <p>You can pass the id as part of the routeValues parameter of the RedirectToAction() method.</p>
<pre><code>return RedirectToAction("Action", new { id = 99 });
</code></pre>
<p>This will cause a redirect to Site/Controller/Action/99. No need for temp or any kind of view data.</p> | {
"question_id": 1257482,
"question_date": "2009-08-10T22:05:09.077Z",
"question_score": 690,
"tags": "c#|asp.net-mvc|controller|redirecttoaction",
"answer_id": 1257632,
"answer_date": "2009-08-10T22:38:49.290Z",
"answer_score": 1118
} |
Please answer the following Stack Overflow question:
Title: Add a tooltip to a div
<p>I have a div tag like this:</p>
<pre class="lang-html prettyprint-override"><code><div>
<label>Name</label>
<input type="text"/>
</div>
</code></pre>
<p>How can I displaying a tooltip on <code>:hover</code> of the div, preferably with a fade in/out effect.</p> | <p>For the basic tooltip, you want:</p>
<pre><code><div title="This is my tooltip">
</code></pre>
<p>like:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.visible {
height: 3em;
width: 10em;
background: yellow;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div title="This is my tooltip" class="visible"></div></code></pre>
</div>
</div>
</p>
<p>For a fancier javascript version, you can look into:</p>
<p><a href="https://jqueryhouse.com/best-jquery-tooltip-plugins/" rel="noreferrer">https://jqueryhouse.com/best-jquery-tooltip-plugins/</a></p>
<p>The above link gives you 25 options for tooltips.</p> | {
"question_id": 7117073,
"question_date": "2011-08-19T04:49:50.040Z",
"question_score": 690,
"tags": "javascript|html|css|tooltip",
"answer_id": 7117107,
"answer_date": "2011-08-19T04:54:43.483Z",
"answer_score": 1101
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.