input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: What is a clearfix?
<p>Recently I was looking through some website's code, and saw that every <code><div></code> had a class <code>clearfix</code>.</p>
<p>After a quick Google search, I learned that it is for IE6 sometimes, but what <strong>actually</strong> is a clearfix? </p>
<p>Could you provide some examples of a layout with a clearfix, compared to a layout without a clearfix?</p> | <h2>If you don't need to support IE9 or lower, you can use flexbox freely, and don't need to use floated layouts.</h2>
<p>It's worth noting that today, the use of floated elements for layout is getting more and more discouraged with the use of better alternatives.</p>
<ul>
<li><code>display: inline-block</code> - Better</li>
<li><strong><a href="https://developer.mozilla.org/en-US/docs/CSS/Using_CSS_flexible_boxes" rel="noreferrer">Flexbox</a></strong> - Best (but limited browser support)</li>
</ul>
<p>Flexbox is supported from Firefox 18, Chrome 21, Opera 12.10, and Internet Explorer 10, Safari 6.1 (including Mobile Safari) and Android's default browser 4.4.</p>
<p>For a detailed browser list see: <a href="https://caniuse.com/flexbox" rel="noreferrer">https://caniuse.com/flexbox</a>.</p>
<p>(Perhaps once its position is established completely, it may be the absolutely recommended way of laying out elements.)</p>
<hr />
<p>A clearfix is a way for an element to <strong>automatically clear its child elements</strong>, so that you don't need to add additional markup. It's generally used in <em>float layouts</em> where elements are floated to be stacked horizontally.</p>
<p>The clearfix is a way to combat the <strong><a href="https://complexspiral.com/publications/containing-floats/" rel="noreferrer">zero-height container problem</a></strong> for floated elements</p>
<p>A clearfix is performed as follows:</p>
<pre class="lang-css prettyprint-override"><code>.clearfix::after {
content: " "; /* Older browser do not support empty content */
visibility: hidden;
display: block;
height: 0;
clear: both;
}
</code></pre>
<p>Or, if you don't require IE<8 support, the following is fine too:</p>
<pre class="lang-css prettyprint-override"><code>.clearfix::after {
content: "";
display: table;
clear: both;
}
</code></pre>
<p>Normally you would need to do something as follows:</p>
<pre class="lang-html prettyprint-override"><code><div>
<div style="float: left;">Sidebar</div>
<div style="clear: both;"></div> <!-- Clear the float -->
</div>
</code></pre>
<p>With clearfix, you only need the following:</p>
<pre class="lang-html prettyprint-override"><code><div class="clearfix">
<div style="float: left;" class="clearfix">Sidebar</div>
<!-- No Clearing div! -->
</div>
</code></pre>
<p>Read about it in <strong><a href="https://css-tricks.com/all-about-floats/" rel="noreferrer">this article - by Chris Coyer @ CSS-Tricks</a></strong></p> | {
"question_id": 8554043,
"question_date": "2011-12-18T19:02:44.250Z",
"question_score": 1064,
"tags": "html|css|layout|cross-browser|clearfix",
"answer_id": 8554054,
"answer_date": "2011-12-18T19:04:24.703Z",
"answer_score": 1033
} |
Please answer the following Stack Overflow question:
Title: How do I check in SQLite whether a table exists?
<p>How do I, <strong>reliably</strong>, check in SQLite, whether a particular user table exists?</p>
<p>I am not asking for unreliable ways like checking if a "select *" on the table returned an error or not (is this even a good idea?).</p>
<p>The reason is like this:</p>
<p>In my program, I need to create and then populate some tables if they do not exist already.</p>
<p>If they do already exist, I need to update some tables.</p>
<p>Should I take some other path instead to signal that the tables in question have already been created - say for example, by creating/putting/setting a certain flag in my program initialization/settings file on disk or something?</p>
<p>Or does my approach make sense?</p> | <p>I missed that FAQ entry.</p>
<p>Anyway, for future reference, the complete query is:</p>
<pre><code>SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';
</code></pre>
<p>Where <code>{table_name}</code> is the name of the table to check.</p>
<p>Documentation section for reference: <a href="http://www.sqlite.org/fileformat2.html#storage_of_the_sql_database_schema" rel="noreferrer">Database File Format. 2.6. Storage Of The SQL Database Schema</a></p>
<ul>
<li>This will return a list of tables with the name specified; that is, the cursor will have a count of 0 (does not exist) or a count of 1 (does exist)</li>
</ul> | {
"question_id": 1601151,
"question_date": "2009-10-21T14:22:10.480Z",
"question_score": 1064,
"tags": "sqlite",
"answer_id": 1604121,
"answer_date": "2009-10-21T22:57:07.187Z",
"answer_score": 1171
} |
Please answer the following Stack Overflow question:
Title: What characters do I need to escape in XML documents?
<p>What characters must be escaped in XML documents, or where could I find such a list?</p> | <p>If you use an appropriate class or library, they will do the escaping for you. Many XML issues are caused by string concatenation.</p>
<h1>XML escape characters</h1>
<p>There are only five:</p>
<pre><code>" &quot;
' &apos;
< &lt;
> &gt;
& &amp;
</code></pre>
<p>Escaping characters depends on where the special character is used.</p>
<p>The examples can be validated at the <a href="https://validator.w3.org/#validate_by_input" rel="noreferrer">W3C Markup Validation Service</a>.</p>
<h2>Text</h2>
<p>The safe way is to escape all five characters in text. However, the three characters <code>"</code>, <code>'</code> and <code>></code> needn't be escaped in text:</p>
<pre><code><?xml version="1.0"?>
<valid>"'></valid>
</code></pre>
<h2>Attributes</h2>
<p>The safe way is to escape all five characters in attributes. However, the <code>></code> character needn't be escaped in attributes:</p>
<pre><code><?xml version="1.0"?>
<valid attribute=">"/>
</code></pre>
<p>The <code>'</code> character needn't be escaped in attributes if the quotes are <code>"</code>:</p>
<pre><code><?xml version="1.0"?>
<valid attribute="'"/>
</code></pre>
<p>Likewise, the <code>"</code> needn't be escaped in attributes if the quotes are <code>'</code>:</p>
<pre><code><?xml version="1.0"?>
<valid attribute='"'/>
</code></pre>
<h2>Comments</h2>
<p>All five special characters <strong>must not</strong> be escaped in comments:</p>
<pre><code><?xml version="1.0"?>
<valid>
<!-- "'<>& -->
</valid>
</code></pre>
<h2>CDATA</h2>
<p>All five special characters <strong>must not</strong> be escaped in <a href="https://en.wikipedia.org/wiki/CDATA" rel="noreferrer">CDATA</a> sections:</p>
<pre><code><?xml version="1.0"?>
<valid>
<![CDATA["'<>&]]>
</valid>
</code></pre>
<h2>Processing instructions</h2>
<p>All five special characters <strong>must not</strong> be escaped in XML processing instructions:</p>
<pre><code><?xml version="1.0"?>
<?process <"'&> ?>
<valid/>
</code></pre>
<h1>XML vs. HTML</h1>
<p>HTML has <a href="http://www.escapecodes.info/" rel="noreferrer">its own set of escape codes</a> which cover a lot more characters.</p> | {
"question_id": 1091945,
"question_date": "2009-07-07T12:07:42.727Z",
"question_score": 1063,
"tags": "xml|escaping|character",
"answer_id": 1091953,
"answer_date": "2009-07-07T12:09:31.850Z",
"answer_score": 1546
} |
Please answer the following Stack Overflow question:
Title: How to print a number using commas as thousands separators
<p>How do I print an integer with commas as thousands separators?</p>
<pre><code>1234567 ⟶ 1,234,567
</code></pre>
<p>It does not need to be locale-specific to decide between periods and commas.</p> | <h3>Locale unaware</h3>
<pre><code>'{:,}'.format(value) # For Python ≥2.7
f'{value:,}' # For Python ≥3.6
</code></pre>
<h3>Locale aware</h3>
<pre><code>import locale
locale.setlocale(locale.LC_ALL, '') # Use '' for auto, or force e.g. to 'en_US.UTF-8'
'{:n}'.format(value) # For Python ≥2.7
f'{value:n}' # For Python ≥3.6
</code></pre>
<h3>Reference</h3>
<p>Per <a href="https://docs.python.org/library/string.html#format-specification-mini-language" rel="noreferrer">Format Specification Mini-Language</a>,</p>
<blockquote>
<p>The <code>','</code> option signals the use of a comma for a thousands separator. For a locale aware separator, use the <code>'n'</code> integer presentation type instead.</p>
</blockquote> | {
"question_id": 1823058,
"question_date": "2009-11-30T23:11:43.990Z",
"question_score": 1063,
"tags": "python|number-formatting",
"answer_id": 10742904,
"answer_date": "2012-05-24T18:02:17.637Z",
"answer_score": 2206
} |
Please answer the following Stack Overflow question:
Title: Angular: conditional class with *ngClass
<p>What is wrong with my Angular code? I am getting the following error:</p>
<blockquote>
<p>Cannot read property 'remove' of undefined at BrowserDomAdapter.removeClass</p>
</blockquote>
<pre class="lang-html prettyprint-override"><code><ol>
<li *ngClass="{active: step==='step1'}" (click)="step='step1'">Step1</li>
<li *ngClass="{active: step==='step2'}" (click)="step='step2'">Step2</li>
<li *ngClass="{active: step==='step3'}" (click)="step='step3'">Step3</li>
</ol>
</code></pre> | <p>Angular version 2+ provides several ways to add classes conditionally:</p>
<p><strong>type one</strong></p>
<pre><code> [class.my_class] = "step === 'step1'"
</code></pre>
<p><strong>type two</strong></p>
<pre><code> [ngClass]="{'my_class': step === 'step1'}"
</code></pre>
<p>and multiple option:</p>
<pre><code> [ngClass]="{'my_class': step === 'step1', 'my_class2' : step === 'step2' }"
</code></pre>
<p><strong>type three</strong></p>
<pre><code> [ngClass]="{1 : 'my_class1', 2 : 'my_class2', 3 : 'my_class4'}[step]"
</code></pre>
<p><strong>type four</strong></p>
<pre><code> [ngClass]="step == 'step1' ? 'my_class1' : 'my_class2'"
</code></pre>
<p>You can find these examples on the <a href="https://angular.io/api/common/NgClass#description" rel="noreferrer">documentation page</a></p> | {
"question_id": 35269179,
"question_date": "2016-02-08T12:00:54.147Z",
"question_score": 1061,
"tags": "javascript|css|angular|angular-template|angular-ng-class",
"answer_id": 41974490,
"answer_date": "2017-02-01T07:50:31.080Z",
"answer_score": 2383
} |
Please answer the following Stack Overflow question:
Title: Convert a String representation of a Dictionary to a dictionary
<p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p>
<pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
</code></pre>
<p>I prefer not to use <code>eval</code>. What else can I use?</p>
<p>The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the mood to go and modify his classes, to deal with this issue.</p> | <p>You can use the built-in <a href="https://docs.python.org/library/ast.html#ast.literal_eval" rel="noreferrer"><code>ast.literal_eval</code></a>:</p>
<pre><code>>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}
</code></pre>
<p>This is safer than using <code>eval</code>. As its own docs say:</p>
<pre>
>>> help(ast.literal_eval)
Help on function literal_eval in module ast:
literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.
</pre>
<p>For example:</p>
<pre><code>>>> eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree
onerror(os.listdir, path, sys.exc_info())
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree
names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'mongo'
>>> ast.literal_eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string
</code></pre> | {
"question_id": 988228,
"question_date": "2009-06-12T18:25:02.997Z",
"question_score": 1061,
"tags": "python|string|dictionary",
"answer_id": 988251,
"answer_date": "2009-06-12T18:30:45.727Z",
"answer_score": 1557
} |
Please answer the following Stack Overflow question:
Title: Another git process seems to be running in this repository
<p>I'm trying to learn how to use Git and have created a small project with an HTML, CSS, and Javascript file. I made a branch from my basically empty project and then made some changes to my code. I tried staging the changes but I get the following error message:</p>
<pre><code>Another git process seems to be running in this repository, e.g.
an editor opened by 'git commit'. Please make sure all processes
are terminated then try again. If it still fails, a git process
may have crashed in this repository earlier:
remove the file manually to continue.
</code></pre>
<p>Granted, I did run into problems trying to commit my empty project earlier and just quit git bash since I didn't know how to get out of where I somehow had gotten. </p>
<p>Is there any way for me to fix this or should I just start a new repository?</p> | <p>Try deleting <code>index.lock</code> file in your <code>.git</code> directory or in one of your <strong>worktrees</strong> <code>.git/worktrees/*/index.lock</code> if you are in a worktree.</p>
<pre class="lang-bash prettyprint-override"><code>rm -f .git/index.lock
</code></pre>
<p>Such problems generally occur when you execute two <code>git</code> commands simultaneously; maybe one from the command prompt and one from an IDE.</p> | {
"question_id": 38004148,
"question_date": "2016-06-24T00:59:24.897Z",
"question_score": 1061,
"tags": "git",
"answer_id": 38004193,
"answer_date": "2016-06-24T01:05:37.173Z",
"answer_score": 2152
} |
Please answer the following Stack Overflow question:
Title: When should I use curly braces for ES6 import?
<p>It seems to be obvious, but I found myself a bit confused about when to use curly braces for importing a single module in ES6. For example, in the React-Native project I am working on, I have the following file and its content:</p>
<h3>File <em>initialState.js</em></h3>
<pre><code>var initialState = {
todo: {
todos: [
{id: 1, task: 'Finish Coding', completed: false},
{id: 2, task: 'Do Laundry', completed: false},
{id: 2, task: 'Shopping Groceries', completed: false},
]
}
};
export default initialState;
</code></pre>
<p>In the TodoReducer.js, I have to import it without curly braces:</p>
<pre><code>import initialState from './todoInitialState';
</code></pre>
<p>If I enclose the <code>initialState</code> in curly braces, I get the following error for the following line of code:</p>
<blockquote>
<p>Cannot read property todo of undefined</p>
</blockquote>
<h3>File <em>TodoReducer.js</em>:</h3>
<pre><code>export default function todos(state = initialState.todo, action) {
// ...
}
</code></pre>
<p>Similar errors also happen to my components with the curly braces. I was wondering when I should use curly braces for a single import, because obviously, when importing multiple component/modules, you have to enclose them in curly braces, which I know.</p>
<p>The Stack Overflow post at <a href="https://stackoverflow.com/questions/31096597/using-brackets-with-javascript-import-syntax">here</a> does not answer my question, instead I am asking <em>when</em> I should or should not use curly braces for importing a <strong>single</strong> module, or I should never use curly braces for importing a single module in ES6 (this is apparently not the case, as I have seen single import with curly braces required).</p> | <p>This is a <strong>default import</strong>:</p>
<pre><code>// B.js
import A from './A'
</code></pre>
<p>It only works if <code>A</code> has the <strong>default export</strong>:</p>
<pre><code>// A.js
export default 42
</code></pre>
<p>In this case it doesn’t matter what name you assign to it when importing:</p>
<pre><code>// B.js
import A from './A'
import MyA from './A'
import Something from './A'
</code></pre>
<p>Because it will always resolve to whatever is the <strong>default export</strong> of <code>A</code>.</p>
<hr>
<p>This is a <strong>named import called <code>A</code></strong>:</p>
<pre><code>import { A } from './A'
</code></pre>
<p>It only works if <code>A</code> contains a <strong>named export called <code>A</code></strong>:</p>
<pre><code>export const A = 42
</code></pre>
<p>In this case the name matters because you’re importing <strong>a specific thing by its export name</strong>:</p>
<pre><code>// B.js
import { A } from './A'
import { myA } from './A' // Doesn't work!
import { Something } from './A' // Doesn't work!
</code></pre>
<p>To make these work, you would add a <strong>corresponding named export</strong> to <code>A</code>:</p>
<pre><code>// A.js
export const A = 42
export const myA = 43
export const Something = 44
</code></pre>
<hr>
<p>A module can only have <strong>one default export</strong>, but <strong>as many named exports as you'd like</strong> (zero, one, two, or many). You can import them all together:</p>
<pre><code>// B.js
import A, { myA, Something } from './A'
</code></pre>
<p>Here, we import the default export as <code>A</code>, and named exports called <code>myA</code> and <code>Something</code>, respectively.</p>
<pre><code>// A.js
export default 42
export const myA = 43
export const Something = 44
</code></pre>
<p>We can also assign them all different names when importing:</p>
<pre><code>// B.js
import X, { myA as myX, Something as XSomething } from './A'
</code></pre>
<hr>
<p>The default exports tend to be used for whatever you normally expect to get from the module. The named exports tend to be used for utilities that might be handy, but aren’t always necessary. However it is up to you to choose how to export things: for example, a module might have no default export at all.</p>
<p><a href="http://www.2ality.com/2014/09/es6-modules-final.html" rel="noreferrer">This is a great guide to ES modules, explaining the difference between default and named exports.</a></p> | {
"question_id": 36795819,
"question_date": "2016-04-22T13:58:14.347Z",
"question_score": 1061,
"tags": "javascript|import|ecmascript-6",
"answer_id": 36796281,
"answer_date": "2016-04-22T14:19:01.617Z",
"answer_score": 2983
} |
Please answer the following Stack Overflow question:
Title: Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails
<p>I'm getting the error:</p>
<pre><code>FATAL: Peer authentication failed for user "postgres"
</code></pre>
<p>when I try to make postgres work with Rails. </p>
<p>Here's my <a href="http://pastebin.com/4V1sMS01" rel="noreferrer"><code>pg_hba.conf</code></a>, my <a href="http://pastebin.com/mS0G6Srp" rel="noreferrer"><code>database.yml</code></a>, and a <a href="http://pastebin.com/bXg1Pkr5" rel="noreferrer">dump of the full trace</a>.</p>
<p>I changed authentication to md5 in pg_hba and tried different things, but none seem to work. </p>
<p>I also tried creating a new user and database as per <a href="https://stackoverflow.com/questions/9987171/rails-3-2-fatal-peer-authentication-failed-for-user-pgerror">Rails 3.2, FATAL: Peer authentication failed for user (PG::Error)</a></p>
<p>But they don't show up on pgadmin or even when I run <code>sudo -u postgres psql -l</code>.</p>
<p>Any idea where I'm going wrong?</p> | <p>The problem is still your <code>pg_hba.conf</code> file*.</p>
<p>This line:</p>
<pre><code>local all postgres peer
</code></pre>
<p>Should be:</p>
<pre><code>local all postgres md5
</code></pre>
<p>After altering this file, don't forget to restart your PostgreSQL server. If you're on Linux, that would be <code>sudo service postgresql restart</code>.</p>
<hr />
<h3>Locating <code>hba.conf</code></h3>
<p>Note that the location of this file isn't very consistent.</p>
<p>You can use <code>locate pg_hba.conf</code> or ask PostgreSQL <code>SHOW hba_file;</code> to discover the file location.</p>
<p>Usual locations are <code>/etc/postgresql/[version]/main/pg_hba.conf</code> and <code>/var/lib/pgsql/data/pg_hba.conf</code>.</p>
<hr />
<p>These are brief descriptions of the <code>peer</code> vs <code>md5</code> options according to the <a href="http://www.postgresql.org/docs/9.3/static/auth-methods.html" rel="noreferrer">official PostgreSQL docs on authentication methods</a>.</p>
<h3>Peer authentication</h3>
<blockquote>
<p>The peer authentication method works by obtaining the client's
operating system user name from the kernel and using it as the allowed
database user name (with optional user name mapping). This method is
only supported on local connections.</p>
</blockquote>
<h3>Password authentication</h3>
<blockquote>
<p>The password-based authentication methods are md5 and password. These
methods operate similarly except for the way that the password is sent
across the connection, namely MD5-hashed and clear-text respectively.</p>
<p>If you are at all concerned about password "sniffing" attacks then md5
is preferred. Plain password should always be avoided if possible.
However, md5 cannot be used with the db_user_namespace feature. If the
connection is protected by SSL encryption then password can be used
safely (though SSL certificate authentication might be a better choice
if one is depending on using SSL).</p>
</blockquote> | {
"question_id": 18664074,
"question_date": "2013-09-06T18:15:06.513Z",
"question_score": 1060,
"tags": "ruby-on-rails|postgresql",
"answer_id": 18664239,
"answer_date": "2013-09-06T18:25:11.150Z",
"answer_score": 1397
} |
Please answer the following Stack Overflow question:
Title: How to convert a Drawable to a Bitmap?
<p>I would like to set a certain <code>Drawable</code> as the device's wallpaper, but all wallpaper functions accept <code>Bitmap</code>s only. I cannot use <code>WallpaperManager</code> because I'm pre 2.1.</p>
<p>Also, my drawables are downloaded from the web and do not reside in <code>R.drawable</code>.</p> | <p>This converts a BitmapDrawable to a Bitmap.</p>
<pre><code>Drawable d = ImagesArrayList.get(0);
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
</code></pre> | {
"question_id": 3035692,
"question_date": "2010-06-14T07:46:35.657Z",
"question_score": 1060,
"tags": "android|bitmap|wallpaper|android-drawable",
"answer_id": 3036187,
"answer_date": "2010-06-14T09:33:55.730Z",
"answer_score": 218
} |
Please answer the following Stack Overflow question:
Title: Convert list of dictionaries to a pandas DataFrame
<p>How can I convert a list of dictionaries into a <code>DataFrame</code>? Given:</p>
<pre><code>[{'points': 50, 'time': '5:00', 'year': 2010},
{'points': 25, 'time': '6:00', 'month': "february"},
{'points':90, 'time': '9:00', 'month': 'january'},
{'points_h1':20, 'month': 'june'}]
</code></pre>
<p>I want to turn the above into a <code>DataFrame</code>:</p>
<pre><code> month points points_h1 time year
0 NaN 50 NaN 5:00 2010
1 february 25 NaN 6:00 NaN
2 january 90 NaN 9:00 NaN
3 june NaN 20 NaN NaN
</code></pre>
<p>Note: Order of the columns does not matter.</p> | <p>If <code>ds</code> is a list of <code>dict</code>s:</p>
<pre><code>df = pd.DataFrame(ds)
</code></pre>
<p>Note: this does not work with nested data.</p> | {
"question_id": 20638006,
"question_date": "2013-12-17T15:24:51.033Z",
"question_score": 1060,
"tags": "python|dictionary|pandas|dataframe",
"answer_id": 20638258,
"answer_date": "2013-12-17T15:35:13.867Z",
"answer_score": 1515
} |
Please answer the following Stack Overflow question:
Title: How do I declare a namespace in JavaScript?
<p>How do I create a namespace in JavaScript so that my objects and functions aren't overwritten by other same-named objects and functions? I've used the following:</p>
<pre><code>if (Foo == null || typeof(Foo) != "object") { var Foo = new Object();}
</code></pre>
<p>Is there a more elegant or succinct way of doing this?</p> | <p>I like this:</p>
<pre><code>var yourNamespace = {
foo: function() {
},
bar: function() {
}
};
...
yourNamespace.foo();
</code></pre> | {
"question_id": 881515,
"question_date": "2009-05-19T08:11:02.660Z",
"question_score": 1060,
"tags": "javascript|namespaces|javascript-namespaces",
"answer_id": 881556,
"answer_date": "2009-05-19T08:22:29.827Z",
"answer_score": 807
} |
Please answer the following Stack Overflow question:
Title: Randomize a List<T>
<p>What is the best way to randomize the order of a generic list in C#? I've got a finite set of 75 numbers in a list I would like to assign a random order to, in order to draw them for a lottery type application.</p> | <p>Shuffle any <code>(I)List</code> with an extension method based on the <a href="http://en.wikipedia.org/wiki/Fisher-Yates_shuffle" rel="noreferrer">Fisher-Yates shuffle</a>:</p>
<pre><code>private static Random rng = new Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
</code></pre>
<p>Usage:</p>
<pre><code>List<Product> products = GetProducts();
products.Shuffle();
</code></pre>
<p>The code above uses the much criticised System.Random method to select swap candidates. It's fast but not as random as it should be. If you need a better quality of randomness in your shuffles use the random number generator in System.Security.Cryptography like so:</p>
<pre><code>using System.Security.Cryptography;
...
public static void Shuffle<T>(this IList<T> list)
{
RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
int n = list.Count;
while (n > 1)
{
byte[] box = new byte[1];
do provider.GetBytes(box);
while (!(box[0] < n * (Byte.MaxValue / n)));
int k = (box[0] % n);
n--;
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
</code></pre>
<p>A simple comparison is available <a href="https://web.archive.org/web/20150801085341/http://blog.thijssen.ch/2010/02/when-random-is-too-consistent.html" rel="noreferrer">at this blog</a> (WayBack Machine).</p>
<p>Edit: Since writing this answer a couple years back, many people have commented or written to me, to point out the big silly flaw in my comparison. They are of course right. There's nothing wrong with System.Random if it's used in the way it was intended. In my first example above, I instantiate the rng variable inside of the Shuffle method, which is asking for trouble if the method is going to be called repeatedly. Below is a fixed, full example based on a really useful comment received today from @weston here on SO.</p>
<p>Program.cs:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Threading;
namespace SimpleLottery
{
class Program
{
private static void Main(string[] args)
{
var numbers = new List<int>(Enumerable.Range(1, 75));
numbers.Shuffle();
Console.WriteLine("The winning numbers are: {0}", string.Join(", ", numbers.GetRange(0, 5)));
}
}
public static class ThreadSafeRandom
{
[ThreadStatic] private static Random Local;
public static Random ThisThreadsRandom
{
get { return Local ?? (Local = new Random(unchecked(Environment.TickCount * 31 + Thread.CurrentThread.ManagedThreadId))); }
}
}
static class MyExtensions
{
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = ThreadSafeRandom.ThisThreadsRandom.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
}
</code></pre> | {
"question_id": 273313,
"question_date": "2008-11-07T19:28:18.853Z",
"question_score": 1059,
"tags": "c#|generic-list",
"answer_id": 1262619,
"answer_date": "2009-08-11T20:07:57.797Z",
"answer_score": 1346
} |
Please answer the following Stack Overflow question:
Title: HTML text input allow only numeric input
<p>Is there a quick way to set an HTML text input (<code><input type=text /></code>) to only allow numeric keystrokes (plus '.')?</p> | <p><sup><strong>Note:</strong> This is an updated answer. Comments below refer to an old version which messed around with keycodes.</sup></p>
<h1>JavaScript</h1>
<p><strong>Try it yourself <a href="https://jsfiddle.net/KarmaProd/tgn9d1uL/4/" rel="noreferrer">on JSFiddle</a>.</strong></p>
<p>You can filter the input values of a text <code><input></code> with the following <code>setInputFilter</code> function (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, validity error message, and <a href="https://caniuse.com/#feat=input-event" rel="noreferrer">all browsers since IE 9</a>):</p>
<pre class="lang-js prettyprint-override"><code>// Restricts input for the given textbox to the given inputFilter function.
function setInputFilter(textbox, inputFilter, errMsg) {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout"].forEach(function(event) {
textbox.addEventListener(event, function(e) {
if (inputFilter(this.value)) {
// Accepted value
if (["keydown","mousedown","focusout"].indexOf(e.type) >= 0){
this.classList.remove("input-error");
this.setCustomValidity("");
}
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
// Rejected value - restore the previous one
this.classList.add("input-error");
this.setCustomValidity(errMsg);
this.reportValidity();
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
// Rejected value - nothing to restore
this.value = "";
}
});
});
}
</code></pre>
<p>You can now use the <code>setInputFilter</code> function to install an input filter:</p>
<pre class="lang-js prettyprint-override"><code>setInputFilter(document.getElementById("myTextBox"), function(value) {
return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp
}, "Only digits and '.' are allowed");
</code></pre>
<p>Apply your preferred style to input-error class. Here's a suggestion:</p>
<pre class="lang-css prettyprint-override"><code>.input-error{
outline: 1px solid red;
}
</code></pre>
<p>See the <a href="https://jsfiddle.net/KarmaProd/tgn9d1uL/4/" rel="noreferrer">JSFiddle demo</a> for more input filter examples. Also note that you still <strong>must do server side validation!</strong></p>
<h1>TypeScript</h1>
<p>Here is a TypeScript version of this.</p>
<pre class="lang-typescript prettyprint-override"><code>function setInputFilter(textbox: Element, inputFilter: (value: string) => boolean, errMsg: string): void {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout"].forEach(function(event) {
textbox.addEventListener(event, function(this: (HTMLInputElement | HTMLTextAreaElement) & {oldValue: string; oldSelectionStart: number | null, oldSelectionEnd: number | null}) {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (Object.prototype.hasOwnProperty.call(this, 'oldValue')) {
this.value = this.oldValue;
if (this.oldSelectionStart !== null &&
this.oldSelectionEnd !== null) {
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
} else {
this.value = "";
}
});
});
}
</code></pre>
<h1>jQuery</h1>
<p>There is also a jQuery version of this. See <a href="https://stackoverflow.com/a/995193/1070129">this answer</a>.</p>
<h1>HTML 5</h1>
<p>HTML 5 has a native solution with <code><input type="number"></code> (see the <a href="https://www.w3.org/TR/html/sec-forms.html#number-state-typenumber" rel="noreferrer">specification</a>), but note that browser support varies:</p>
<ul>
<li>Most browsers will only validate the input when submitting the form, and not when typing.</li>
<li><a href="https://caniuse.com/#feat=input-number" rel="noreferrer">Most mobile browsers</a> don't support the <code>step</code>, <code>min</code> and <code>max</code> attributes.</li>
<li>Chrome (version 71.0.3578.98) still allows the user to enter the characters <code>e</code> and <code>E</code> into the field. Also see <a href="https://stackoverflow.com/q/31706611">this question</a>.</li>
<li>Firefox (version 64.0) and Edge (EdgeHTML version 17.17134) still allow the user to enter <em>any</em> text into the field.</li>
</ul>
<p>Try it yourself <a href="http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_type_number" rel="noreferrer">on w3schools.com</a>.</p> | {
"question_id": 469357,
"question_date": "2009-01-22T14:36:17.960Z",
"question_score": 1057,
"tags": "javascript|jquery|html",
"answer_id": 469362,
"answer_date": "2009-01-22T14:37:57.037Z",
"answer_score": 1320
} |
Please answer the following Stack Overflow question:
Title: Is there a "theirs" version of "git merge -s ours"?
<p>When merging topic branch "B" into "A" using <code>git merge</code>, I get some conflicts. I know all the conflicts can be solved using the version in "B".</p>
<p>I am aware of <code>git merge -s ours</code>. But what I want is something like <code>git merge -s theirs</code>.</p>
<p>Why doesn't it exist? How can I achieve the same result after the conflicting merge with existing <code>git</code> commands? (<code>git checkout</code> every unmerged file from B)</p>
<p>The "solution" of just discarding anything from branch A (the merge commit point to B version of the tree) is not what I am looking for.</p> | <p>A similar alternative is the <code>--strategy-option</code> (short form <code>-X</code>) option, which accepts <code>theirs</code>. For example:</p>
<pre><code>git checkout branchA
git merge -X theirs branchB
</code></pre>
<p>However, this is more equivalent to <code>-X ours</code> than <code>-s ours</code>. The key difference being that <code>-X</code> performs a regular recursive merge, resolving any conflicts using the chosen side, whereas <code>-s ours</code> changes the merge to just completely ignore the other side.</p>
<p>In some cases, the main problem using <code>-X theirs</code> instead of the hypothetical <code>-s theirs</code> is deleted files. In this case, just run <code>git rm</code> with the name of any files that were deleted:</p>
<pre><code>git rm {DELETED-FILE-NAME}
</code></pre>
<p>After that, the <code>-X theirs</code> may work as expected.</p>
<p>Of course, doing the actual removal with the <code>git rm</code> command will prevent the conflict from happening in the first place.</p> | {
"question_id": 173919,
"question_date": "2008-10-06T11:16:43.217Z",
"question_score": 1057,
"tags": "git|git-merge",
"answer_id": 3364506,
"answer_date": "2010-07-29T15:58:58.037Z",
"answer_score": 1216
} |
Please answer the following Stack Overflow question:
Title: How do I use sudo to redirect output to a location I don't have permission to write to?
<p>I've been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don't normally have write access to.</p>
<p>The trouble is, this contrived example doesn't work:</p>
<pre><code>sudo ls -hal /root/ > /root/test.out
</code></pre>
<p>I just receive the response:</p>
<pre><code>-bash: /root/test.out: Permission denied
</code></pre>
<p>How can I get this to work?</p> | <p>Your command does not work because the redirection is performed by your shell which does not have the permission to write to <code>/root/test.out</code>. The redirection of the output <strong>is not</strong> performed by sudo.</p>
<p>There are multiple solutions:</p>
<ul>
<li><p>Run a shell with sudo and give the command to it by using the <code>-c</code> option:</p>
<pre><code>sudo sh -c 'ls -hal /root/ > /root/test.out'
</code></pre></li>
<li><p>Create a script with your commands and run that script with sudo:</p>
<pre><code>#!/bin/sh
ls -hal /root/ > /root/test.out
</code></pre>
<p>Run <code>sudo ls.sh</code>. See Steve Bennett's <a href="https://stackoverflow.com/a/16514624/12892">answer</a> if you don't want to create a temporary file.</p></li>
<li><p>Launch a shell with <code>sudo -s</code> then run your commands:</p>
<pre><code>[nobody@so]$ sudo -s
[root@so]# ls -hal /root/ > /root/test.out
[root@so]# ^D
[nobody@so]$
</code></pre></li>
<li><p>Use <code>sudo tee</code> (if you have to escape a lot when using the <code>-c</code> option):</p>
<pre><code>sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null
</code></pre>
<p>The redirect to <code>/dev/null</code> is needed to stop <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/tee.html" rel="noreferrer"><strong>tee</strong></a> from outputting to the screen. To <em>append</em> instead of overwriting the output file
(<code>>></code>), use <code>tee -a</code> or <code>tee --append</code> (the last one is specific to <a href="https://www.gnu.org/software/coreutils/manual/html_node/tee-invocation.html" rel="noreferrer">GNU coreutils</a>).</p></li>
</ul>
<p>Thanks go to <a href="https://stackoverflow.com/a/82274/12892">Jd</a>, <a href="https://stackoverflow.com/a/82279/12892">Adam J. Forster</a> and <a href="https://stackoverflow.com/a/82553/12892">Johnathan</a> for the second, third and fourth solutions.</p> | {
"question_id": 82256,
"question_date": "2008-09-17T11:44:39.820Z",
"question_score": 1057,
"tags": "linux|bash|permissions|sudo|io-redirection",
"answer_id": 82278,
"answer_date": "2008-09-17T11:48:56.063Z",
"answer_score": 1458
} |
Please answer the following Stack Overflow question:
Title: How to deal with persistent storage (e.g. databases) in Docker
<p>How do people deal with persistent storage for your Docker containers?</p>
<p>I am currently using this approach: build the image, e.g. for PostgreSQL, and then start the container with</p>
<pre><code>docker run --volumes-from c0dbc34fd631 -d app_name/postgres
</code></pre>
<p>IMHO, that has the drawback, that I must not ever (by accident) delete container "c0dbc34fd631".</p>
<p>Another idea would be to mount host volumes "-v" into the container, however, the <strong>userid</strong> within the container does not necessarily match the <strong>userid</strong> from the host, and then permissions might be messed up.</p>
<p>Note: Instead of <code>--volumes-from 'cryptic_id'</code> you can also use <code>--volumes-from my-data-container</code> where <code>my-data-container</code> is a name you assigned to a data-only container, e.g. <code>docker run --name my-data-container ...</code> (see the accepted answer)</p> | <h2>Docker 1.9.0 and above</h2>
<p>Use <a href="https://docs.docker.com/engine/reference/commandline/volume_create/" rel="noreferrer">volume API</a></p>
<pre><code>docker volume create --name hello
docker run -d -v hello:/container/path/for/volume container_image my_command
</code></pre>
<p>This means that the data-only container pattern must be abandoned in favour of the new volumes.</p>
<p>Actually the volume API is only a better way to achieve what was the data-container pattern.</p>
<p>If you create a container with a <code>-v volume_name:/container/fs/path</code> Docker will automatically create a named volume for you that can:</p>
<ol>
<li>Be listed through the <code>docker volume ls</code></li>
<li>Be identified through the <code>docker volume inspect volume_name</code></li>
<li>Backed up as a normal directory</li>
<li>Backed up as before through a <code>--volumes-from</code> connection</li>
</ol>
<p>The new volume API adds a useful command that lets you identify dangling volumes:</p>
<pre><code>docker volume ls -f dangling=true
</code></pre>
<p>And then remove it through its name:</p>
<pre><code>docker volume rm <volume name>
</code></pre>
<p>As @mpugach underlines in the comments, you can get rid of all the dangling volumes with a nice one-liner:</p>
<pre><code>docker volume rm $(docker volume ls -f dangling=true -q)
# Or using 1.13.x
docker volume prune
</code></pre>
<h2>Docker 1.8.x and below</h2>
<p>The approach that seems to work best for production is to use a <strong>data only container</strong>.</p>
<p>The data only container is run on a barebones image and actually does nothing except exposing a data volume.</p>
<p>Then you can run any other container to have access to the data container volumes:</p>
<pre><code>docker run --volumes-from data-container some-other-container command-to-execute
</code></pre>
<ul>
<li><a href="http://www.offermann.us/2013/12/tiny-docker-pieces-loosely-joined.html" rel="noreferrer">Here</a> you can get a good picture of how to arrange the different containers.</li>
<li><a href="http://crosbymichael.com/advanced-docker-volumes.html" rel="noreferrer">Here</a> there is a good insight on how volumes work.</li>
</ul>
<p>In <a href="http://container42.com/2013/12/16/persistent-volumes-with-docker-container-as-volume-pattern/" rel="noreferrer">this blog post</a> there is a good description of the so-called <strong>container as volume pattern</strong> which clarifies the main point of having <strong>data only containers</strong>.</p>
<p><a href="https://docs.docker.com/engine/userguide/dockervolumes/" rel="noreferrer">Docker documentation has now the DEFINITIVE description of the <strong>container as volume/s</strong> pattern.</a></p>
<p>Following is the backup/restore procedure for Docker 1.8.x and below.</p>
<p><strong>BACKUP:</strong></p>
<pre><code>sudo docker run --rm --volumes-from DATA -v $(pwd):/backup busybox tar cvf /backup/backup.tar /data
</code></pre>
<ul>
<li>--rm: remove the container when it exits</li>
<li>--volumes-from DATA: attach to the volumes shared by the DATA container</li>
<li>-v $(pwd):/backup: bind mount the current directory into the container; to write the tar file to</li>
<li>busybox: a small simpler image - good for quick maintenance</li>
<li>tar cvf /backup/backup.tar /data: creates an uncompressed tar file of all the files in the /data directory</li>
</ul>
<p><strong>RESTORE:</strong></p>
<pre><code># Create a new data container
$ sudo docker run -v /data -name DATA2 busybox true
# untar the backup files into the new container᾿s data volume
$ sudo docker run --rm --volumes-from DATA2 -v $(pwd):/backup busybox tar xvf /backup/backup.tar
data/
data/sven.txt
# Compare to the original container
$ sudo docker run --rm --volumes-from DATA -v `pwd`:/backup busybox ls /data
sven.txt
</code></pre>
<p>Here is a nice <a href="http://container42.com/2014/11/18/data-only-container-madness/" rel="noreferrer">article from the excellent Brian Goff</a> explaining why it is good to use the same image for a container and a data container.</p> | {
"question_id": 18496940,
"question_date": "2013-08-28T19:45:44.323Z",
"question_score": 1056,
"tags": "docker|docker-container",
"answer_id": 20652410,
"answer_date": "2013-12-18T07:50:09.230Z",
"answer_score": 1010
} |
Please answer the following Stack Overflow question:
Title: How to download a file over HTTP?
<p>I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows <code>.bat</code> file to download the actual MP3 file. I would prefer to have the entire utility written in Python.</p>
<p>I struggled to find a way to actually download the file in Python, thus why I resorted to using <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p> | <p>Use <a href="https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen" rel="noreferrer"><code>urllib.request.urlopen()</code></a>:</p>
<pre><code>import urllib.request
with urllib.request.urlopen('http://www.example.com/') as f:
html = f.read().decode('utf-8')
</code></pre>
<p>This is the most basic way to use the library, minus any error handling. You can also do more complex stuff such as changing headers.</p>
<p>On Python 2, the method is in <a href="http://docs.python.org/2/library/urllib2.html" rel="noreferrer"><code>urllib2</code></a>:</p>
<pre><code>import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read()
</code></pre> | {
"question_id": 22676,
"question_date": "2008-08-22T15:34:13.760Z",
"question_score": 1054,
"tags": "python|http|urllib",
"answer_id": 22682,
"answer_date": "2008-08-22T15:38:22.330Z",
"answer_score": 539
} |
Please answer the following Stack Overflow question:
Title: Undefined behavior and sequence points
<p>What are "sequence points"?</p>
<p>What is the relation between undefined behaviour and sequence points?</p>
<p>I often use funny and convoluted expressions like <code>a[++i] = i;</code>, to make myself feel better. Why should I stop using them?</p>
<p>If you've read this, be sure to visit the follow-up question <em><a href="https://stackoverflow.com/questions/4638364">Undefined behavior and sequence points reloaded</a></em>.</p>
<sub>
<i>(Note: This is meant to be an entry to <a href="https://stackoverflow.com/questions/tagged/c++-faq">Stack Overflow's C++ FAQ</a>. If you want to critique the idea of providing an FAQ in this form, then <a href="https://meta.stackexchange.com/questions/68647/setting-up-a-faq-for-the-c-tag">the posting on meta that started all this</a> would be the place to do that. Answers to that question are monitored in the <a href="https://chat.stackoverflow.com/rooms/10/c-lounge">C++ chatroom</a>, where the FAQ idea started out in the first place, so your answer is very likely to get read by those who came up with the idea.)</i>
</sub> | <h3>C++98 and C++03</h3>
<p>This answer is for the older versions of the C++ standard. The C++11 and C++14 versions of the standard do not formally contain 'sequence points'; operations are 'sequenced before' or 'unsequenced' or 'indeterminately sequenced' instead. The net effect is essentially the same, but the terminology is different.</p>
<hr>
<p><strong>Disclaimer</strong> : Okay. This answer is a bit long. So have patience while reading it. If you already know these things, reading them again won't make you crazy.</p>
<p><strong>Pre-requisites</strong> : An elementary knowledge of <a href="http://www.open-std.org/jtc1/sc22/wg21/" rel="noreferrer">C++ Standard</a></p>
<hr />
<h2>What are Sequence Points?</h2>
<p>The Standard says</p>
<blockquote>
<p>At certain specified points in the execution sequence called <strong>sequence points</strong>, all <em>side effects</em> of previous evaluations
shall be complete and no <em>side effects</em> of subsequent evaluations shall have taken place. (§1.9/7)</p>
</blockquote>
<h2>Side effects? What are side effects?</h2>
<p>Evaluation of an expression produces something and if in addition there is a change in the state of the execution environment it is said that the expression (its evaluation) has some side effect(s).</p>
<p>For example:</p>
<pre><code>int x = y++; //where y is also an int
</code></pre>
<p>In addition to the initialization operation the value of <code>y</code> gets changed due to the side effect of <code>++</code> operator.</p>
<p>So far so good. Moving on to sequence points. An alternation definition of seq-points given by the comp.lang.c author <code>Steve Summit</code>:</p>
<blockquote>
<p>Sequence point is a point in time at which the dust has settled and all side effects which have been seen so far are guaranteed to be complete.</p>
</blockquote>
<hr />
<h2>What are the common sequence points listed in the C++ Standard?</h2>
<p>Those are:</p>
<ul>
<li><p>at the end of the evaluation of full expression (<code>§1.9/16</code>) (A full-expression is an expression that is not a subexpression of another expression.)<sup>1</sup></p>
<p>Example :</p>
<pre><code>int a = 5; // ; is a sequence point here
</code></pre>
</li>
<li><p>in the evaluation of each of the following expressions after the evaluation of the first expression (<code>§1.9/18</code>) <sup>2</sup></p>
<ul>
<li><code>a && b (§5.14)</code></li>
<li><code>a || b (§5.15)</code></li>
<li><code>a ? b : c (§5.16)</code></li>
<li><code>a , b (§5.18)</code> (here a , b is a comma operator; in <code>func(a,a++)</code> <code>,</code> is not a comma operator, it's merely a separator between the arguments <code>a</code> and <code>a++</code>. Thus the behaviour is undefined in that case (if <code>a</code> is considered to be a primitive type)) <br></li>
</ul>
</li>
<li><p>at a function call (whether or not the function is inline), after the evaluation of all function arguments (if any) which
takes place before execution of any expressions or statements in the function body (<code>§1.9/17</code>).</p>
</li>
</ul>
<p><sub>1 : Note : the evaluation of a full-expression can include the evaluation of subexpressions that are not lexically
part of the full-expression. For example, subexpressions involved in evaluating default argument expressions (8.3.6) are considered to be created in the expression that calls the function, not the expression that defines the default argument</sub></p>
<p><sub>2 : The operators indicated are the built-in operators, as described in clause 5. When one of these operators is overloaded (clause 13) in a valid context, thus designating a user-defined operator function, the expression designates a function invocation and the operands form an argument list, without an implied sequence point between them.</sub></p>
<hr />
<h2>What is Undefined Behaviour?</h2>
<p>The Standard defines Undefined Behaviour in Section <code>§1.3.12</code> as</p>
<blockquote>
<p>behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes <strong>no requirements <sup>3</sup></strong>.</p>
</blockquote>
<blockquote>
<p>Undefined behavior may also be expected when this
International Standard omits the description of any explicit definition of behavior.</p>
</blockquote>
<p><sub> 3 : permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or with-
out the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).</sub></p>
<p>In short, undefined behaviour means <strong>anything</strong> can happen from daemons flying out of your nose to your girlfriend getting pregnant.</p>
<hr />
<h2>What is the relation between Undefined Behaviour and Sequence Points?</h2>
<p>Before I get into that you must know the difference(s) between <a href="https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior">Undefined Behaviour, Unspecified Behaviour and Implementation Defined Behaviour</a>.</p>
<p>You must also know that <code>the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified</code>.</p>
<p>For example:</p>
<pre><code>int x = 5, y = 6;
int z = x++ + y++; //it is unspecified whether x++ or y++ will be evaluated first.
</code></pre>
<p>Another example <a href="https://stackoverflow.com/questions/3457967/what-belongs-in-an-educational-tool-to-demonstrate-the-unwarranted-assumptions-pe/3458842#3458842">here</a>.</p>
<hr />
<p>Now the Standard in <code>§5/4</code> says</p>
<ul>
<li>
<ol>
<li><strong>Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.</strong></li>
</ol>
</li>
</ul>
<p>What does it mean?</p>
<p>Informally it means that between two sequence points a variable must not be modified more than once.
In an expression statement, the <code>next sequence point</code> is usually at the terminating semicolon, and the <code>previous sequence point</code> is at the end of the previous statement. An expression may also contain intermediate <code>sequence points</code>.</p>
<p>From the above sentence the following expressions invoke Undefined Behaviour:</p>
<pre><code>i++ * ++i; // UB, i is modified more than once btw two SPs
i = ++i; // UB, same as above
++i = 2; // UB, same as above
i = ++i + 1; // UB, same as above
++++++i; // UB, parsed as (++(++(++i)))
i = (i, ++i, ++i); // UB, there's no SP between `++i` (right most) and assignment to `i` (`i` is modified more than once btw two SPs)
</code></pre>
<p>But the following expressions are fine:</p>
<pre><code>i = (i, ++i, 1) + 1; // well defined (AFAIK)
i = (++i, i++, i); // well defined
int j = i;
j = (++i, i++, j*i); // well defined
</code></pre>
<hr />
<ul>
<li>
<ol start="2">
<li><strong>Furthermore, the prior value shall be accessed only to determine the value to be stored.</strong></li>
</ol>
</li>
</ul>
<p>What does it mean? It means if an object is written to within a full expression, any and all accesses to it within the same expression <strong>must be directly involved in the computation of the value to be written</strong>.</p>
<p>For example in <code>i = i + 1</code> all the access of <code>i</code> (in L.H.S and in R.H.S) are <strong>directly involved in computation</strong> of the value to be written. So it is fine.</p>
<p>This rule effectively constrains legal expressions to those in which the accesses demonstrably precede the modification.</p>
<p>Example 1:</p>
<pre><code>std::printf("%d %d", i,++i); // invokes Undefined Behaviour because of Rule no 2
</code></pre>
<p>Example 2:</p>
<pre><code>a[i] = i++ // or a[++i] = i or a[i++] = ++i etc
</code></pre>
<p>is disallowed because one of the accesses of <code>i</code> (the one in <code>a[i]</code>) has nothing to do with the value which ends up being stored in i (which happens over in <code>i++</code>), and so there's no good way to define--either for our understanding or the compiler's--whether the access should take place before or after the incremented value is stored. So the behaviour is undefined.</p>
<p>Example 3 :</p>
<pre><code>int x = i + i++ ;// Similar to above
</code></pre>
<hr />
<p><strong>Follow up answer for C++11 <a href="https://stackoverflow.com/questions/4176328/faq-undefined-behavior-and-sequence-points/4183735#4183735">here</a>.</strong></p> | {
"question_id": 4176328,
"question_date": "2010-11-14T05:37:46.333Z",
"question_score": 1054,
"tags": "c++|undefined-behavior|c++-faq|sequence-points",
"answer_id": 4176333,
"answer_date": "2010-11-14T05:39:00.593Z",
"answer_score": 726
} |
Please answer the following Stack Overflow question:
Title: Sort array by firstname (alphabetically) in JavaScript
<p>I got an array (see below for one object in the array) that I need to sort by firstname using JavaScript.
How can I do it?</p>
<pre><code>var user = {
bio: null,
email: "[email protected]",
firstname: "Anna",
id: 318,
lastAvatar: null,
lastMessage: null,
lastname: "Nickson",
nickname: "anny"
};
</code></pre> | <p>Suppose you have an array <code>users</code>. You may use <code>users.sort</code> and pass a function that takes two arguments and compare them (comparator)</p>
<p>It should return</p>
<ul>
<li>something negative if first argument is less than second (should be placed before the second in resulting array)</li>
<li>something positive if first argument is greater (should be placed after second one)</li>
<li>0 if those two elements are equal.</li>
</ul>
<p>In our case if two elements are <code>a</code> and <code>b</code> we want to compare <code>a.firstname</code> and <code>b.firstname</code></p>
<p>Example:</p>
<pre><code>users.sort(function(a, b){
if(a.firstname < b.firstname) { return -1; }
if(a.firstname > b.firstname) { return 1; }
return 0;
})
</code></pre>
<p>This code is going to work with any type.</p>
<p>Note that in "real life"™ you often want to ignore case, correctly sort diacritics, weird symbols like ß, etc. when you compare strings, so you may want to use <code>localeCompare</code>. See other answers for clarity.</p> | {
"question_id": 6712034,
"question_date": "2011-07-15T19:10:55.933Z",
"question_score": 1053,
"tags": "javascript",
"answer_id": 6712080,
"answer_date": "2011-07-15T19:15:42.033Z",
"answer_score": 1443
} |
Please answer the following Stack Overflow question:
Title: What does the "~" (tilde/squiggle/twiddle) CSS selector mean?
<p>Searching for the <code>~</code> character isn't easy. I was looking over some CSS and found this</p>
<pre><code>.check:checked ~ .content {
}
</code></pre>
<p>What does it mean?</p> | <p>The <code>~</code> selector is in fact the <a href="https://www.w3.org/TR/selectors-3/#general-sibling-combinators" rel="noreferrer">subsequent-sibling combinator</a> (previously called general sibling combinator <a href="https://github.com/w3c/csswg-drafts/issues/1382" rel="noreferrer">until 2017</a>):</p>
<blockquote>
<p>The subsequent-sibling combinator is made of the "tilde" (U+007E, ~)
character that separates two sequences of simple selectors. The
elements represented by the two sequences share the same parent in the
document tree and the element represented by the first sequence
precedes (not necessarily immediately) the element represented by the
second one.</p>
</blockquote>
<p>Consider the following example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.a ~ .b {
background-color: powderblue;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li class="b">1st</li>
<li class="a">2nd</li>
<li>3rd</li>
<li class="b">4th</li>
<li class="b">5th</li>
</ul></code></pre>
</div>
</div>
</p>
<p><code>.a ~ .b</code> matches the 4th and 5th list item because they:</p>
<ul>
<li>Are <code>.b</code> elements</li>
<li>Are siblings of <code>.a</code></li>
<li>Appear after <code>.a</code> in HTML source order.</li>
</ul>
<p>Likewise, <code>.check:checked ~ .content</code> matches all <code>.content</code> elements that are siblings of <code>.check:checked</code> and appear after it.</p> | {
"question_id": 10782054,
"question_date": "2012-05-28T09:10:00.950Z",
"question_score": 1053,
"tags": "css|css-selectors",
"answer_id": 10782297,
"answer_date": "2012-05-28T09:29:20.363Z",
"answer_score": 1585
} |
Please answer the following Stack Overflow question:
Title: How can I navigate back to the last cursor position in Visual Studio Code?
<p>What is the keyboard shortcut to navigate back to the last cursor position in Visual Studio Code?</p> | <p>The <em>keyboard shortcut commands</em> are <em>Go Forward</em> and <em>Go Back</em>.</p>
<hr />
<p>On Windows:</p>
<p><kbd>Alt</kbd> + <kbd>←</kbd> ... navigate back</p>
<p><kbd>Alt</kbd> + <kbd>→</kbd> ... navigate forward</p>
<p>On Mac:</p>
<p><kbd>Ctrl</kbd> + <kbd>-</kbd> ... navigate back</p>
<p><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>-</kbd> ... navigate forward</p>
<p>On Ubuntu Linux:</p>
<p><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>-</kbd> .., navigate back</p>
<p><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>-</kbd> ... navigate forward</p> | {
"question_id": 35424367,
"question_date": "2016-02-16T05:20:35.933Z",
"question_score": 1051,
"tags": "visual-studio-code|keyboard-shortcuts",
"answer_id": 35433087,
"answer_date": "2016-02-16T12:48:57.560Z",
"answer_score": 1796
} |
Please answer the following Stack Overflow question:
Title: How do you comment out code in PowerShell?
<p>How do you comment out code in <strong>PowerShell</strong> (1.0 or 2.0)?</p> | <p>In PowerShell V1 there's only <code>#</code> to make the text after it a comment.</p>
<pre class="lang-powershell prettyprint-override"><code># This is a comment in PowerShell
</code></pre>
<p>In PowerShell V2 <code><# #></code> can be used for block comments and more specifically for help comments.</p>
<pre class="lang-none prettyprint-override"><code>#REQUIRES -Version 2.0
<#
.SYNOPSIS
A brief description of the function or script. This keyword can be used
only once in each topic.
.DESCRIPTION
A detailed description of the function or script. This keyword can be
used only once in each topic.
.NOTES
File Name : xxxx.ps1
Author : J.P. Blanc ([email protected])
Prerequisite : PowerShell V2 over Vista and upper.
Copyright 2011 - Jean Paul Blanc/Silogix
.LINK
Script posted over:
http://silogix.fr
.EXAMPLE
Example 1
.EXAMPLE
Example 2
#>
Function blabla
{}
</code></pre>
<p>For more explanation about <code>.SYNOPSIS</code> and <code>.*</code> see <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comment_based_help?view=powershell-7.1" rel="noreferrer">about_Comment_Based_Help</a>.</p>
<p>Remark: These function comments are used by the <code>Get-Help</code> CmdLet and can be put before the keyword <code>Function</code>, or inside the <code>{}</code> before or after the code itself.</p> | {
"question_id": 7342597,
"question_date": "2011-09-08T02:43:10.283Z",
"question_score": 1050,
"tags": "powershell|syntax|powershell-2.0|comments",
"answer_id": 7344038,
"answer_date": "2011-09-08T06:33:59.360Z",
"answer_score": 1399
} |
Please answer the following Stack Overflow question:
Title: 'this' vs $scope in AngularJS controllers
<p>In the <a href="https://angularjs.org/#create-components" rel="noreferrer">"Create Components" section of AngularJS's homepage</a>, there is this example:</p>
<pre><code>controller: function($scope, $element) {
var panes = $scope.panes = [];
$scope.select = function(pane) {
angular.forEach(panes, function(pane) {
pane.selected = false;
});
pane.selected = true;
}
this.addPane = function(pane) {
if (panes.length == 0) $scope.select(pane);
panes.push(pane);
}
}
</code></pre>
<p>Notice how the <code>select</code> method is added to <code>$scope</code>, but the <code>addPane</code> method is added to <code>this</code>. If I change it to <code>$scope.addPane</code>, the code breaks.</p>
<p>The documentation says that there in fact is a difference, but it doesn't mention what the difference is:</p>
<blockquote>
<p>Previous versions of Angular (pre 1.0 RC) allowed you to use <code>this</code> interchangeably with the <code>$scope</code> method, but this is no longer the case. Inside of methods defined on the scope <code>this</code> and <code>$scope</code> are interchangeable (angular sets <code>this</code> to <code>$scope</code>), but not otherwise inside your controller constructor.</p>
</blockquote>
<p>How does <code>this</code> and <code>$scope</code> work in AngularJS controllers?</p> | <blockquote>
<p>"How does <code>this</code> and <code>$scope</code> work in AngularJS controllers?"</p>
</blockquote>
<p><strong>Short answer</strong>:</p>
<ul>
<li><code>this</code>
<ul>
<li>When the controller constructor function is called, <code>this</code> is the controller.</li>
<li>When a function defined on a <code>$scope</code> object is called, <code>this</code> is the "scope in effect when the function was called". This may (or may not!) be the <code>$scope</code> that the function is defined on. So, inside the function, <code>this</code> and <code>$scope</code> may <strong>not</strong> be the same.</li>
</ul></li>
<li><code>$scope</code>
<ul>
<li>Every controller has an associated <code>$scope</code> object.</li>
<li>A controller (constructor) function is responsible for setting model properties and functions/behaviour on its associated <code>$scope</code>.</li>
<li>Only methods defined on this <code>$scope</code> object (and parent scope objects, if prototypical inheritance is in play) are accessible from the HTML/view. E.g., from <code>ng-click</code>, filters, etc.</li>
</ul></li>
</ul>
<p><strong>Long answer</strong>:</p>
<p>A controller function is a JavaScript constructor function. When the constructor function executes (e.g., when a view loads), <code>this</code> (i.e., the "function context") is set to the controller object. So in the "tabs" controller constructor function, when the addPane function is created</p>
<pre><code>this.addPane = function(pane) { ... }
</code></pre>
<p>it is created on the controller object, not on $scope. Views cannot see the addPane function -- they only have access to functions defined on $scope. In other words, in the HTML, this won't work:</p>
<pre><code><a ng-click="addPane(newPane)">won't work</a>
</code></pre>
<p>After the "tabs" controller constructor function executes, we have the following:</p>
<p><img src="https://i.stack.imgur.com/PUMuU.png" alt="after tabs controller constructor function"></p>
<p>The dashed black line indicates prototypal inheritance -- an isolate scope prototypically inherits from <a href="http://docs.angularjs.org/api/ng.$rootScope.Scope">Scope</a>. (It does not prototypically inherit from the scope in effect where the directive was encountered in the HTML.)</p>
<p>Now, the pane directive's link function wants to communicate with the tabs directive (which really means it needs to affect the tabs isolate $scope in some way). Events could be used, but another mechanism is to have the pane directive <code>require</code> the tabs controller. (There appears to be no mechanism for the pane directive to <code>require</code> the tabs $scope.)</p>
<p>So, this begs the question: if we only have access to the tabs controller, how do we get access to the tabs isolate $scope (which is what we really want)?</p>
<p>Well, the red dotted line is the answer. The addPane() function's "scope" (I'm referring to JavaScript's function scope/closures here) gives the function access to the tabs isolate $scope. I.e., addPane() has access to the "tabs IsolateScope" in the diagram above because of a closure that was created when addPane() was defined. (If we instead defined addPane() on the tabs $scope object, the pane directive would not have access to this function, and hence it would have no way to communicate with the tabs $scope.)</p>
<p>To answer the other part of your question: <code>how does $scope work in controllers?</code>:</p>
<p>Within functions defined on $scope, <code>this</code> is set to "the $scope in effect where/when the function was called". Suppose we have the following HTML:</p>
<pre><code><div ng-controller="ParentCtrl">
<a ng-click="logThisAndScope()">log "this" and $scope</a> - parent scope
<div ng-controller="ChildCtrl">
<a ng-click="logThisAndScope()">log "this" and $scope</a> - child scope
</div>
</div>
</code></pre>
<p>And the <code>ParentCtrl</code> (Solely) has</p>
<pre><code>$scope.logThisAndScope = function() {
console.log(this, $scope)
}
</code></pre>
<p>Clicking the first link will show that <code>this</code> and <code>$scope</code> are the same, since "<em>the scope in effect when the function was called</em>" is the scope associated with the <code>ParentCtrl</code>.</p>
<p>Clicking the second link will reveal <code>this</code> and <code>$scope</code> are <strong>not</strong> the same, since "<em>the scope in effect when the function was called</em>" is the scope associated with the <code>ChildCtrl</code>. So here, <code>this</code> is set to <code>ChildCtrl</code>'s <code>$scope</code>. Inside the method, <code>$scope</code> is still the <code>ParentCtrl</code>'s $scope.</p>
<p><a href="http://jsfiddle.net/mrajcok/sbZw7/">Fiddle</a></p>
<p>I try to not use <code>this</code> inside of a function defined on $scope, as it becomes confusing which $scope is being affected, especially considering that ng-repeat, ng-include, ng-switch, and directives can all create their own child scopes.</p> | {
"question_id": 11605917,
"question_date": "2012-07-23T02:55:47.643Z",
"question_score": 1050,
"tags": "angularjs|angularjs-scope|this",
"answer_id": 14168699,
"answer_date": "2013-01-05T04:48:53.450Z",
"answer_score": 1014
} |
Please answer the following Stack Overflow question:
Title: How do I rotate the Android emulator display?
<p>How can I rotate the Android emulator display to see it in landscape mode?</p> | <p><strong>Windows:</strong> <kbd>left Ctrl</kbd> + <kbd>F12</kbd></p>
<p><strong>Mac:</strong> <kbd>Fn</kbd> + <kbd>Ctrl</kbd> + <kbd>F12</kbd></p> | {
"question_id": 4535298,
"question_date": "2010-12-26T20:32:39.540Z",
"question_score": 1050,
"tags": "android|android-emulator|emulation",
"answer_id": 4535315,
"answer_date": "2010-12-26T20:35:35.987Z",
"answer_score": 1200
} |
Please answer the following Stack Overflow question:
Title: When to use static methods
<p>I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?</p>
<p>Example:</p>
<pre><code>Obj x = new Obj();
x.someMethod();
</code></pre>
<p>...or:</p>
<pre><code>Obj.someMethod(); // Is this the static way?
</code></pre>
<p>I'm rather confused!</p> | <p>One rule-of-thumb: ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static.</p>
<p>So in a class <code>Car</code> you might have a method:</p>
<pre><code>double convertMpgToKpl(double mpg)
</code></pre>
<p>...which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a <code>Car</code>. But this method (which sets the efficiency of one particular <code>Car</code>):</p>
<pre><code>void setMileage(double mpg)
</code></pre>
<p>...can't be static since it's inconceivable to call the method before any <code>Car</code> has been constructed.</p>
<p>(By the way, the converse isn't always true: you might sometimes have a method which involves two <code>Car</code> objects, and still want it to be static. E.g.:</p>
<pre><code>Car theMoreEfficientOf(Car c1, Car c2)
</code></pre>
<p>Although this could be converted to a non-static version, some would argue that since there isn't a "privileged" choice of which <code>Car</code> is more important, you shouldn't force a caller to choose one <code>Car</code> as the object you'll invoke the method on. This situation accounts for a fairly small fraction of all static methods, though.</p> | {
"question_id": 2671496,
"question_date": "2010-04-19T23:05:33.103Z",
"question_score": 1049,
"tags": "java|static-methods",
"answer_id": 2671636,
"answer_date": "2010-04-19T23:42:13.737Z",
"answer_score": 1620
} |
Please answer the following Stack Overflow question:
Title: Difference between HashMap, LinkedHashMap and TreeMap
<p>What is the difference between <code>HashMap</code>, <code>LinkedHashMap</code> and <code>TreeMap</code> in Java?
I don't see any difference in the output as all the three has <code>keySet</code> and <code>values</code>. What are <code>Hashtable</code>s?</p>
<pre><code>Map m1 = new HashMap();
m1.put("map", "HashMap");
m1.put("schildt", "java2");
m1.put("mathew", "Hyden");
m1.put("schildt", "java2s");
print(m1.keySet());
print(m1.values());
SortedMap sm = new TreeMap();
sm.put("map", "TreeMap");
sm.put("schildt", "java2");
sm.put("mathew", "Hyden");
sm.put("schildt", "java2s");
print(sm.keySet());
print(sm.values());
LinkedHashMap lm = new LinkedHashMap();
lm.put("map", "LinkedHashMap");
lm.put("schildt", "java2");
lm.put("mathew", "Hyden");
lm.put("schildt", "java2s");
print(lm.keySet());
print(lm.values());
</code></pre> | <p>All three classes implement the <code>Map</code> interface and offer mostly the same functionality. The most important difference is the order in which iteration through the entries will happen:</p>
<ul>
<li><code>HashMap</code> makes absolutely no guarantees about the iteration order. It can (and will) even change completely when new elements are added.</li>
<li><code>TreeMap</code> will iterate according to the "natural ordering" of the keys according to their <code>compareTo()</code> method (or an externally supplied <code>Comparator</code>). Additionally, it implements the <a href="http://java.sun.com/javase/6/docs/api/java/util/SortedMap.html" rel="noreferrer"><code>SortedMap</code></a> interface, which contains methods that depend on this sort order.</li>
<li><code>LinkedHashMap</code> will iterate in the order in which the entries were put into the map</li>
</ul>
<p><a href="http://en.wikipedia.org/wiki/Hashtable" rel="noreferrer">"Hashtable"</a> is the generic name for hash-based maps. In the context of the Java API,
<code>Hashtable</code> is an obsolete class from the days of Java 1.1 before the collections framework existed. It should not be used anymore, because its API is cluttered with obsolete methods that duplicate functionality, and its methods are synchronized (which can decrease performance and is generally useless). Use <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="noreferrer">ConcurrentHashMap</a> instead of Hashtable. </p> | {
"question_id": 2889777,
"question_date": "2010-05-22T21:10:15.773Z",
"question_score": 1049,
"tags": "java|map",
"answer_id": 2889800,
"answer_date": "2010-05-22T21:18:16.793Z",
"answer_score": 1237
} |
Please answer the following Stack Overflow question:
Title: What's the difference between git reset --mixed, --soft, and --hard?
<p>I'm looking to split a commit up and not sure which reset option to use.</p>
<p>I was looking at the page <a href="https://stackoverflow.com/questions/2530060/can-you-explain-to-me-git-reset-in-plain-english">In plain English, what does "git reset" do?</a>, but I realized I don't really understand what the git index or staging area is and thus the explanations didn't help.</p>
<p>Also, the use cases for <code>--mixed</code> and <code>--soft</code> look the same to me in that answer (when you want to fix and recommit). Can someone break it down even more? I realize <code>--mixed</code> is probably the option to go with, but I want to know <em>why</em>. Lastly, what about <code>--hard</code>?</p>
<p>Can someone give me a workflow example of how selecting the 3 options would happen?</p> | <p>When you modify a file in your repository, the change is initially unstaged. In order to commit it, you must stage it—that is, add it to the index—using <code>git add</code>. When you make a commit, the changes that are committed are those that have been added to the index.</p>
<p><code>git reset</code> changes, at minimum, where the current branch (<code>HEAD</code>) is pointing. The difference between <code>--mixed</code> and <code>--soft</code> is whether or not your index is also modified. So, if we're on branch <code>master</code> with this series of commits:</p>
<pre><code>- A - B - C (master)
</code></pre>
<p><code>HEAD</code>points to <code>C</code> and the index matches <code>C</code>.</p>
<p>When we run <code>git reset --soft B</code>, <code>master</code> (and thus <code>HEAD</code>) now points to <code>B</code>, but the index still has the changes from <code>C</code>; <code>git status</code> will show them as staged. So if we run <code>git commit</code> at this point, we'll get a new commit with the same changes as <code>C</code>.</p>
<hr>
<p>Okay, so starting from here again:</p>
<pre><code>- A - B - C (master)
</code></pre>
<p>Now let's do <code>git reset --mixed B</code>. (Note: <code>--mixed</code> is the default option). Once again, <code>master</code> and <code>HEAD</code> point to B, but this time the index is also modified to match <code>B</code>. If we run <code>git commit</code> at this point, nothing will happen since the index matches <code>HEAD</code>. We still have the changes in the working directory, but since they're not in the index, <code>git status</code> shows them as unstaged. To commit them, you would <code>git add</code> and then commit as usual.</p>
<hr>
<p>And finally, <code>--hard</code> is the same as <code>--mixed</code> (it changes your <code>HEAD</code> and index), except that <code>--hard</code> also modifies your working directory. If we're at <code>C</code> and run <code>git reset --hard B</code>, then the changes added in <code>C</code>, as well as any uncommitted changes you have, will be removed, and the files in your working copy will match commit <code>B</code>. Since you can permanently lose changes this way, you should always run <code>git status</code> before doing a hard reset to make sure your working directory is clean or that you're okay with losing your uncommitted changes.</p>
<hr>
<p>And finally, a visualization:
<img src="https://i.stack.imgur.com/qRAte.jpg" alt="enter image description here"></p> | {
"question_id": 3528245,
"question_date": "2010-08-20T04:41:20.213Z",
"question_score": 1049,
"tags": "git|version-control",
"answer_id": 3528483,
"answer_date": "2010-08-20T05:53:19.450Z",
"answer_score": 1918
} |
Please answer the following Stack Overflow question:
Title: Angular HTML binding
<p>I am writing an Angular application and I have an HTML response I want to display. </p>
<p>How do I do that? If I simply use the binding syntax <code>{{myVal}}</code> it encodes all HTML characters (of course).</p>
<p>I need somehow to bind the <code>innerHTML</code> of a <code>div</code> to the variable value.</p> | <p>The correct syntax is the following:</p>
<pre class="lang-html prettyprint-override"><code><div [innerHTML]="theHtmlString"></div>
</code></pre>
<p><a href="https://angular.io/guide/property-binding#binding-targets" rel="noreferrer">Documentation Reference</a></p> | {
"question_id": 31548311,
"question_date": "2015-07-21T19:48:39.193Z",
"question_score": 1048,
"tags": "angular|angular2-template|angular2-databinding",
"answer_id": 34424375,
"answer_date": "2015-12-22T21:02:51.027Z",
"answer_score": 1600
} |
Please answer the following Stack Overflow question:
Title: How do I put an already-running process under nohup?
<p>I have a process that is already running for a long time and don't want to end it.</p>
<p>How do I put it under nohup (that is, how do I cause it to continue running even if I close the terminal?)</p> | <p>Using the <a href="http://web.mit.edu/gnu/doc/html/features_5.html" rel="noreferrer">Job Control</a> of bash to send the process into the background:</p>
<ol>
<li><kbd>Ctrl</kbd>+<kbd>Z</kbd> to stop (pause) the program and get back to the shell.</li>
<li><code>bg</code> to run it in the background.</li>
<li><code>disown -h [job-spec]</code> where [job-spec] is the job number (like <code>%1</code> for the first running job; find about your number with the <code>jobs</code> command) so that the job isn't killed when the terminal closes.</li>
</ol> | {
"question_id": 625409,
"question_date": "2009-03-09T08:33:37.543Z",
"question_score": 1048,
"tags": "bash|shell|job-scheduling|nohup|interruption",
"answer_id": 625436,
"answer_date": "2009-03-09T08:41:58.320Z",
"answer_score": 1498
} |
Please answer the following Stack Overflow question:
Title: Use jQuery to hide a DIV when the user clicks outside of it
<p>I am using this code:</p>
<pre><code>$('body').click(function() {
$('.form_wrapper').hide();
});
$('.form_wrapper').click(function(event){
event.stopPropagation();
});
</code></pre>
<p>And this <strong>HTML</strong>:</p>
<pre><code><div class="form_wrapper">
<a class="agree" href="javascript:;">I Agree</a>
<a class="disagree" href="javascript:;">Disagree</a>
</div>
</code></pre>
<p>The problem is that I have links inside the <code>div</code> and when they no longer work when clicked.</p> | <p>Had the same problem, came up with this easy solution. It's even working recursive:</p>
<pre><code>$(document).mouseup(function(e)
{
var container = $("YOUR CONTAINER SELECTOR");
// if the target of the click isn't the container nor a descendant of the container
if (!container.is(e.target) && container.has(e.target).length === 0)
{
container.hide();
}
});
</code></pre> | {
"question_id": 1403615,
"question_date": "2009-09-10T06:11:27.247Z",
"question_score": 1047,
"tags": "jquery|html|hide|styling",
"answer_id": 7385673,
"answer_date": "2011-09-12T09:19:34.130Z",
"answer_score": 2647
} |
Please answer the following Stack Overflow question:
Title: Bash - Get Current Directory or Folder Name (Without Full Path) In Bash Script
<p>How could I retrieve the current working directory/folder name in a bash script, or even better, just a terminal command.</p>
<p><code>pwd</code> gives the full path of the current working directory, e.g. <code>/opt/local/bin</code> but I only want <code>bin</code></p>
<p>Thanks.</p> | <p>No need for basename, and especially no need for a subshell running pwd (which <A HREF="http://mywiki.wooledge.org/SubShell" rel="noreferrer">adds an extra, and expensive, fork operation</A>); the shell can do this internally using <A HREF="http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html" rel="noreferrer">parameter expansion</A>:</p>
<pre class="lang-bash prettyprint-override"><code>result=${PWD##*/} # to assign to a variable
result=${result:-/} # to correct for the case where PWD=/
printf '%s\n' "${PWD##*/}" # to print to stdout
# ...more robust than echo for unusual names
# (consider a directory named -e or -n)
printf '%q\n' "${PWD##*/}" # to print to stdout, quoted for use as shell input
# ...useful to make hidden characters readable.
</code></pre>
<hr />
<p>Note that if you're applying this technique in other circumstances (not <code>PWD</code>, but some other variable holding a directory name), you might need to trim any trailing slashes. The below uses bash's <a href="http://wiki.bash-hackers.org/syntax/pattern#extended_pattern_language" rel="noreferrer">extglob support</a> to work even with multiple trailing slashes:</p>
<pre class="lang-bash prettyprint-override"><code>dirname=/path/to/somewhere//
shopt -s extglob # enable +(...) glob syntax
result=${dirname%%+(/)} # trim however many trailing slashes exist
result=${result##*/} # remove everything before the last / that still remains
result=${result:-/} # correct for dirname=/ case
printf '%s\n' "$result"
</code></pre>
<p>Alternatively, without <code>extglob</code>:</p>
<pre class="lang-bash prettyprint-override"><code>dirname="/path/to/somewhere//"
result="${dirname%"${dirname##*[!/]}"}" # extglob-free multi-trailing-/ trim
result="${result##*/}" # remove everything before the last /
result=${result:-/} # correct for dirname=/ case
</code></pre> | {
"question_id": 1371261,
"question_date": "2009-09-03T03:11:53.060Z",
"question_score": 1047,
"tags": "bash|shell",
"answer_id": 1371283,
"answer_date": "2009-09-03T03:21:39.810Z",
"answer_score": 1409
} |
Please answer the following Stack Overflow question:
Title: What is the difference between JDK and JRE?
<p>What is the difference between JDK and JRE?</p>
<p>What are their roles and when should I use one or the other?</p> | <p>The <strong>JRE</strong> is the <strong>Java Runtime Environment</strong>. It is a package of everything necessary to run a compiled Java program, including the Java Virtual Machine (JVM), the Java Class Library, the <code>java</code> command, and other infrastructure. However, it cannot be used to create new programs.</p>
<p>The <strong>JDK</strong> is the <strong>Java Development Kit</strong>, the full-featured SDK for Java. It has everything the JRE has, but also the compiler (<code>javac</code>) and tools (like <code>javadoc</code> and <code>jdb</code>). It is capable of creating and compiling programs.</p>
<p>Usually, if you only care about running Java programs on computer you will only install the JRE. It's all you need. On the other hand, if you are planning to do some Java programming, you need to install the JDK instead. </p>
<p>Sometimes, even if you are not planning to do any Java development on a computer, you still need the JDK installed. For example, if you are deploying a web application with JSP, you are technically just running Java programs inside the application server. Why would you need the JDK then? Because the application server will convert JSP into Java servlets and needs to use the JDK to compile the servlets. I am sure that there are more examples.</p> | {
"question_id": 1906445,
"question_date": "2009-12-15T10:19:27.430Z",
"question_score": 1046,
"tags": "java",
"answer_id": 1906455,
"answer_date": "2009-12-15T10:21:05.683Z",
"answer_score": 1370
} |
Please answer the following Stack Overflow question:
Title: What's the difference between event.stopPropagation and event.preventDefault?
<p>They seem to be doing the same thing...<br>
Is one modern and one old? Or are they supported by different browsers?</p>
<p>When I handle events myself (without framework) I just always check for both and execute both if present. (I also <code>return false</code>, but I have the feeling that doesn't work with events attached with <code>node.addEventListener</code>).</p>
<blockquote>
<p>So why both? Should I keep checking for both? Or is there actually a difference?</p>
</blockquote>
<p>(I know, a lot of questions, but they're all sort of the same =))</p> | <p><code>stopPropagation</code> prevents further propagation of the current event in the capturing and bubbling phases.</p>
<p><code>preventDefault</code> prevents the default action the browser makes on that event.</p>
<h2>Examples</h2>
<p><strong>preventDefault</strong></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>$("#but").click(function (event) {
event.preventDefault()
})
$("#foo").click(function () {
alert("parent click event fired!")
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
<button id="but">button</button>
</div></code></pre>
</div>
</div>
</p>
<p><strong>stopPropagation</strong></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>$("#but").click(function (event) {
event.stopPropagation()
})
$("#foo").click(function () {
alert("parent click event fired!")
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
<button id="but">button</button>
</div></code></pre>
</div>
</div>
</p>
<p>With <code>stopPropagation</code>, only the <strong><code>button</code>'s click handler</strong> is called while the <strong><code>div</code>'s click handler</strong> never fires.</p>
<p>Where as if you use <code>preventDefault</code>, only the browser's default action is stopped but the div's click handler still fires.</p>
<p>Below are some docs on the DOM event properties and methods from MDN:</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelBubble" rel="noreferrer"><code>event.cancelBubble</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault" rel="noreferrer"><code>event.preventDefault()</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Event/returnValue" rel="noreferrer"><code>event.returnValue</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation" rel="noreferrer"><code>event.stopPropagation()</code></a></li>
</ul>
<p>For IE9 and FF you can just use preventDefault & stopPropagation.</p>
<p>To support IE8 and lower replace <code>stopPropagation</code> with <code>cancelBubble</code> and replace <code>preventDefault</code> with <code>returnValue</code></p> | {
"question_id": 5963669,
"question_date": "2011-05-11T11:45:18.697Z",
"question_score": 1046,
"tags": "javascript|events|preventdefault|stoppropagation",
"answer_id": 5963688,
"answer_date": "2011-05-11T11:46:34.027Z",
"answer_score": 1237
} |
Please answer the following Stack Overflow question:
Title: How do I redirect with JavaScript?
<p>How do you redirect to a page from another page with JavaScript?</p> | <p>To redirect to another page, you can use:</p>
<pre><code>window.location = "http://www.yoururl.com";
</code></pre> | {
"question_id": 4744751,
"question_date": "2011-01-20T08:08:18.767Z",
"question_score": 1044,
"tags": "javascript|redirect",
"answer_id": 4745622,
"answer_date": "2011-01-20T09:52:49.467Z",
"answer_score": 1573
} |
Please answer the following Stack Overflow question:
Title: How to copy commits from one branch to another?
<p>I've got two branches from my master:</p>
<ul>
<li><strong>v2.1</strong>: (version 2) I've been working on for several months</li>
<li><strong>wss</strong>: that I created yesterday to add one specific feature to my master (in production)</li>
</ul>
<p>Is there a way to copy yesterday's commits from wss to v2.1?</p> | <p>You should really have a workflow that lets you do this all by merging:</p>
<pre><code>- x - x - x (v2) - x - x - x (v2.1)
\
x - x - x (wss)
</code></pre>
<p>So all you have to do is <code>git checkout v2.1</code> and <code>git merge wss</code>. If for some reason you really can't do this, and you can't use <a href="http://kernel.org/pub/software/scm/git/docs/git-rebase.html" rel="noreferrer">git rebase</a> to move your wss branch to the right place, the command to grab a single commit from somewhere and apply it elsewhere is <a href="http://kernel.org/pub/software/scm/git/docs/git-cherry-pick.html" rel="noreferrer">git cherry-pick</a>. Just check out the branch you want to apply it on, and run <code>git cherry-pick <SHA of commit to cherry-pick></code>.</p>
<p>Some of the ways rebase might save you:</p>
<p>If your history looks like this:</p>
<pre><code>- x - x - x (v2) - x - x - x (v2.1)
\
x - x - x (v2-only) - x - x - x (wss)
</code></pre>
<p>You could use <code>git rebase --onto v2 v2-only wss</code> to move wss directly onto v2:</p>
<pre><code>- x - x - x (v2) - x - x - x (v2.1)
|\
| x - x - x (v2-only)
\
x - x - x (wss)
</code></pre>
<p>Then you can merge! If you really, really, <em>really</em> can't get to the point where you can merge, you can still use rebase to effectively do several cherry-picks at once:</p>
<pre><code># wss-starting-point is the SHA1/branch immediately before the first commit to rebase
git branch wss-to-rebase wss
git rebase --onto v2.1 wss-starting-point wss-to-rebase
git checkout v2.1
git merge wss-to-rebase
</code></pre>
<p>Note: the reason that it takes some extra work in order to do this is that it's creating duplicate commits in your repository. This isn't really a good thing - the whole point of easy branching and merging is to be able to do everything by making commit(s) one place and merging them into wherever they're needed. Duplicate commits mean an intent never to merge those two branches (if you decide you want to later, you'll get conflicts).</p> | {
"question_id": 2474353,
"question_date": "2010-03-19T00:51:39.187Z",
"question_score": 1044,
"tags": "git|branching-and-merging",
"answer_id": 2474371,
"answer_date": "2010-03-19T00:59:27.757Z",
"answer_score": 709
} |
Please answer the following Stack Overflow question:
Title: Make body have 100% of the browser height
<p>I want to make <code>body</code> have 100% of the browser height. Can I do that using CSS?</p>
<p>I tried setting <code>height: 100%</code>, but it doesn't work.</p>
<p>I want to set a background color for a page to fill the entire browser window, but if the page has little content I get a ugly white bar at the bottom.</p> | <p>Try setting the height of the html element to 100% as well. </p>
<pre><code>html,
body {
height: 100%;
}
</code></pre>
<p>Body looks to its parent (HTML) for how to scale the dynamic property, so the HTML element needs to have its height set as well. </p>
<p>However the content of body will probably need to change dynamically.
Setting min-height to 100% will accomplish this goal.</p>
<pre><code>html {
height: 100%;
}
body {
min-height: 100%;
}
</code></pre> | {
"question_id": 6654958,
"question_date": "2011-07-11T18:50:56.757Z",
"question_score": 1043,
"tags": "html|css|height",
"answer_id": 6654996,
"answer_date": "2011-07-11T18:53:54.933Z",
"answer_score": 1346
} |
Please answer the following Stack Overflow question:
Title: How do I check file size in Python?
<p>How do I get the size of a file in Python?</p> | <p>You need the <a href="https://docs.python.org/library/os.html#os.stat_result.st_size" rel="noreferrer"><code>st_size</code></a> property of <a href="https://docs.python.org/library/os.html#os.stat_result" rel="noreferrer">the object returned by <code>os.stat</code></a>. You can get it by either using <a href="https://docs.python.org/library/pathlib.html" rel="noreferrer"><code>pathlib</code></a> (Python 3.4+):</p>
<pre><code>>>> from pathlib import Path
>>> Path('somefile.txt').stat()
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> Path('somefile.txt').stat().st_size
1564
</code></pre>
<p>or using <a href="https://docs.python.org/library/os.html#os.stat" rel="noreferrer"><code>os.stat</code></a>:</p>
<pre><code>>>> import os
>>> os.stat('somefile.txt')
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> os.stat('somefile.txt').st_size
1564
</code></pre>
<p>Output is in bytes.</p> | {
"question_id": 2104080,
"question_date": "2010-01-20T18:58:29.827Z",
"question_score": 1043,
"tags": "python|file",
"answer_id": 2104107,
"answer_date": "2010-01-20T19:01:53.750Z",
"answer_score": 977
} |
Please answer the following Stack Overflow question:
Title: Constants in Objective-C
<p>I'm developing a <a href="http://en.wikipedia.org/wiki/Cocoa_%28API%29" rel="noreferrer">Cocoa</a> application, and I'm using constant <code>NSString</code>s as ways to store key names for my preferences.</p>
<p>I understand this is a good idea because it allows easy changing of keys if necessary.<br>
Plus, it's the whole 'separate your data from your logic' notion.</p>
<blockquote>
<p>Anyway, is there a good way to make these constants defined once for the whole application? </p>
</blockquote>
<p>I'm sure that there's an easy and intelligent way, but right now my classes just redefine the ones they use. </p> | <p>You should create a header file like:</p>
<pre><code>// Constants.h
FOUNDATION_EXPORT NSString *const MyFirstConstant;
FOUNDATION_EXPORT NSString *const MySecondConstant;
//etc.
</code></pre>
<p>(You can use <code>extern</code> instead of <code>FOUNDATION_EXPORT</code> if your code will not be used in mixed C/C++ environments or on other platforms.)</p>
<p>You can include this file in each file that uses the constants or in the pre-compiled header for the project.</p>
<p>You define these constants in a <code>.m</code> file like:</p>
<pre><code>// Constants.m
NSString *const MyFirstConstant = @"FirstConstant";
NSString *const MySecondConstant = @"SecondConstant";
</code></pre>
<p><code>Constants.m</code> should be added to your application/framework's target so that it is linked in to the final product.</p>
<p>The advantage of using string constants instead of <code>#define</code>'d constants is that you can test for equality using pointer comparison (<code>stringInstance == MyFirstConstant</code>) which is much faster than string comparison (<code>[stringInstance isEqualToString:MyFirstConstant]</code>) (and easier to read, IMO).</p> | {
"question_id": 538996,
"question_date": "2009-02-11T21:52:02.593Z",
"question_score": 1043,
"tags": "ios|objective-c|cocoa|nsstring|constants",
"answer_id": 539191,
"answer_date": "2009-02-11T22:38:22.200Z",
"answer_score": 1309
} |
Please answer the following Stack Overflow question:
Title: How do I use vim registers?
<p>I only know of one instance using registers is via <kbd>Ctrl</kbd><kbd>R</kbd><kbd>*</kbd> whereby I paste text from a clipboard. </p>
<p>What are other uses of registers? How to use them? </p>
<p>Everything you know about VI registers (let's focus on vi 7.2) -- share with us.</p> | <p>Registers in Vim let you run actions or commands on text stored within them. To access a register, you type <code>"a</code> before a command, where <code>a</code> is the name of a register. If you want to copy the current line into register <code>k</code>, you can type</p>
<pre><code>"kyy
</code></pre>
<p>Or you can <em>append</em> to a register by using a capital letter</p>
<pre><code>"Kyy
</code></pre>
<p>You can then move through the document and paste it elsewhere using</p>
<pre><code>"kp
</code></pre>
<p>To paste from system clipboard on Linux</p>
<pre><code>"+p
</code></pre>
<p>To paste from system clipboard on Windows (or from "mouse highlight" clipboard on Linux)</p>
<pre><code>"*p
</code></pre>
<p>To access all currently defined registers type</p>
<pre><code>:reg
</code></pre> | {
"question_id": 1497958,
"question_date": "2009-09-30T13:02:14.810Z",
"question_score": 1043,
"tags": "vim|vi",
"answer_id": 1498026,
"answer_date": "2009-09-30T13:12:34.540Z",
"answer_score": 1337
} |
Please answer the following Stack Overflow question:
Title: Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail
<p>What would be a good way to attempt to load <a href="http://code.google.com/apis/ajaxlibs/" rel="noreferrer">the hosted jQuery at Google</a> (or other Google hosted libs), but load my copy of jQuery if the Google attempt fails?</p>
<p>I'm not saying Google is flaky. There are cases where the Google copy is blocked (apparently in Iran, for instance).</p>
<p>Would I set up a timer and check for the jQuery object?</p>
<p>What would be the danger of both copies coming through?</p>
<p>Not really looking for answers like "just use the Google one" or "just use your own." I understand those arguments. I also understand that the user is likely to have the Google version cached. I'm thinking about fallbacks for the cloud in general.</p>
<hr>
<p>Edit: This part added...</p>
<p>Since Google suggests using google.load to load the ajax libraries, and it performs a callback when done, I'm wondering if that's the key to serializing this problem.</p>
<p>I know it sounds a bit crazy. I'm just trying to figure out if it can be done in a reliable way or not.</p>
<hr>
<p>Update: jQuery now hosted on Microsoft's CDN.</p>
<p><a href="http://www.asp.net/ajax/cdn/" rel="noreferrer">http://www.asp.net/ajax/cdn/</a></p> | <p>You can achieve it like this:</p>
<pre class="lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="/path/to/your/jquery"><\/script>');
</script>
</code></pre>
<p>This should be in your page's <code><head></code> and any jQuery ready event handlers should be in the <code><body></code> to avoid errors (although it's not fool-proof!).</p>
<p>One more reason to <strong>not</strong> use Google-hosted <strong>jQuery</strong> is that in some countries, Google's domain name is banned.</p> | {
"question_id": 1014203,
"question_date": "2009-06-18T17:51:33.107Z",
"question_score": 1043,
"tags": "jquery|cdn|google-ajax-libraries",
"answer_id": 1014251,
"answer_date": "2009-06-18T18:00:16.540Z",
"answer_score": 824
} |
Please answer the following Stack Overflow question:
Title: How to permanently set $PATH on Linux/Unix
<p>On Linux, how can I add a directory to the $PATH so it remains persistent across different sessions?</p>
<h4>Background</h4>
<p>I'm trying to add a directory to my path so it will always be in my Linux path. I've tried:</p>
<pre><code>export PATH=$PATH:/path/to/dir
</code></pre>
<p>This works, however each time I exit the terminal and start a new terminal instance, this path is lost, and I need to run the export command again.</p>
<p>How can I do it so this will be set permanently?</p> | <p>There are multiple ways to do it. The actual solution depends on the purpose.</p>
<p>The variable values are usually stored in either a list of assignments or a shell script that is run at the start of the system or user session. In case of the shell script you must use a specific shell syntax and <code>export</code> or <code>set</code> commands.</p>
<h2 id="system-wide-4zld">System wide</h2>
<ol>
<li><p><code>/etc/environment</code> List of unique assignments. Allows references. Perfect for adding system-wide directories like <code>/usr/local/something/bin</code> to <code>PATH</code> variable or defining <code>JAVA_HOME</code>. Used by <a href="https://en.wikipedia.org/wiki/Linux_PAM" rel="noreferrer">PAM</a> and <a href="https://en.wikipedia.org/wiki/Systemd" rel="noreferrer">systemd</a>.</p>
</li>
<li><p><code>/etc/environment.d/*.conf</code> List of unique assignments. Allows references. Perfect for adding system-wide directories like <code>/usr/local/something/bin</code> to <code>PATH</code> variable or defining <code>JAVA_HOME</code>. The configuration can be split into multiple files, usually one per each tool (Java, Go, and Node.js). Used by systemd that by design do not pass those values to user login shells.</p>
</li>
<li><p><code>/etc/xprofile</code> Shell script executed while starting X Window System session. This is run for every user that logs into X Window System. It is a good choice for <code>PATH</code> entries that are valid for every user like <code>/usr/local/something/bin</code>. The file is included by other script so use POSIX shell syntax not the syntax of your user shell.</p>
</li>
<li><p><code>/etc/profile</code> and <code>/etc/profile.d/*</code> Shell script. This is a good choice for shell-only systems. Those files are read only by shells in login mode.</p>
</li>
<li><p><code>/etc/<shell>.<shell>rc</code>. Shell script. This is a poor choice because it is single shell specific. Used in non-login mode.</p>
</li>
</ol>
<h2 id="user-session-8syc">User session</h2>
<ol>
<li><p><code>~/.pam_environment</code>. List of unique assignments, no references allowed. Loaded by PAM at the start of every user session irrelevant if it is an X Window System session or shell. You cannot reference other variables including <code>HOME</code> or <code>PATH</code> so it has limited use. Used by PAM.</p>
</li>
<li><p><code>~/.xprofile</code> Shell script. This is executed when the user logs into X Window System system. The variables defined here are visible to every X application. Perfect choice for extending <code>PATH</code> with values such as <code>~/bin</code> or <code>~/go/bin</code> or defining user specific <code>GOPATH</code> or <code>NPM_HOME</code>. The file is included by other script so use POSIX shell syntax not the syntax of your user shell. Your graphical text editor or IDE started by shortcut will see those values.</p>
</li>
<li><p><code>~/.profile</code>, <code>~/.<shell>_profile</code>, <code>~/.<shell>_login</code> Shell script. It will be visible only for programs started from terminal or terminal emulator. It is a good choice for shell-only systems. Used by shells in login mode.</p>
</li>
<li><p><code>~/.<shell>rc</code>. Shell script. This is a poor choice because it is single shell specific. Used by shells in non-login mode.</p>
</li>
</ol>
<h2 id="notes-xat3">Notes</h2>
<p><a href="https://en.wikipedia.org/wiki/GNOME" rel="noreferrer">GNOME</a> on <a href="https://en.wikipedia.org/wiki/Wayland_(display_server_protocol)" rel="noreferrer">Wayland</a> starts a user login shell to get the environment. It effectively uses the login shell configurations <code>~/.profile</code>, <code>~/.<shell>_profile</code>, <code>~/.<shell>_login</code> files.</p>
<h2 id="man-pages-boua"><a href="https://en.wikipedia.org/wiki/Man_page" rel="noreferrer">Man pages</a></h2>
<ul>
<li><a href="https://linux.die.net/man/1/environment" rel="noreferrer">environment</a></li>
<li><a href="https://linux.die.net/man/1/environment.d" rel="noreferrer">environment.d</a> <a href="https://linux.die.net/man/1/environment.d" rel="noreferrer">https://linux.die.net/man/1/environment.d</a></li>
<li><a href="https://linux.die.net/man/1/bash" rel="noreferrer">bash</a></li>
<li><a href="https://linux.die.net/man/1/dash" rel="noreferrer">dash</a></li>
</ul>
<h2 id="distribution-specific-documentation-l15c">Distribution-specific documentation</h2>
<ul>
<li><a href="https://help.ubuntu.com/community/EnvironmentVariables#Persistent_environment_variables" rel="noreferrer">Ubuntu</a></li>
<li><a href="https://wiki.archlinux.org/index.php/Environment_variables" rel="noreferrer">Arch Linux</a></li>
</ul>
<h2 id="related-1za8">Related</h2>
<p><a href="https://unix.stackexchange.com/a/46856/39410">Difference between Login Shell and Non-Login Shell?</a></p> | {
"question_id": 14637979,
"question_date": "2013-02-01T00:57:08.747Z",
"question_score": 1042,
"tags": "linux|bash|unix|path|zsh",
"answer_id": 26962251,
"answer_date": "2014-11-16T21:29:08.633Z",
"answer_score": 362
} |
Please answer the following Stack Overflow question:
Title: Why can't I use switch statement on a String?
<p>Is this functionality going to be put into a later Java version?</p>
<p>Can someone explain why I can't do this, as in, the technical way Java's <code>switch</code> statement works?</p> | <p>Switch statements with <code>String</code> cases have been implemented in <a href="http://openjdk.java.net/projects/jdk7/features/" rel="nofollow noreferrer">Java SE 7</a>, at least 16 years <a href="https://bugs.java.com/bugdatabase/view_bug.do?bug_id=1223179" rel="nofollow noreferrer">after they were first requested.</a> A clear reason for the delay was not provided, but it likely had to do with performance.</p>
<h2>Implementation in JDK 7</h2>
<p>The feature has now been implemented in <code>javac</code> <a href="http://blogs.oracle.com/darcy/entry/project_coin_string_switch_anatomy" rel="nofollow noreferrer">with a "de-sugaring" process;</a> a clean, high-level syntax using <code>String</code> constants in <code>case</code> declarations is expanded at compile-time into more complex code following a pattern. The resulting code uses JVM instructions that have always existed.</p>
<p>A <code>switch</code> with <code>String</code> cases is translated into two switches during compilation. The first maps each string to a unique integer—its position in the original switch. This is done by first switching on the hash code of the label. The corresponding case is an <code>if</code> statement that tests string equality; if there are collisions on the hash, the test is a cascading <code>if-else-if</code>. The second switch mirrors that in the original source code, but substitutes the case labels with their corresponding positions. This two-step process makes it easy to preserve the flow control of the original switch.</p>
<h2>Switches in the JVM</h2>
<p>For more technical depth on <code>switch</code>, you can refer to the JVM Specification, where the <a href="http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.10" rel="nofollow noreferrer">compilation of switch statements</a> is described. In a nutshell, there are two different JVM instructions that can be used for a switch, depending on the sparsity of the constants used by the cases. Both depend on using integer constants for each case to execute efficiently.</p>
<p>If the constants are dense, they are used as an index (after subtracting the lowest value) into a table of instruction pointers—the <code>tableswitch</code> instruction.</p>
<p>If the constants are sparse, a binary search for the correct case is performed—the <code>lookupswitch</code> instruction.</p>
<p>In de-sugaring a <code>switch</code> on <code>String</code> objects, both instructions are likely to be used. The <code>lookupswitch</code> is suitable for the first switch on hash codes to find the original position of the case. The resulting ordinal is a natural fit for a <code>tableswitch</code>.</p>
<p>Both instructions require the integer constants assigned to each case to be sorted at compile time. At runtime, while the <code>O(1)</code> performance of <code>tableswitch</code> generally appears better than the <code>O(log(n))</code> performance of <code>lookupswitch</code>, it requires some analysis to determine whether the table is dense enough to justify the space–time tradeoff. Bill Venners wrote <a href="http://www.artima.com/underthehood/flowP.html" rel="nofollow noreferrer">a great article</a> that covers this in more detail, along with an under-the-hood look at other Java flow control instructions.</p>
<h2>Before JDK 7</h2>
<p>Prior to JDK 7, <code>enum</code> could approximate a <code>String</code>-based switch. This uses <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9.3" rel="nofollow noreferrer">the static <code>valueOf</code></a> method generated by the compiler on every <code>enum</code> type. For example:</p>
<pre><code>Pill p = Pill.valueOf(str);
switch(p) {
case RED: pop(); break;
case BLUE: push(); break;
}
</code></pre> | {
"question_id": 338206,
"question_date": "2008-12-03T18:23:57.127Z",
"question_score": 1042,
"tags": "java|string|switch-statement",
"answer_id": 338230,
"answer_date": "2008-12-03T18:30:45.677Z",
"answer_score": 1022
} |
Please answer the following Stack Overflow question:
Title: How do I duplicate a line or selection within Visual Studio Code?
<p>Using Microsoft's Visual Studio Code, how do I duplicate a line of code and then move it up and down? (Similar to Sublime's <kbd>cmd</kbd>+<kbd>shift</kbd>+<kbd>d</kbd> behaviour)</p>
<p>It's a feature that I use constantly, and am struggling using Visual Studio Code without it.</p> | <p>The commands your are looking for are <code>editor.action.copyLinesDownAction</code> and <code>editor.action.copyLinesUpAction</code>. </p>
<p>You can see the associated keybindings by picking: <em>File > Preferences > Keyboard Shortcuts</em> </p>
<p><strong>Windows:</strong> </p>
<p><kbd>Shift</kbd>+<kbd>Alt</kbd>+<kbd>Down</kbd> and <kbd>Shift</kbd>+<kbd>Alt</kbd>+<kbd>Up</kbd></p>
<p><strong>Mac:</strong></p>
<p><kbd>Shift</kbd>+<kbd>Option</kbd>+<kbd>Down</kbd> and <kbd>Shift</kbd>+<kbd>Option</kbd><kbd>Up</kbd></p>
<p><strong>Linux:</strong></p>
<p><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Alt</kbd>+<kbd>Down</kbd> and <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Alt</kbd>+<kbd>Up</kbd></p>
<p>(Might need to use numpad <kbd>Down</kbd> and <kbd>Up</kbd> for Linux)</p>
<p>Furthermore, commands <code>editor.action.moveLinesUpAction</code> and <code>editor.action.moveLinesDownAction</code> are the ones to move lines and they are bound to <kbd>Alt</kbd>+<kbd>Down</kbd> and <kbd>Alt</kbd>+<kbd>Up</kbd> on Windows and Mac and <kbd>Ctrl</kbd>+<kbd>Down</kbd> and <kbd>Ctrl</kbd>+<kbd>Up</kbd> on Linux. </p> | {
"question_id": 30203752,
"question_date": "2015-05-13T00:38:40.800Z",
"question_score": 1042,
"tags": "editor|visual-studio-code|keyboard-shortcuts",
"answer_id": 30207023,
"answer_date": "2015-05-13T06:16:06.327Z",
"answer_score": 1864
} |
Please answer the following Stack Overflow question:
Title: Find all files in a directory with extension .txt in Python
<p>How can I find all the files in a directory having the extension <code>.txt</code> in python?</p> | <p>You can use <a href="https://docs.python.org/2/library/glob.html" rel="noreferrer"><code>glob</code></a>:</p>
<pre><code>import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
print(file)
</code></pre>
<p>or simply <a href="https://docs.python.org/2/library/os.html#os.listdir" rel="noreferrer"><code>os.listdir</code></a>:</p>
<pre><code>import os
for file in os.listdir("/mydir"):
if file.endswith(".txt"):
print(os.path.join("/mydir", file))
</code></pre>
<p>or if you want to traverse directory, use <a href="https://docs.python.org/2/library/os.html#os.walk" rel="noreferrer"><code>os.walk</code></a>:</p>
<pre><code>import os
for root, dirs, files in os.walk("/mydir"):
for file in files:
if file.endswith(".txt"):
print(os.path.join(root, file))
</code></pre> | {
"question_id": 3964681,
"question_date": "2010-10-19T01:09:13.617Z",
"question_score": 1041,
"tags": "python|file-io",
"answer_id": 3964691,
"answer_date": "2010-10-19T01:12:00.163Z",
"answer_score": 2976
} |
Please answer the following Stack Overflow question:
Title: How to emulate a do-while loop?
<p>I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:</p>
<pre><code>list_of_ints = [ 1, 2, 3 ]
iterator = list_of_ints.__iter__()
element = None
while True:
if element:
print element
try:
element = iterator.next()
except StopIteration:
break
print "done"
</code></pre>
<p>Instead of "1,2,3,done", it prints the following output:</p>
<pre><code>[stdout:]1
[stdout:]2
[stdout:]3
None['Traceback (most recent call last):
', ' File "test_python.py", line 8, in <module>
s = i.next()
', 'StopIteration
']
</code></pre>
<p>What can I do in order to catch the 'stop iteration' exception and break a while
loop properly?</p>
<p>An example of why such a thing may be needed is shown below as pseudocode.</p>
<p>State machine:</p>
<pre><code>s = ""
while True :
if state is STATE_CODE :
if "//" in s :
tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
state = STATE_COMMENT
else :
tokens.add( TOKEN_CODE, s )
if state is STATE_COMMENT :
if "//" in s :
tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
else
state = STATE_CODE
# Re-evaluate same line
continue
try :
s = i.next()
except StopIteration :
break
</code></pre> | <p>I am not sure what you are trying to do. You can implement a do-while loop like this:</p>
<pre><code>while True:
stuff()
if fail_condition:
break
</code></pre>
<p>Or:</p>
<pre><code>stuff()
while not fail_condition:
stuff()
</code></pre>
<p>What are you doing trying to use a do while loop to print the stuff in the list? Why not just use:</p>
<pre><code>for i in l:
print i
print "done"
</code></pre>
<p>Update:</p>
<p>So do you have a list of lines? And you want to keep iterating through it? How about: </p>
<pre><code>for s in l:
while True:
stuff()
# use a "break" instead of s = i.next()
</code></pre>
<p>Does that seem like something close to what you would want? With your code example, it would be:</p>
<pre><code>for s in some_list:
while True:
if state is STATE_CODE:
if "//" in s:
tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
state = STATE_COMMENT
else :
tokens.add( TOKEN_CODE, s )
if state is STATE_COMMENT:
if "//" in s:
tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
break # get next s
else:
state = STATE_CODE
# re-evaluate same line
# continues automatically
</code></pre> | {
"question_id": 743164,
"question_date": "2009-04-13T06:18:42.693Z",
"question_score": 1041,
"tags": "python|while-loop|do-while",
"answer_id": 743186,
"answer_date": "2009-04-13T06:28:43.760Z",
"answer_score": 1260
} |
Please answer the following Stack Overflow question:
Title: Check whether a string matches a regex in JS
<p>I want to use JavaScript (can be with jQuery) to do some client-side validation to check whether a string matches the regex:</p>
<pre><code>^([a-z0-9]{5,})$
</code></pre>
<p>Ideally it would be an expression that returned true or false. </p>
<p>I'm a JavaScript newbie, does <code>match()</code> do what I need? It seems to check whether part of a string matches a regex, not the whole thing. </p> | <p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test" rel="noreferrer"><code>regex.test()</code></a> if all you want is a boolean result:</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>console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false
console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true
console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true</code></pre>
</div>
</div>
</p>
<p>...and you could remove the <code>()</code> from your regexp since you've no need for a capture.</p> | {
"question_id": 6603015,
"question_date": "2011-07-06T21:08:50.767Z",
"question_score": 1041,
"tags": "javascript|regex|match",
"answer_id": 6603043,
"answer_date": "2011-07-06T21:10:28.573Z",
"answer_score": 1613
} |
Please answer the following Stack Overflow question:
Title: Why is setTimeout(fn, 0) sometimes useful?
<p>I've recently run into a rather nasty bug, wherein the code was loading a <code><select></code> dynamically via JavaScript. This dynamically loaded <code><select></code> had a pre-selected value. In IE6, we already had code to fix the selected <code><option></code>, because sometimes the <code><select></code>'s <code>selectedIndex</code> value would be out of sync with the selected <code><option></code>'s <code>index</code> attribute, as below:</p>
<pre><code>field.selectedIndex = element.index;
</code></pre>
<p>However, this code wasn't working. Even though the field's <code>selectedIndex</code> was being set correctly, the wrong index would end up being selected. However, if I stuck an <code>alert()</code> statement in at the right time, the correct option would be selected. Thinking this might be some sort of timing issue, I tried something random that I'd seen in code before:</p>
<pre><code>var wrapFn = (function() {
var myField = field;
var myElement = element;
return function() {
myField.selectedIndex = myElement.index;
}
})();
setTimeout(wrapFn, 0);
</code></pre>
<p>And this worked!</p>
<p>I've got a solution for my problem, but I'm uneasy that I don't know exactly why this fixes my problem. Does anyone have an official explanation? What browser issue am I avoiding by calling my function "later" using <code>setTimeout()</code>?</p> | <p>In the question, there existed a <a href="https://en.wikipedia.org/wiki/Race_condition" rel="noreferrer">race condition</a> between:</p>
<ol>
<li>The browser's attempt to initialize the drop-down list, ready to have its selected index updated, and</li>
<li>Your code to set the selected index</li>
</ol>
<p>Your code was consistently winning this race and attempting to set drop-down selection before the browser was ready, meaning that the bug would appear.</p>
<p>This race existed because JavaScript has a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop" rel="noreferrer">single thread of execution</a> that is shared with page rendering. In effect, running JavaScript blocks the updating of the DOM.</p>
<p>Your workaround was:</p>
<pre><code>setTimeout(callback, 0)
</code></pre>
<p>Invoking <code>setTimeout</code> with a callback, and zero as the second argument will schedule the callback to be run <strong>asynchronously</strong>, after the shortest possible delay - which will be around 10ms when the tab has focus and the JavaScript thread of execution is not busy.</p>
<p>The OP's solution, therefore was to delay by about 10ms, the setting of the selected index. This gave the browser an opportunity to initialize the DOM, fixing the bug.</p>
<p>Every version of Internet Explorer exhibited quirky behaviors and this kind of workaround was necessary at times. Alternatively it might have been a genuine bug in the OP's codebase. </p>
<hr>
<p>See Philip Roberts talk <a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ" rel="noreferrer">"What the heck is the event loop?"</a> for more thorough explanation.</p> | {
"question_id": 779379,
"question_date": "2009-04-22T21:46:08.390Z",
"question_score": 1041,
"tags": "javascript|dom|event-loop",
"answer_id": 779785,
"answer_date": "2009-04-23T00:14:17.927Z",
"answer_score": 939
} |
Please answer the following Stack Overflow question:
Title: How do I remove/delete a folder that is not empty?
<p>I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: <code>os.remove("/folder_name")</code>. </p>
<p>What is the most effective way of removing/deleting a folder/directory that is not empty?</p> | <pre><code>import shutil
shutil.rmtree('/folder_name')
</code></pre>
<p><a href="http://docs.python.org/library/shutil.html#shutil.rmtree" rel="noreferrer">Standard Library Reference: shutil.rmtree</a>.</p>
<p>By design, <code>rmtree</code> fails on folder trees containing read-only files. If you want the folder to be deleted regardless of whether it contains read-only files, then use</p>
<pre><code>shutil.rmtree('/folder_name', ignore_errors=True)
</code></pre> | {
"question_id": 303200,
"question_date": "2008-11-19T20:15:38.557Z",
"question_score": 1040,
"tags": "python|file",
"answer_id": 303225,
"answer_date": "2008-11-19T20:23:16.997Z",
"answer_score": 1661
} |
Please answer the following Stack Overflow question:
Title: List comprehension vs. lambda + filter
<p>I have a list that I want to filter by an attribute of the items.</p>
<p>Which of the following is preferred (readability, performance, other reasons)?</p>
<pre><code>xs = [x for x in xs if x.attribute == value]
</code></pre>
<pre><code>xs = filter(lambda x: x.attribute == value, xs)
</code></pre> | <p>It is strange how much beauty varies for different people. I find the list comprehension much clearer than <code>filter</code>+<code>lambda</code>, but use whichever you find easier.</p>
<p>There are two things that may slow down your use of <code>filter</code>.</p>
<p>The first is the function call overhead: as soon as you use a Python function (whether created by <code>def</code> or <code>lambda</code>) it is likely that filter will be slower than the list comprehension. It almost certainly is not enough to matter, and you shouldn't think much about performance until you've timed your code and found it to be a bottleneck, but the difference will be there.</p>
<p>The other overhead that might apply is that the lambda is being forced to access a scoped variable (<code>value</code>). That is slower than accessing a local variable and in Python 2.x the list comprehension only accesses local variables. If you are using Python 3.x the list comprehension runs in a separate function so it will also be accessing <code>value</code> through a closure and this difference won't apply.</p>
<p>The other option to consider is to use a generator instead of a list comprehension:</p>
<pre><code>def filterbyvalue(seq, value):
for el in seq:
if el.attribute==value: yield el
</code></pre>
<p>Then in your main code (which is where readability really matters) you've replaced both list comprehension and filter with a hopefully meaningful function name.</p> | {
"question_id": 3013449,
"question_date": "2010-06-10T10:14:00.497Z",
"question_score": 1040,
"tags": "python|list|functional-programming|filter|lambda",
"answer_id": 3013686,
"answer_date": "2010-06-10T10:52:49.703Z",
"answer_score": 690
} |
Please answer the following Stack Overflow question:
Title: Remove rows with all or some NAs (missing values) in data.frame
<p>I'd like to remove the lines in this data frame that:</p>
<p>a) <strong>contain <code>NA</code>s across all columns.</strong> Below is my example data frame. </p>
<pre><code> gene hsap mmul mmus rnor cfam
1 ENSG00000208234 0 NA NA NA NA
2 ENSG00000199674 0 2 2 2 2
3 ENSG00000221622 0 NA NA NA NA
4 ENSG00000207604 0 NA NA 1 2
5 ENSG00000207431 0 NA NA NA NA
6 ENSG00000221312 0 1 2 3 2
</code></pre>
<p>Basically, I'd like to get a data frame such as the following.</p>
<pre><code> gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
6 ENSG00000221312 0 1 2 3 2
</code></pre>
<p>b) <strong>contain <code>NA</code>s in only some columns</strong>, so I can also get this result:</p>
<pre><code> gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
4 ENSG00000207604 0 NA NA 1 2
6 ENSG00000221312 0 1 2 3 2
</code></pre> | <p>Also check <a href="http://stat.ethz.ch/R-manual/R-patched/library/stats/html/complete.cases.html" rel="noreferrer"><code>complete.cases</code></a> :</p>
<pre><code>> final[complete.cases(final), ]
gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
6 ENSG00000221312 0 1 2 3 2
</code></pre>
<p><code>na.omit</code> is nicer for just removing all <code>NA</code>'s. <code>complete.cases</code> allows partial selection by including only certain columns of the dataframe:</p>
<pre><code>> final[complete.cases(final[ , 5:6]),]
gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
4 ENSG00000207604 0 NA NA 1 2
6 ENSG00000221312 0 1 2 3 2
</code></pre>
<p>Your solution can't work. If you insist on using <code>is.na</code>, then you have to do something like:</p>
<pre><code>> final[rowSums(is.na(final[ , 5:6])) == 0, ]
gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
4 ENSG00000207604 0 NA NA 1 2
6 ENSG00000221312 0 1 2 3 2
</code></pre>
<p>but using <code>complete.cases</code> is quite a lot more clear, and faster.</p> | {
"question_id": 4862178,
"question_date": "2011-02-01T11:52:31.150Z",
"question_score": 1039,
"tags": "r|dataframe|filter|missing-data|r-faq",
"answer_id": 4862502,
"answer_date": "2011-02-01T12:21:42.927Z",
"answer_score": 1255
} |
Please answer the following Stack Overflow question:
Title: Creating a byte array from a stream
<p>What is the prefered method for creating a byte array from an input stream? </p>
<p>Here is my current solution with .NET 3.5. </p>
<pre><code>Stream s;
byte[] b;
using (BinaryReader br = new BinaryReader(s))
{
b = br.ReadBytes((int)s.Length);
}
</code></pre>
<p>Is it still a better idea to read and write chunks of the stream?</p> | <p>It really depends on whether or not you can trust <code>s.Length</code>. For many streams, you just don't know how much data there will be. In such cases - and before .NET 4 - I'd use code like this:</p>
<pre><code>public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
</code></pre>
<p>With .NET 4 and above, I'd use <a href="https://msdn.microsoft.com/en-us/library/system.io.stream.copyto" rel="noreferrer"><code>Stream.CopyTo</code></a>, which is basically equivalent to the loop in my code - create the <code>MemoryStream</code>, call <code>stream.CopyTo(ms)</code> and then return <code>ms.ToArray()</code>. Job done.</p>
<p>I should perhaps explain why my answer is longer than the others. <a href="http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx" rel="noreferrer"><code>Stream.Read</code></a> doesn't guarantee that it will read everything it's asked for. If you're reading from a network stream, for example, it may read one packet's worth and then return, even if there will be more data soon. <a href="http://msdn.microsoft.com/en-us/library/system.io.binaryreader.read.aspx" rel="noreferrer"><code>BinaryReader.Read</code></a> will keep going until the end of the stream or your specified size, but you still have to know the size to start with.</p>
<p>The above method will keep reading (and copying into a <code>MemoryStream</code>) until it runs out of data. It then asks the <code>MemoryStream</code> to return a copy of the data in an array. If you know the size to start with - or <em>think</em> you know the size, without being sure - you can construct the <code>MemoryStream</code> to be that size to start with. Likewise you can put a check at the end, and if the length of the stream is the same size as the buffer (returned by <a href="http://msdn.microsoft.com/en-us/library/system.io.memorystream.getbuffer.aspx" rel="noreferrer"><code>MemoryStream.GetBuffer</code></a>) then you can just return the buffer. So the above code isn't quite optimised, but will at least be correct. It doesn't assume any responsibility for closing the stream - the caller should do that.</p>
<p>See <a href="https://jonskeet.uk/csharp/readbinary.html" rel="noreferrer">this article</a> for more info (and an alternative implementation).</p> | {
"question_id": 221925,
"question_date": "2008-10-21T13:42:55.103Z",
"question_score": 1039,
"tags": "c#|.net-3.5|inputstream",
"answer_id": 221941,
"answer_date": "2008-10-21T13:45:57.500Z",
"answer_score": 1415
} |
Please answer the following Stack Overflow question:
Title: How to list all commits that changed a specific file?
<p>Is there a way to list all commits that changed a specific file?</p> | <p>The <code>--follow</code> works for a particular file</p>
<pre><code>git log --follow -- filename
</code></pre>
<p><strong>Difference to other solutions given</strong></p>
<p>Note that other solutions include <code>git log path</code> (without the <code>--follow</code>). That approach is handy if you want to track e.g. changes in a <strong>directory</strong>, but <strong>stumbles when files were renamed</strong> (thus use <strong><code>--follow filename</code></strong>).</p> | {
"question_id": 3701404,
"question_date": "2010-09-13T14:37:00.730Z",
"question_score": 1039,
"tags": "git|commit",
"answer_id": 8808453,
"answer_date": "2012-01-10T18:26:04.687Z",
"answer_score": 1364
} |
Please answer the following Stack Overflow question:
Title: How to convert a std::string to const char* or char*
<p>How can I convert an <code>std::string</code> to a <code>char*</code> or a <code>const char*</code>?</p> | <p>If you just want to pass a <a href="http://en.cppreference.com/w/cpp/string/basic_string" rel="noreferrer"><code>std::string</code></a> to a function that needs <code>const char*</code> you can use </p>
<pre><code>std::string str;
const char * c = str.c_str();
</code></pre>
<p>If you want to get a writable copy, like <code>char *</code>, you can do that with this:</p>
<pre><code>std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0'; // don't forget the terminating 0
// don't forget to free the string after finished using it
delete[] writable;
</code></pre>
<p><strong>Edit</strong>: Notice that the above is not exception safe. If anything between the <code>new</code> call and the <code>delete</code> call throws, you will leak memory, as nothing will call <code>delete</code> for you automatically. There are two immediate ways to solve this.</p>
<h3>boost::scoped_array</h3>
<p><a href="http://www.boost.org/doc/libs/release/libs/smart_ptr/scoped_array.htm" rel="noreferrer"><code>boost::scoped_array</code></a> will delete the memory for you upon going out of scope:</p>
<pre><code>std::string str;
boost::scoped_array<char> writable(new char[str.size() + 1]);
std::copy(str.begin(), str.end(), writable.get());
writable[str.size()] = '\0'; // don't forget the terminating 0
// get the char* using writable.get()
// memory is automatically freed if the smart pointer goes
// out of scope
</code></pre>
<h3>std::vector</h3>
<p>This is the standard way (does not require any external library). You use <a href="http://en.cppreference.com/w/cpp/container/vector" rel="noreferrer"><code>std::vector</code></a>, which completely manages the memory for you.</p>
<pre><code>std::string str;
std::vector<char> writable(str.begin(), str.end());
writable.push_back('\0');
// get the char* using &writable[0] or &*writable.begin()
</code></pre> | {
"question_id": 347949,
"question_date": "2008-12-07T19:30:56.800Z",
"question_score": 1038,
"tags": "c++|string|char|constants",
"answer_id": 347959,
"answer_date": "2008-12-07T19:35:43.763Z",
"answer_score": 1234
} |
Please answer the following Stack Overflow question:
Title: Where can I find php.ini?
<p>A few years ago I installed Apache 2.2x and PHP 5.3.1 on a Linux server I maintain. I used .tar.gz's and built them as instructed (instead of rpms and what-have-you). And all was fine.</p>
<p>Today I need to install <a href="http://us2.php.net/ibm_db2" rel="noreferrer">this</a> which seems like a PHP library. I went through all the steps up to make install, and I found ibm_db2.so in <code>$PHP_HOME/lib/extensions/somecomplicatedname/ibm_db2.so</code>.</p>
<p>The great catch is the last step is to configure file <em>php.ini</em>, but there aren't <em><strong>any</strong></em> <em>php.ini</em> files on my system. Horror of horrors. PHP works fine, except of course for this newfangled ibm_db2 thingamajig that I want to use so somebody can use a GUI to tinker with <a href="https://en.wikipedia.org/wiki/IBM_DB2" rel="noreferrer">DB2</a>. (I tried a small PHP script which fails and indicates that the ibm_db2 functions are not available.)</p>
<p>I have to deal with PHP once every few years, so please enlighten me at a very basic level about what I could do to enable web-based GUI access to DB2.</p> | <p>The best way to find this is:</p>
<p>Create a PHP (<em>.php</em>) file and add the following code:</p>
<pre><code><?php phpinfo(); ?>
</code></pre>
<p>and open it in a browser. It will show the file which is actually being read!</p>
<p>Updates by the OP:</p>
<ol>
<li>The previously accepted <a href="https://stackoverflow.com/questions/8684609/dude-wheres-my-php-ini/8684638#8684638">answer</a> is likely to be faster and more convenient for you, but it is not always correct. See comments on that answer.</li>
<li>Please also note the more convenient alternative <code><?php echo php_ini_loaded_file(); ?></code> mentioned in <a href="https://stackoverflow.com/questions/8684609/dude-wheres-my-php-ini/24342463#24342463">this answer</a>.</li>
</ol> | {
"question_id": 8684609,
"question_date": "2011-12-30T22:20:06.290Z",
"question_score": 1038,
"tags": "php|linux|php-ini",
"answer_id": 17185370,
"answer_date": "2013-06-19T07:32:29.320Z",
"answer_score": 531
} |
Please answer the following Stack Overflow question:
Title: How to create a directory if it doesn't exist using Node.js
<p>Is the following the right way to create a directory if it doesn't exist?</p>
<p>It should have full permission for the script and readable by others.</p>
<pre><code>var dir = __dirname + '/upload';
if (!path.existsSync(dir)) {
fs.mkdirSync(dir, 0744);
}
</code></pre> | <p>For individual dirs:</p>
<pre><code>var fs = require('fs');
var dir = './tmp';
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
</code></pre>
<p>Or, for nested dirs:</p>
<pre><code>var fs = require('fs');
var dir = './tmp/but/then/nested';
if (!fs.existsSync(dir)){
fs.mkdirSync(dir, { recursive: true });
}
</code></pre> | {
"question_id": 21194934,
"question_date": "2014-01-17T20:08:41.263Z",
"question_score": 1038,
"tags": "node.js",
"answer_id": 26815894,
"answer_date": "2014-11-08T10:03:15.343Z",
"answer_score": 1941
} |
Please answer the following Stack Overflow question:
Title: Join vs. sub-query
<p>I am an old-school MySQL user and have always preferred <code>JOIN</code> over sub-query. But nowadays everyone uses sub-query, and I hate it; I don't know why. </p>
<p>I lack the theoretical knowledge to judge for myself if there is any difference. Is a sub-query as good as a <code>JOIN</code> and therefore is there nothing to worry about?</p> | <p><strong>Taken from the MySQL manual</strong> (<a href="https://dev.mysql.com/doc/refman/5.7/en/rewriting-subqueries.html" rel="noreferrer">13.2.10.11 Rewriting Subqueries as Joins</a>):</p>
<blockquote>
<p>A LEFT [OUTER] JOIN can be faster than an equivalent subquery because the server might be able to optimize it better—a fact that is not specific to MySQL Server alone.</p>
</blockquote>
<p>So subqueries can be slower than <code>LEFT [OUTER] JOIN</code>, but in my opinion their strength is slightly higher readability.</p> | {
"question_id": 2577174,
"question_date": "2010-04-05T06:22:22.540Z",
"question_score": 1038,
"tags": "sql|mysql|subquery|join",
"answer_id": 39588846,
"answer_date": "2016-09-20T08:09:26.647Z",
"answer_score": 260
} |
Please answer the following Stack Overflow question:
Title: Understanding the Rails Authenticity Token
<p>What is the Authenticity Token in Rails?</p> | <p><strong>What happens</strong></p>
<p>When the user views a form to create, update, or destroy a resource, the Rails app creates a random <code>authenticity_token</code>, stores this token in the session, and places it in a hidden field in the form. When the user submits the form, Rails looks for the <code>authenticity_token</code>, compares it to the one stored in the session, and if they match the request is allowed to continue.</p>
<p><strong>Why it happens</strong></p>
<p>Since the authenticity token is stored in the session, the client cannot know its value. This prevents people from submitting forms to a Rails app without viewing the form within that app itself.
Imagine that you are using service A, you logged into the service and everything is OK. Now imagine that you went to use service B, and you saw a picture you like, and pressed on the picture to view a larger size of it. Now, if some evil code was there at service B, it might send a request to service A (which you are logged into), and ask to delete your account, by sending a request to <code>http://serviceA.example/close_account</code>. This is what is known as <a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery" rel="noreferrer">CSRF (Cross Site Request Forgery)</a>.</p>
<p>If service A is using authenticity tokens, this attack vector is no longer applicable, since the request from service B would not contain the correct authenticity token, and will not be allowed to continue.</p>
<p><a href="http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html" rel="noreferrer">API docs</a> describes details about meta tag:</p>
<blockquote>
<p>CSRF protection is turned on with the <code>protect_from_forgery</code> method,
which checks the token and resets the session if it doesn't match what
was expected. A call to this method is generated for new Rails
applications by default.
The token parameter is named <code>authenticity_token</code> by default. The name
and value of this token must be added to every layout that renders
forms by including <code>csrf_meta_tags</code> in the HTML head.</p>
</blockquote>
<p><strong>Notes</strong></p>
<p>Keep in mind, Rails only verifies not idempotent methods (POST, PUT/PATCH and DELETE). GET request are not checked for authenticity token. Why? because the HTTP specification states that GET requests is idempotent and should <strong>not</strong> create, alter, or destroy resources at the server, and the request should be idempotent (if you run the same command multiple times, you should get the same result every time).</p>
<p>Also the real implementation is a bit more complicated as defined in the beginning, ensuring better security. Rails does not issue the same stored token with every form. Neither does it generate and store a different token every time. It generates and stores a cryptographic hash in a session and issues new cryptographic tokens, which can be matched against the stored one, every time a page is rendered. See <a href="https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/request_forgery_protection.rb#L329" rel="noreferrer">request_forgery_protection.rb</a>.</p>
<p><strong>Lessons</strong></p>
<p>Use <code>authenticity_token</code> to protect your not idempotent methods (POST, PUT/PATCH, and DELETE). Also make sure not to allow any GET requests that could potentially modify resources on the server.</p>
<hr />
<p>Check <a href="https://stackoverflow.com/questions/941594/understand-rails-authenticity-token#comment16039314_1571900">the comment by @erturne</a> regarding GET requests being idempotent. He explains it in a better way than I have done here.</p> | {
"question_id": 941594,
"question_date": "2009-06-02T20:01:38.163Z",
"question_score": 1038,
"tags": "ruby-on-rails|ruby|authenticity-token",
"answer_id": 1571900,
"answer_date": "2009-10-15T11:52:29.583Z",
"answer_score": 1520
} |
Please answer the following Stack Overflow question:
Title: Search all of Git history for a string
<p>I have a code base which I want to push to GitHub as open source. In this Git-controlled source tree, I have certain configuration files which contain passwords. I made sure not to track this file and I also added it to the <code>.gitignore</code> file. However, I want to be absolutely positive that no sensitive information is going to be pushed, perhaps if something slipped in-between commits or something. I doubt I was careless enough to do this, but I want to be <em>positive</em>.</p>
<p>Is there a way to "grep" all of Git? I know that sounds weird, but by "all" I mean every version of every file that ever existed. I guess if there is a command that dumps the diff file for every commit, that might work?</p> | <p>Git can search diffs with the -S option (it's called pickaxe <a href="https://git-scm.com/docs/git-log#Documentation/git-log.txt--Sltstringgt" rel="noreferrer">in the docs</a>)</p>
<pre><code>git log -S password
</code></pre>
<p>This will find any commit that added or removed the string <code>password</code>. Here a few options:</p>
<ul>
<li><code>-p</code>: will show the diffs. If you provide a file (<code>-p file</code>), it will generate a patch for you.</li>
<li><code>-G</code>: looks for differences whose added or removed line matches the given regexp, as opposed to <code>-S</code>, which "looks for differences that introduce or remove an instance of string".</li>
<li><code>--all</code>: searches over all branches and tags; alternatively, use <code>--branches[=<pattern>]</code> or <code>--tags[=<pattern>]</code></li>
</ul> | {
"question_id": 4468361,
"question_date": "2010-12-17T06:49:54.573Z",
"question_score": 1037,
"tags": "git",
"answer_id": 4472267,
"answer_date": "2010-12-17T15:57:24.007Z",
"answer_score": 1608
} |
Please answer the following Stack Overflow question:
Title: What is the easiest way to remove all packages installed by pip?
<p>I'm trying to fix up one of my virtualenvs - I'd like to reset all of the installed libraries back to the ones that match production.</p>
<p>Is there a quick and easy way to do this with pip?</p> | <p>I've found this snippet as an alternative solution. It's a more graceful removal of libraries than remaking the virtualenv:</p>
<pre><code>pip freeze | xargs pip uninstall -y
</code></pre>
<hr>
<p>In case you have packages installed via VCS, you need to exclude those lines and remove the packages manually (elevated from the comments below):</p>
<pre><code>pip freeze | grep -v "^-e" | xargs pip uninstall -y
</code></pre> | {
"question_id": 11248073,
"question_date": "2012-06-28T15:36:44.040Z",
"question_score": 1036,
"tags": "python|pip|virtualenv|python-packaging",
"answer_id": 11250821,
"answer_date": "2012-06-28T18:32:29.103Z",
"answer_score": 1477
} |
Please answer the following Stack Overflow question:
Title: How to create a GUID/UUID in Python
<p>How do I create a GUID/UUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python?</p> | <blockquote>
<p>The <a href="https://docs.python.org/3/library/uuid.html" rel="noreferrer">uuid module</a> provides immutable UUID objects (the UUID class) and the functions <a href="https://docs.python.org/3/library/uuid.html#uuid.uuid1" rel="noreferrer"><code>uuid1()</code></a>, <a href="https://docs.python.org/3/library/uuid.html#uuid.uuid3" rel="noreferrer"><code>uuid3()</code></a>, <a href="https://docs.python.org/3/library/uuid.html#uuid.uuid4" rel="noreferrer"><code>uuid4()</code></a>, <a href="https://docs.python.org/3/library/uuid.html#uuid.uuid5" rel="noreferrer"><code>uuid5()</code></a> for generating version 1, 3, 4, and 5 UUIDs as specified in <a href="https://www.rfc-editor.org/rfc/rfc4122" rel="noreferrer">RFC 4122</a>.</p>
</blockquote>
<blockquote>
<p>If all you want is a unique ID, you should probably call <code>uuid1()</code> or <code>uuid4()</code>. <strong>Note that <code>uuid1()</code> may compromise privacy since it creates a UUID containing the computer’s network address.</strong> <code>uuid4()</code> creates a random UUID.</p>
</blockquote>
<p>UUID versions 6 and 7 - <em>new Universally Unique Identifier (UUID) formats for use in modern applications and databases</em> <a href="https://uuid6.github.io/uuid6-ietf-draft/" rel="noreferrer">(<strong>draft</strong>) rfc</a> - are available from <a href="https://pypi.org/project/uuid6/" rel="noreferrer">https://pypi.org/project/uuid6/</a></p>
<p>Docs:</p>
<ul>
<li><a href="https://docs.python.org/2/library/uuid.html" rel="noreferrer">Python 2</a></li>
<li><a href="https://docs.python.org/3/library/uuid.html" rel="noreferrer">Python 3</a></li>
</ul>
<p>Examples (for both Python 2 and 3):</p>
<pre><code>>>> import uuid
>>> # make a random UUID
>>> uuid.uuid4()
UUID('bd65600d-8669-4903-8a14-af88203add38')
>>> # Convert a UUID to a string of hex digits in standard form
>>> str(uuid.uuid4())
'f50ec0b7-f960-400d-91f0-c42a6d44e3d0'
>>> # Convert a UUID to a 32-character hexadecimal string
>>> uuid.uuid4().hex
'9fe2c4e93f654fdbb24c02b15259716c'
</code></pre> | {
"question_id": 534839,
"question_date": "2009-02-10T23:51:21.473Z",
"question_score": 1035,
"tags": "python|uuid|guid|uniqueidentifier",
"answer_id": 534847,
"answer_date": "2009-02-10T23:54:26.040Z",
"answer_score": 1276
} |
Please answer the following Stack Overflow question:
Title: Calculate RSA key fingerprint
<p>I need to do the SSH key audit for GitHub, but I am not sure how do find my RSA key fingerprint. I originally followed a guide to generate an SSH key on Linux.</p>
<p>What is the command I need to enter to find my current RSA key fingerprint?</p> | <p>Run the following command to retrieve the SHA256 fingerprint of your SSH key (<code>-l</code> means "list" instead of create a new key, <code>-f</code> means "filename"):</p>
<pre><code>$ ssh-keygen -lf /path/to/ssh/key
</code></pre>
<p>So for example, on my machine the command I ran was (using RSA public key):</p>
<pre><code>$ ssh-keygen -lf ~/.ssh/id_rsa.pub
2048 00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff /Users/username/.ssh/id_rsa.pub (RSA)
</code></pre>
<p>To get the GitHub (MD5) fingerprint format with newer versions of ssh-keygen, run:</p>
<pre><code>$ ssh-keygen -E md5 -lf <fileName>
</code></pre>
<p>Bonus information:</p>
<p><code>ssh-keygen -lf</code> also works on <code>known_hosts</code> and <code>authorized_keys</code> files.</p>
<p>To find most public keys on Linux/Unix/OS X systems, run</p>
<pre><code>$ find /etc/ssh /home/*/.ssh /Users/*/.ssh -name '*.pub' -o -name 'authorized_keys' -o -name 'known_hosts'
</code></pre>
<p>(If you want to see inside other users' homedirs, you'll have to be root or sudo.)</p>
<p>The <code>ssh-add -l</code> is very similar, but lists the fingerprints of keys added to your agent. (OS X users take note that magic passwordless SSH via Keychain is not the same as using ssh-agent.)</p> | {
"question_id": 9607295,
"question_date": "2012-03-07T18:48:14.510Z",
"question_score": 1035,
"tags": "github|ssh|rsa|ssh-keys",
"answer_id": 9607373,
"answer_date": "2012-03-07T18:54:07.070Z",
"answer_score": 1440
} |
Please answer the following Stack Overflow question:
Title: Why doesn't RecyclerView have onItemClickListener()?
<p>I was exploring <code>RecyclerView</code> and I was surprised to see that <code>RecyclerView</code> does not have <code>onItemClickListener()</code>.</p>
<p>I've two question.</p>
<h1>Main Question</h1>
<p>I want to know why Google removed <code>onItemClickListener()</code>? </p>
<p>Is there a performance issue or something else?</p>
<h1>Secondary Question</h1>
<p>I solved my problem by writing <code>onClick</code> in my <code>RecyclerView.Adapter</code>:</p>
<pre><code>public static class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {
public TextView txtViewTitle;
public ImageView imgViewIcon;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title);
imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
}
@Override
public void onClick(View v) {
}
}
</code></pre>
<p>Is this ok / is there any better way?</p> | <p><strong>tl;dr 2016</strong> Use RxJava and a PublishSubject to expose an Observable for the clicks.</p>
<pre><code>public class ReactiveAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
String[] mDataset = { "Data", "In", "Adapter" };
private final PublishSubject<String> onClickSubject = PublishSubject.create();
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final String element = mDataset[position];
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onClickSubject.onNext(element);
}
});
}
public Observable<String> getPositionClicks(){
return onClickSubject.asObservable();
}
}
</code></pre>
<p><strong>Original Post:</strong></p>
<p>Since the introduction of <code>ListView</code>, <code>onItemClickListener</code> has been problematic. The moment you have a click listener for any of the internal elements the callback would not be triggered but it wasn't notified or well documented (if at all) so there was a lot of confusion and SO questions about it.</p>
<p>Given that <code>RecyclerView</code> takes it a step further and doesn't have a concept of a row/column, but rather an arbitrarily laid out amount of children, they have delegated the onClick to each one of them, or to programmer implementation.</p>
<p>Think of <code>Recyclerview</code> not as a <code>ListView</code> 1:1 replacement but rather as a more flexible component for complex use cases. And as you say, your solution is what google expected of you. Now you have an adapter who can delegate onClick to an interface passed on the constructor, which is the correct pattern for both <code>ListView</code> and <code>Recyclerview</code>.</p>
<pre><code>public static class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {
public TextView txtViewTitle;
public ImageView imgViewIcon;
public IMyViewHolderClicks mListener;
public ViewHolder(View itemLayoutView, IMyViewHolderClicks listener) {
super(itemLayoutView);
mListener = listener;
txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title);
imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
imgViewIcon.setOnClickListener(this);
itemLayoutView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v instanceof ImageView){
mListener.onTomato((ImageView)v);
} else {
mListener.onPotato(v);
}
}
public static interface IMyViewHolderClicks {
public void onPotato(View caller);
public void onTomato(ImageView callerImage);
}
}
</code></pre>
<p>and then on your adapter</p>
<pre><code>public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
String[] mDataset = { "Data" };
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout, parent, false);
MyAdapter.ViewHolder vh = new ViewHolder(v, new MyAdapter.ViewHolder.IMyViewHolderClicks() {
public void onPotato(View caller) { Log.d("VEGETABLES", "Poh-tah-tos"); };
public void onTomato(ImageView callerImage) { Log.d("VEGETABLES", "To-m8-tohs"); }
});
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Get element from your dataset at this position
// Replace the contents of the view with that element
// Clear the ones that won't be used
holder.txtViewTitle.setText(mDataset[position]);
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDataset.length;
}
...
</code></pre>
<p>Now look into that last piece of code: <code>onCreateViewHolder(ViewGroup parent, int viewType)</code> the signature already suggest different view types. For each one of them you'll require a different viewholder too, and subsequently each one of them can have a different set of clicks. Or you can just create a generic viewholder that takes any view and one <code>onClickListener</code> and applies accordingly. Or delegate up one level to the orchestrator so several fragments/activities have the same list with different click behaviour. Again, all flexibility is on your side.</p>
<p>It is a really needed component and fairly close to what our internal implementations and improvements to <code>ListView</code> were until now. It's good that Google finally acknowledges it.</p> | {
"question_id": 24885223,
"question_date": "2014-07-22T10:43:39.813Z",
"question_score": 1035,
"tags": "java|android|android-recyclerview",
"answer_id": 24933117,
"answer_date": "2014-07-24T12:00:40.327Z",
"answer_score": 1242
} |
Please answer the following Stack Overflow question:
Title: How can I disable landscape mode in Android?
<p>How can I disable landscape mode for some of the views in my Android app?</p> | <p>Add <code>android:screenOrientation="portrait"</code> to the activity in the AndroidManifest.xml. For example:</p>
<pre><code><activity android:name=".SomeActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" />
</code></pre>
<p>Since this has become a super-popular answer, I feel very guilty as forcing portrait is rarely the right solution to the problems it's frequently applied to. <br/>
The major caveats with forced portrait:</p>
<ul>
<li>This does not absolve you of having to think about activity
lifecycle events or properly saving/restoring state. There are plenty of
things besides app rotation that can trigger an activity
destruction/recreation, including unavoidable things like multitasking. There are no shortcuts; learn to use bundles and <code>retainInstance</code> fragments.</li>
<li>Keep in mind that unlike the fairly uniform iPhone experience, there are some devices where portrait is not the clearly popular orientation. When users are on devices with hardware keyboards or game pads a la the Nvidia Shield, on <a href="https://support.google.com/chromebook/answer/7021273?hl=en" rel="noreferrer">Chromebooks</a>, on <a href="https://android-developers.googleblog.com/2018/11/get-your-app-ready-for-foldable-phones.html" rel="noreferrer">foldables</a>, or on <a href="https://www.samsung.com/global/galaxy/apps/samsung-dex/" rel="noreferrer">Samsung DeX</a>, forcing portrait can make your app experience either limiting or a giant usability hassle. If your app doesn't have a strong UX argument that would lead to a negative experience for supporting other orientations, you should probably not force landscape. I'm talking about things like "this is a cash register app for one specific model of tablet always used in a fixed hardware dock."</li>
</ul>
<p>So most apps should just let the phone sensors, software, and physical configuration make their own decision about how the user wants to interact with your app. A few cases you may still want to think about, though, if you're not happy with the default behavior of <code>sensor</code> orientation in your use case:</p>
<ul>
<li>If your main concern is accidental orientation changes mid-activity that you think the device's sensors and software won't cope with well (for example, in a tilt-based game) consider supporting landscape and portrait, but using <code>nosensor</code> for the orientation. This forces landscape on most tablets and portrait on most phones, but I still wouldn't recommend this for most "normal" apps (some users just like to type in the landscape softkeyboard on their phones, and many tablet users read in portrait - and you should let them).</li>
<li>If you <em>still</em> need to force portrait for some reason, <code>sensorPortrait</code> may be better than <code>portrait</code> for <a href="https://en.wikipedia.org/wiki/Android_Gingerbread" rel="noreferrer">Android 2.3</a> (Gingerbread) and later; this allows for upside-down portrait, which is quite common in tablet usage.</li>
</ul> | {
"question_id": 582185,
"question_date": "2009-02-24T15:29:25.437Z",
"question_score": 1034,
"tags": "android|android-manifest|android-orientation",
"answer_id": 582585,
"answer_date": "2009-02-24T17:04:33.523Z",
"answer_score": 1785
} |
Please answer the following Stack Overflow question:
Title: What is the meaning of "POSIX"?
<p>What is POSIX? I have read the <a href="http://en.wikipedia.org/wiki/POSIX" rel="noreferrer">Wikipedia article</a> and I read it every time I encounter the term. The fact is that I never really understood what it is.</p>
<p>Can anyone please explain it to me by explaining "the need for POSIX" too?</p> | <p><a href="http://en.wikipedia.org/wiki/POSIX" rel="noreferrer">POSIX</a> is a family of standards, specified by the <a href="http://www.ieee.org/portal/site" rel="noreferrer">IEEE</a>, to clarify and make uniform the application programming interfaces (and ancillary issues, such as commandline shell utilities) provided by Unix-y operating systems.</p>
<p>When you write your programs to rely on POSIX standards, you can be pretty sure to be able to port them easily among a large family of Unix derivatives (including Linux, but not limited to it!); if and when you use some Linux API that's not standardized as part of Posix, you will have a harder time if and when you want to port that program or library to other Unix-y systems (e.g., MacOSX) in the future.</p> | {
"question_id": 1780599,
"question_date": "2009-11-23T00:42:49.093Z",
"question_score": 1034,
"tags": "linux|unix|posix|terminology",
"answer_id": 1780614,
"answer_date": "2009-11-23T00:47:14.967Z",
"answer_score": 731
} |
Please answer the following Stack Overflow question:
Title: Reading a plain text file in Java
<p>It seems there are different ways to read and write data of files in Java.</p>
<p>I want to read ASCII data from a file. What are the possible ways and their differences?</p> | <p>ASCII is a TEXT file so you would use <a href="http://docs.oracle.com/javase/7/docs/api/java/io/Reader.html" rel="noreferrer"><code>Readers</code></a> for reading. Java also supports reading from a binary file using <a href="http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html" rel="noreferrer"><code>InputStreams</code></a>. If the files being read are huge then you would want to use a <a href="http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html" rel="noreferrer"><code>BufferedReader</code></a> on top of a <a href="http://docs.oracle.com/javase/7/docs/api/java/io/FileReader.html" rel="noreferrer"><code>FileReader</code></a> to improve read performance.</p>
<p>Go through <a href="http://www.javapractices.com/topic/TopicAction.do?Id=42" rel="noreferrer">this article</a> on how to use a <code>Reader</code></p>
<p>I'd also recommend you download and read this wonderful (yet free) book called <a href="https://www.mindviewllc.com/quicklinks/#java" rel="noreferrer"><strong>Thinking In Java</strong></a></p>
<p><strong>In Java 7</strong>:</p>
<pre><code>new String(Files.readAllBytes(...))
</code></pre>
<p><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllBytes%28java.nio.file.Path%29" rel="noreferrer">(docs)</a>
or</p>
<pre><code>Files.readAllLines(...)
</code></pre>
<p><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines%28java.nio.file.Path,%20java.nio.charset.Charset%29" rel="noreferrer">(docs)</a></p>
<p><strong>In Java 8</strong>:</p>
<pre><code>Files.lines(..).forEach(...)
</code></pre>
<p><a href="http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-" rel="noreferrer">(docs)</a></p> | {
"question_id": 4716503,
"question_date": "2011-01-17T18:29:13.063Z",
"question_score": 1033,
"tags": "java|file-io|ascii",
"answer_id": 4716521,
"answer_date": "2011-01-17T18:31:39.167Z",
"answer_score": 624
} |
Please answer the following Stack Overflow question:
Title: scp with port number specified
<p>I'm trying to scp a file from a remote server to my local machine. Only port 80 is accessible.</p>
<p>I tried:</p>
<pre><code>scp -p 80 [email protected]:/root/file.txt .
</code></pre>
<p>but got this error: <code>cp: 80: No such file or directory</code></p>
<p>How do I specify the port number in a scp command?</p> | <p>Unlike ssh, scp uses the uppercase P switch to set the port instead of the lowercase p:</p>
<pre><code>scp -P 80 ... # Use port 80 to bypass the firewall, instead of the scp default
</code></pre>
<p>The lowercase p switch is used with scp for the preservation of times and modes.</p>
<p>Here is an excerpt from scp's man page with all of the details concerning the two switches, as well as an explanation of why uppercase P was chosen for scp:</p>
<blockquote>
<p>-P port Specifies the port to connect to on the remote host. Note that this option is written with a capital 'P', because -p is already
reserved for preserving the times and modes of the file in rcp(1).</p>
<p>-p Preserves modification times, access times, and modes from the original file.</p>
</blockquote>
<p><em>Bonus Tip</em>: How can I determine the port being used by the/an SSH daemon to accept SSH connections?</p>
<p>This question can be answered by using the <code>netstat</code> utility, as follows:</p>
<pre><code>sudo netstat -tnlp | grep sshd
</code></pre>
<p>Or, using the far more readable word based netstat option names:</p>
<pre><code>sudo netstat --tcp --numeric-ports --listening --program | grep sshd
</code></pre>
<p>The output you will see, assuming your ssh daemon is configured with default values its listening ports, is shown below (with a little trimming of the whitespace in between columns, in order to get the entire table to be visible without having to scroll):</p>
<pre><code>Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State ID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 888/sshd: /usr/sbin
tcp6 0 0 :::22 :::* LISTEN 888/sshd: /usr/sbin
</code></pre>
<p><em>Important Note</em></p>
<p>For the above examples, <code>sudo</code> was used to run netstat with administrator privs, in order to be able to see <em>all</em> of the <em>Program Names</em>. If you run netstat as a regular user (i.e., without sudo and assuming you don't have admin rights granted to you, via some other method), you will only see program names shown for sockets that have your UID as the owner. The <em>Program Names</em> for sockets belonging to other users will not be shown (i.e., will be hidden and a placeholder hyphen will be displayed, instead):</p>
<pre><code>Proto Recv-Q Send-Q Local Address Foreign Address State ID/Program name
tcp 0 0 127.0.0.1:46371 0.0.0.0:* LISTEN 4489/code
...
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN -
tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN -
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN -
...
</code></pre>
<p><em>Update and aside to address one of the (heavily upvoted) comments</em>:</p>
<p>With regard to Abdull's comment about <code>scp</code> option order, what he suggests:</p>
<pre><code>scp -r some_directory -P 80 ...
</code></pre>
<p>..., intersperses options and parameters, since the <code>-r</code> switch takes no additional arguments and <code>some_directory</code> is treated as the first parameter to the command, making <code>-P</code> and all subsequent command line arguments look like additional parameters to the command (i.e., hyphen prefixed arguments are no longer considered as switches).</p>
<p><code>getopt(1)</code> clearly defines that parameters must come <em>after</em> options (i.e., switches) and not be interspersed with them, willy-nilly:</p>
<blockquote>
<p>The parameters getopt is called with can be divided into two parts: options which modify the way getopt will do the parsing (the options and the optstring in the SYNOPSIS), and the parameters which are to be parsed (parameters in the SYNOPSIS). The second part will start at
the first non-option parameter that is not an option argument, or after the first occurrence of '--'. If no '-o' or '--options' option is found in the first part, the first parameter of the second part is used as the short options string.</p>
</blockquote>
<p>Since the <code>-r</code> command line option takes no further arguments, <code>some_directory</code> is "the first non-option parameter that is not an option argument." Therefore, as clearly spelled out in the <code>getopt(1)</code> man page, all succeeding command line arguments that follow it (i.e., <code>-P 80 ...</code>) are assumed to be non-options (and non-option arguments).</p>
<p>So, in effect, this is how <code>getopt(1)</code> sees the example presented with the end of the options and the beginning of the parameters demarcated by gray text:</p>
<p>scp -r <code>some_directory -P 80 ...</code></p>
<p>This has nothing to do with <code>scp</code> behavior and everything to do with how POSIX standard applications parse command line options using the <code>getopt(3)</code> set of C functions.</p>
<p>For more details with regard to command line ordering and processing, please read the <code>getopt(1)</code> manpage using:</p>
<pre><code>man 1 getopt
</code></pre> | {
"question_id": 10341032,
"question_date": "2012-04-26T20:35:05.753Z",
"question_score": 1033,
"tags": "port|scp",
"answer_id": 10341062,
"answer_date": "2012-04-26T20:37:03.303Z",
"answer_score": 1790
} |
Please answer the following Stack Overflow question:
Title: How to check if a service is running on Android?
<p>How do I check if a background service is running?</p>
<p>I want an Android activity that toggles the state of the service -- it lets me turn it on if it is off and off if it is on.</p> | <p>I had the same problem not long ago. Since my service was local, I ended up simply using a static field in the service class to toggle state, as described by hackbod <a href="http://groups.google.com/group/android-developers/browse_thread/thread/8c4bd731681b8331/bf3ae8ef79cad75d" rel="noreferrer">here</a></p>
<p><strong>EDIT (for the record):</strong></p>
<p>Here is the solution proposed by hackbod:</p>
<blockquote>
<p>If your client and server code is part of the same .apk and you are
binding to the service with a concrete Intent (one that specifies the
exact service class), then you can simply have your service set a
global variable when it is running that your client can check. </p>
<p>We deliberately don't have an API to check whether a service is
running because, nearly without fail, when you want to do something
like that you end up with race conditions in your code. </p>
</blockquote> | {
"question_id": 600207,
"question_date": "2009-03-01T18:09:09.397Z",
"question_score": 1032,
"tags": "android|android-service",
"answer_id": 608600,
"answer_date": "2009-03-03T22:58:35.127Z",
"answer_score": 313
} |
Please answer the following Stack Overflow question:
Title: JPA EntityManager: Why use persist() over merge()?
<p><code>EntityManager.merge()</code> can insert new objects and update existing ones.</p>
<p>Why would one want to use <code>persist()</code> (which can only create new objects)?</p> | <p>Either way will add an entity to a PersistenceContext, the difference is in what you do with the entity afterwards.</p>
<p>Persist takes an entity instance, adds it to the context and makes that instance managed (i.e. future updates to the entity will be tracked).</p>
<p>Merge returns the managed instance that the state was merged with. It does return something that exists in PersistenceContext or creates a new instance of your entity. In any case, it will copy the state from the supplied entity, and return a managed copy. The instance you pass in will not be managed (any changes you make will not be part of the transaction - unless you call merge again). Though you can use the returned instance (managed one).</p>
<p>Maybe a code example will help.</p>
<pre><code>MyEntity e = new MyEntity();
// scenario 1
// tran starts
em.persist(e);
e.setSomeField(someValue);
// tran ends, and the row for someField is updated in the database
// scenario 2
// tran starts
e = new MyEntity();
em.merge(e);
e.setSomeField(anotherValue);
// tran ends but the row for someField is not updated in the database
// (you made the changes *after* merging)
// scenario 3
// tran starts
e = new MyEntity();
MyEntity e2 = em.merge(e);
e2.setSomeField(anotherValue);
// tran ends and the row for someField is updated
// (the changes were made to e2, not e)
</code></pre>
<p>Scenario 1 and 3 are roughly equivalent, but there are some situations where you'd want to use Scenario 2.</p> | {
"question_id": 1069992,
"question_date": "2009-07-01T16:03:59.703Z",
"question_score": 1031,
"tags": "jpa|merge|entitymanager|persist|java-persistence-api",
"answer_id": 1070629,
"answer_date": "2009-07-01T18:28:29.480Z",
"answer_score": 1718
} |
Please answer the following Stack Overflow question:
Title: Tab space instead of multiple non-breaking spaces ("nbsp")?
<p>Is it possible to insert a tab character in HTML instead of having to type <code>&nbsp;</code> four times?</p> | <p>It's much cleaner to use CSS. Try <code>padding-left:5em</code> or <code>margin-left:5em</code> as appropriate instead.</p> | {
"question_id": 1571648,
"question_date": "2009-10-15T11:03:39.507Z",
"question_score": 1030,
"tags": "html",
"answer_id": 1571662,
"answer_date": "2009-10-15T11:06:42.623Z",
"answer_score": 619
} |
Please answer the following Stack Overflow question:
Title: How to style a checkbox using CSS
<p>I am trying to style a checkbox using the following:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" /></code></pre>
</div>
</div>
</p>
<p>But the style is not applied. The checkbox still displays its default style. How do I give it the specified style?</p> | <p>UPDATE:</p>
<p>The below answer references the state of things before widespread availability of CSS 3. In modern browsers (including Internet Explorer 9 and later) it is more straightforward to create checkbox replacements with your preferred styling, without using JavaScript.</p>
<p>Here are some useful links:</p>
<ul>
<li><a href="http://www.inserthtml.com/2012/06/custom-form-radio-checkbox/" rel="noreferrer">Creating Custom Form Checkboxes with Just CSS</a></li>
<li><a href="http://csscheckbox.com" rel="noreferrer">Easy CSS Checkbox Generator</a></li>
<li><a href="http://css-tricks.com/the-checkbox-hack/" rel="noreferrer">Stuff You Can Do With The Checkbox Hack</a></li>
<li><a href="http://www.css3.com/implementing-custom-checkboxes-and-radio-buttons-with-css3/" rel="noreferrer">Implementing Custom Checkboxes and Radio Buttons with CSS3</a></li>
<li><a href="https://www.paulund.co.uk/how-to-style-a-checkbox-with-css" rel="noreferrer">How to Style a Checkbox With CSS</a></li>
</ul>
<p>It is worth noting that the fundamental issue has not changed. You still can't apply styles (borders, etc.) directly to the checkbox element and have those styles affect the display of the HTML checkbox. What has changed, however, is that it's now possible to hide the actual checkbox and replace it with a styled element of your own, using nothing but CSS. In particular, because CSS now has a widely supported <code>:checked</code> selector, you can make your replacement correctly reflect the checked status of the box.</p>
<hr />
<p>OLDER ANSWER</p>
<p>Here's <a href="http://www.456bereastreet.com/archive/200701/styling_form_controls_with_css_revisited/" rel="noreferrer">a useful article about styling checkboxes</a>. Basically, that writer found that it varies tremendously from browser to browser, and that many browsers always display the default checkbox no matter how you style it. So there really isn't an easy way.</p>
<p>It's not hard to imagine a workaround where you would use JavaScript to overlay an image on the checkbox and have clicks on that image cause the real checkbox to be checked. Users without JavaScript would see the default checkbox.</p>
<p>Edited to add: here's <a href="https://web.archive.org/web/20160430165815/http://ryanfait.com:80/resources/custom-checkboxes-and-radio-buttons/#" rel="noreferrer">a nice script that does this for you</a>; it hides the real checkbox element, replaces it with a styled span, and redirects the click events.</p> | {
"question_id": 4148499,
"question_date": "2010-11-10T19:57:01.050Z",
"question_score": 1030,
"tags": "html|css|checkbox",
"answer_id": 4148544,
"answer_date": "2010-11-10T20:02:27.617Z",
"answer_score": 885
} |
Please answer the following Stack Overflow question:
Title: How do you set the Content-Type header for an HttpClient request?
<p>I'm trying to set the <code>Content-Type</code> header of an <code>HttpClient</code> object as required by an API I am calling.</p>
<p>I tried setting the <code>Content-Type</code> like below:</p>
<pre><code>using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://example.com/");
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json");
// ...
}
</code></pre>
<p>It allows me to add the <code>Accept</code> header but when I try to add <code>Content-Type</code> it throws the following exception:</p>
<blockquote>
<p>Misused header name. Make sure request headers are used with
<code>HttpRequestMessage</code>, response headers with <code>HttpResponseMessage</code>, and
content headers with <code>HttpContent</code> objects.</p>
</blockquote>
<p>How can I set the <code>Content-Type</code> header in a <code>HttpClient</code> request?</p> | <p>The content type is a header of the content, not of the request, which is why this is failing. <a href="https://stackoverflow.com/a/10679234/542251"><code>AddWithoutValidation</code> as suggested by Robert Levy</a> may work, but you can also set the content type when creating the request content itself (note that the code snippet adds <code>application/json</code> in two places-for Accept and Content-Type headers):</p>
<pre><code>HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://example.com/");
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",
Encoding.UTF8,
"application/json");//CONTENT-TYPE header
client.SendAsync(request)
.ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
});
</code></pre> | {
"question_id": 10679214,
"question_date": "2012-05-21T03:29:17.847Z",
"question_score": 1030,
"tags": "c#|asp.net|rest|content-type|dotnet-httpclient",
"answer_id": 10679340,
"answer_date": "2012-05-21T03:54:34.030Z",
"answer_score": 1274
} |
Please answer the following Stack Overflow question:
Title: How to validate phone numbers using regex
<p>I'm trying to put together a comprehensive regex to validate phone numbers. Ideally it would handle international formats, but it must handle US formats, including the following:</p>
<ul>
<li><code>1-234-567-8901</code></li>
<li><code>1-234-567-8901 x1234</code></li>
<li><code>1-234-567-8901 ext1234</code></li>
<li><code>1 (234) 567-8901</code></li>
<li><code>1.234.567.8901</code></li>
<li><code>1/234/567/8901</code></li>
<li><code>12345678901</code></li>
</ul>
<p>I'll answer with my current attempt, but I'm hoping somebody has something better and/or more elegant.</p> | <p>Better option... just strip all non-digit characters on input (except 'x' and leading '+' signs), taking care because of the British tendency to write numbers in the non-standard form <code>+44 (0) ...</code> when asked to use the international prefix (in that specific case, you should discard the <code>(0)</code> entirely).</p>
<p>Then, you end up with values like:</p>
<pre><code> 12345678901
12345678901x1234
345678901x1234
12344678901
12345678901
12345678901
12345678901
+4112345678
+441234567890
</code></pre>
<p>Then when you display, reformat to your hearts content. e.g.</p>
<pre><code> 1 (234) 567-8901
1 (234) 567-8901 x1234
</code></pre> | {
"question_id": 123559,
"question_date": "2008-09-23T20:13:42.937Z",
"question_score": 1030,
"tags": "regex|validation|phone-number",
"answer_id": 123681,
"answer_date": "2008-09-23T20:35:51.260Z",
"answer_score": 541
} |
Please answer the following Stack Overflow question:
Title: How do I unload (reload) a Python module?
<p>I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?</p>
<pre><code>if foo.py has changed:
unimport foo <-- How do I do this?
import foo
myfoo = foo.Foo()
</code></pre> | <p>You can reload a module when it has already been imported by using <a href="https://docs.python.org/3/library/importlib.html#importlib.reload" rel="noreferrer"><code>importlib.reload()</code></a>:</p>
<pre><code>from importlib import reload # Python 3.4+
import foo
while True:
# Do some things.
if is_changed(foo):
foo = reload(foo)
</code></pre>
<p>In Python 2, <a href="https://docs.python.org/2.7/library/functions.html#reload" rel="noreferrer"><code>reload</code></a> was a builtin. In Python 3, it was <a href="https://docs.python.org/3/whatsnew/3.0.html#builtins" rel="noreferrer">moved</a> to the <a href="https://docs.python.org/3/library/imp.html" rel="noreferrer"><code>imp</code></a> module. In 3.4, <code>imp</code> was <a href="https://docs.python.org/3/whatsnew/3.4.html#importlib" rel="noreferrer">deprecated</a> in favor of <a href="https://docs.python.org/3/library/importlib.html" rel="noreferrer"><code>importlib</code></a>. When targeting 3 or later, either reference the appropriate module when calling <code>reload</code> or import it.</p>
<p>I think that this is what you want. Web servers like Django's development server use this so that you can see the effects of your code changes without restarting the server process itself.</p>
<p>To quote from the docs:</p>
<blockquote>
<ul>
<li>Python module’s code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module’s dictionary by reusing the <a href="https://docs.python.org/3/glossary.html#term-loader" rel="noreferrer">loader</a> which originally loaded the module. The <code>init</code> function of extension modules is not called a second time.</li>
<li>As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero.</li>
<li>The names in the module namespace are updated to point to any new or changed objects.</li>
<li>Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.</li>
</ul>
</blockquote>
<p>As you noted in your question, you'll have to reconstruct <code>Foo</code> objects if the <code>Foo</code> class resides in the <code>foo</code> module.</p> | {
"question_id": 437589,
"question_date": "2009-01-13T00:33:36.040Z",
"question_score": 1030,
"tags": "python|module|reload|python-import",
"answer_id": 437591,
"answer_date": "2009-01-13T00:34:40.110Z",
"answer_score": 1055
} |
Please answer the following Stack Overflow question:
Title: How to detect Safari, Chrome, IE, Firefox and Opera browsers?
<p>I have 5 addons/extensions for Firefox, Chrome, Internet Explorer(IE), Opera, and Safari.</p>
<p>How can I correctly recognize the user browser and redirect (once an install button has been clicked) to download the corresponding addon?</p> | <p>Googling for browser reliable detection often results in checking the User agent string. This method is <strong>not</strong> reliable, because it's trivial to spoof this value.<br />
I've written a method to detect browsers by <a href="https://en.wikipedia.org/wiki/Duck_typing" rel="noreferrer">duck-typing</a>.</p>
<p>Only use the browser detection method if it's truly necessary, such as showing browser-specific instructions to install an extension. <strong>Use feature detection when possible.</strong></p>
<p>Demo: <a href="https://jsfiddle.net/6spj1059/" rel="noreferrer">https://jsfiddle.net/6spj1059/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Opera 8.0+
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
var isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+ "[object HTMLElementConstructor]"
var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && window['safari'].pushNotification));
// Internet Explorer 6-11
var isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1 - 79
var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
// Edge (based on chromium) detection
var isEdgeChromium = isChrome && (navigator.userAgent.indexOf("Edg") != -1);
// Blink engine detection
var isBlink = (isChrome || isOpera) && !!window.CSS;
var output = 'Detecting browsers by ducktyping:<hr>';
output += 'isFirefox: ' + isFirefox + '<br>';
output += 'isChrome: ' + isChrome + '<br>';
output += 'isSafari: ' + isSafari + '<br>';
output += 'isOpera: ' + isOpera + '<br>';
output += 'isIE: ' + isIE + '<br>';
output += 'isEdge: ' + isEdge + '<br>';
output += 'isEdgeChromium: ' + isEdgeChromium + '<br>';
output += 'isBlink: ' + isBlink + '<br>';
document.body.innerHTML = output;</code></pre>
</div>
</div>
</p>
<h2>Analysis of reliability</h2>
<p>The <a href="https://stackoverflow.com/revisions/9851769/1">previous method</a> depended on properties of the rendering engine (<a href="https://developer.mozilla.org/En/CSS/Box-sizing#Browser_compatibility" rel="noreferrer"><code>-moz-box-sizing</code></a> and <code>-webkit-transform</code>) to detect the browser. These prefixes will eventually be dropped, so to make detection even more robust, I switched to browser-specific characteristics:</p>
<ul>
<li>Internet Explorer: JScript's <a href="https://msdn.microsoft.com/en-us/library/8ka90k2e(v=vs.94).aspx" rel="noreferrer">Conditional compilation</a> (up until IE9) and <a href="https://msdn.microsoft.com/en-us/library/ie/cc196988%28v=vs.85%29.aspx" rel="noreferrer"><code>document.documentMode</code></a>.</li>
<li>Edge: In Trident and Edge browsers, Microsoft's implementation exposes the <code>StyleMedia</code> constructor. Excluding Trident leaves us with Edge.</li>
<li>Edge (based on chromium): The user agent include the value "Edg/[version]" at the end (ex: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.16 Safari/537.36 <strong>Edg/80.0.361.9</strong>").</li>
<li>Firefox: Firefox's API to install add-ons: <a href="https://developer.mozilla.org/en-US/docs/XPInstall_API_Reference/InstallTrigger_Object" rel="noreferrer"><code>InstallTrigger</code></a></li>
<li>Chrome: The global <code>chrome</code> object, containing several properties including a documented <a href="https://developer.chrome.com/extensions/webstore" rel="noreferrer"><code>chrome.webstore</code></a> object.</li>
<li>Update 3 <code>chrome.webstore</code> is deprecated and undefined in recent versions</li>
<li>Safari: A unique naming pattern in its naming of constructors. This is the least durable method of all listed properties and guess what? In Safari 9.1.3 it was fixed. So we are checking against <code>SafariRemoteNotification</code>, which was introduced after version 7.1, to cover all Safaris from 3.0 and upwards.</li>
<li>Opera: <code>window.opera</code> has existed for years, but <a href="https://dev.opera.com/blog/300-million-users-and-move-to-webkit/" rel="noreferrer">will be dropped</a> when Opera replaces its engine with Blink + V8 (used by Chromium).</li>
<li>Update 1: <a href="http://blogs.opera.com/desktop/2013/05/opera-next-15-0-released/" rel="noreferrer">Opera 15 has been released</a>, its UA string looks like Chrome, but with the addition of "OPR". In this version the <code>chrome</code> object is defined (but <code>chrome.webstore</code> isn't). Since Opera tries hard to clone Chrome, I use user agent sniffing for this purpose.</li>
<li>Update 2: <code>!!window.opr && opr.addons</code> can be used to detect <a href="https://dev.opera.com/extensions/addons.html" rel="noreferrer">Opera 20+</a> (evergreen).</li>
<li>Blink: <code>CSS.supports()</code> <a href="http://caniuse.com/#feat=css-supports-api" rel="noreferrer">was introduced in Blink</a> once Google switched on Chrome 28. It's of course, the same Blink used in Opera.</li>
</ul>
<h2>Successfully tested in:</h2>
<ul>
<li>Firefox 0.8 - 61</li>
<li>Chrome 1.0 - 71</li>
<li>Opera 8.0 - 34</li>
<li>Safari 3.0 - 10</li>
<li>IE 6 - 11</li>
<li>Edge - 20-42</li>
<li>Edge Dev - 80.0.361.9</li>
</ul>
<blockquote>
<p>Updated in November 2016 to include detection of Safari browsers from 9.1.3 and upwards</p>
<p>Updated in August 2018 to update the latest successful tests on chrome, firefox IE and edge.</p>
<p>Updated in January 2019 to fix chrome detection (because of the window.chrome.webstore deprecation) and include the latest successful tests on chrome.</p>
<p>Updated in December 2019 to add Edge based on Chromium detection (based on the @Nimesh comment).</p>
</blockquote> | {
"question_id": 9847580,
"question_date": "2012-03-23T23:06:42Z",
"question_score": 1029,
"tags": "javascript|browser-detection",
"answer_id": 9851769,
"answer_date": "2012-03-24T12:29:44.680Z",
"answer_score": 1965
} |
Please answer the following Stack Overflow question:
Title: Visualizing branch topology in Git
<p>I'm playing with Git in isolation on my own machine, and I find it difficult to maintain a mental model of all my branches and commits. I know I can do a <code>git log</code> to see the commit history from where I am, but is there a way to see the entire branch topography, something like these ASCII maps that seem to be used everywhere for explaining branches?</p>
<pre><code> .-A---M---N---O---P
/ / / / /
I B C D E
\ / / / /
`-------------'
</code></pre>
<p>It just feels like someone coming along and trying to pick up my repository would have difficulty working out exactly what was going on.</p>
<p>I guess I'm influenced by AccuRev's <a href="https://www.microfocus.com/documentation/accurev/72/WebHelp/AccuRev_WUI_Guide/GUID-C21657AA-7CDF-4484-9658-7E28A5BB7A91.html" rel="noreferrer">stream browser</a>...</p> | <p>Use <code>git log --graph</code> or <code>gitk</code>. (Both also accept <code>--all</code>, which will show all the branches instead of just the current one.)</p>
<p>For branch names and a compact view, try:</p>
<pre><code>git log --graph --decorate --oneline
</code></pre> | {
"question_id": 1838873,
"question_date": "2009-12-03T09:55:04.067Z",
"question_score": 1029,
"tags": "git",
"answer_id": 1838881,
"answer_date": "2009-12-03T09:56:27.317Z",
"answer_score": 1251
} |
Please answer the following Stack Overflow question:
Title: How do I animate constraint changes?
<p>I'm updating an old app with an <code>AdBannerView</code> and when there is no ad, it slides off screen. When there is an ad it slides on the screen. Basic stuff.</p>
<p>Old style, I set the frame in an animation block.
New style, I have a <code>IBOutlet</code> to the auto-layout constraint which determines the <code>Y</code> position, in this case it's distance from the bottom of the superview, and modify the constant:</p>
<pre><code>- (void)moveBannerOffScreen {
[UIView animateWithDuration:5 animations:^{
_addBannerDistanceFromBottomConstraint.constant = -32;
}];
bannerIsVisible = FALSE;
}
- (void)moveBannerOnScreen {
[UIView animateWithDuration:5 animations:^{
_addBannerDistanceFromBottomConstraint.constant = 0;
}];
bannerIsVisible = TRUE;
}
</code></pre>
<p>And the banner moves, exactly as expected, but <em>no</em> animation.</p>
<hr />
<p><strong>UPDATE:</strong> I re-watched <a href="https://developer.apple.com/videos/play/wwdc2012/228/" rel="noreferrer">WWDC 12 talk Best Practices for Mastering Auto Layout</a> which covers animation. It discusses how to update constraints using <strong>CoreAnimation</strong>:</p>
<p><img src="https://i.stack.imgur.com/576mp.png" alt="" />
<img src="https://i.stack.imgur.com/lr9mQ.png" alt="" /></p>
<p>I've tried with the following code, but get the exact same results:</p>
<pre><code>- (void)moveBannerOffScreen {
_addBannerDistanceFromBottomConstraint.constant = -32;
[UIView animateWithDuration:2 animations:^{
[self.view setNeedsLayout];
}];
bannerIsVisible = FALSE;
}
- (void)moveBannerOnScreen {
_addBannerDistanceFromBottomConstraint.constant = 0;
[UIView animateWithDuration:2 animations:^{
[self.view setNeedsLayout];
}];
bannerIsVisible = TRUE;
}
</code></pre>
<p>On a side note, I have checked numerous times and this is being executed on the <em>main</em> thread.</p> | <p>Two important notes:</p>
<ol>
<li><p>You need to call <code>layoutIfNeeded</code> within the animation block. Apple actually recommends you call it once before the animation block to ensure that all pending layout operations have been completed </p></li>
<li><p>You need to call it specifically on the <strong>parent view</strong> (e.g. <code>self.view</code>), not the child view that has the constraints attached to it. Doing so will update <em>all</em> constrained views, including animating other views that might be constrained to the view that you changed the constraint of (e.g. View B is attached to the bottom of View A and you just changed View A's top offset and you want View B to animate with it)</p></li>
</ol>
<p>Try this:</p>
<p><strong>Objective-C</strong></p>
<pre><code>- (void)moveBannerOffScreen {
[self.view layoutIfNeeded];
[UIView animateWithDuration:5
animations:^{
self._addBannerDistanceFromBottomConstraint.constant = -32;
[self.view layoutIfNeeded]; // Called on parent view
}];
bannerIsVisible = FALSE;
}
- (void)moveBannerOnScreen {
[self.view layoutIfNeeded];
[UIView animateWithDuration:5
animations:^{
self._addBannerDistanceFromBottomConstraint.constant = 0;
[self.view layoutIfNeeded]; // Called on parent view
}];
bannerIsVisible = TRUE;
}
</code></pre>
<p><strong>Swift 3</strong></p>
<pre><code>UIView.animate(withDuration: 5) {
self._addBannerDistanceFromBottomConstraint.constant = 0
self.view.layoutIfNeeded()
}
</code></pre> | {
"question_id": 12622424,
"question_date": "2012-09-27T13:23:06.300Z",
"question_score": 1029,
"tags": "ios|objective-c|animation|autolayout|ios6",
"answer_id": 12664093,
"answer_date": "2012-09-30T19:00:58.860Z",
"answer_score": 1795
} |
Please answer the following Stack Overflow question:
Title: Can I set subject/content of email using mailto:?
<p>Is it possible to set the subject/content of email when I use mailto:?</p> | <p>Yes, look all tips and tricks with mailto: <a href="http://www.angelfire.com/dc/html-webmaster/mailto.htm" rel="noreferrer">http://www.angelfire.com/dc/html-webmaster/mailto.htm</a></p>
<p>mailto subject example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="mailto:[email protected]?subject=free chocolate">example</a></code></pre>
</div>
</div>
</p>
<p>mailto with content:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="mailto:[email protected]?subject=look at this website&body=Hi,I found this website and thought you might like it http://www.geocities.com/wowhtml/">tell a friend</a></code></pre>
</div>
</div>
</p>
<p>As alluded to in the comments, both <code>subject</code> and <code>body</code> must be escaped properly. Use <code>encodeURIComponent(subject)</code> on each, rather than hand-coding for specific cases.</p>
<p>As <a href="https://stackoverflow.com/users/892018/hoody">Hoody</a> mentioned in the comments, you can add line breaks by adding the following encoded sequence in the string: </p>
<pre><code>%0D%0A // one line break
</code></pre> | {
"question_id": 4782068,
"question_date": "2011-01-24T12:41:08.640Z",
"question_score": 1028,
"tags": "html|email|mailto",
"answer_id": 4782084,
"answer_date": "2011-01-24T12:42:53.457Z",
"answer_score": 1656
} |
Please answer the following Stack Overflow question:
Title: How to create a file in memory for user to download, but not through server?
<p>Is there any way I can create a text file on the client side and prompt the user to download it, without any interaction with the server?
I know I can't write directly to their machine (security and all), but can I create and prompt them to save it?</p> | <p>You can use data URIs. Browser support varies; see <a href="http://en.wikipedia.org/wiki/Data_URI_scheme#Web_browser_support" rel="noreferrer">Wikipedia</a>. Example:</p>
<pre><code><a href="data:application/octet-stream;charset=utf-16le;base64,//5mAG8AbwAgAGIAYQByAAoA">text file</a>
</code></pre>
<p>The octet-stream is to force a download prompt. Otherwise, it will probably open in the browser.</p>
<p>For CSV, you can use:</p>
<pre><code><a href="data:application/octet-stream,field1%2Cfield2%0Afoo%2Cbar%0Agoo%2Cgai%0A">CSV Octet</a>
</code></pre>
<p>Try the <a href="http://jsfiddle.net/VBJ9h/319/" rel="noreferrer">jsFiddle demo</a>.</p> | {
"question_id": 3665115,
"question_date": "2010-09-08T06:24:18.897Z",
"question_score": 1028,
"tags": "javascript|file|web-applications|client-side",
"answer_id": 3665147,
"answer_date": "2010-09-08T06:29:02.893Z",
"answer_score": 468
} |
Please answer the following Stack Overflow question:
Title: What are C++ functors and their uses?
<p>I keep hearing a lot about functors in C++. Can someone give me an overview as to what they are and in what cases they would be useful?</p> | <p>A functor is pretty much just a class which defines the operator(). That lets you create objects which "look like" a function:</p>
<pre><code>// this is a functor
struct add_x {
add_x(int val) : x(val) {} // Constructor
int operator()(int y) const { return x + y; }
private:
int x;
};
// Now you can use it like this:
add_x add42(42); // create an instance of the functor class
int i = add42(8); // and "call" it
assert(i == 50); // and it added 42 to its argument
std::vector<int> in; // assume this contains a bunch of values)
std::vector<int> out(in.size());
// Pass a functor to std::transform, which calls the functor on every element
// in the input sequence, and stores the result to the output sequence
std::transform(in.begin(), in.end(), out.begin(), add_x(1));
assert(out[i] == in[i] + 1); // for all i
</code></pre>
<p>There are a couple of nice things about functors. One is that unlike regular functions, they can contain state. The above example creates a function which adds 42 to whatever you give it. But that value 42 is not hardcoded, it was specified as a constructor argument when we created our functor instance. I could create another adder, which added 27, just by calling the constructor with a different value. This makes them nicely customizable.</p>
<p>As the last lines show, you often pass functors as arguments to other functions such as std::transform or the other standard library algorithms. You could do the same with a regular function pointer except, as I said above, functors can be "customized" because they contain state, making them more flexible (If I wanted to use a function pointer, I'd have to write a function which added exactly 1 to its argument. The functor is general, and adds whatever you initialized it with), and they are also potentially more efficient. In the above example, the compiler knows exactly which function <code>std::transform</code> should call. It should call <code>add_x::operator()</code>. That means it can inline that function call. And that makes it just as efficient as if I had manually called the function on each value of the vector.</p>
<p>If I had passed a function pointer instead, the compiler couldn't immediately see which function it points to, so unless it performs some fairly complex global optimizations, it'd have to dereference the pointer at runtime, and then make the call.</p> | {
"question_id": 356950,
"question_date": "2008-12-10T17:47:21.077Z",
"question_score": 1028,
"tags": "c++|functor|function-object|function-call-operator",
"answer_id": 356993,
"answer_date": "2008-12-10T17:58:35.843Z",
"answer_score": 1174
} |
Please answer the following Stack Overflow question:
Title: What exactly is a Maven Snapshot and why do we need it?
<p>I am a bit confused about the meaning of a Maven Snapshot and why we build one?</p> | <p>A snapshot version in Maven is one that has not been released.</p>
<p>The idea is that <strong>before</strong> a <code>1.0</code> release (or any other release) is done, there exists a <code>1.0-SNAPSHOT</code>. That version is what <em>might become</em> <code>1.0</code>. It's basically "<code>1.0</code> under development". This might be <em>close</em> to a real <code>1.0</code> release, or pretty far (right after the <code>0.9</code> release, for example).</p>
<p>The difference between a "real" version and a snapshot version is that snapshots might get updates. That means that downloading <code>1.0-SNAPSHOT</code> today might give a different file than downloading it yesterday or tomorrow.</p>
<p>Usually, snapshot dependencies should <strong>only</strong> exist during development and no released version (i.e. no non-snapshot) should have a dependency on a snapshot version.</p> | {
"question_id": 5901378,
"question_date": "2011-05-05T16:50:50.297Z",
"question_score": 1028,
"tags": "java|maven|dependency-management",
"answer_id": 5901460,
"answer_date": "2011-05-05T16:57:39.563Z",
"answer_score": 1227
} |
Please answer the following Stack Overflow question:
Title: Git workflow and rebase vs merge questions
<p>I've been using Git now for a couple of months on a project with one other developer. I have several years of experience with <a href="http://en.wikipedia.org/wiki/Apache_Subversion" rel="noreferrer">SVN</a>, so I guess I bring a lot of baggage to the relationship.</p>
<p>I have heard that Git is excellent for branching and merging, and so far, I just don't see it. Sure, branching is dead simple, but when I try to merge, everything goes all to hell. Now, I'm used to that from SVN, but it seems to me that I just traded one sub-par versioning system for another.</p>
<p>My partner tells me that my problems stem from my desire to merge willy-nilly, and that I should be using rebase instead of merge in many situations. For example, here's the workflow that he's laid down:</p>
<pre><code>clone the remote repository
git checkout -b my_new_feature
..work and commit some stuff
git rebase master
..work and commit some stuff
git rebase master
..finish the feature
git checkout master
git merge my_new_feature
</code></pre>
<p>Essentially, create a feature branch, ALWAYS rebase from master to the branch, and merge from the branch back to master. Important to note is that the branch always stays local.</p>
<p>Here is the workflow that I started with</p>
<pre><code>clone remote repository
create my_new_feature branch on remote repository
git checkout -b --track my_new_feature origin/my_new_feature
..work, commit, push to origin/my_new_feature
git merge master (to get some changes that my partner added)
..work, commit, push to origin/my_new_feature
git merge master
..finish my_new_feature, push to origin/my_new_feature
git checkout master
git merge my_new_feature
delete remote branch
delete local branch
</code></pre>
<p>There are two essential differences (I think): I use merge always instead of rebasing, and I push my feature branch (and my feature branch commits) to the remote repository.</p>
<p>My reasoning for the remote branch is that I want my work backed up as I'm working. Our repository is automatically backed up and can be restored if something goes wrong. My laptop is not, or not as thoroughly. Therefore, I hate to have code on my laptop that's not mirrored somewhere else.</p>
<p>My reasoning for the merge instead of rebase is that merge seems to be standard and rebase seems to be an advanced feature. My gut feeling is that what I'm trying to do is not an advanced setup, so rebase should be unnecessary. I've even perused the new Pragmatic Programming book on Git, and they cover merge extensively and barely mention rebase.</p>
<p>Anyway, I was following my workflow on a recent branch, and when I tried to merge it back to master, it all went to hell. There were tons of conflicts with things that should have not mattered. The conflicts just made no sense to me. It took me a day to sort everything out, and eventually culminated in a forced push to the remote master, since my local master has all conflicts resolved, but the remote one still wasn't happy.</p>
<p>What is the "correct" workflow for something like this? Git is supposed to make branching and merging super-easy, and I'm just not seeing it.</p>
<p><strong>Update 2011-04-15</strong></p>
<p>This seems to be a very popular question, so I thought I'd update with my two years experience since I first asked.</p>
<p>It turns out that the original workflow is correct, at least in our case. In other words, this is what we do and it works:</p>
<pre><code>clone the remote repository
git checkout -b my_new_feature
..work and commit some stuff
git rebase master
..work and commit some stuff
git rebase master
..finish the feature, commit
git rebase master
git checkout master
git merge my_new_feature
</code></pre>
<p>In fact, our workflow is a little different, as we tend to do <em>squash merges</em> instead of raw merges. (<strong>Note: This is controversial, see below.</strong>) This allows us to turn our entire feature branch into a single commit on master. Then we delete our feature branch. This allows us to logically structure our commits on master, even if they're a little messy on our branches. So, this is what we do:</p>
<pre><code>clone the remote repository
git checkout -b my_new_feature
..work and commit some stuff
git rebase master
..work and commit some stuff
git rebase master
..finish the feature, commit
git rebase master
git checkout master
git merge --squash my_new_feature
git commit -m "added my_new_feature"
git branch -D my_new_feature
</code></pre>
<p><strong>Squash Merge Controversy</strong> - As several commenters have pointed out, the squash merge will throw away all history on your feature branch. As the name implies, it squashes all the commits down into a single one. For small features, this makes sense as it condenses it down into a single package. For larger features, it's probably not a great idea, especially if your individual commits are already atomic. It really comes down to personal preference.</p>
<p><strong>Github and Bitbucket (others?) Pull Requests</strong> - In case you're wondering how merge/rebase relates to Pull Requests, I recommend following all the above steps up until you're ready to merge back to master. Instead of manually merging with git, you just accept the PR. Note that this will not do a squash merge (at least not by default), but non-squash, non-fast-forward is the accepted merge convention in the Pull Request community (as far as I know). Specifically, it works like this:</p>
<pre><code>clone the remote repository
git checkout -b my_new_feature
..work and commit some stuff
git rebase master
..work and commit some stuff
git rebase master
..finish the feature, commit
git rebase master
git push # May need to force push
...submit PR, wait for a review, make any changes requested for the PR
git rebase master
git push # Will probably need to force push (-f), due to previous rebases from master
...accept the PR, most likely also deleting the feature branch in the process
git checkout master
git branch -d my_new_feature
git remote prune origin
</code></pre>
<p>I've come to love Git and never want to go back to SVN. If you're struggling, just stick with it and eventually you'll see the light at the end of the tunnel.</p> | <p>"Conflicts" mean "parallel evolutions of a same content". So if it goes "all to hell" during a merge, it means you have massive evolutions on the same set of files.</p>
<p>The reason why a rebase is then better than a merge is that:</p>
<ul>
<li>you rewrite your local commit history with the one of the master (and then reapply your work, resolving any conflict then)</li>
<li>the final merge will certainly be a "fast forward" one, because it will have all the commit history of the master, plus only your changes to reapply.</li>
</ul>
<p>I confirm that the correct workflow in that case (evolutions on common set of files) is <strong>rebase first, then merge</strong>.</p>
<p>However, that means that, if you push your local branch (for backup reason), that branch should not be pulled (or at least used) by anyone else (since the commit history will be rewritten by the successive rebase).</p>
<hr>
<p>On that topic (rebase then merge workflow), <a href="https://stackoverflow.com/users/207119/barraponto">barraponto</a> mentions in the comments two interesting posts, both from <a href="https://www.randyfay.com/" rel="noreferrer">randyfay.com</a>:</p>
<ul>
<li><a href="https://randyfay.com/content/rebase-workflow-git" rel="noreferrer"><strong>A Rebase Workflow for Git</strong></a>: reminds us to fetch first, rebase:</li>
</ul>
<blockquote>
<p>Using this technique, your work always goes on top of the public branch like a patch that is up-to-date with current <code>HEAD</code>. </p>
</blockquote>
<p>(a similar technique <a href="http://fourkitchens.com/blog/2009/04/20/alternatives-rebasing-bazaar" rel="noreferrer">exists for bazaar</a>)</p>
<ul>
<li><a href="https://randyfay.com/content/avoiding-git-disasters-gory-story" rel="noreferrer"><strong>Avoiding Git Disasters: A Gory Story</strong></a>: about the dangers of <code>git push --force</code> (instead of a <code>git pull --rebase</code> for instance)</li>
</ul> | {
"question_id": 457927,
"question_date": "2009-01-19T15:16:52.623Z",
"question_score": 1028,
"tags": "git|version-control|git-merge|git-rebase",
"answer_id": 457988,
"answer_date": "2009-01-19T15:32:24.947Z",
"answer_score": 386
} |
Please answer the following Stack Overflow question:
Title: Can't start Eclipse - Java was started but returned exit code=13
<p>I am trying to get my first taste of Android development using Eclipse. I ran into this problem when trying to run Eclipse, having installed version 4.2 only minutes ago.</p>
<p>After first trying to start <code>Eclipse</code> without any parameters to specify the Java VM, I got an error message saying it <code>couldn't find a Java VM called javaw.exe inside the Eclipse folder</code>, so I found where Java was installed and specified that location as the parameter in the shortcut's target. Now I get a different error, <code>Java was started but returned exit code=13</code>.</p>
<p>Similar questions seem to indicate that it's a 32-bit/64-bit conflict, but I'm 99% positive that I downloaded 64-bit versions of both Eclipse and <code>Java (RE 7u5)</code>, which I chose because I have 64-bit Windows 7. </p>
<ul>
<li>If anyone knows how to confirm that my Eclipse and Java are 64-bit,
that'd be appreciated.</li>
<li>If you think my problem is a different one, please help!</li>
<li>Please speak as plainly as you can, as I am totally new to Eclipse
and Java.</li>
</ul>
<blockquote>
<p>Shortcut Target: "C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\eclipse.exe" -vm "C:\Program Files (x86)\Java\jre7\bin\javaw.exe"</p>
</blockquote>
<p><strong>Full error code...:</strong></p>
<pre><code>Java was started but returned exit code=13
C:\Program Files (x86)\Java\jre7\bin\javaw.exe
-Xms40m
-Xmx512m
-XX:MaxPermSize=256m
-jar C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher_1.30v20120522-1813.jar
-os win32
-ws win32
-arch x86_64
-showsplash C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\\plugins\org.eclipse.platform_4.2.0.v201206081400\splash.bmp
-launcher C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\eclipse.exe
-name Eclipse
--launcher.library C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v201205221813\eclipse_1503.dll
-startup C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher_1.30v20120522-1813.jar
--launcher.overrideVmargs
-exitdata 1e30_5c
-vm C:\Program Files (x86)\Java\jre7\bin\javaw.exe
-vmargs
-Xms40m
-Xmx512m
-XX:MaxPermSize=256m
-jar C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher_1.30v20120522-1813.jar
</code></pre> | <p>There are working combinations of OS, JDK and Eclipse bitness. In my case, I was using a 64-bit JDK with a 32-bit Eclipse on a 64-bit OS. After downgrading the JDK to 32-bit, Eclipse started working.</p>
<p><strong>Use one of the following combinations.</strong></p>
<ul>
<li>32-bit OS, 32-bit JDK, 32-bit Eclipse (32-bit only)</li>
<li>64-bit OS, 32-bit JDK, 32-bit Eclipse</li>
<li>64-bit OS, 64-bit JDK, 64-bit Eclipse (64-bit only)</li>
</ul> | {
"question_id": 11461607,
"question_date": "2012-07-12T22:23:31.640Z",
"question_score": 1027,
"tags": "java|android|windows|eclipse|32bit-64bit",
"answer_id": 41441870,
"answer_date": "2017-01-03T10:54:34.317Z",
"answer_score": 226
} |
Please answer the following Stack Overflow question:
Title: In Bash, how can I check if a string begins with some value?
<p>I would like to check if a string begins with "node" e.g. "node001". Something like</p>
<pre><code>if [ $HOST == user* ]
then
echo yes
fi
</code></pre>
<p>How can I do it correctly?</p>
<hr>
<p>I further need to combine expressions to check if HOST is either "user1" or begins with "node"</p>
<pre><code>if [ [[ $HOST == user1 ]] -o [[ $HOST == node* ]] ];
then
echo yes
fi
> > > -bash: [: too many arguments
</code></pre>
<p>How can I do it correctly?</p> | <p>This snippet on the <a href="http://tldp.org/LDP/abs/html/comparison-ops.html" rel="noreferrer">Advanced Bash Scripting Guide</a> says:</p>
<pre><code># The == comparison operator behaves differently within a double-brackets
# test than within single brackets.
[[ $a == z* ]] # True if $a starts with a "z" (wildcard matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).
</code></pre>
<p>So you had it <em>nearly</em> correct; you needed <em>double</em> brackets, not single brackets.</p>
<hr>
<p>With regards to your second question, you can write it this way:</p>
<pre><code>HOST=user1
if [[ $HOST == user1 ]] || [[ $HOST == node* ]] ;
then
echo yes1
fi
HOST=node001
if [[ $HOST == user1 ]] || [[ $HOST == node* ]] ;
then
echo yes2
fi
</code></pre>
<p>Which will echo</p>
<pre><code>yes1
yes2
</code></pre>
<p>Bash's <code>if</code> syntax is hard to get used to (IMO).</p> | {
"question_id": 2172352,
"question_date": "2010-01-31T16:12:46.883Z",
"question_score": 1027,
"tags": "string|bash|comparison",
"answer_id": 2172367,
"answer_date": "2010-01-31T16:16:02.740Z",
"answer_score": 1424
} |
Please answer the following Stack Overflow question:
Title: What is tail call optimization?
<p>Very simply, what is tail-call optimization?</p>
<p>More specifically, what are some small code snippets where it could be applied, and where not, with an explanation of why?</p> | <p>Tail-call optimization is where you are able to avoid allocating a new stack frame for a function because the calling function will simply return the value that it gets from the called function. The most common use is tail-recursion, where a recursive function written to take advantage of tail-call optimization can use constant stack space.</p>
<p>Scheme is one of the few programming languages that guarantee in the spec that any implementation must provide this optimization, so here are two examples of the factorial function in Scheme:</p>
<pre class="lang-lisp prettyprint-override"><code>(define (fact x)
(if (= x 0) 1
(* x (fact (- x 1)))))
(define (fact x)
(define (fact-tail x accum)
(if (= x 0) accum
(fact-tail (- x 1) (* x accum))))
(fact-tail x 1))
</code></pre>
<p>The first function is not tail recursive because when the recursive call is made, the function needs to keep track of the multiplication it needs to do with the result after the call returns. As such, the stack looks as follows:</p>
<pre class="lang-scheme prettyprint-override"><code>(fact 3)
(* 3 (fact 2))
(* 3 (* 2 (fact 1)))
(* 3 (* 2 (* 1 (fact 0))))
(* 3 (* 2 (* 1 1)))
(* 3 (* 2 1))
(* 3 2)
6
</code></pre>
<p>In contrast, the stack trace for the tail recursive factorial looks as follows:</p>
<pre class="lang-scheme prettyprint-override"><code>(fact 3)
(fact-tail 3 1)
(fact-tail 2 3)
(fact-tail 1 6)
(fact-tail 0 6)
6
</code></pre>
<p>As you can see, we only need to keep track of the same amount of data for every call to fact-tail because we are simply returning the value we get right through to the top. This means that even if I were to call (fact 1000000), I need only the same amount of space as (fact 3). This is not the case with the non-tail-recursive fact, and as such large values may cause a stack overflow.</p> | {
"question_id": 310974,
"question_date": "2008-11-22T06:56:32.053Z",
"question_score": 1027,
"tags": "algorithm|recursion|language-agnostic|tail-recursion|tail-call-optimization",
"answer_id": 310980,
"answer_date": "2008-11-22T07:07:50.910Z",
"answer_score": 898
} |
Please answer the following Stack Overflow question:
Title: How to find event listeners on a DOM node in JavaScript or in debugging?
<p>I have a page where some event listeners are attached to input boxes and select boxes. Is there a way to find out which event listeners are observing a particular DOM node and for what event?</p>
<p>Events are attached using:</p>
<ol>
<li><a href="http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework" rel="noreferrer">Prototype's</a> <code>Event.observe</code>;</li>
<li>DOM's <code>addEventListener</code>;</li>
<li>As element attribute <code>element.onclick</code>.</li>
</ol> | <p>If you just need to inspect what's happening on a page, you might try the <a href="http://www.sprymedia.co.uk/article/Visual+Event" rel="noreferrer">Visual Event</a> bookmarklet.</p>
<p><strong>Update</strong>: <a href="http://www.sprymedia.co.uk/article/Visual+Event+2" rel="noreferrer">Visual Event 2</a> available.</p> | {
"question_id": 446892,
"question_date": "2009-01-15T14:19:44.420Z",
"question_score": 1026,
"tags": "javascript|events|dom",
"answer_id": 3426352,
"answer_date": "2010-08-06T17:48:47.433Z",
"answer_score": 536
} |
Please answer the following Stack Overflow question:
Title: No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
<p>I'm trying to fetch some data from the REST API of HP Alm. It works pretty well with a small curl script—I get my data.</p>
<p>Now doing that with JavaScript, fetch and ES6 (more or less) seems to be a bigger issue. I keep getting this error message:</p>
<blockquote>
<p>Fetch API cannot load . Response to preflight request doesn't
pass access control check: No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin 'http://127.0.0.1:3000' is
therefore not allowed access. The response had HTTP status code 501.
If an opaque response serves your needs, set the request's mode to
'no-cors' to fetch the resource with CORS disabled.</p>
</blockquote>
<p>I understand that this is because I am trying to fetch that data from within my localhost and the solution should be using <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" rel="noreferrer">Cross-Origin Resource Sharing (CORS)</a>. I thought I actually did that, but somehow it either ignores what I write in the header or the problem is something else.</p>
<p>So, is there an implementation issue? Am I doing it wrong? I can't check the server logs unfortunately. I'm really a bit stuck here.</p>
<pre><code>function performSignIn() {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
headers.append('Access-Control-Allow-Credentials', 'true');
headers.append('GET', 'POST', 'OPTIONS');
headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));
fetch(sign_in, {
//mode: 'no-cors',
credentials: 'include',
method: 'POST',
headers: headers
})
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log('Authorization failed : ' + error.message));
}
</code></pre>
<p>I am using Chrome. I also tried using that Chrome CORS Plugin, but then I am getting another error message:</p>
<blockquote>
<p>The value of the 'Access-Control-Allow-Origin' header in the response
must not be the wildcard '*' when the request's credentials mode is
'include'. Origin 'http://127.0.0.1:3000' is therefore not allowed
access. The credentials mode of requests initiated by the
XMLHttpRequest is controlled by the withCredentials attribute.</p>
</blockquote> | <p>This answer covers a lot of ground, so it’s divided into three parts:</p>
<ul>
<li>How to use a CORS proxy to avoid <em>“No Access-Control-Allow-Origin header”</em> problems</li>
<li>How to avoid the CORS preflight</li>
<li>How to fix <em>“Access-Control-Allow-Origin header must not be the wildcard”</em> problems</li>
</ul>
<hr />
<p><strong>How to use a CORS proxy to avoid <em>“No Access-Control-Allow-Origin header”</em> problems</strong></p>
<p>If you don’t control the server your frontend code is sending a request to, and the problem with the response from that server is just the lack of the necessary <code>Access-Control-Allow-Origin</code> header, you can still get things to work—by making the request through a CORS proxy.</p>
<p>You can easily run your own proxy with code from <a href="https://github.com/Rob--W/cors-anywhere/" rel="noreferrer">https://github.com/Rob--W/cors-anywhere/</a>.<br>
You can also easily deploy your own proxy to Heroku in just 2-3 minutes, with 5 commands:</p>
<pre><code>git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master
</code></pre>
<p>After running those commands, you’ll end up with your own CORS Anywhere server running at, e.g., <code>https://cryptic-headland-94862.herokuapp.com/</code>.</p>
<p>Now, prefix your request URL with the URL for your proxy:</p>
<pre><code>https://cryptic-headland-94862.herokuapp.com/https://example.com
</code></pre>
<p>Adding the proxy URL as a prefix causes the request to get made through your proxy, which:</p>
<ol>
<li>Forwards the request to <code>https://example.com</code>.</li>
<li>Receives the response from <code>https://example.com</code>.</li>
<li>Adds the <code>Access-Control-Allow-Origin</code> header to the response.</li>
<li>Passes that response, with that added header, back to the requesting frontend code.</li>
</ol>
<p>The browser then allows the frontend code to access the response, because that response with the <code>Access-Control-Allow-Origin</code> response header is what the browser sees.</p>
<p>This works even if the request is one that triggers browsers to do a CORS preflight <code>OPTIONS</code> request, because in that case, the proxy also sends the <code>Access-Control-Allow-Headers</code> and <code>Access-Control-Allow-Methods</code> headers needed to make the preflight succeed.</p>
<hr />
<p><strong>How to avoid the CORS preflight</strong></p>
<p>The code in the question triggers a CORS preflight—since it sends an <code>Authorization</code> header.</p>
<p><a href="https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Preflighted_requests" rel="noreferrer">https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Preflighted_requests</a></p>
<p>Even without that, the <code>Content-Type: application/json</code> header will also trigger a preflight.</p>
<p>What “preflight” means: before the browser tries the <code>POST</code> in the code in the question, it first sends an <code>OPTIONS</code> request to the server, to determine if the server is opting-in to receiving a cross-origin <code>POST</code> that has <code>Authorization</code> and <code>Content-Type: application/json</code> headers.</p>
<blockquote>
<p>It works pretty well with a small curl script - I get my data.</p>
</blockquote>
<p>To properly test with <code>curl</code>, you must emulate the preflight <code>OPTIONS</code> the browser sends:</p>
<pre><code>curl -i -X OPTIONS -H "Origin: http://127.0.0.1:3000" \
-H 'Access-Control-Request-Method: POST' \
-H 'Access-Control-Request-Headers: Content-Type, Authorization' \
"https://the.sign_in.url"
</code></pre>
<p>…with <code>https://the.sign_in.url</code> replaced by whatever your actual <code>sign_in</code> URL is.</p>
<p>The response the browser needs from that <code>OPTIONS</code> request must have headers like this:</p>
<pre class="lang-none prettyprint-override"><code>Access-Control-Allow-Origin: http://127.0.0.1:3000
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Content-Type, Authorization
</code></pre>
<p>If the <code>OPTIONS</code> response doesn’t include those headers, the browser will stop right there and never attempt to send the <code>POST</code> request. Also, the HTTP status code for the response must be a 2xx—typically 200 or 204. If it’s any other status code, the browser will stop right there.</p>
<p>The server in the question responds to the <code>OPTIONS</code> request with a 501 status code, which apparently means it’s trying to indicate it doesn’t implement support for <code>OPTIONS</code> requests. Other servers typically respond with a 405 “Method not allowed” status code in this case.</p>
<p>So you’ll never be able to make <code>POST</code> requests directly to that server from your frontend JavaScript code if the server responds to that <code>OPTIONS</code> request with a 405 or 501 or anything other than a 200 or 204 or if doesn’t respond with those necessary response headers.</p>
<p>The way to avoid triggering a preflight for the case in the question would be:</p>
<ul>
<li>if the server didn’t require an <code>Authorization</code> request header but instead, e.g., relied on authentication data embedded in the body of the <code>POST</code> request or as a query param</li>
<li>if the server didn’t require the <code>POST</code> body to have a <code>Content-Type: application/json</code> media type but instead accepted the <code>POST</code> body as <code>application/x-www-form-urlencoded</code> with a parameter named <code>json</code> (or whatever) whose value is the JSON data</li>
</ul>
<hr />
<p><strong>How to fix <em>“Access-Control-Allow-Origin header must not be the wildcard”</em> problems</strong></p>
<blockquote>
<p><sub>I am getting another error message:</sub></p>
<p><sub>The value of the 'Access-Control-Allow-Origin' header in the response</sub>
<sub>must not be the wildcard '*' when the request's credentials mode is</sub>
<sub>'include'. Origin '<code>http://127.0.0.1:3000</code>' is therefore not allowed</sub>
<sub>access. The credentials mode of requests initiated by the</sub>
<sub>XMLHttpRequest is controlled by the withCredentials attribute.</sub></p>
</blockquote>
<p>For requests that have credentials, browsers won’t let your frontend JavaScript code access the response if the value of the <code>Access-Control-Allow-Origin</code> header is <code>*</code>. Instead the value in that case must exactly match your frontend code’s origin, <code>http://127.0.0.1:3000</code>.</p>
<p>See <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Credentialed_requests_and_wildcards" rel="noreferrer"><em>Credentialed requests and wildcards</em></a> in the MDN HTTP access control (CORS) article.</p>
<p>If you control the server you’re sending the request to, a common way to deal with this case is to configure the server to take the value of the <code>Origin</code> request header, and echo/reflect that back into the value of the <code>Access-Control-Allow-Origin</code> response header; e.g., with nginx:</p>
<pre class="lang-none prettyprint-override"><code>add_header Access-Control-Allow-Origin $http_origin
</code></pre>
<p>But that’s just an example; other (web) server systems have similar ways to echo origin values.</p>
<hr />
<blockquote>
<p>I am using Chrome. I also tried using that Chrome CORS Plugin</p>
</blockquote>
<p>That Chrome CORS plugin apparently just simplemindedly injects an <code>Access-Control-Allow-Origin: *</code> header into the response the browser sees. If the plugin were smarter, what it would be doing is setting the value of that fake <code>Access-Control-Allow-Origin</code> response header to the actual origin of your frontend JavaScript code, <code>http://127.0.0.1:3000</code>.</p>
<p>So avoid using that plugin, even for testing. It’s just a distraction. To test what responses you get from the server with no browser filtering them, you’re better off using <code>curl -H</code> as above.</p>
<hr />
<p>As far as the frontend JavaScript code for the <code>fetch(…)</code> request in the question:</p>
<pre><code>headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
headers.append('Access-Control-Allow-Credentials', 'true');
</code></pre>
<p>Remove those lines. The <code>Access-Control-Allow-*</code> headers are <em>response</em> headers. You never want to send them in requests. The only effect of that is to trigger a browser to do a preflight.</p> | {
"question_id": 43871637,
"question_date": "2017-05-09T13:47:47.647Z",
"question_score": 1025,
"tags": "javascript|cors|fetch-api",
"answer_id": 43881141,
"answer_date": "2017-05-09T23:03:53.547Z",
"answer_score": 1545
} |
Please answer the following Stack Overflow question:
Title: Shell command to sum integers, one per line?
<p>I am looking for a command that will accept (as input) multiple lines of text, each line containing a single integer, and output the sum of these integers.</p>
<p>As a bit of background, I have a log file which includes timing measurements. Through grepping for the relevant lines and a bit of <code>sed</code> reformatting I can list all of the timings in that file. I would like to work out the total. I can pipe this intermediate output to any command in order to do the final sum. I have always used <code>expr</code> in the past, but unless it runs in RPN mode I do not think it is going to cope with this (and even then it would be tricky).</p>
<p>How can I get the summation of integers?</p> | <p>Bit of awk should do it? </p>
<pre><code>awk '{s+=$1} END {print s}' mydatafile
</code></pre>
<p>Note: some versions of awk have some odd behaviours if you are going to be adding anything exceeding 2^31 (2147483647). See comments for more background. One suggestion is to use <code>printf</code> rather than <code>print</code>:</p>
<pre><code>awk '{s+=$1} END {printf "%.0f", s}' mydatafile
</code></pre> | {
"question_id": 450799,
"question_date": "2009-01-16T15:42:03.500Z",
"question_score": 1025,
"tags": "shell",
"answer_id": 450821,
"answer_date": "2009-01-16T15:46:00.763Z",
"answer_score": 1543
} |
Please answer the following Stack Overflow question:
Title: How to check a not-defined variable in JavaScript
<p>I wanted to check whether the variable is defined or not. For example, the following throws a not-defined error </p>
<pre><code>alert( x );
</code></pre>
<p>How can I catch this error?</p> | <p>In JavaScript, <code>null</code> is an object. There's another value for things that don't exist, <code>undefined</code>. The DOM returns <code>null</code> for almost all cases where it fails to find some structure in the document, but in JavaScript itself <code>undefined</code> is the value used.</p>
<p>Second, no, there is not a direct equivalent. If you really want to check for specifically for <code>null</code>, do:</p>
<pre><code>if (yourvar === null) // Does not execute if yourvar is `undefined`
</code></pre>
<p>If you want to check if a variable exists, that can only be done with <code>try</code>/<code>catch</code>, since <code>typeof</code> will treat an undeclared variable and a variable declared with the value of <code>undefined</code> as equivalent.</p>
<p>But, to check if a variable is declared <em>and</em> is not <code>undefined</code>:</p>
<pre><code>if (yourvar !== undefined) // Any scope
</code></pre>
<p>Previously, it was necessary to use the <code>typeof</code> operator to check for undefined safely, because it was possible to reassign <code>undefined</code> just like a variable. The old way looked like this:</p>
<pre><code>if (typeof yourvar !== 'undefined') // Any scope
</code></pre>
<p>The issue of <code>undefined</code> being re-assignable was fixed in ECMAScript 5, which was released in 2009. You can now safely use <code>===</code> and <code>!==</code> to test for <code>undefined</code> without using <code>typeof</code> as <code>undefined</code> has been read-only for some time.</p>
<p>If you want to know if a member exists independent but don't care what its value is:</p>
<pre><code>if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance
</code></pre>
<p>If you want to to know whether a variable is <a href="https://developer.mozilla.org/en-US/docs/Glossary/Truthy" rel="noreferrer">truthy</a>:</p>
<pre><code>if (yourvar)
</code></pre>
<p><a href="http://lists.evolt.org/archive/Week-of-Mon-20050214/099714.html" rel="noreferrer">Source</a></p> | {
"question_id": 858181,
"question_date": "2009-05-13T14:09:45.407Z",
"question_score": 1024,
"tags": "javascript|variables|undefined",
"answer_id": 858193,
"answer_date": "2009-05-13T14:11:30.320Z",
"answer_score": 1820
} |
Please answer the following Stack Overflow question:
Title: How can I find the time complexity of an algorithm?
<p>I have gone through <a href="https://www.google.co.in/search?aq=f&sugexp=chrome,mod=19&sourceid=chrome&ie=UTF-8&q=How%20to%20find%20time%20complexity%20of%20an%20algorithm" rel="noreferrer">Google</a> and <a href="https://stackoverflow.com/search?q=how%20to%20calculate%20time%20complexity%20of%20an%20algorithm">Stack Overflow</a> search, but nowhere I was able to find a clear and straightforward explanation for how to calculate time complexity.</p>
<h3>What do I know already?</h3>
<p>Say for code as simple as the one below:</p>
<pre class="lang-cs prettyprint-override"><code>char h = 'y'; // This will be executed 1 time
int abc = 0; // This will be executed 1 time
</code></pre>
<p>Say for a loop like the one below:</p>
<pre class="lang-cs prettyprint-override"><code>for (int i = 0; i < N; i++) {
Console.Write('Hello, World!!');
}
</code></pre>
<ul>
<li><code>int i=0;</code> This will be executed only <strong>once</strong>.</li>
</ul>
<p>The time is actually calculated to <code>i=0</code> and not the declaration.</p>
<ul>
<li><code>i < N;</code> This will be executed <strong>N+1</strong> times</li>
<li><code>i++</code> This will be executed <strong>N</strong> times</li>
</ul>
<p>So the number of operations required by this loop are <strong>{1+(N+1)+N} = 2N+2</strong>. (But this still may be wrong, as I am not confident about my understanding.)</p>
<p>OK, so these small basic calculations I think I know, but in most cases I have seen the time complexity as <strong>O(N), O(n^2), O(log n), O(n!)</strong>, and <a href="http://en.wikipedia.org/wiki/Time_complexity" rel="noreferrer">many others</a>.</p> | <blockquote>
<p>How to find time complexity of an algorithm</p>
</blockquote>
<p>You add up how many machine instructions it will execute as a function of the size of its input, and then simplify the expression to the largest (when N is very large) term and can include any simplifying constant factor.</p>
<p>For example, lets see how we simplify <code>2N + 2</code> machine instructions to describe this as just <code>O(N)</code>.</p>
<p><strong>Why do we remove the two <code>2</code>s ?</strong></p>
<p>We are interested in the performance of the algorithm as N becomes large.</p>
<p>Consider the two terms 2N and 2. </p>
<p>What is the relative influence of these two terms as N becomes large? Suppose N is a million.</p>
<p>Then the first term is 2 million and the second term is only 2.</p>
<p>For this reason, we drop all but the largest terms for large N.</p>
<p>So, now we have gone from <code>2N + 2</code> to <code>2N</code>.</p>
<p>Traditionally, we are only interested in performance <em>up to constant factors</em>. </p>
<p>This means that we don't really care if there is some constant multiple of difference in performance when N is large. The unit of 2N is not well-defined in the first place anyway. So we can multiply or divide by a constant factor to get to the simplest expression.</p>
<p>So <code>2N</code> becomes just <code>N</code>.</p> | {
"question_id": 11032015,
"question_date": "2012-06-14T11:21:15.163Z",
"question_score": 1024,
"tags": "algorithm|time-complexity|complexity-theory",
"answer_id": 11032063,
"answer_date": "2012-06-14T11:25:12.177Z",
"answer_score": 460
} |
Please answer the following Stack Overflow question:
Title: Using HTML5/Canvas/JavaScript to take in-browser screenshots
<p>Google's "Report a Bug" or "Feedback Tool" lets you select an area of your browser window to create a screenshot that is submitted with your feedback about a bug.</p>
<p><img src="https://i.stack.imgur.com/CDhEi.png" alt="Google Feedback Tool Screenshot" />
<sub><em>Screenshot by Jason Small, posted in a <a href="https://stackoverflow.com/questions/6608327/google-style-send-feedback">duplicate question</a>.</em> </sub></p>
<p>How are they doing this? Google's JavaScript feedback API is loaded from <a href="https://ssl.gstatic.com/feedback/api.js" rel="noreferrer">here</a> and <a href="http://www.google.com/tools/feedback/intl/en/learnmore.html" rel="noreferrer">their overview of the feedback module</a> will demonstrate the screenshot capability.</p> | <p>JavaScript can read the DOM and render a fairly accurate representation of that using <code>canvas</code>. I have been working on a script which converts HTML into a canvas image. Decided today to make an implementation of it into sending feedbacks like you described.</p>
<p>The script allows you to create feedback forms which include a screenshot, created on the client's browser, along with the form. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.</p>
<p>It <strong>does not require any rendering from the server</strong>, as the whole image is created on the client's browser. The HTML2Canvas script itself is still in a very experimental state, as it does not parse nearly as much of the CSS3 attributes I would want it to, nor does it have any support to load CORS images even if a proxy was available.</p>
<p>Still quite limited browser compatibility (not because more couldn't be supported, just haven't had time to make it more cross browser supported).</p>
<p>For more information, have a look at the examples here:</p>
<p><a href="http://hertzen.com/experiments/jsfeedback/" rel="noreferrer">http://hertzen.com/experiments/jsfeedback/</a></p>
<p><strong>edit</strong>
The html2canvas script is now available separately <a href="https://github.com/niklasvh/html2canvas" rel="noreferrer">here</a> and some <a href="http://html2canvas.hertzen.com/" rel="noreferrer">examples here</a>.</p>
<p><strong>edit 2</strong>
Another confirmation that Google uses a very similar method (in fact, based on the documentation, the only major difference is their async method of traversing/drawing) can be found in this presentation by Elliott Sprehn from the Google Feedback team:
<a href="http://www.elliottsprehn.com/preso/fluentconf/" rel="noreferrer">http://www.elliottsprehn.com/preso/fluentconf/</a></p> | {
"question_id": 4912092,
"question_date": "2011-02-06T06:58:53.113Z",
"question_score": 1024,
"tags": "javascript|html|canvas|screenshot|html2canvas",
"answer_id": 6678156,
"answer_date": "2011-07-13T11:29:53.443Z",
"answer_score": 1247
} |
Please answer the following Stack Overflow question:
Title: How can I do 'insert if not exists' in MySQL?
<p>I started by googling and found the article <em><a href="http://www.xaprb.com/blog/2005/09/25/insert-if-not-exists-queries-in-mysql/" rel="noreferrer">How to write INSERT if NOT EXISTS queries in standard SQL</a></em> which talks about mutex tables.</p>
<p>I have a table with ~14 million records. If I want to add more data in the same format, is there a way to ensure the record I want to insert does not already exist without using a pair of queries (i.e., one query to check and one to insert is the result set is empty)?</p>
<p>Does a <code>unique</code> constraint on a field guarantee the <code>insert</code> will fail if it's already there?</p>
<p>It seems that with <em>merely</em> a constraint, when I issue the insert via PHP, the script croaks.</p> | <p>Use <code>INSERT IGNORE INTO table</code>.</p>
<p>There's also <code>INSERT … ON DUPLICATE KEY UPDATE</code> syntax, and you can find explanations in <em><a href="https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html" rel="noreferrer">13.2.6.2 INSERT ... ON DUPLICATE KEY UPDATE Statement</a></em>.</p>
<hr />
<p><strong>Post from <a href="http://ee%20http://bogdan.org.ua/2007/10/18/mysql-insert-if-not-exists-syntax.html" rel="noreferrer">bogdan.org.ua</a> according to <a href="http://webcache.googleusercontent.com/search?q=cache:bogdan.org.ua/2007/10/18/mysql-insert-if-not-exists-syntax.html" rel="noreferrer">Google's webcache</a>:</strong></p>
<blockquote>
<p>18th October 2007</p>
<p>To start: as of the latest MySQL, syntax presented in the title is not
possible. But there are several very easy ways to accomplish what is
expected using existing functionality.</p>
<p>There are 3 possible solutions: using INSERT IGNORE, REPLACE, or
INSERT … ON DUPLICATE KEY UPDATE.</p>
<p>Imagine we have a table:</p>
<pre><code>CREATE TABLE `transcripts` (
`ensembl_transcript_id` varchar(20) NOT NULL,
`transcript_chrom_start` int(10) unsigned NOT NULL,
`transcript_chrom_end` int(10) unsigned NOT NULL,
PRIMARY KEY (`ensembl_transcript_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code></pre>
<p>Now imagine that we have an automatic pipeline importing transcripts
meta-data from Ensembl, and that due to various reasons the pipeline
might be broken at any step of execution. Thus, we need to ensure two
things:</p>
</blockquote>
<blockquote>
<ol>
<li>repeated executions of the pipeline will not destroy our
> database</li>
</ol>
</blockquote>
<blockquote>
<ol start="2">
<li>repeated executions will not die due to ‘duplicate
> primary key’ errors.</li>
</ol>
<p><strong>Method 1: using REPLACE</strong></p>
<p>It’s very simple:</p>
<pre><code>REPLACE INTO `transcripts`
SET `ensembl_transcript_id` = 'ENSORGT00000000001',
`transcript_chrom_start` = 12345,
`transcript_chrom_end` = 12678;
</code></pre>
<p>If the record exists, it will be overwritten; if it does not yet
exist, it will be created. However, using this method isn’t efficient
for our case: we do not need to overwrite existing records, it’s fine
just to skip them.</p>
<p><strong>Method 2: using INSERT IGNORE Also very simple:</strong></p>
<pre><code>INSERT IGNORE INTO `transcripts`
SET `ensembl_transcript_id` = 'ENSORGT00000000001',
`transcript_chrom_start` = 12345,
`transcript_chrom_end` = 12678;
</code></pre>
<p>Here, if the ‘ensembl_transcript_id’ is already present in the
database, it will be silently skipped (ignored). (To be more precise,
here’s a quote from MySQL reference manual: “If you use the IGNORE
keyword, errors that occur while executing the INSERT statement are
treated as warnings instead. For example, without IGNORE, a row that
duplicates an existing UNIQUE index or PRIMARY KEY value in the table
causes a duplicate-key error and the statement is aborted.”.) If the
record doesn’t yet exist, it will be created.</p>
<p>This second method has several potential weaknesses, including
non-abortion of the query in case any other problem occurs (see the
manual). Thus it should be used if previously tested without the
IGNORE keyword.</p>
<p><strong>Method 3: using INSERT … ON DUPLICATE KEY UPDATE:</strong></p>
<p>Third option is to use <code>INSERT … ON DUPLICATE KEY UPDATE</code>
syntax, and in the UPDATE part just do nothing do some meaningless
(empty) operation, like calculating 0+0 (Geoffray suggests doing the
id=id assignment for the MySQL optimization engine to ignore this
operation). Advantage of this method is that it only ignores duplicate
key events, and still aborts on other errors.</p>
<p>As a final notice: this post was inspired by Xaprb. I’d also advise to
consult his other post on writing flexible SQL queries.</p>
</blockquote> | {
"question_id": 1361340,
"question_date": "2009-09-01T08:56:41.863Z",
"question_score": 1023,
"tags": "mysql|sql|sql-insert|primary-key|unique-constraint",
"answer_id": 1361368,
"answer_date": "2009-09-01T09:02:01.727Z",
"answer_score": 954
} |
Please answer the following Stack Overflow question:
Title: Java 8 List<V> into Map<K, V>
<p>I want to translate a List of objects into a Map using Java 8's streams and lambdas.</p>
<p>This is how I would write it in Java 7 and below.</p>
<pre><code>private Map<String, Choice> nameMap(List<Choice> choices) {
final Map<String, Choice> hashMap = new HashMap<>();
for (final Choice choice : choices) {
hashMap.put(choice.getName(), choice);
}
return hashMap;
}
</code></pre>
<p>I can accomplish this easily using Java 8 and Guava but I would like to know how to do this without Guava.</p>
<p>In Guava:</p>
<pre><code>private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, new Function<Choice, String>() {
@Override
public String apply(final Choice input) {
return input.getName();
}
});
}
</code></pre>
<p>And Guava with Java 8 lambdas.</p>
<pre><code>private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, Choice::getName);
}
</code></pre> | <p>Based on <a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toMap-java.util.function.Function-java.util.function.Function-" rel="noreferrer"><code>Collectors</code> documentation</a> it's as simple as:</p>
<pre><code>Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(Choice::getName,
Function.identity()));
</code></pre> | {
"question_id": 20363719,
"question_date": "2013-12-03T23:18:49.007Z",
"question_score": 1023,
"tags": "java|lambda|java-8|java-stream",
"answer_id": 20363874,
"answer_date": "2013-12-03T23:30:58.423Z",
"answer_score": 1487
} |
Please answer the following Stack Overflow question:
Title: How to create RecyclerView with multiple view types
<p>From <em><a href="https://developer.android.com/preview/material/ui-widgets.html" rel="noreferrer">Create dynamic lists with RecyclerView</a></em>:</p>
<p>When we create a <code>RecyclerView.Adapter</code> we have to specify <code>ViewHolder</code> that will bind with the adapter.</p>
<pre><code>public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private String[] mDataset;
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ViewHolder(TextView v) {
super(v);
mTextView = v;
}
}
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.some_layout, parent, false);
//findViewById...
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTextView.setText(mDataset[position]);
}
@Override
public int getItemCount() {
return mDataset.length;
}
}
</code></pre>
<p>Is it possible to create <code>RecyclerView</code> with multiple view types?</p> | <p>Yes, it's possible. Just implement <a href="https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#getItemViewType(int)">getItemViewType()</a>, and take care of the <code>viewType</code> parameter in <code>onCreateViewHolder()</code>.</p>
<p>So you do something like:</p>
<pre><code>public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
class ViewHolder0 extends RecyclerView.ViewHolder {
...
public ViewHolder0(View itemView){
...
}
}
class ViewHolder2 extends RecyclerView.ViewHolder {
...
public ViewHolder2(View itemView){
...
}
@Override
public int getItemViewType(int position) {
// Just as an example, return 0 or 2 depending on position
// Note that unlike in ListView adapters, types don't have to be contiguous
return position % 2 * 2;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0: return new ViewHolder0(...);
case 2: return new ViewHolder2(...);
...
}
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
switch (holder.getItemViewType()) {
case 0:
ViewHolder0 viewHolder0 = (ViewHolder0)holder;
...
break;
case 2:
ViewHolder2 viewHolder2 = (ViewHolder2)holder;
...
break;
}
}
}
</code></pre> | {
"question_id": 26245139,
"question_date": "2014-10-07T20:55:30.513Z",
"question_score": 1023,
"tags": "java|android|user-interface|android-recyclerview",
"answer_id": 26245463,
"answer_date": "2014-10-07T21:17:46.833Z",
"answer_score": 1471
} |
Please answer the following Stack Overflow question:
Title: How do I get list of all tables in a database using TSQL?
<p>What is the best way to get the names of all of the tables in a specific database on SQL Server?</p> | <p>SQL Server 2000, 2005, 2008, 2012, 2014, 2016, 2017 or 2019:</p>
<pre><code>SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
</code></pre>
<p>To show only tables from a particular database</p>
<pre><code>SELECT TABLE_NAME
FROM [<DATABASE_NAME>].INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
</code></pre>
<p>Or,</p>
<pre><code>SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_CATALOG='dbName' --(for MySql, use: TABLE_SCHEMA='dbName' )
</code></pre>
<p>PS: For SQL Server 2000:</p>
<pre><code>SELECT * FROM sysobjects WHERE xtype='U'
</code></pre> | {
"question_id": 175415,
"question_date": "2008-10-06T17:53:21.950Z",
"question_score": 1022,
"tags": "sql-server|tsql|database-table",
"answer_id": 175446,
"answer_date": "2008-10-06T18:00:56.227Z",
"answer_score": 1606
} |
Please answer the following Stack Overflow question:
Title: Text editor to open big (giant, huge, large) text files
<p>I mean 100+ MB big; such text files can push the envelope of editors.</p>
<p>I need to look through a large XML file, but cannot if the editor is buggy.</p>
<p>Any suggestions?</p> | <p>Free read-only viewers:</p>
<ul>
<li><a href="https://web.archive.org/web/20140908181354fw_/http://swiftgear.com/ltfviewer/features.html" rel="noreferrer"><strong>Large Text File Viewer</strong></a> (Windows) – Fully customizable theming (colors, fonts, word wrap, tab size). Supports horizontal and vertical split view. Also support file following and regex search. Very fast, simple, and has small executable size.</li>
<li><a href="https://klogg.filimonov.dev/" rel="noreferrer"><strong>klogg</strong></a> (Windows, macOS, Linux) – A maintained fork of <a href="https://glogg.bonnefon.org/description.html" rel="noreferrer">glogg</a>. Its main feature is regular expression search. It supports monitoring file changes (like <code>tail</code>), bookmarks, highlighting patterns using different colors, and has serious optimizations built in. But from a UI standpoint, it's rather minimal.</li>
<li><a href="https://github.com/zarunbal/LogExpert" rel="noreferrer"><strong>LogExpert</strong></a> (Windows) – "A GUI replacement for <code>tail</code>." It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools.</li>
<li><a href="https://www.ghisler.com/lister/" rel="noreferrer"><strong>Lister</strong></a> (Windows) – Very small and minimalist. It's one executable, barely 500 KB, but it still supports searching (with regexes), printing, a hex editor mode, and settings.</li>
</ul>
<p>Free editors:</p>
<ul>
<li>Your regular editor or IDE. Modern editors can handle surprisingly large files. In particular, <a href="https://neovim.io/" rel="noreferrer"><strong>Vim</strong></a> (Windows, macOS, Linux), <a href="https://www.gnu.org/software/emacs/" rel="noreferrer"><strong>Emacs</strong></a> (Windows, macOS, Linux), <a href="https://notepad-plus-plus.org/" rel="noreferrer"><strong>Notepad++</strong></a> (Windows), <a href="https://www.sublimetext.com/" rel="noreferrer"><strong>Sublime Text</strong></a> (Windows, macOS, Linux), and <a href="https://code.visualstudio.com/" rel="noreferrer"><strong>VS Code</strong></a> (Windows, macOS, Linux) support large (~4 GB) files, assuming you have the RAM.</li>
<li><a href="https://www.liquid-technologies.com/large-file-editor" rel="noreferrer"><strong>Large File Editor</strong></a> (Windows) – Opens and edits TB+ files, supports Unicode, uses little memory, has XML-specific features, and includes a binary mode.</li>
<li><a href="https://heliwave.github.io/GigaEdit.html" rel="noreferrer"><strong>GigaEdit</strong></a> (Windows) – Supports searching, character statistics, and font customization. But it's buggy – with large files, it only allows overwriting characters, not inserting them; it doesn't respect LF as a line terminator, only CRLF; and it's slow.</li>
</ul>
<p>Builtin programs (no installation required):</p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Less_(Unix)" rel="noreferrer"><strong>less</strong></a> (macOS, Linux) – The traditional Unix command-line pager tool. Lets you view text files of practically any size. Can be installed on Windows, too.</li>
<li><a href="https://en.wikipedia.org/wiki/Microsoft_Notepad" rel="noreferrer"><strong>Notepad</strong></a> (Windows) – Decent with large files, especially with word wrap turned off.</li>
<li><a href="https://ss64.com/nt/more.html" rel="noreferrer"><strong>MORE</strong></a> (Windows) – This refers to the Windows <code>MORE</code>, not the Unix <code>more</code>. A console program that allows you to view a file, one screen at a time.</li>
</ul>
<p>Web viewers:</p>
<ul>
<li><a href="https://www.readfileonline.com/" rel="noreferrer"><strong>readfileonline.com</strong></a> – Another HTML5 large file viewer. Supports search.</li>
</ul>
<p>Paid editors/viewers:</p>
<ul>
<li><a href="https://www.sweetscape.com/010editor/" rel="noreferrer"><strong>010 Editor</strong></a> (Windows, macOS, Linux) – Opens giant (as large as 50 GB) files.</li>
<li><a href="https://www.slickedit.com/products/slickedit" rel="noreferrer"><strong>SlickEdit</strong></a> (Windows, macOS, Linux) – Opens large files.</li>
<li><a href="https://www.ultraedit.com/" rel="noreferrer"><strong>UltraEdit</strong></a> (Windows, macOS, Linux) – Opens files of more than 6 GB, but the configuration must be changed for this to be practical: Menu » Advanced » Configuration » File Handling » Temporary Files » Open file without temp file...</li>
<li><a href="https://www.emeditor.com/" rel="noreferrer"><strong>EmEditor</strong></a> (Windows) – Handles very large text files nicely (officially up to 248 GB, but as much as 900 GB according to one report).</li>
<li><a href="https://www.bergstreiser.com/bsseditor" rel="noreferrer"><strong>BssEditor</strong></a> (Windows) – Handles large files and very long lines. Don’t require an installation. Free for non commercial use.</li>
<li><a href="https://www.mommos-software.com/index.php/loxx" rel="noreferrer"><strong>loxx</strong></a> (Windows) – Supports file following, highlighting, line numbers, huge files, regex, multiple files and views, and much more. The free version can not: process regex, filter files, synchronize timestamps, and save changed files.</li>
</ul> | {
"question_id": 159521,
"question_date": "2008-10-01T20:22:35.133Z",
"question_score": 1022,
"tags": "windows|xml|editor|text-editor|large-files",
"answer_id": 159537,
"answer_date": "2008-10-01T20:25:19.993Z",
"answer_score": 1587
} |
Please answer the following Stack Overflow question:
Title: Search text in stored procedure in SQL Server
<p>I want to search a text from all my database stored procedures. I use the below SQL:</p>
<pre><code>SELECT DISTINCT
o.name AS Object_Name,
o.type_desc
FROM sys.sql_modules m
INNER JOIN
sys.objects o
ON m.object_id = o.object_id
WHERE m.definition Like '%[ABD]%';
</code></pre>
<p>I want to search for <code>[ABD]</code> in all stored procedures including square brackets, but it's not giving the proper result. How can I change my query to achieve this?</p> | <p>Escape the square brackets:</p>
<pre><code>...
WHERE m.definition Like '%\[ABD\]%' ESCAPE '\'
</code></pre>
<p>Then the square brackets will be treated as a string literals not as wild cards.</p> | {
"question_id": 14704105,
"question_date": "2013-02-05T09:30:39.060Z",
"question_score": 1021,
"tags": "sql|sql-server|stored-procedures",
"answer_id": 14704157,
"answer_date": "2013-02-05T09:33:42.153Z",
"answer_score": 660
} |
Please answer the following Stack Overflow question:
Title: What's the difference between a POST and a PUT HTTP REQUEST?
<p>They both seem to be sending data to the server inside the body, so what makes them different?</p> | <p><strong>HTTP PUT:</strong></p>
<p>PUT puts a file or resource at a specific URI, and exactly at that URI. If there's already a file or resource at that URI, PUT replaces that file or resource. If there is no file or resource there, PUT creates one. PUT is <a href="https://www.rfc-editor.org/rfc/rfc9110.html#name-idempotent-methods" rel="noreferrer">idempotent</a>, but paradoxically PUT responses are not cacheable.</p>
<p><a href="https://www.rfc-editor.org/rfc/rfc9110.html#name-put" rel="noreferrer">HTTP 1.1 RFC location for PUT</a></p>
<p><strong>HTTP POST:</strong></p>
<p>POST sends data to a specific URI and expects the resource at that URI to handle the request. The web server at this point can determine what to do with the data in the context of the specified resource. The POST method is not <a href="https://www.rfc-editor.org/rfc/rfc9110.html#name-idempotent-methods" rel="noreferrer">idempotent</a>, however POST responses <em>are</em> cacheable so long as the server sets the appropriate Cache-Control and Expires headers.</p>
<p>The official HTTP RFC specifies POST to be:</p>
<ul>
<li>Annotation of existing resources;</li>
<li>Posting a message to a bulletin board, newsgroup, mailing list,
or similar group of articles;</li>
<li>Providing a block of data, such as the result of submitting a
form, to a data-handling process;</li>
<li>Extending a database through an append operation.</li>
</ul>
<p><a href="https://www.rfc-editor.org/rfc/rfc9110.html#name-post" rel="noreferrer">HTTP 1.1 RFC location for POST</a></p>
<p><strong>Difference between POST and PUT:</strong></p>
<p>The RFC itself explains the core difference:</p>
<blockquote>
<p>The fundamental difference between the
POST and PUT requests is reflected in
the different meaning of the
Request-URI. The URI in a POST request
identifies the resource that will
handle the enclosed entity. That
resource might be a data-accepting
process, a gateway to some other
protocol, or a separate entity that
accepts annotations. In contrast, the
URI in a PUT request identifies the
entity enclosed with the request --
the user agent knows what URI is
intended and the server MUST NOT
attempt to apply the request to some
other resource. If the server desires
that the request be applied to a
different URI, it MUST send a 301 (Moved Permanently) response; the user agent MAY then make
its own decision regarding whether or not to redirect the request.</p>
</blockquote>
<p>Additionally, and a bit more concisely, <a href="https://www.rfc-editor.org/rfc/rfc7231#section-4.3.4" rel="noreferrer">RFC 7231 Section 4.3.4 PUT</a> states (emphasis added),</p>
<blockquote>
<p><strong>4.3.4. PUT</strong></p>
<p>The PUT method requests that the state of the target resource be
<code>created</code> or <code>replaced</code> with the state defined by the representation
enclosed in the request message payload.</p>
</blockquote>
<p><strong>Using the right method, unrelated aside:</strong></p>
<p>One benefit of <a href="http://en.wikipedia.org/wiki/Resource_oriented_architecture" rel="noreferrer">REST ROA</a> vs SOAP is that when using HTTP REST ROA, it encourages the proper usage of the HTTP verbs/methods. So for example you would only use PUT when you want to create a resource at that exact location. And you would never use GET to create or modify a resource.</p> | {
"question_id": 107390,
"question_date": "2008-09-20T06:34:41.417Z",
"question_score": 1021,
"tags": "http|post|put",
"answer_id": 107450,
"answer_date": "2008-09-20T06:54:01.293Z",
"answer_score": 995
} |
Please answer the following Stack Overflow question:
Title: What is the difference between a framework and a library?
<p>What is the difference between a <strong><em>framework</em></strong> and a <strong><em>library</em></strong>? </p>
<p>I always thought of a library as a set of objects and functions that focuses on solving a particular problem or a specific area of application development (i.e. database access); and a framework on the other hand as a collection of libraries centered on a particular methodology (i.e. MVC) and which covers all areas of application development.</p> | <p>Actually these terms can mean a lot of different things depending the context they are used. </p>
<p>For example, on Mac OS X frameworks are just libraries, packed into a bundle. Within the bundle you will find an actual dynamic library (libWhatever.dylib). The difference between a bare library and the framework on Mac is that a framework can contain multiple different versions of the library. It can contain extra resources (images, localized strings, XML data files, UI objects, etc.) and unless the framework is released to public, it usually contains the necessary .h files you need to use the library. </p>
<p>Thus you have everything within a single package you need to use the library in your application (a C/C++/Objective-C library without .h files is pretty useless, unless you write them yourself according to some library documentation), instead of a bunch of files to move around (a Mac bundle is just a directory on the Unix level, but the UI treats it like a single file, pretty much like you have JAR files in Java and when you click it, you usually don't see what's inside, unless you explicitly select to show the content).</p>
<p>Wikipedia calls framework a "buzzword". It defines a software framework as</p>
<blockquote>
<p>A software framework is a re-usable
design for a software system (or
subsystem). A software framework may
include support programs, code
libraries, a scripting language, or
other software to help develop and
glue together the different components
of a software project. Various parts
of the framework may be exposed
through an API..</p>
</blockquote>
<p>So I'd say a library is just that, "a library". It is a collection of objects/functions/methods (depending on your language) and your application "links" against it and thus can use the objects/functions/methods. It is basically a file containing re-usable code that can usually be shared among multiple applications (you don't have to write the same code over and over again).</p>
<p>A framework can be everything you use in application development. It can be a library, a collection of many libraries, a collection of scripts, or any piece of software you need to create your application. Framework is just a very vague term.</p>
<p>Here's an article about some guy regarding the topic "<a href="https://web.archive.org/web/20070504053354/http://www.ddj.com/blog/architectblog/archives/2006/07/frameworks_vs_l.html" rel="noreferrer">Library vs. Framework</a>". I personally think this article is highly arguable. It's not wrong what he's saying there, however, he's just picking out one of the multiple definitions of framework and compares that to the classic definition of library. E.g. he says you need a framework for sub-classing. Really? I can have an object defined in a library, I can link against it, and sub-class it in my code. I don't see how I need a "framework" for that. In some way he rather explains how the term framework is used nowadays. It's just a hyped word, as I said before. Some companies release just a normal library (in any sense of a classical library) and call it a "framework" because it sounds more fancy.</p> | {
"question_id": 148747,
"question_date": "2008-09-29T13:56:50.317Z",
"question_score": 1021,
"tags": "frameworks|language-agnostic|libraries|terminology",
"answer_id": 148852,
"answer_date": "2008-09-29T14:17:09.723Z",
"answer_score": 401
} |
Please answer the following Stack Overflow question:
Title: Definition of "downstream" and "upstream"
<p>I've started playing with Git and have come across the terms "upstream" and "downstream". I've seen these before but never understood them fully. What do these terms mean in the context of SCMs (<a href="https://en.wikipedia.org/wiki/Software_configuration_management" rel="noreferrer">Software Configuration Management</a> tools) and source code?</p> | <p>In terms of source control, you're downstream when you copy (clone, checkout, etc) from a repository. Information flowed "downstream" to you.</p>
<p>When you make changes, you usually want to send them back "upstream" so they make it into that repository so that everyone pulling from the same source is working with all the same changes. This is mostly a social issue of how everyone can coordinate their work rather than a technical requirement of source control. You want to get your changes into the main project so you're not tracking divergent lines of development.</p>
<p>Sometimes you'll read about package or release managers (the people, not the tool) talking about submitting changes to "upstream". That usually means they had to adjust the original sources so they could create a package for their system. They don't want to keep making those changes, so if they send them "upstream" to the original source, they shouldn't have to deal with the same issue in the next release.</p> | {
"question_id": 2739376,
"question_date": "2010-04-29T17:18:21.957Z",
"question_score": 1021,
"tags": "git|version-control|versioning|terminology|definition",
"answer_id": 2739476,
"answer_date": "2010-04-29T17:36:55.550Z",
"answer_score": 811
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.