input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: What do 'real', 'user' and 'sys' mean in the output of time(1)?
<pre><code>$ time foo
real 0m0.003s
user 0m0.000s
sys 0m0.004s
$
</code></pre>
<p>What do <code>real</code>, <code>user</code> and <code>sys</code> mean in the output of time? Which one is meaningful when benchmarking my app?</p> | <p><strong>Real, User and Sys process time statistics</strong></p>
<p>One of these things is not like the other. Real refers to actual elapsed time; User and Sys refer to CPU time used <em>only by the process.</em></p>
<ul>
<li><p><strong>Real</strong> is wall clock time - time from start to finish of the call. This is all elapsed time including time slices used by other processes and time the process spends blocked (for example if it is waiting for I/O to complete).</p></li>
<li><p><strong>User</strong> is the amount of CPU time spent in user-mode code (outside the kernel) <em>within</em> the process. This is only actual CPU time used in executing the process. Other processes and time the process spends blocked do not count towards this figure.</p></li>
<li><p><strong>Sys</strong> is the amount of CPU time spent in the kernel within the process. This means executing CPU time spent in system calls <em>within the kernel,</em> as opposed to library code, which is still running in user-space. Like 'user', this is only CPU time used by the process. See below for a brief description of kernel mode (also known as 'supervisor' mode) and the system call mechanism.</p></li>
</ul>
<p><code>User+Sys</code> will tell you how much actual CPU time your process used. Note that this is across all CPUs, so if the process has multiple threads (and this process is running on a computer with more than one processor) it could potentially exceed the wall clock time reported by <code>Real</code> (which usually occurs). Note that in the output these figures include the <code>User</code> and <code>Sys</code> time of all child processes (and their descendants) as well when they could have been collected, e.g. by <code>wait(2)</code> or <code>waitpid(2)</code>, although the underlying system calls return the statistics for the process and its children separately.</p>
<p><strong>Origins of the statistics reported by <code>time (1)</code></strong></p>
<p>The statistics reported by <code>time</code> are gathered from various system calls. 'User' and 'Sys' come from <a href="https://docs.oracle.com/cd/E23823_01/html/816-5168/wait-3c.html#scrolltoc" rel="noreferrer"><code>wait (2)</code></a> (<a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html" rel="noreferrer">POSIX</a>) or <a href="https://linux.die.net/man/2/times" rel="noreferrer"><code>times (2)</code></a> (<a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/times.html" rel="noreferrer">POSIX</a>), depending on the particular system. 'Real' is calculated from a start and end time gathered from the <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/gettimeofday.html" rel="noreferrer"><code>gettimeofday (2)</code></a> call. Depending on the version of the system, various other statistics such as the number of context switches may also be gathered by <code>time</code>.</p>
<p>On a multi-processor machine, a multi-threaded process or a process forking children could have an elapsed time smaller than the total CPU time - as different threads or processes may run in parallel. Also, the time statistics reported come from different origins, so times recorded for very short running tasks may be subject to rounding errors, as the example given by the original poster shows.</p>
<p><strong>A brief primer on Kernel vs. User mode</strong></p>
<p>On Unix, or any protected-memory operating system, <a href="https://en.wikipedia.org/wiki/Kernel_mode#Supervisor_mode" rel="noreferrer">'Kernel' or 'Supervisor'</a> mode refers to a <a href="https://en.wikipedia.org/wiki/Process_management_(computing)#Processor_modes" rel="noreferrer">privileged mode</a> that the CPU can operate in. Certain privileged actions that could affect security or stability can only be done when the CPU is operating in this mode; these actions are not available to application code. An example of such an action might be manipulation of the <a href="https://en.wikipedia.org/wiki/Memory_management_unit" rel="noreferrer">MMU</a> to gain access to the address space of another process. Normally, <a href="https://en.wikipedia.org/wiki/User_space" rel="noreferrer">user-mode</a> code cannot do this (with good reason), although it can request <a href="https://en.wikipedia.org/wiki/Shared_memory" rel="noreferrer">shared memory</a> from the kernel, which <em>could</em> be read or written by more than one process. In this case, the shared memory is explicitly requested from the kernel through a secure mechanism and both processes have to explicitly attach to it in order to use it.</p>
<p>The privileged mode is usually referred to as 'kernel' mode because the kernel is executed by the CPU running in this mode. In order to switch to kernel mode you have to issue a specific instruction (often called a <a href="https://en.wikipedia.org/wiki/Trap_(computing)" rel="noreferrer"><em>trap</em></a>) that switches the CPU to running in kernel mode <em>and runs code from a specific location held in a jump table.</em> For security reasons, you cannot switch to kernel mode and execute arbitrary code - the traps are managed through a table of addresses that cannot be written to unless the CPU is running in supervisor mode. You trap with an explicit trap number and the address is looked up in the jump table; the kernel has a finite number of controlled entry points.</p>
<p>The 'system' calls in the C library (particularly those described in Section 2 of the man pages) have a user-mode component, which is what you actually call from your C program. Behind the scenes, they may issue one or more system calls to the kernel to do specific services such as I/O, but they still also have code running in user-mode. It is also quite possible to directly issue a trap to kernel mode from any user space code if desired, although you may need to write a snippet of assembly language to set up the registers correctly for the call.</p>
<p><strong>More about 'sys'</strong></p>
<p>There are things that your code cannot do from user mode - things like allocating memory or accessing hardware (HDD, network, etc.). These are under the supervision of the kernel, and it alone can do them. Some operations like <code>malloc</code> or<code>fread</code>/<code>fwrite</code> will invoke these kernel functions and that then will count as 'sys' time. Unfortunately it's not as simple as "every call to malloc will be counted in 'sys' time". The call to <code>malloc</code> will do some processing of its own (still counted in 'user' time) and then somewhere along the way it may call the function in kernel (counted in 'sys' time). After returning from the kernel call, there will be some more time in 'user' and then <code>malloc</code> will return to your code. As for when the switch happens, and how much of it is spent in kernel mode... you cannot say. It depends on the implementation of the library. Also, other seemingly innocent functions might also use <code>malloc</code> and the like in the background, which will again have some time in 'sys' then.</p> | {
"question_id": 556405,
"question_date": "2009-02-17T11:33:51.660Z",
"question_score": 2123,
"tags": "unix|time|benchmarking",
"answer_id": 556411,
"answer_date": "2009-02-17T11:34:57.103Z",
"answer_score": 2485
} |
Please answer the following Stack Overflow question:
Title: How can I add new array elements at the beginning of an array in JavaScript?
<p>I have a need to add or prepend elements at the beginning of an array.</p>
<p>For example, if my array looks like below:</p>
<pre><code>[23, 45, 12, 67]
</code></pre>
<p>And the response from my AJAX call is <code>34</code>, I want the updated array to be like the following:</p>
<pre><code>[34, 23, 45, 12, 67]
</code></pre>
<p>Currently I am planning to do it like this:</p>
<pre><code>var newArray = [];
newArray.push(response);
for (var i = 0; i < theArray.length; i++) {
newArray.push(theArray[i]);
}
theArray = newArray;
delete newArray;
</code></pre>
<p>Is there a better way to do this? Does JavaScript have any built-in functionality that does this?</p>
<p>The complexity of my method is <code>O(n)</code> and it would be really interesting to see better implementations.</p> | <p>Use <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift" rel="noreferrer"><code>unshift</code></a>. It's like <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push" rel="noreferrer"><code>push</code></a>, except it adds elements to the beginning of the array instead of the end.</p>
<ul>
<li><code>unshift</code>/<code>push</code> - add an element to the beginning/end of an array</li>
<li><code>shift</code>/<code>pop</code> - remove and return the first/last element of an array</li>
</ul>
<p>A simple diagram...</p>
<pre class="lang-none prettyprint-override"><code> unshift -> [array] <- push
shift <- [array] -> pop
</code></pre>
<p>and chart:</p>
<pre class="lang-none prettyprint-override"><code> add remove start end
push X X
pop X X
unshift X X
shift X X
</code></pre>
<p>Check out the <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array" rel="noreferrer">MDN Array documentation</a>. Virtually every language that has the ability to push/pop elements from an array will also have the ability to unshift/shift (sometimes called <code>push_front</code>/<code>pop_front</code>) elements, you should never have to implement these yourself.</p>
<hr />
<p>As pointed out in the comments, if you want to avoid mutating your original array, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat" rel="noreferrer"><code>concat</code></a>, which concatenates two or more arrays together. You can use this to functionally push a single element onto the front or back of an existing array; to do so, you need to turn the new element into a single element array:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const array = [3, 2, 1]
const newFirstElement = 4
const newArray = [newFirstElement].concat(array) // [ 4, 3, 2, 1 ]
console.log(newArray);</code></pre>
</div>
</div>
</p>
<p><code>concat</code> can also append items. The arguments to <code>concat</code> can be of any type; they are implicitly wrapped in a single-element array, if they are not already an array:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const array = [3, 2, 1]
const newLastElement = 0
// Both of these lines are equivalent:
const newArray1 = array.concat(newLastElement) // [ 3, 2, 1, 0 ]
const newArray2 = array.concat([newLastElement]) // [ 3, 2, 1, 0 ]
console.log(newArray1);
console.log(newArray2);</code></pre>
</div>
</div>
</p> | {
"question_id": 8073673,
"question_date": "2011-11-10T00:35:22.150Z",
"question_score": 2109,
"tags": "javascript|arrays",
"answer_id": 8073687,
"answer_date": "2011-11-10T00:37:49.080Z",
"answer_score": 3557
} |
Please answer the following Stack Overflow question:
Title: Why is reading lines from stdin much slower in C++ than Python?
<p>I wanted to compare reading lines of string input from stdin using Python and C++ and was shocked to see my C++ code run an order of magnitude slower than the equivalent Python code. Since my C++ is rusty and I'm not yet an expert Pythonista, please tell me if I'm doing something wrong or if I'm misunderstanding something.</p>
<hr />
<p>(<strong>TLDR answer:</strong> include the statement: <code>cin.sync_with_stdio(false)</code> or just use <code>fgets</code> instead.</p>
<p><strong>TLDR results:</strong> scroll all the way down to the bottom of my question and look at the table.)</p>
<hr />
<p><strong>C++ code:</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <time.h>
using namespace std;
int main() {
string input_line;
long line_count = 0;
time_t start = time(NULL);
int sec;
int lps;
while (cin) {
getline(cin, input_line);
if (!cin.eof())
line_count++;
};
sec = (int) time(NULL) - start;
cerr << "Read " << line_count << " lines in " << sec << " seconds.";
if (sec > 0) {
lps = line_count / sec;
cerr << " LPS: " << lps << endl;
} else
cerr << endl;
return 0;
}
// Compiled with:
// g++ -O3 -o readline_test_cpp foo.cpp
</code></pre>
<p><strong>Python Equivalent:</strong></p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python
import time
import sys
count = 0
start = time.time()
for line in sys.stdin:
count += 1
delta_sec = int(time.time() - start_time)
if delta_sec >= 0:
lines_per_sec = int(round(count/delta_sec))
print("Read {0} lines in {1} seconds. LPS: {2}".format(count, delta_sec,
lines_per_sec))
</code></pre>
<p><strong>Here are my results:</strong></p>
<pre class="lang-none prettyprint-override"><code>$ cat test_lines | ./readline_test_cpp
Read 5570000 lines in 9 seconds. LPS: 618889
$ cat test_lines | ./readline_test.py
Read 5570000 lines in 1 seconds. LPS: 5570000
</code></pre>
<p><em>I should note that I tried this both under Mac OS X v10.6.8 (Snow Leopard) and Linux 2.6.32 (Red Hat Linux 6.2). The former is a MacBook Pro, and the latter is a very beefy server, not that this is too pertinent.</em></p>
<pre class="lang-sh prettyprint-override"><code>$ for i in {1..5}; do echo "Test run $i at `date`"; echo -n "CPP:"; cat test_lines | ./readline_test_cpp ; echo -n "Python:"; cat test_lines | ./readline_test.py ; done
</code></pre>
<pre class="lang-none prettyprint-override"><code>Test run 1 at Mon Feb 20 21:29:28 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 2 at Mon Feb 20 21:29:39 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 3 at Mon Feb 20 21:29:50 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 4 at Mon Feb 20 21:30:01 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 5 at Mon Feb 20 21:30:11 EST 2012
CPP: Read 5570001 lines in 10 seconds. LPS: 557000
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
</code></pre>
<hr />
<p>Tiny benchmark addendum and recap</p>
<p>For completeness, I thought I'd update the read speed for the same file on the same box with the original (synced) C++ code. Again, this is for a 100M line file on a fast disk. Here's the comparison, with several solutions/approaches:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Implementation</th>
<th style="text-align: right;">Lines per second</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">python (default)</td>
<td style="text-align: right;">3,571,428</td>
</tr>
<tr>
<td style="text-align: left;">cin (default/naive)</td>
<td style="text-align: right;">819,672</td>
</tr>
<tr>
<td style="text-align: left;">cin (no sync)</td>
<td style="text-align: right;">12,500,000</td>
</tr>
<tr>
<td style="text-align: left;">fgets</td>
<td style="text-align: right;">14,285,714</td>
</tr>
<tr>
<td style="text-align: left;">wc (not fair comparison)</td>
<td style="text-align: right;">54,644,808</td>
</tr>
</tbody>
</table>
</div> | <h3>tl;dr: Because of different default settings in C++ requiring more system calls.</h3>
<p>By default, <code>cin</code> is synchronized with stdio, which causes it to avoid any input buffering. If you add this to the top of your main, you should see much better performance:</p>
<pre><code>std::ios_base::sync_with_stdio(false);
</code></pre>
<p>Normally, when an input stream is buffered, instead of reading one character at a time, the stream will be read in larger chunks. This reduces the number of system calls, which are typically relatively expensive. However, since the <code>FILE*</code> based <code>stdio</code> and <code>iostreams</code> often have separate implementations and therefore separate buffers, this could lead to a problem if both were used together. For example:</p>
<pre><code>int myvalue1;
cin >> myvalue1;
int myvalue2;
scanf("%d",&myvalue2);
</code></pre>
<p>If more input was read by <code>cin</code> than it actually needed, then the second integer value wouldn't be available for the <code>scanf</code> function, which has its own independent buffer. This would lead to unexpected results.</p>
<p>To avoid this, by default, streams are synchronized with <code>stdio</code>. One common way to achieve this is to have <code>cin</code> read each character one at a time as needed using <code>stdio</code> functions. Unfortunately, this introduces a lot of overhead. For small amounts of input, this isn't a big problem, but when you are reading millions of lines, the performance penalty is significant.</p>
<p>Fortunately, the library designers decided that you should also be able to disable this feature to get improved performance if you knew what you were doing, so they provided the <a href="http://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio" rel="noreferrer"><code>sync_with_stdio</code></a> method. From this link (emphasis added):</p>
<blockquote>
<p>If the synchronization is turned off, the C++ standard streams are allowed to buffer their I/O independently, <strong>which may be considerably faster in some cases</strong>.</p>
</blockquote> | {
"question_id": 9371238,
"question_date": "2012-02-21T02:17:50.463Z",
"question_score": 2109,
"tags": "python|c++|benchmarking|iostream|getline",
"answer_id": 9371717,
"answer_date": "2012-02-21T03:24:19.650Z",
"answer_score": 1879
} |
Please answer the following Stack Overflow question:
Title: Programmatically navigate using React router
<p>With <code>react-router</code> I can use the <code>Link</code> element to create links which are natively handled by react router. </p>
<p>I see internally it calls <code>this.context.transitionTo(...)</code>.</p>
<p>I want to do a navigation. Not from a link, but from a dropdown selection (as an example). How can I do this in code? What is <code>this.context</code>? </p>
<p>I saw the <code>Navigation</code> mixin, but can I do this without <code>mixins</code>?</p> | <blockquote>
<p><strong>React Router v5.1.0 with hooks</strong></p>
</blockquote>
<p>There is a new <code>useHistory</code> hook in React Router >5.1.0 if you are using React >16.8.0 and functional components.</p>
<pre><code>import { useHistory } from "react-router-dom";
function HomeButton() {
const history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
</code></pre>
<blockquote>
<p><strong>React Router v4</strong></p>
</blockquote>
<p>With v4 of React Router, there are three approaches that you can take to programmatic routing within components.</p>
<ol>
<li>Use the <code>withRouter</code> higher-order component.</li>
<li>Use composition and render a <code><Route></code></li>
<li>Use the <code>context</code>.</li>
</ol>
<p>React Router is mostly a wrapper around the <a href="https://github.com/ReactTraining/history" rel="noreferrer"><code>history</code></a> library. <code>history</code> handles interaction with the browser's <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/history" rel="noreferrer"><code>window.history</code></a> for you with its browser and hash histories. It also provides a memory history which is useful for environments that don't have a global history. This is particularly useful in mobile app development (<code>react-native</code>) and unit testing with Node.</p>
<p>A <code>history</code> instance has two methods for navigating: <code>push</code> and <code>replace</code>. If you think of the <code>history</code> as an array of visited locations, <code>push</code> will add a new location to the array and <code>replace</code> will replace the current location in the array with the new one. Typically you will want to use the <code>push</code> method when you are navigating.</p>
<p>In earlier versions of React Router, you had to create your own <code>history</code> instance, but in v4 the <code><BrowserRouter></code>, <code><HashRouter></code>, and <code><MemoryRouter></code> components will create a browser, hash, and memory instances for you. React Router makes the properties and methods of the <code>history</code> instance associated with your router available through the context, under the <code>router</code> object.</p>
<h3>1. Use the <code>withRouter</code> higher-order component</h3>
<p>The <code>withRouter</code> higher-order component will inject the <code>history</code> object as a prop of the component. This allows you to access the <code>push</code> and <code>replace</code> methods without having to deal with the <code>context</code>.</p>
<pre class="lang-js prettyprint-override"><code>import { withRouter } from 'react-router-dom'
// this also works with react-router-native
const Button = withRouter(({ history }) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
))
</code></pre>
<h3>2. Use composition and render a <code><Route></code></h3>
<p>The <code><Route></code> component isn't just for matching locations. You can render a pathless route and <strong>it will always match the current location</strong>. The <code><Route></code> component passes the same props as <code>withRouter</code>, so you will be able to access the <code>history</code> methods through the <code>history</code> prop.</p>
<pre class="lang-js prettyprint-override"><code>import { Route } from 'react-router-dom'
const Button = () => (
<Route render={({ history}) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
)} />
)
</code></pre>
<h3>3. Use the context*</h3>
<p><strong>But you probably should not</strong></p>
<p>The last option is one that you should only use if you feel comfortable working with React's <a href="https://facebook.github.io/react/docs/context.html" rel="noreferrer">context</a> model (React's Context API is stable as of v16).</p>
<pre class="lang-js prettyprint-override"><code>const Button = (props, context) => (
<button
type='button'
onClick={() => {
// context.history.push === history.push
context.history.push('/new-location')
}}
>
Click Me!
</button>
)
// you need to specify the context type so that it
// is available within the component
Button.contextTypes = {
history: React.PropTypes.shape({
push: React.PropTypes.func.isRequired
})
}
</code></pre>
<p>1 and 2 are the simplest choices to implement, so for most use cases, they are your best bets.</p> | {
"question_id": 31079081,
"question_date": "2015-06-26T17:38:51.977Z",
"question_score": 2099,
"tags": "reactjs|react-router",
"answer_id": 42121109,
"answer_date": "2017-02-08T18:39:41.177Z",
"answer_score": 2269
} |
Please answer the following Stack Overflow question:
Title: How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?
<p>How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?</p> | <p>You can use a library called ExcelLibrary. It's a free, open source library posted on Google Code:</p>
<p><a href="https://code.google.com/archive/p/excellibrary/" rel="noreferrer">ExcelLibrary</a></p>
<p>This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that functionality in.</p>
<p>It's very simple, small and easy to use. Plus it has a DataSetHelper that lets you use DataSets and DataTables to easily work with Excel data.</p>
<p>ExcelLibrary seems to still only work for the older Excel format (.xls files), but may be adding support in the future for newer 2007/2010 formats. </p>
<p>You can also use <a href="https://github.com/JanKallman/EPPlus" rel="noreferrer">EPPlus</a>, which works only for Excel 2007/2010 format files (.xlsx files). There's also <a href="https://github.com/tonyqus/npoi" rel="noreferrer">NPOI</a> which works with both.</p>
<p>There are a few known bugs with each library as noted in the comments. In all, EPPlus seems to be the best choice as time goes on. It seems to be more actively updated and documented as well.</p>
<p>Also, as noted by @АртёмЦарионов below, EPPlus has support for Pivot Tables and ExcelLibrary may have some support (<a href="https://code.google.com/archive/p/excellibrary/issues/98" rel="noreferrer">Pivot table issue in ExcelLibrary</a>)</p>
<p>Here are a couple links for quick reference:<br/>
<a href="https://code.google.com/archive/p/excellibrary/" rel="noreferrer">ExcelLibrary</a> - <a href="https://www.gnu.org/licenses/lgpl.html" rel="noreferrer">GNU Lesser GPL</a><br/>
<a href="https://github.com/JanKallman/EPPlus" rel="noreferrer">EPPlus</a> - <a href="https://github.com/JanKallman/EPPlus#license" rel="noreferrer">GNU (LGPL) - No longer maintained</a><br/>
<a href="https://www.epplussoftware.com/" rel="noreferrer">EPPlus 5</a> - <a href="https://www.epplussoftware.com/en/LicenseOverview" rel="noreferrer">Polyform Noncommercial - Starting May 2020</a><br/>
<a href="https://github.com/tonyqus/npoi" rel="noreferrer">NPOI</a> - <a href="https://github.com/tonyqus/npoi/blob/master/LICENSE" rel="noreferrer">Apache License</a></p>
<p><b>Here some example code for ExcelLibrary:</b></p>
<p>Here is an example taking data from a database and creating a workbook from it. Note that the ExcelLibrary code is the single line at the bottom:</p>
<pre><code>//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
//Open a DB connection (in this example with OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();
//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();
adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();
//Add the table to the data set
ds.Tables.Add(dt);
//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);
</code></pre>
<p>Creating the Excel file is as easy as that. You can also manually create Excel files, but the above functionality is what really impressed me.</p> | {
"question_id": 151005,
"question_date": "2008-09-29T22:30:28.680Z",
"question_score": 2098,
"tags": "c#|.net|excel|file-io",
"answer_id": 2603625,
"answer_date": "2010-04-08T21:36:03.573Z",
"answer_score": 1152
} |
Please answer the following Stack Overflow question:
Title: How can I git stash a specific file?
<p>How can I stash a specific file leaving the others currently modified out of the stash I am about to save?</p>
<p>For example, if git status gives me this:</p>
<pre><code>younker % gst
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
# Changes not staged for commit:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: app/controllers/cart_controller.php
# modified: app/views/cart/welcome.thtml
#
no changes added to commit (use "git add" and/or "git commit -a")
</code></pre>
<p>and I only want to stash app/views/cart/welcome.thtml, how would I do that? Something like (but of course this does not work):</p>
<pre><code>git stash save welcome_cart app/views/cart/welcome.thtml
</code></pre> | <p><strong>EDIT:</strong> Since git 2.13, there is a command to save a specific path to the stash: <code>git stash push <path></code>. For example: </p>
<pre><code>git stash push -m welcome_cart app/views/cart/welcome.thtml
</code></pre>
<p><strong>OLD ANSWER:</strong></p>
<p>You can do that using <code>git stash --patch</code> (or <code>git stash -p</code>) -- you'll enter interactive mode where you'll be presented with each hunk that was changed. Use <code>n</code> to skip the files that you don't want to stash, <code>y</code> when you encounter the one that you want to stash, and <code>q</code> to quit and leave the remaining hunks unstashed. <code>a</code> will stash the shown hunk and the rest of the hunks in that file.</p>
<p>Not the most user-friendly approach, but it gets the work done if you really need it.</p> | {
"question_id": 5506339,
"question_date": "2011-03-31T21:05:38.867Z",
"question_score": 2097,
"tags": "git|git-stash",
"answer_id": 5506483,
"answer_date": "2011-03-31T21:19:11.700Z",
"answer_score": 3014
} |
Please answer the following Stack Overflow question:
Title: How do I fetch all Git branches?
<p>I cloned a Git repository containing many branches. However, <code>git branch</code> only shows one:</p>
<pre><code>$ git branch
* master
</code></pre>
<p>How would I pull all the branches locally so when I do <code>git branch</code>, it shows the following?</p>
<pre><code>$ git branch
* master
* staging
* etc...
</code></pre> | <h3>TL;DR answer</h3>
<pre class="lang-sh prettyprint-override"><code>git branch -r | grep -v '\->' | sed "s,\x1B\[[0-9;]*[a-zA-Z],,g" | while read remote; do git branch --track "${remote#origin/}" "$remote"; done
git fetch --all
git pull --all
</code></pre>
<p>(It seems that pull fetches all branches from all remotes, but I always fetch first just to be sure.)</p>
<p>Run the first command only if there are remote branches on the server that aren't tracked by your local branches.</p>
<h3>Complete answer</h3>
<p>You can fetch all branches from all remotes like this:</p>
<pre><code>git fetch --all
</code></pre>
<p>It's basically a <a href="https://www.atlassian.com/git/tutorials/syncing/git-fetch" rel="noreferrer">power move</a>.</p>
<p><code>fetch</code> updates local copies of remote branches so this is always safe for your local branches <strong>BUT</strong>:</p>
<ol>
<li><p><code>fetch</code> will not <strong>update</strong> local branches (which <strong>track</strong> remote branches); if you want to update your local branches you still need to pull every branch.</p>
</li>
<li><p><code>fetch</code> will not <strong>create</strong> local branches (which <strong>track</strong> remote branches), you have to do this manually. If you want to list all remote branches:
<code>git branch -a</code></p>
</li>
</ol>
<p>To <strong>update</strong> local branches which track remote branches:</p>
<pre><code>git pull --all
</code></pre>
<p>However, this can be still insufficient. It will work only for your local branches which track remote branches. To track all remote branches execute this oneliner <strong>BEFORE</strong> <code>git pull --all</code>:</p>
<pre class="lang-sh prettyprint-override"><code>git branch -r | grep -v '\->' | sed "s,\x1B\[[0-9;]*[a-zA-Z],,g" | while read remote; do git branch --track "${remote#origin/}" "$remote"; done
</code></pre>
<p>P.S. AFAIK <code>git fetch --all</code> and <code>git remote update</code> are equivalent.</p>
<hr />
<hr />
<p>Kamil Szot's <a href="https://stackoverflow.com/questions/10312521/how-to-fetch-all-git-branches#comment27984640_10312587">comment</a>, which folks have found useful.</p>
<blockquote>
<p>I had to use:</p>
<pre><code>for remote in `git branch -r`; do git branch --track ${remote#origin/} $remote; done
</code></pre>
<p>because your code created local branches named <code>origin/branchname</code> and
I was getting "refname 'origin/branchname' is ambiguous whenever I
referred to it.</p>
</blockquote> | {
"question_id": 10312521,
"question_date": "2012-04-25T09:05:26.403Z",
"question_score": 2096,
"tags": "git|branch|git-branch",
"answer_id": 10312587,
"answer_date": "2012-04-25T09:10:23.977Z",
"answer_score": 2816
} |
Please answer the following Stack Overflow question:
Title: How do I delete an exported environment variable?
<p>Before installing <a href="https://en.wikipedia.org/wiki/Gnuplot" rel="noreferrer">gnuplot</a>, I set the environment variable <code>GNUPLOT_DRIVER_DIR = /home/gnuplot/build/src</code>. During the installation, something went wrong.</p>
<p>I want to remove the <code>GNUPLOT_DRIVER_DIR</code> environment variable. How can I achieve it?</p> | <p><code>unset</code> is the command you're looking for.</p>
<pre><code>unset GNUPLOT_DRIVER_DIR
</code></pre> | {
"question_id": 6877727,
"question_date": "2011-07-29T18:58:27.603Z",
"question_score": 2092,
"tags": "linux|environment-variables|unset",
"answer_id": 6877747,
"answer_date": "2011-07-29T19:00:39.337Z",
"answer_score": 3292
} |
Please answer the following Stack Overflow question:
Title: What's the difference between a method and a function?
<p>Can someone provide a simple explanation of <strong>methods</strong> vs. <strong>functions</strong> in OOP context?</p> | <p>A <strong>function</strong> is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.</p>
<p>A <strong>method</strong> is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:</p>
<ol>
<li>A method is implicitly passed the object on which it was called.</li>
<li>A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).</li>
</ol>
<p>(this is a simplified explanation, ignoring issues of <a href="http://en.wikipedia.org/wiki/Scope_(computer_science)" rel="noreferrer">scope</a> etc.)</p> | {
"question_id": 155609,
"question_date": "2008-09-30T23:45:10.007Z",
"question_score": 2089,
"tags": "oop|language-agnostic|terminology",
"answer_id": 155655,
"answer_date": "2008-10-01T00:00:13.977Z",
"answer_score": 2160
} |
Please answer the following Stack Overflow question:
Title: How can I see the changes in a Git commit?
<p>When I do <code>git diff COMMIT</code> I see the changes between that commit and HEAD (as far as I know), but I would like to see the changes that were made by that single commit.</p>
<p>I haven't found any obvious options on <code>diff</code> / <code>log</code> that will give me that output.</p> | <p>To see the diff for a particular <code>COMMIT</code> hash, where <code>COMMIT</code> is the hash of the commit:</p>
<p><code>git diff COMMIT~ COMMIT</code> will show you the difference between that <code>COMMIT</code>'s ancestor and the <code>COMMIT</code>. See the man pages for <a href="http://jk.gs/git-diff.html" rel="noreferrer">git diff</a> for details about the command and <a href="http://jk.gs/gitrevisions.html" rel="noreferrer">gitrevisions</a> about the <code>~</code> notation and its friends.</p>
<p>Alternatively, <code>git show COMMIT</code> will do something very similar. (The commit's data, including its diff - but not for merge commits.) See the <a href="http://jk.gs/git-show.html" rel="noreferrer">git show manpage</a>.</p>
<p>(also <code>git diff COMMIT</code> will show you the difference between that <code>COMMIT</code> and the head.)</p> | {
"question_id": 17563726,
"question_date": "2013-07-10T06:22:43.077Z",
"question_score": 2088,
"tags": "git|version-control|diff|git-diff",
"answer_id": 17563740,
"answer_date": "2013-07-10T06:23:49.177Z",
"answer_score": 2600
} |
Please answer the following Stack Overflow question:
Title: What is a smart pointer and when should I use one?
<p>What is a smart pointer and when should I use one?</p> | <p><strong>UPDATE</strong></p>
<p>This answer is rather old, and so describes what was 'good' at the time, which was smart pointers provided by the Boost library. Since C++11, the standard library has provided sufficient smart pointers types, and so you should favour the use of <a href="http://en.cppreference.com/w/cpp/memory/unique_ptr" rel="noreferrer"><code>std::unique_ptr</code></a>, <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr" rel="noreferrer"><code>std::shared_ptr</code></a> and <a href="http://en.cppreference.com/w/cpp/memory/weak_ptr" rel="noreferrer"><code>std::weak_ptr</code></a>. </p>
<p>There was also <a href="http://en.cppreference.com/w/cpp/memory/auto_ptr" rel="noreferrer"><code>std::auto_ptr</code></a>. It was very much like a scoped pointer, except that it also had the "special" dangerous ability to be copied — which also unexpectedly transfers ownership.<br>
<strong>It was deprecated in C++11 and removed in C++17</strong>, so you shouldn't use it.</p>
<pre><code>std::auto_ptr<MyObject> p1 (new MyObject());
std::auto_ptr<MyObject> p2 = p1; // Copy and transfer ownership.
// p1 gets set to empty!
p2->DoSomething(); // Works.
p1->DoSomething(); // Oh oh. Hopefully raises some NULL pointer exception.
</code></pre>
<hr>
<p><strong>OLD ANSWER</strong></p>
<p>A smart pointer is a class that wraps a 'raw' (or 'bare') C++ pointer, to manage the lifetime of the object being pointed to. There is no single smart pointer type, but all of them try to abstract a raw pointer in a practical way.</p>
<p>Smart pointers should be preferred over raw pointers. If you feel you need to use pointers (first consider if you <em>really</em> do), you would normally want to use a smart pointer as this can alleviate many of the problems with raw pointers, mainly forgetting to delete the object and leaking memory.</p>
<p>With raw pointers, the programmer has to explicitly destroy the object when it is no longer useful.</p>
<pre><code>// Need to create the object to achieve some goal
MyObject* ptr = new MyObject();
ptr->DoSomething(); // Use the object in some way
delete ptr; // Destroy the object. Done with it.
// Wait, what if DoSomething() raises an exception...?
</code></pre>
<p>A smart pointer by comparison defines a policy as to when the object is destroyed. You still have to create the object, but you no longer have to worry about destroying it.</p>
<pre><code>SomeSmartPtr<MyObject> ptr(new MyObject());
ptr->DoSomething(); // Use the object in some way.
// Destruction of the object happens, depending
// on the policy the smart pointer class uses.
// Destruction would happen even if DoSomething()
// raises an exception
</code></pre>
<p>The simplest policy in use involves the scope of the smart pointer wrapper object, such as implemented by <a href="http://www.boost.org/doc/libs/release/libs/smart_ptr/scoped_ptr.htm" rel="noreferrer"><code>boost::scoped_ptr</code></a> or <a href="http://en.cppreference.com/w/cpp/memory/unique_ptr" rel="noreferrer"><code>std::unique_ptr</code></a>. </p>
<pre><code>void f()
{
{
std::unique_ptr<MyObject> ptr(new MyObject());
ptr->DoSomethingUseful();
} // ptr goes out of scope --
// the MyObject is automatically destroyed.
// ptr->Oops(); // Compile error: "ptr" not defined
// since it is no longer in scope.
}
</code></pre>
<p>Note that <code>std::unique_ptr</code> instances cannot be copied. This prevents the pointer from being deleted multiple times (incorrectly). You can, however, pass references to it around to other functions you call.</p>
<p><code>std::unique_ptr</code>s are useful when you want to tie the lifetime of the object to a particular block of code, or if you embedded it as member data inside another object, the lifetime of that other object. The object exists until the containing block of code is exited, or until the containing object is itself destroyed.</p>
<p>A more complex smart pointer policy involves reference counting the pointer. This does allow the pointer to be copied. When the last "reference" to the object is destroyed, the object is deleted. This policy is implemented by <a href="http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm" rel="noreferrer"><code>boost::shared_ptr</code></a> and <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr" rel="noreferrer"><code>std::shared_ptr</code></a>.</p>
<pre><code>void f()
{
typedef std::shared_ptr<MyObject> MyObjectPtr; // nice short alias
MyObjectPtr p1; // Empty
{
MyObjectPtr p2(new MyObject());
// There is now one "reference" to the created object
p1 = p2; // Copy the pointer.
// There are now two references to the object.
} // p2 is destroyed, leaving one reference to the object.
} // p1 is destroyed, leaving a reference count of zero.
// The object is deleted.
</code></pre>
<p>Reference counted pointers are very useful when the lifetime of your object is much more complicated, and is not tied directly to a particular section of code or to another object.</p>
<p>There is one drawback to reference counted pointers — the possibility of creating a dangling reference:</p>
<pre><code>// Create the smart pointer on the heap
MyObjectPtr* pp = new MyObjectPtr(new MyObject())
// Hmm, we forgot to destroy the smart pointer,
// because of that, the object is never destroyed!
</code></pre>
<p>Another possibility is creating circular references:</p>
<pre><code>struct Owner {
std::shared_ptr<Owner> other;
};
std::shared_ptr<Owner> p1 (new Owner());
std::shared_ptr<Owner> p2 (new Owner());
p1->other = p2; // p1 references p2
p2->other = p1; // p2 references p1
// Oops, the reference count of of p1 and p2 never goes to zero!
// The objects are never destroyed!
</code></pre>
<p>To work around this problem, both Boost and C++11 have defined a <code>weak_ptr</code> to define a weak (uncounted) reference to a <code>shared_ptr</code>.</p> | {
"question_id": 106508,
"question_date": "2008-09-20T00:09:24.963Z",
"question_score": 2086,
"tags": "c++|pointers|c++11|smart-pointers|c++-faq",
"answer_id": 106614,
"answer_date": "2008-09-20T00:48:23.480Z",
"answer_score": 2019
} |
Please answer the following Stack Overflow question:
Title: Is there a way to run Python on Android?
<p>We are working on an <a href="http://en.wikipedia.org/wiki/S60_%28software_platform%29" rel="noreferrer">S60</a> version and this platform has a nice Python API..</p>
<p>However, there is nothing official about Python on Android, but since <a href="http://en.wikipedia.org/wiki/Jython" rel="noreferrer">Jython</a> exists, is there a way to let the snake and the robot work together??</p> | <p>One way is to use <a href="http://kivy.org/" rel="noreferrer">Kivy</a>:</p>
<blockquote>
<p>Open source Python library for rapid development of applications
that make use of innovative user interfaces, such as multi-touch apps.</p>
</blockquote>
<p></p>
<blockquote>
<p>Kivy runs on Linux, Windows, OS X, Android and iOS. You can run the same [python] code on all supported platforms.</p>
</blockquote>
<p><a href="https://play.google.com/store/apps/details?id=org.kivy.showcase" rel="noreferrer">Kivy Showcase app</a> </p> | {
"question_id": 101754,
"question_date": "2008-09-19T13:21:12.417Z",
"question_score": 2085,
"tags": "android|python|jython|ase|android-scripting",
"answer_id": 8189603,
"answer_date": "2011-11-18T21:49:45.343Z",
"answer_score": 1171
} |
Please answer the following Stack Overflow question:
Title: How to check if a column exists in a SQL Server table
<p>I need to add a specific column if it does not exist. I have something like the following, but it always returns false:</p>
<pre><code>IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTableName'
AND COLUMN_NAME = 'myColumnName')
</code></pre>
<p>How can I check if a column exists in a table of the SQL Server database?</p> | <p>SQL Server 2005 onwards:</p>
<pre><code>IF EXISTS(SELECT 1 FROM sys.columns
WHERE Name = N'columnName'
AND Object_ID = Object_ID(N'schemaName.tableName'))
BEGIN
-- Column Exists
END
</code></pre>
<p>Martin Smith's version is shorter:</p>
<pre><code>IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
BEGIN
-- Column Exists
END
</code></pre> | {
"question_id": 133031,
"question_date": "2008-09-25T12:34:00.093Z",
"question_score": 2083,
"tags": "sql-server|sql-server-2008|tsql|sql-server-2012|sql-server-2016",
"answer_id": 133057,
"answer_date": "2008-09-25T12:39:21.297Z",
"answer_score": 2277
} |
Please answer the following Stack Overflow question:
Title: How to return only the Date from a SQL Server DateTime datatype
<pre><code>SELECT GETDATE()
</code></pre>
<p>Returns: <code>2008-09-22 15:24:13.790</code></p>
<p>I want that date part without the time part: <code>2008-09-22 00:00:00.000</code></p>
<p>How can I get that?</p> | <pre><code>SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @your_date))
</code></pre>
<p>for example</p>
<pre><code>SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
</code></pre>
<p>gives me</p>
<pre><code>2008-09-22 00:00:00.000
</code></pre>
<p>Pros:</p>
<ul>
<li>No varchar<->datetime conversions required</li>
<li>No need to think about locale</li>
</ul> | {
"question_id": 113045,
"question_date": "2008-09-22T03:31:33.277Z",
"question_score": 2081,
"tags": "sql|date|tsql|datetime|sql-server-2008",
"answer_id": 113055,
"answer_date": "2008-09-22T03:34:16.873Z",
"answer_score": 2774
} |
Please answer the following Stack Overflow question:
Title: Download a specific tag with Git
<p>I'm trying to figure out how I can download a particular tag of a Git repository - it's one version behind the current version.</p>
<p>I saw there was a tag for the previous version on the git web page, with object name of something long hex number. </p>
<p>But the version name is "<code>Tagged release 1.1.5</code>" according the site.</p>
<p>I tried a command like this (with names changed):</p>
<pre><code>git clone http://git.abc.net/git/abc.git my_abc
</code></pre>
<p>And I did get something - a directory, a bunch of subdirectories, etc. </p>
<p>If it's the whole repository, how do I get at the version I'm seeking? If not, how do I download that particular version? </p> | <pre class="lang-bash prettyprint-override"><code>$ git clone
</code></pre>
<p>will give you the whole repository.</p>
<p>After the clone, you can list the tags with <code>$ git tag -l</code> and then checkout a specific tag:</p>
<pre class="lang-bash prettyprint-override"><code>$ git checkout tags/<tag_name>
</code></pre>
<p>Even better, checkout and create a branch (otherwise you will be on a branch named after the revision number of tag):</p>
<pre class="lang-bash prettyprint-override"><code>$ git checkout tags/<tag_name> -b <branch_name>
</code></pre> | {
"question_id": 791959,
"question_date": "2009-04-27T01:15:12.417Z",
"question_score": 2076,
"tags": "git|git-clone|git-tag",
"answer_id": 792027,
"answer_date": "2009-04-27T01:53:48.190Z",
"answer_score": 3020
} |
Please answer the following Stack Overflow question:
Title: How do I profile C++ code running on Linux?
<p>How do I find areas of my code that run slowly in a C++ application running on Linux?</p> | <p>If your goal is to use a profiler, use one of the suggested ones.</p>
<p>However, if you're in a hurry and you can manually interrupt your program under the debugger while it's being subjectively slow, there's a simple way to find performance problems.</p>
<p>Just halt it several times, and each time look at the call stack. If there is some code that is wasting some percentage of the time, 20% or 50% or whatever, that is the probability that you will catch it in the act on each sample. So, that is roughly the percentage of samples on which you will see it. There is no educated guesswork required. If you do have a guess as to what the problem is, this will prove or disprove it.</p>
<p>You may have multiple performance problems of different sizes. If you clean out any one of them, the remaining ones will take a larger percentage, and be easier to spot, on subsequent passes. This <em>magnification effect</em>, when compounded over multiple problems, can lead to truly massive speedup factors.</p>
<p><strong>Caveat</strong>: Programmers tend to be skeptical of this technique unless they've used it themselves. They will say that profilers give you this information, but that is only true if they sample the entire call stack, and then let you examine a random set of samples. (The summaries are where the insight is lost.) Call graphs don't give you the same information, because </p>
<ol>
<li>They don't summarize at the instruction level, and</li>
<li>They give confusing summaries in the presence of recursion.</li>
</ol>
<p>They will also say it only works on toy programs, when actually it works on any program, and it seems to work better on bigger programs, because they tend to have more problems to find. They will say it sometimes finds things that aren't problems, but that is only true if you see something <em>once</em>. If you see a problem on more than one sample, it is real.</p>
<p><strong>P.S.</strong> This can also be done on multi-thread programs if there is a way to collect call-stack samples of the thread pool at a point in time, as there is in Java.</p>
<p><strong>P.P.S</strong> As a rough generality, the more layers of abstraction you have in your software, the more likely you are to find that that is the cause of performance problems (and the opportunity to get speedup).</p>
<p><strong>Added</strong>: It might not be obvious, but the stack sampling technique works equally well in the presence of recursion. The reason is that the time that would be saved by removal of an instruction is approximated by the fraction of samples containing it, regardless of the number of times it may occur within a sample.</p>
<p>Another objection I often hear is: "<em>It will stop someplace random, and it will miss the real problem</em>".
This comes from having a prior concept of what the real problem is.
A key property of performance problems is that they defy expectations.
Sampling tells you something is a problem, and your first reaction is disbelief.
That is natural, but you can be sure if it finds a problem it is real, and vice-versa.</p>
<p><strong>Added</strong>: Let me make a Bayesian explanation of how it works. Suppose there is some instruction <code>I</code> (call or otherwise) which is on the call stack some fraction <code>f</code> of the time (and thus costs that much). For simplicity, suppose we don't know what <code>f</code> is, but assume it is either 0.1, 0.2, 0.3, ... 0.9, 1.0, and the prior probability of each of these possibilities is 0.1, so all of these costs are equally likely a-priori.</p>
<p>Then suppose we take just 2 stack samples, and we see instruction <code>I</code> on both samples, designated observation <code>o=2/2</code>. This gives us new estimates of the frequency <code>f</code> of <code>I</code>, according to this:</p>
<pre><code>Prior
P(f=x) x P(o=2/2|f=x) P(o=2/2&&f=x) P(o=2/2&&f >= x) P(f >= x | o=2/2)
0.1 1 1 0.1 0.1 0.25974026
0.1 0.9 0.81 0.081 0.181 0.47012987
0.1 0.8 0.64 0.064 0.245 0.636363636
0.1 0.7 0.49 0.049 0.294 0.763636364
0.1 0.6 0.36 0.036 0.33 0.857142857
0.1 0.5 0.25 0.025 0.355 0.922077922
0.1 0.4 0.16 0.016 0.371 0.963636364
0.1 0.3 0.09 0.009 0.38 0.987012987
0.1 0.2 0.04 0.004 0.384 0.997402597
0.1 0.1 0.01 0.001 0.385 1
P(o=2/2) 0.385
</code></pre>
<p>The last column says that, for example, the probability that <code>f</code> >= 0.5 is 92%, up from the prior assumption of 60%.</p>
<p>Suppose the prior assumptions are different. Suppose we assume <code>P(f=0.1)</code> is .991 (nearly certain), and all the other possibilities are almost impossible (0.001). In other words, our prior certainty is that <code>I</code> is cheap. Then we get:</p>
<pre><code>Prior
P(f=x) x P(o=2/2|f=x) P(o=2/2&& f=x) P(o=2/2&&f >= x) P(f >= x | o=2/2)
0.001 1 1 0.001 0.001 0.072727273
0.001 0.9 0.81 0.00081 0.00181 0.131636364
0.001 0.8 0.64 0.00064 0.00245 0.178181818
0.001 0.7 0.49 0.00049 0.00294 0.213818182
0.001 0.6 0.36 0.00036 0.0033 0.24
0.001 0.5 0.25 0.00025 0.00355 0.258181818
0.001 0.4 0.16 0.00016 0.00371 0.269818182
0.001 0.3 0.09 0.00009 0.0038 0.276363636
0.001 0.2 0.04 0.00004 0.00384 0.279272727
0.991 0.1 0.01 0.00991 0.01375 1
P(o=2/2) 0.01375
</code></pre>
<p>Now it says <code>P(f >= 0.5)</code> is 26%, up from the prior assumption of 0.6%. So Bayes allows us to update our estimate of the probable cost of <code>I</code>. If the amount of data is small, it doesn't tell us accurately what the cost is, only that it is big enough to be worth fixing.</p>
<p>Yet another way to look at it is called the <a href="http://en.wikipedia.org/wiki/Rule_of_succession" rel="noreferrer">Rule Of Succession</a>.
If you flip a coin 2 times, and it comes up heads both times, what does that tell you about the probable weighting of the coin?
The respected way to answer is to say that it's a Beta distribution, with average value <code>(number of hits + 1) / (number of tries + 2) = (2+1)/(2+2) = 75%</code>.</p>
<p>(The key is that we see <code>I</code> more than once. If we only see it once, that doesn't tell us much except that <code>f</code> > 0.)</p>
<p>So, even a very small number of samples can tell us a lot about the cost of instructions that it sees. (And it will see them with a frequency, on average, proportional to their cost. If <code>n</code> samples are taken, and <code>f</code> is the cost, then <code>I</code> will appear on <code>nf+/-sqrt(nf(1-f))</code> samples. Example, <code>n=10</code>, <code>f=0.3</code>, that is <code>3+/-1.4</code> samples.)</p>
<hr>
<p><strong>Added</strong>: To give an intuitive feel for the difference between measuring and random stack sampling:<br>
There are profilers now that sample the stack, even on wall-clock time, but <em>what comes out</em> is measurements (or hot path, or hot spot, from which a "bottleneck" can easily hide). What they don't show you (and they easily could) is the actual samples themselves. And if your goal is to <em>find</em> the bottleneck, the number of them you need to see is, <em>on average</em>, 2 divided by the fraction of time it takes.
So if it takes 30% of time, 2/.3 = 6.7 samples, on average, will show it, and the chance that 20 samples will show it is 99.2%.</p>
<p>Here is an off-the-cuff illustration of the difference between examining measurements and examining stack samples.
The bottleneck could be one big blob like this, or numerous small ones, it makes no difference.</p>
<p><a href="https://i.stack.imgur.com/FpWuS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FpWuS.png" alt="enter image description here"></a></p>
<p>Measurement is horizontal; it tells you what fraction of time specific routines take.
Sampling is vertical.
If there is any way to avoid what the whole program is doing at that moment, <em>and if you see it on a second sample</em>, you've found the bottleneck.
That's what makes the difference - seeing the whole reason for the time being spent, not just how much.</p> | {
"question_id": 375913,
"question_date": "2008-12-17T20:29:24.277Z",
"question_score": 2076,
"tags": "c++|linux|profiling",
"answer_id": 378024,
"answer_date": "2008-12-18T14:36:43.940Z",
"answer_score": 1560
} |
Please answer the following Stack Overflow question:
Title: What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?
<p>What's the difference between <code>INNER JOIN</code>, <code>LEFT JOIN</code>, <code>RIGHT JOIN</code> and <code>FULL JOIN</code>
in <strong><em>MySQL</em></strong>?</p> | <p>Reading this original article on <strong>The Code Project</strong> will help you a lot: <a href="https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins" rel="noreferrer">Visual Representation of SQL Joins</a>.</p>
<p><img src="https://i.stack.imgur.com/VQ5XP.png" alt="alt text" /></p>
<p>Also check this post: <a href="http://blog.sqlauthority.com/2008/04/22/sql-server-better-performance-left-join-or-not-in/" rel="noreferrer">SQL SERVER – Better Performance – LEFT JOIN or NOT IN?</a>.</p>
<p>Find original one at: <a href="https://stackoverflow.com/questions/3308122/how-do-i-decide-when-to-use-right-joins-left-joins-or-inner-joins-or-how-to-dete/3308153#3308153">Difference between JOIN and OUTER JOIN in MySQL</a>.</p> | {
"question_id": 5706437,
"question_date": "2011-04-18T17:15:24.680Z",
"question_score": 2075,
"tags": "mysql|sql|join|inner-join|outer-join",
"answer_id": 6188334,
"answer_date": "2011-05-31T13:29:46.900Z",
"answer_score": 3800
} |
Please answer the following Stack Overflow question:
Title: How to remove an element from a list by index
<p>How do I remove an element from a list <strong>by index</strong>?</p>
<p>I found <code>list.remove()</code>, but this slowly scans the list for an item <strong>by value</strong>.</p> | <p>Use <code>del</code> and specify the index of the element you want to delete:</p>
<pre><code>>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]
</code></pre>
<p>Also supports slices:</p>
<pre><code>>>> del a[2:4]
>>> a
[0, 1, 4, 5, 6, 7, 8, 9]
</code></pre>
<p><a href="http://docs.python.org/tutorial/datastructures.html#the-del-statement" rel="noreferrer">Here</a> is the section from the tutorial.</p> | {
"question_id": 627435,
"question_date": "2009-03-09T18:16:11.060Z",
"question_score": 2072,
"tags": "python|list|indexing",
"answer_id": 627453,
"answer_date": "2009-03-09T18:21:24.400Z",
"answer_score": 2336
} |
Please answer the following Stack Overflow question:
Title: Throw away local commits in Git
<p>Due to some bad cherry-picking, my local Git repository is currently five commits ahead of the origin, and not in a good state. I want to get rid of all these commits and start over again.</p>
<p>Obviously, deleting my working directory and re-cloning would do it, but downloading everything from GitHub again seems like overkill, and not a good use of my time.</p>
<p>Maybe <code>git revert</code> is what I need, but I don't want to end up <em>10</em> commits ahead of the origin (or even six), even if it does get the code itself back to the right state. I just want to pretend the last half-hour never happened.</p>
<p>Is there a simple command that will do this? It seems like an obvious use case, but I'm not finding any examples of it.</p>
<hr>
<p>Note that this question is specifically about <em>commits</em>, <em>not</em> about:</p>
<ul>
<li>untracked files</li>
<li>unstaged changes</li>
<li>staged, but uncommitted changes</li>
</ul> | <p>If your excess commits are only visible to you, you can just do
<code>git reset --hard origin/<branch_name></code>
to move back to where the origin is. This will reset the state of the repository to the previous commit, and it will discard all local changes.</p>
<p>Doing a <code>git revert</code> makes <em>new</em> commits to remove <em>old</em> commits in a way that keeps everyone's history sane.</p> | {
"question_id": 5097456,
"question_date": "2011-02-23T21:33:55.633Z",
"question_score": 2072,
"tags": "git",
"answer_id": 5097495,
"answer_date": "2011-02-23T21:38:10.577Z",
"answer_score": 3369
} |
Please answer the following Stack Overflow question:
Title: How do you stash an untracked file?
<p>I have changes to a file, plus a new file, and would like to use git stash to put them away while I switch to another task. But git stash by itself stashes only the changes to the existing file; the new file remains in my working tree, cluttering up my future work. How do I stash this untracked file?</p> | <p>To stash your working directory including untracked files (especially those that are in the <code>.gitignore</code>) then you probably want to use this cmd:</p>
<pre class="lang-sh prettyprint-override"><code>git stash --include-untracked
</code></pre>
<p>Alternatively, you can use the shorthand <code>-u</code> instead of <code>--include-untracked</code>, or simply <code>git stash --all</code> which stashes all files, including <strong>untracked</strong> and <strong>ignored</strong> files. This bahaviour changed in 2018, so make sure your git is up to date.</p>
<hr />
<p><strong>Warning: there seems to be (or have been) situations in which contents of ignored directories could be deleted permanently. <a href="http://web.archive.org/web/20140310215100/http://blog.icefusion.co.uk:80/git-stash-can-delete-ignored-files-git-stash-u/" rel="noreferrer">See this archived website for more information</a></strong>.</p> | {
"question_id": 835501,
"question_date": "2009-05-07T15:54:20.423Z",
"question_score": 2069,
"tags": "git|git-stash",
"answer_id": 835561,
"answer_date": "2009-05-07T16:02:50.870Z",
"answer_score": 2962
} |
Please answer the following Stack Overflow question:
Title: Determine the type of an object?
<p>Is there a simple way to determine if a variable is a list, dictionary, or something else?</p> | <p>There are two built-in functions that help you identify the type of an object. You can use <a href="http://docs.python.org/3/library/functions.html#type" rel="noreferrer"><code>type()</code></a> if you need the exact type of an object, and <a href="http://docs.python.org/3/library/functions.html#isinstance" rel="noreferrer"><code>isinstance()</code></a> to <em>check</em> an object’s type against something. Usually, you want to use <code>isinstance()</code> most of the times since it is very robust and also supports type inheritance.</p>
<hr />
<p>To get the actual type of an object, you use the built-in <a href="http://docs.python.org/3/library/functions.html#type" rel="noreferrer"><code>type()</code></a> function. Passing an object as the only parameter will return the type object of that object:</p>
<pre><code>>>> type([]) is list
True
>>> type({}) is dict
True
>>> type('') is str
True
>>> type(0) is int
True
</code></pre>
<p>This of course also works for custom types:</p>
<pre><code>>>> class Test1 (object):
pass
>>> class Test2 (Test1):
pass
>>> a = Test1()
>>> b = Test2()
>>> type(a) is Test1
True
>>> type(b) is Test2
True
</code></pre>
<p>Note that <code>type()</code> will only return the immediate type of the object, but won’t be able to tell you about type inheritance.</p>
<pre><code>>>> type(b) is Test1
False
</code></pre>
<p>To cover that, you should use the <a href="http://docs.python.org/3/library/functions.html#isinstance" rel="noreferrer"><code>isinstance</code></a> function. This of course also works for built-in types:</p>
<pre><code>>>> isinstance(b, Test1)
True
>>> isinstance(b, Test2)
True
>>> isinstance(a, Test1)
True
>>> isinstance(a, Test2)
False
>>> isinstance([], list)
True
>>> isinstance({}, dict)
True
</code></pre>
<p><code>isinstance()</code> is usually the preferred way to ensure the type of an object because it will also accept derived types. So unless you actually need the type object (for whatever reason), using <code>isinstance()</code> is preferred over <code>type()</code>.</p>
<p>The second parameter of <code>isinstance()</code> also accepts a tuple of types, so it’s possible to check for multiple types at once. <code>isinstance</code> will then return true, if the object is of any of those types:</p>
<pre><code>>>> isinstance([], (tuple, list, set))
True
</code></pre> | {
"question_id": 2225038,
"question_date": "2010-02-08T21:37:20.240Z",
"question_score": 2060,
"tags": "python|dictionary|types|typeof",
"answer_id": 2225066,
"answer_date": "2010-02-08T21:40:06.563Z",
"answer_score": 2233
} |
Please answer the following Stack Overflow question:
Title: Short circuit Array.forEach like calling break
<pre><code>[1,2,3].forEach(function(el) {
if(el === 1) break;
});
</code></pre>
<p>How can I do this using the new <code>forEach</code> method in JavaScript? I've tried <code>return;</code>, <code>return false;</code> and <code>break</code>. <code>break</code> crashes and <code>return</code> does nothing but continue iteration.</p> | <p>There's no built-in ability to <code>break</code> in <code>forEach</code>. To interrupt execution you would have to throw an exception of some sort. eg.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var BreakException = {};
try {
[1, 2, 3].forEach(function(el) {
console.log(el);
if (el === 2) throw BreakException;
});
} catch (e) {
if (e !== BreakException) throw e;
}</code></pre>
</div>
</div>
</p>
<p>JavaScript exceptions aren't terribly pretty. A traditional <code>for</code> loop might be more appropriate if you really need to <code>break</code> inside it. </p>
<h2>Use <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/some" rel="noreferrer"><code>Array#some</code></a></h2>
<p>Instead, use <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/some" rel="noreferrer"><code>Array#some</code></a>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>[1, 2, 3].some(function(el) {
console.log(el);
return el === 2;
});</code></pre>
</div>
</div>
</p>
<p>This works because <code>some</code> returns <code>true</code> as soon as any of the callbacks, executed in array order, return <code>true</code>, short-circuiting the execution of the rest.</p>
<p><code>some</code>, its inverse <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/every" rel="noreferrer"><code>every</code></a> (which will stop on a <code>return false</code>), and <code>forEach</code> are all ECMAScript Fifth Edition methods which will need to be added to the <code>Array.prototype</code> on browsers where they're missing.</p> | {
"question_id": 2641347,
"question_date": "2010-04-14T21:57:31.967Z",
"question_score": 2054,
"tags": "javascript|arrays|foreach",
"answer_id": 2641374,
"answer_date": "2010-04-14T22:02:14.630Z",
"answer_score": 2710
} |
Please answer the following Stack Overflow question:
Title: How to lazy load images in ListView in Android
<p>I am using a <code>ListView</code> to display some images and captions associated with those images. I am getting the images from the Internet. Is there a way to lazy load images so while the text displays, the UI is not blocked and images are displayed as they are downloaded? </p>
<p>The total number of images is not fixed.</p> | <p>Here's what I created to hold the images that my app is currently displaying. Please note that the "Log" object in use here is my custom wrapper around the final Log class inside Android.</p>
<pre><code>package com.wilson.android.library;
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
import java.io.IOException;
public class DrawableManager {
private final Map<String, Drawable> drawableMap;
public DrawableManager() {
drawableMap = new HashMap<String, Drawable>();
}
public Drawable fetchDrawable(String urlString) {
if (drawableMap.containsKey(urlString)) {
return drawableMap.get(urlString);
}
Log.d(this.getClass().getSimpleName(), "image url:" + urlString);
try {
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
if (drawable != null) {
drawableMap.put(urlString, drawable);
Log.d(this.getClass().getSimpleName(), "got a thumbnail drawable: " + drawable.getBounds() + ", "
+ drawable.getIntrinsicHeight() + "," + drawable.getIntrinsicWidth() + ", "
+ drawable.getMinimumHeight() + "," + drawable.getMinimumWidth());
} else {
Log.w(this.getClass().getSimpleName(), "could not get thumbnail");
}
return drawable;
} catch (MalformedURLException e) {
Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
return null;
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
return null;
}
}
public void fetchDrawableOnThread(final String urlString, final ImageView imageView) {
if (drawableMap.containsKey(urlString)) {
imageView.setImageDrawable(drawableMap.get(urlString));
}
final Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message message) {
imageView.setImageDrawable((Drawable) message.obj);
}
};
Thread thread = new Thread() {
@Override
public void run() {
//TODO : set imageView to a "pending" image
Drawable drawable = fetchDrawable(urlString);
Message message = handler.obtainMessage(1, drawable);
handler.sendMessage(message);
}
};
thread.start();
}
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
}
</code></pre> | {
"question_id": 541966,
"question_date": "2009-02-12T15:59:00.827Z",
"question_score": 2053,
"tags": "android|image|listview|url|universal-image-loader",
"answer_id": 559781,
"answer_date": "2009-02-18T03:56:58.083Z",
"answer_score": 1145
} |
Please answer the following Stack Overflow question:
Title: PostgreSQL "DESCRIBE TABLE"
<p>How do you perform the equivalent of Oracle's <code>DESCRIBE TABLE</code> in PostgreSQL (using the psql command)?</p> | <p>Try this (in the <code>psql</code> command-line tool):</p>
<pre><code>\d+ tablename
</code></pre>
<p>See <a href="http://www.postgresql.org/docs/current/interactive/app-psql.html#APP-PSQL-META-COMMANDS" rel="noreferrer">the manual</a> for more info.</p> | {
"question_id": 109325,
"question_date": "2008-09-20T20:47:48.917Z",
"question_score": 2052,
"tags": "postgresql|psql|table-structure",
"answer_id": 109334,
"answer_date": "2008-09-20T20:50:17.243Z",
"answer_score": 3044
} |
Please answer the following Stack Overflow question:
Title: How to reload .bashrc settings without logging out and back in again?
<p>If I make changes to <code>.bashrc</code>, how do I reload it without logging out and back in?</p> | <p>You can enter the long form command:</p>
<pre><code>source ~/.bashrc
</code></pre>
<p>or you can use the shorter version of the command:</p>
<pre><code>. ~/.bashrc
</code></pre> | {
"question_id": 2518127,
"question_date": "2010-03-25T17:58:36.267Z",
"question_score": 2051,
"tags": "bash|shell|terminal|reload|profile",
"answer_id": 2518150,
"answer_date": "2010-03-25T18:01:04.580Z",
"answer_score": 3262
} |
Please answer the following Stack Overflow question:
Title: Comparing Java enum members: == or equals()?
<p>I know that Java enums are compiled to classes with private constructors and a bunch of public static members. When comparing two members of a given enum, I've always used <code>.equals()</code>, e.g.</p>
<pre><code>public useEnums(SomeEnum a)
{
if(a.equals(SomeEnum.SOME_ENUM_VALUE))
{
...
}
...
}
</code></pre>
<p>However, I just came across some code that uses the equals operator <code>==</code> instead of .equals():</p>
<pre><code>public useEnums2(SomeEnum a)
{
if(a == SomeEnum.SOME_ENUM_VALUE)
{
...
}
...
}
</code></pre>
<p>Which operator is the one I should be using?</p> | <p>Both are technically correct. If you look at the source code for <code>.equals()</code>, it simply defers to <code>==</code>.</p>
<p>I use <code>==</code>, however, as that will be null safe.</p> | {
"question_id": 1750435,
"question_date": "2009-11-17T17:26:27.227Z",
"question_score": 2049,
"tags": "java|enums",
"answer_id": 1750453,
"answer_date": "2009-11-17T17:29:35.577Z",
"answer_score": 1880
} |
Please answer the following Stack Overflow question:
Title: RegEx match open tags except XHTML self-contained tags
<p>I need to match all of these opening tags:</p>
<pre><code><p>
<a href="foo">
</code></pre>
<p>But not these:</p>
<pre><code><br />
<hr class="foo" />
</code></pre>
<p>I came up with this and wanted to make sure I've got it right. I am only capturing the <code>a-z</code>.</p>
<pre><code><([a-z]+) *[^/]*?>
</code></pre>
<p>I believe it says:</p>
<ul>
<li>Find a less-than, then</li>
<li>Find (and capture) a-z one or more times, then</li>
<li>Find zero or more spaces, then</li>
<li>Find any character zero or more times, greedy, except <code>/</code>, then</li>
<li>Find a greater-than</li>
</ul>
<p>Do I have that right? And more importantly, what do you think?</p> | <p>You can't parse [X]HTML with regex. Because HTML can't be parsed by regex. Regex is not a tool that can be used to correctly parse HTML. As I have answered in HTML-and-regex questions here so many times before, the use of regex will not allow you to consume HTML. Regular expressions are a tool that is insufficiently sophisticated to understand the constructs employed by HTML. HTML is not a regular language and hence cannot be parsed by regular expressions. Regex queries are not equipped to break down HTML into its meaningful parts. so many times but it is not getting to me. Even enhanced irregular regular expressions as used by Perl are not up to the task of parsing HTML. You will never make me crack. HTML is a language of sufficient complexity that it cannot be parsed by regular expressions. Even Jon Skeet cannot parse HTML using regular expressions. Every time you attempt to parse HTML with regular expressions, the unholy child weeps the blood of virgins, and Russian hackers pwn your webapp. Parsing HTML with regex summons tainted souls into the realm of the living. HTML and regex go together like love, marriage, and ritual infanticide. The <center> cannot hold it is too late. The force of regex and HTML together in the same conceptual space will destroy your mind like so much watery putty. If you parse HTML with regex you are giving in to Them and their blasphemous ways which doom us all to inhuman toil for the One whose Name cannot be expressed in the Basic Multilingual Plane, he comes. HTML-plus-regexp will liquify the nerves of the sentient whilst you observe, your psyche withering in the onslaught of horror. Rege̿̔̉x-based HTML parsers are the cancer that is killing StackOverflow <i>it is too late it is too late we cannot be saved</i> the transgression of a chi͡ld ensures regex will consume all living tissue (except for HTML which it cannot, as previously prophesied) <i>dear lord help us how can anyone survive this scourge</i> using regex to parse HTML has doomed humanity to an eternity of dread torture and security holes <i>using rege</i>x as a tool to process HTML establishes a brea<i>ch between this world</i> and the dread realm of c͒ͪo͛ͫrrupt entities (like SGML entities, but <i>more corrupt) a mere glimp</i>se of the world of reg<b>ex parsers for HTML will ins</b>tantly transport a p<i>rogrammer's consciousness i</i>nto a w<i>orl</i>d of ceaseless screaming, he comes<strike>, the pestilent sl</strike>ithy regex-infection wil<b>l devour your HT</b>ML parser, application and existence for all time like Visual Basic only worse <i>he comes he com</i>es <i>do not fi</i>ght h<b>e com̡e̶s, ̕h̵i</b>s un̨ho͞ly radiańcé de<i>stro҉ying all enli̍̈́̂̈́ghtenment, HTML tags <b>lea͠ki̧n͘g fr̶ǫm ̡yo͟ur eye͢s̸ ̛l̕ik͏e liq</b>uid p</i>ain, the song of re̸gular expre<strike>ssion parsing </strike>will exti<i>nguish the voices of mor<b>tal man from the sp</b>here I can see it can you see ̲͚̖͔̙î̩́t̲͎̩̱͔́̋̀ it is beautiful t</i>he f<code>inal snuf</code>fing o<i>f the lie<b>s of Man ALL IS LOŚ͖̩͇̗̪̏̈́T A</b></i><b>LL IS L</b>OST th<i>e pon̷y he come</i>s he c̶̮om<strike>es he co</strike><b><strike>me</strike>s t<i>he</i> ich</b>or permeat<i>es al</i>l MY FAC<i>E MY FACE ᵒh god n<b>o NO NOO̼</b></i><b>OO N</b>Θ stop t<i>he an*̶͑̾̾̅ͫ͏̙̤g͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͥͨ</i>e̠̅s<code> ͎a̧͈͖r̽̾̈́͒͑e</code> n<b>ot rè̑ͧ̌aͨl̘̝̙̃ͤ͂̾̆ ZA̡͊͠͝LGΌ ISͮ̂҉̯͈͕̹̘̱ T</b>O͇̹̺ͅƝ̴ȳ̳ TH̘<b>Ë͖́̉ ͠P̯͍̭O̚N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝</b>S̨̥̫͎̭ͯ̿̔̀ͅ</p>
<hr />
<p>Have you tried using an XML parser instead?</p>
<hr />
<blockquote>
<p><strong>Moderator's Note</strong></p>
<p>This post is locked to prevent inappropriate edits to its content. The post looks exactly as it is supposed to look - there are no problems with its content. Please do not flag it for our attention.</p>
</blockquote> | {
"question_id": 1732348,
"question_date": "2009-11-13T22:38:26.177Z",
"question_score": 2047,
"tags": "html|regex|xhtml",
"answer_id": 1732454,
"answer_date": "2009-11-13T23:04:30.740Z",
"answer_score": 4409
} |
Please answer the following Stack Overflow question:
Title: Is there a way to cache https credentials for pushing commits?
<p>I recently switched to synchronizing my repositories to https:// on GitHub (due to firewall issues), and it asks for a password every time.</p>
<p>Is there a way to cache the credentials, instead of authenticating every time that <code>git push</code>?</p> | <p>Since Git 1.7.9 (released 2012), there is a neat mechanism in Git to avoid having to type your password all the time for HTTP / HTTPS, called <a href="http://www.kernel.org/pub/software/scm/git/docs/gitcredentials.html" rel="noreferrer">credential helpers</a>.</p>
<p>You can just use one of the following credential helpers:</p>
<pre><code>git config --global credential.helper cache
</code></pre>
<p>The <a href="https://git-scm.com/docs/git-credential-cache" rel="noreferrer">credential.helper cache value</a> tells Git to keep your password cached in memory for a particular amount of <strong>minutes</strong>. The default is 15 minutes, you can set a longer timeout with:</p>
<pre><code># Cache for 1 hour
git config --global credential.helper "cache --timeout=3600"
# Cache for 1 day
git config --global credential.helper "cache --timeout=86400"
# Cache for 1 week
git config --global credential.helper "cache --timeout=604800"
</code></pre>
<p>You can also store your credentials permanently if so desired, see the other answers below.</p>
<p>GitHub's help <a href="https://help.github.com/articles/set-up-git#platform-mac" rel="noreferrer">also suggests</a> that if you're on Mac OS X and used <a href="https://en.wikipedia.org/wiki/Homebrew_%28package_management_software%29" rel="noreferrer">Homebrew</a> to install Git, you can use the native Mac OS X keystore with:</p>
<pre><code>git config --global credential.helper osxkeychain
</code></pre>
<p><strong>For Windows</strong>, there is a helper called <a href="https://github.com/Microsoft/Git-Credential-Manager-for-Windows" rel="noreferrer">Git Credential Manager for Windows</a> or <a href="https://stackoverflow.com/questions/11693074/git-credential-cache-is-not-a-git-command">wincred in msysgit</a>.</p>
<pre><code>git config --global credential.helper wincred # obsolete
</code></pre>
<p>With <a href="https://github.com/git-for-windows/git/releases/tag/v2.7.3.windows.1" rel="noreferrer">Git for Windows 2.7.3+</a> (March 2016):</p>
<pre><code>git config --global credential.helper manager
</code></pre>
<p><strong>For Linux</strong>, you would use (in 2011) <a href="https://stackoverflow.com/questions/13385690/how-to-use-git-with-gnome-keyring-integration"><code>gnome-keyring</code></a>(or other keyring implementation such as KWallet).</p>
<p>Nowadays (2020), that would be (on Linux)</p>
<h3>Fedora</h3>
<pre class="lang-bash prettyprint-override"><code>sudo dnf install git-credential-libsecret
git config --global credential.helper /usr/libexec/git-core/git-credential-libsecret
</code></pre>
<h3>Ubuntu</h3>
<pre><code>sudo apt-get install libsecret-1-0 libsecret-1-dev
cd /usr/share/doc/git/contrib/credential/libsecret
sudo make
git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret
</code></pre> | {
"question_id": 5343068,
"question_date": "2011-03-17T17:47:44.053Z",
"question_score": 2045,
"tags": "git|github|git-push|git-config",
"answer_id": 5343146,
"answer_date": "2011-03-17T17:54:13.077Z",
"answer_score": 2563
} |
Please answer the following Stack Overflow question:
Title: What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?
<p>The "N+1 selects problem" is generally stated as a problem in Object-Relational mapping (ORM) discussions, and I understand that it has something to do with having to make a lot of database queries for something that seems simple in the object world.</p>
<p>Does anybody have a more detailed explanation of the problem?</p> | <p>Let's say you have a collection of <code>Car</code> objects (database rows), and each <code>Car</code> has a collection of <code>Wheel</code> objects (also rows). In other words, <code>Car</code> → <code>Wheel</code> is a 1-to-many relationship.</p>
<p>Now, let's say you need to iterate through all the cars, and for each one, print out a list of the wheels. The naive O/R implementation would do the following:</p>
<pre><code>SELECT * FROM Cars;
</code></pre>
<p>And then <strong>for each <code>Car</code>:</strong></p>
<pre><code>SELECT * FROM Wheel WHERE CarId = ?
</code></pre>
<p>In other words, you have one select for the Cars, and then N additional selects, where N is the total number of cars.</p>
<p>Alternatively, one could get all wheels and perform the lookups in memory:</p>
<pre><code>SELECT * FROM Wheel;
</code></pre>
<p>This reduces the number of round-trips to the database from N+1 to 2.
Most ORM tools give you several ways to prevent N+1 selects.</p>
<p>Reference: <em><a href="http://www.manning.com/bauer2/" rel="noreferrer">Java Persistence with Hibernate</a></em>, chapter 13.</p> | {
"question_id": 97197,
"question_date": "2008-09-18T21:30:00.963Z",
"question_score": 2044,
"tags": "database|orm",
"answer_id": 97253,
"answer_date": "2008-09-18T21:36:40.683Z",
"answer_score": 1367
} |
Please answer the following Stack Overflow question:
Title: Remove file from latest commit
<p>How do I remove a file from the latest commit?</p> | <p>I think other answers here are wrong, because this is a question of moving the mistakenly committed files back to the staging area from the previous commit, without cancelling the changes done to them. This can be done like Paritosh Singh suggested:</p>
<pre><code>git reset --soft HEAD^
</code></pre>
<p>or</p>
<pre><code>git reset --soft HEAD~1
</code></pre>
<p>Then reset the unwanted files in order to leave them out from the commit (the old way):</p>
<pre><code>git reset HEAD path/to/unwanted_file
</code></pre>
<p>Note, that since Git <code>2.23.0</code> one can (<strong>the new way</strong>):</p>
<pre><code>git restore --staged path/to/unwanted_file
</code></pre>
<p>Now commit again, you can even re-use the same commit message:</p>
<pre><code>git commit -c ORIG_HEAD
</code></pre> | {
"question_id": 12481639,
"question_date": "2012-09-18T16:59:12.070Z",
"question_score": 2043,
"tags": "git|git-commit",
"answer_id": 15321456,
"answer_date": "2013-03-10T10:56:37.877Z",
"answer_score": 3835
} |
Please answer the following Stack Overflow question:
Title: Copy array by value
<p>When copying an array in JavaScript to another array:</p>
<pre><code>var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d'); //Now, arr1 = ['a','b','c','d']
</code></pre>
<p>I realized that <code>arr2</code> refers to the same array as <code>arr1</code>, rather than a new, independent array. How can I copy the array to get two independent arrays?</p> | <p>Use this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let oldArray = [1, 2, 3, 4, 5];
let newArray = oldArray.slice();
console.log({newArray});</code></pre>
</div>
</div>
</p>
<p>Basically, the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice" rel="noreferrer"><code>slice()</code></a> operation clones the array and returns a reference to a new array.</p>
<h3>Also note that:</h3>
<p>For references, strings and numbers (and not the actual object), <strong><code>slice()</code> copies object references into the new array.</strong> Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.</p>
<p>Primitives such as strings and numbers are immutable, so changes to the string or number are impossible.</p> | {
"question_id": 7486085,
"question_date": "2011-09-20T13:38:08.950Z",
"question_score": 2043,
"tags": "javascript|arrays",
"answer_id": 7486130,
"answer_date": "2011-09-20T13:41:21.113Z",
"answer_score": 3029
} |
Please answer the following Stack Overflow question:
Title: NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack
<p>I'm trying to summarize my knowledge about the most popular JavaScript package managers, bundlers, and task runners. Please correct me if I'm wrong:</p>
<ul>
<li><code>npm</code> & <code>bower</code> are package managers. They just download the dependencies and don't know how to build projects on their own. What they know is to call <code>webpack</code>/<code>gulp</code>/<code>grunt</code> after fetching all the dependencies.</li>
<li><code>bower</code> is like <code>npm</code>, but builds a flattened dependency trees (unlike <code>npm</code> which does it recursively). Meaning <code>npm</code> fetches the dependencies for each dependency (may fetch the same a few times), while <code>bower</code> expects you to manually include sub-dependencies. Sometimes <code>bower</code> and <code>npm</code> are used together for front-end and back-end respectively (since each megabyte might matter in front-end).</li>
<li><code>grunt</code> and <code>gulp</code> are task runners to automate everything that can be automated (i.e. compile CSS/Sass, optimize images, make a bundle and minify/transpile it).</li>
<li><code>grunt</code> vs. <code>gulp</code> (is like <code>maven</code> vs. <code>gradle</code> or configuration vs. code). Grunt is based on configuring separate independent tasks, each task opens/handles/closes file. Gulp requires less amount of code and is based on Node streams, which allows it to build pipe chains (w/o reopening the same file) and makes it faster. </li>
<li><code>webpack</code> (<code>webpack-dev-server</code>) - for me it's a task runner with hot reloading of changes which allows you to forget about all JS/CSS watchers. </li>
<li><code>npm</code>/<code>bower</code> + plugins may replace task runners. Their abilities often intersect so there are different implications if you need to use <code>gulp</code>/<code>grunt</code> over <code>npm</code> + plugins. But task runners are definitely better for complex tasks (e.g. "on each build create bundle, transpile from ES6 to ES5, run it at all browsers emulators, make screenshots and deploy to dropbox through ftp").</li>
<li><code>browserify</code> allows packaging node modules for browsers. <code>browserify</code> vs <code>node</code>'s <code>require</code> is actually <a href="https://addyosmani.com/writing-modular-js/" rel="noreferrer">AMD vs CommonJS</a>.</li>
</ul>
<p><strong><em>Questions:</em></strong></p>
<ol>
<li><em>What is <code>webpack</code> & <code>webpack-dev-server</code>?</em> Official documentation says it's a module bundler but for me it's just a task runner. <em>What's the difference?</em></li>
<li><em>Where would you use <code>browserify</code>? Can't we do the same with node/ES6 imports?</em> </li>
<li><em>When would you use <code>gulp</code>/<code>grunt</code> over <code>npm</code> + plugins?</em></li>
<li><em>Please provide examples when you need to use a combination</em></li>
</ol> | <h3>Webpack and Browserify</h3>
<p>Webpack and Browserify do pretty much the same job, which is <strong>processing your code to be used in a target environment</strong> (mainly browser, though you can target other environments like Node). Result of such processing is one or more <strong>bundles</strong> - assembled scripts suitable for targeted environment. </p>
<p>For example, let's say you wrote ES6 code divided into modules and want to be able to run it in a browser. If those modules are Node modules, the browser won't understand them since they exist only in the Node environment. ES6 modules also won't work in older browsers like IE11. Moreover, you might have used experimental language features (ES next proposals) that browsers don't implement yet so running such script would just throw errors. Tools like Webpack and Browserify solve these problems by <strong>translating such code to a form a browser is able to execute</strong>. On top of that, they make it possible to apply a huge variety of optimisations on those bundles.</p>
<p>However, Webpack and Browserify differ in many ways, Webpack offers many tools by default (e.g. code splitting), while Browserify can do this only after downloading plugins but <strong>using both leads to very similar results</strong>. It comes down to personal preference (Webpack is trendier). Btw, Webpack is not a task runner, it is just processor of your files (it processes them by so called loaders and plugins) and it can be run (among other ways) by a task runner.</p>
<hr>
<h3>Webpack Dev Server</h3>
<p>Webpack Dev Server provides a similar solution to Browsersync - a development server where you can deploy your app rapidly as you are working on it, and verify your development progress immediately, with the dev server automatically refreshing the browser on code changes or even propagating changed code to browser without reloading with so called hot module replacement.</p>
<hr>
<h3>Task runners vs NPM scripts</h3>
<p>I've been using Gulp for its conciseness and easy task writing, but have later found out I need neither Gulp nor Grunt at all. Everything I have ever needed could have been done using NPM scripts to run 3rd-party tools through their API. <strong>Choosing between Gulp, Grunt or NPM scripts depends on taste and experience of your team.</strong></p>
<p>While tasks in Gulp or Grunt are easy to read even for people not so familiar with JS, it is yet another tool to require and learn and I personally prefer to narrow my dependencies and make things simple. On the other hand, replacing these tasks with the combination of NPM scripts and (propably JS) scripts which run those 3rd party tools (eg. Node script configuring and running <a href="https://github.com/isaacs/rimraf" rel="noreferrer">rimraf</a> for cleaning purposes) might be more challenging. But in the majority of cases, <strong>those three are equal in terms of their results.</strong></p>
<hr>
<h3>Examples</h3>
<p>As for the examples, I suggest you have a look at this <a href="https://github.com/kriasoft/react-starter-kit" rel="noreferrer">React starter project</a>, which shows you a nice combination of NPM and JS scripts covering the whole build and deploy process. You can find those NPM scripts in <code>package.json</code> in the root folder, in a property named <code>scripts</code>. There you will mostly encounter commands like <code>babel-node tools/run start</code>. Babel-node is a CLI tool (not meant for production use), which at first compiles ES6 file <code>tools/run</code> (run.js file located in <a href="https://github.com/kriasoft/react-starter-kit/tree/master/tools" rel="noreferrer">tools</a>) - basically a runner utility. This runner takes a function as an argument and executes it, which in this case is <code>start</code> - another utility (<code>start.js</code>) responsible for bundling source files (both client and server) and starting the application and development server (the dev server will be probably either Webpack Dev Server or Browsersync).</p>
<p>Speaking more precisely, <code>start.js</code> creates both client and server side bundles, starts an express server and after a successful launch initializes Browser-sync, which at the time of writing looked like this (please refer to <a href="https://github.com/kriasoft/react-starter-kit" rel="noreferrer">react starter project</a> for the newest code).</p>
<pre><code>const bs = Browsersync.create();
bs.init({
...(DEBUG ? {} : { notify: false, ui: false }),
proxy: {
target: host,
middleware: [wpMiddleware, ...hotMiddlewares],
},
// no need to watch '*.js' here, webpack will take care of it for us,
// including full page reloads if HMR won't work
files: ['build/content/**/*.*'],
}, resolve)
</code></pre>
<p>The important part is <code>proxy.target</code>, where they set server address they want to proxy, which could be <a href="http://localhost:3000" rel="noreferrer">http://localhost:3000</a>, and Browsersync starts a server listening on <a href="http://localhost:3001" rel="noreferrer">http://localhost:3001</a>, where the generated assets are served with automatic change detection and hot module replacement. As you can see, there is another configuration property <code>files</code> with individual files or patterns Browser-sync watches for changes and reloads the browser if some occur, but as the comment says, Webpack takes care of watching js sources by itself with HMR, so they cooperate there.</p>
<p>Now I don't have any equivalent example of such Grunt or Gulp configuration, but with Gulp (and somewhat similarly with Grunt) you would write individual tasks in gulpfile.js like</p>
<pre><code>gulp.task('bundle', function() {
// bundling source files with some gulp plugins like gulp-webpack maybe
});
gulp.task('start', function() {
// starting server and stuff
});
</code></pre>
<p>where you would be doing essentially pretty much the same things as in the starter-kit, this time with task runner, which solves some problems for you, but presents its own issues and some difficulties during learning the usage, and as I say, the more dependencies you have, the more can go wrong. And that is the reason I like to get rid of such tools.</p> | {
"question_id": 35062852,
"question_date": "2016-01-28T13:28:39.440Z",
"question_score": 2041,
"tags": "gruntjs|npm|gulp|bower|webpack",
"answer_id": 35064297,
"answer_date": "2016-01-28T14:34:48.787Z",
"answer_score": 1092
} |
Please answer the following Stack Overflow question:
Title: Loop through an array of strings in Bash?
<p>I want to write a script that loops through 15 strings (array possibly?) Is that possible?</p>
<p>Something like:</p>
<pre><code>for databaseName in listOfNames
then
# Do something
end
</code></pre> | <p>You can use it like this:</p>
<pre><code>## declare an array variable
declare -a arr=("element1" "element2" "element3")
## now loop through the above array
for i in "${arr[@]}"
do
echo "$i"
# or do whatever with individual element of the array
done
# You can access them using echo "${arr[0]}", "${arr[1]}" also
</code></pre>
<p>Also works for multi-line array declaration</p>
<pre><code>declare -a arr=("element1"
"element2" "element3"
"element4"
)
</code></pre> | {
"question_id": 8880603,
"question_date": "2012-01-16T13:21:16.343Z",
"question_score": 2040,
"tags": "arrays|bash|shell",
"answer_id": 8880633,
"answer_date": "2012-01-16T13:24:47.810Z",
"answer_score": 3153
} |
Please answer the following Stack Overflow question:
Title: What is the optimal algorithm for the game 2048?
<p>I have recently stumbled upon the game <a href="http://gabrielecirulli.github.io/2048/" rel="noreferrer">2048</a>. You merge similar tiles by moving them in any of the four directions to make "bigger" tiles. After each move, a new tile appears at random empty position with a value of either <code>2</code> or <code>4</code>. The game terminates when all the boxes are filled and there are no moves that can merge tiles, or you create a tile with a value of <code>2048</code>.</p>
<p>One, I need to follow a well-defined strategy to reach the goal. So, I thought of writing a program for it.</p>
<p>My current algorithm:</p>
<pre><code>while (!game_over) {
for each possible move:
count_no_of_merges_for_2-tiles and 4-tiles
choose the move with a large number of merges
}
</code></pre>
<p>What I am doing is at any point, I will try to merge the tiles with values <code>2</code> and <code>4</code>, that is, I try to have <code>2</code> and <code>4</code> tiles, as minimum as possible. If I try it this way, all other tiles were automatically getting merged and the strategy seems good.</p>
<p>But, when I actually use this algorithm, I only get around 4000 points before the game terminates. Maximum points AFAIK is slightly more than 20,000 points which is way larger than my current score. Is there a better algorithm than the above?</p> | <p>I developed a 2048 AI using <em>expectimax</em> optimization, instead of the minimax search used by @ovolve's algorithm. The AI simply performs maximization over all possible moves, followed by expectation over all possible tile spawns (weighted by the probability of the tiles, i.e. 10% for a 4 and 90% for a 2). As far as I'm aware, it is not possible to prune expectimax optimization (except to remove branches that are exceedingly unlikely), and so the algorithm used is a carefully optimized brute force search.</p>
<h2>Performance</h2>
<p>The AI in its default configuration (max search depth of 8) takes anywhere from 10ms to 200ms to execute a move, depending on the complexity of the board position. In testing, the AI achieves an average move rate of 5-10 moves per second over the course of an entire game. If the search depth is limited to 6 moves, the AI can easily execute 20+ moves per second, which makes for some <a href="https://www.youtube.com/watch?v=96ab_dK6JM0">interesting watching</a>.</p>
<p>To assess the score performance of the AI, I ran the AI 100 times (connected to the browser game via remote control). For each tile, here are the proportions of games in which that tile was achieved at least once:</p>
<pre><code>2048: 100%
4096: 100%
8192: 100%
16384: 94%
32768: 36%
</code></pre>
<p>The minimum score over all runs was 124024; the maximum score achieved was 794076. The median score is 387222. The AI never failed to obtain the 2048 tile (so it never lost the game even once in 100 games); in fact, it achieved the <strong>8192</strong> tile at least once in every run!</p>
<p>Here's the screenshot of the best run:</p>
<p><img src="https://i.stack.imgur.com/jG2CL.png" alt="32768 tile, score 794076"></p>
<p>This game took 27830 moves over 96 minutes, or an average of 4.8 moves per second. </p>
<h2>Implementation</h2>
<p>My approach encodes the entire board (16 entries) as a single 64-bit integer (where tiles are the nybbles, i.e. 4-bit chunks). On a 64-bit machine, this enables the entire board to be passed around in a single machine register.</p>
<p>Bit shift operations are used to extract individual rows and columns. A single row or column is a 16-bit quantity, so a table of size 65536 can encode transformations which operate on a single row or column. For example, moves are implemented as 4 lookups into a precomputed "move effect table" which describes how each move affects a single row or column (for example, the "move right" table contains the entry "1122 -> 0023" describing how the row [2,2,4,4] becomes the row [0,0,4,8] when moved to the right).</p>
<p>Scoring is also done using table lookup. The tables contain heuristic scores computed on all possible rows/columns, and the resultant score for a board is simply the sum of the table values across each row and column.</p>
<p>This board representation, along with the table lookup approach for movement and scoring, allows the AI to search a huge number of game states in a short period of time (over 10,000,000 game states per second on one core of my mid-2011 laptop).</p>
<p>The expectimax search itself is coded as a recursive search which alternates between "expectation" steps (testing all possible tile spawn locations and values, and weighting their optimized scores by the probability of each possibility), and "maximization" steps (testing all possible moves and selecting the one with the best score). The tree search terminates when it sees a previously-seen position (using a <a href="http://en.wikipedia.org/wiki/Transposition_table">transposition table</a>), when it reaches a predefined depth limit, or when it reaches a board state that is highly unlikely (e.g. it was reached by getting 6 "4" tiles in a row from the starting position). The typical search depth is 4-8 moves.</p>
<h2>Heuristics</h2>
<p>Several heuristics are used to direct the optimization algorithm towards favorable positions. The precise choice of heuristic has a huge effect on the performance of the algorithm. The various heuristics are weighted and combined into a positional score, which determines how "good" a given board position is. The optimization search will then aim to maximize the average score of all possible board positions. The actual score, as shown by the game, is <em>not</em> used to calculate the board score, since it is too heavily weighted in favor of merging tiles (when delayed merging could produce a large benefit).</p>
<p>Initially, I used two very simple heuristics, granting "bonuses" for open squares and for having large values on the edge. These heuristics performed pretty well, frequently achieving 16384 but never getting to 32768.</p>
<p>Petr Morávek (@xificurk) took my AI and added two new heuristics. The first heuristic was a penalty for having non-monotonic rows and columns which increased as the ranks increased, ensuring that non-monotonic rows of small numbers would not strongly affect the score, but non-monotonic rows of large numbers hurt the score substantially. The second heuristic counted the number of potential merges (adjacent equal values) in addition to open spaces. These two heuristics served to push the algorithm towards monotonic boards (which are easier to merge), and towards board positions with lots of merges (encouraging it to align merges where possible for greater effect).</p>
<p>Furthermore, Petr also optimized the heuristic weights using a "meta-optimization" strategy (using an algorithm called <a href="https://en.wikipedia.org/wiki/CMA-ES">CMA-ES</a>), where the weights themselves were adjusted to obtain the highest possible average score.</p>
<p>The effect of these changes are extremely significant. The algorithm went from achieving the 16384 tile around 13% of the time to achieving it over 90% of the time, and the algorithm began to achieve 32768 over 1/3 of the time (whereas the old heuristics never once produced a 32768 tile).</p>
<p>I believe there's still room for improvement on the heuristics. This algorithm definitely isn't yet "optimal", but I feel like it's getting pretty close.</p>
<hr>
<p>That the AI achieves the 32768 tile in over a third of its games is a huge milestone; I will be surprised to hear if any human players have achieved 32768 on the official game (i.e. without using tools like savestates or undo). I think the 65536 tile is within reach!</p>
<p>You can try the AI for yourself. The code is available at <a href="https://github.com/nneonneo/2048-ai">https://github.com/nneonneo/2048-ai</a>.</p> | {
"question_id": 22342854,
"question_date": "2014-03-12T05:37:21.207Z",
"question_score": 2037,
"tags": "algorithm|logic|artificial-intelligence|2048",
"answer_id": 22498940,
"answer_date": "2014-03-19T07:22:15.070Z",
"answer_score": 1337
} |
Please answer the following Stack Overflow question:
Title: How do I count the occurrences of a list item?
<p>Given a single item, how do I count occurrences of it in a list, in Python?</p>
<hr />
<p><sub>A related but different problem is counting occurrences of <strong>each different element</strong> in a collection, getting a dictionary or list as a histogram result instead of a single integer. For that problem, see <a href="https://stackoverflow.com/questions/3496518">Using a dictionary to count the items in a list</a>.</sub></p> | <p>If you only want a single item's count, use the <code>count</code> method:</p>
<pre><code>>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
</code></pre>
<hr />
<h4><strong>Important: this is very slow if you are counting <em>multiple</em> different items</strong></h4>
<p>Each <code>count</code> call goes over the entire list of <code>n</code> elements. Calling <code>count</code> in a loop <code>n</code> times means <code>n * n</code> total checks, which can be catastrophic for performance.</p>
<p>If you want to count multiple items, use <a href="https://stackoverflow.com/a/5829377/365102"><code>Counter</code></a>, which only does <code>n</code> total checks.</p> | {
"question_id": 2600191,
"question_date": "2010-04-08T13:30:00.120Z",
"question_score": 2028,
"tags": "python|list|count",
"answer_id": 2600208,
"answer_date": "2010-04-08T13:31:52.763Z",
"answer_score": 2388
} |
Please answer the following Stack Overflow question:
Title: How do you merge two Git repositories?
<p>Consider the following scenario:</p>
<p>I have developed a small experimental project A in its own Git repo. It has now matured, and I'd like A to be part of larger project B, which has its own big repository. I'd now like to add A as a subdirectory of B.</p>
<p>How do I merge A into B, without losing history on any side?</p> | <p>A single branch of another repository can be easily placed under a subdirectory retaining its history. For example:</p>
<pre><code>git subtree add --prefix=rails git://github.com/rails/rails.git master
</code></pre>
<p>This will appear as a single commit where all files of Rails master branch are added into "rails" directory.
However the commit's title contains a reference to the old history tree:</p>
<blockquote>
<p>Add 'rails/' from commit <code><rev></code></p>
</blockquote>
<p>Where <code><rev></code> is a SHA-1 commit hash. You can still see the history, blame some changes.</p>
<pre><code>git log <rev>
git blame <rev> -- README.md
</code></pre>
<p>Note that you can't see the directory prefix from here since this is an actual old branch left intact.
You should treat this like a usual file move commit: you will need an extra jump when reaching it.</p>
<pre><code># finishes with all files added at once commit
git log rails/README.md
# then continue from original tree
git log <rev> -- README.md
</code></pre>
<p>There are more complex solutions like doing this manually or rewriting the history as described in other answers.</p>
<p>The git-subtree command is a part of official git-contrib, some packet managers install it by default (OS X Homebrew).
But you might have to install it by yourself in addition to git.</p> | {
"question_id": 1425892,
"question_date": "2009-09-15T08:31:54.643Z",
"question_score": 2027,
"tags": "git|merge|repository|git-subtree",
"answer_id": 14992078,
"answer_date": "2013-02-20T23:44:27.257Z",
"answer_score": 506
} |
Please answer the following Stack Overflow question:
Title: How does data binding work in AngularJS?
<p>How does data binding work in the <code>AngularJS</code> framework?</p>
<p>I haven't found technical details on <a href="http://angularjs.org" rel="noreferrer">their site</a>. It's more or less clear how it works when data is propagated from view to model. But how does AngularJS track changes of model properties without setters and getters?</p>
<p>I found that there are <a href="https://stackoverflow.com/questions/1029241/javascript-object-watch-for-all-browsers">JavaScript watchers</a> that may do this work. But they are not supported in <a href="http://en.wikipedia.org/wiki/Internet_Explorer_6" rel="noreferrer">Internet Explorer 6</a> and <a href="http://en.wikipedia.org/wiki/Internet_Explorer_7" rel="noreferrer">Internet Explorer 7</a>. So how does AngularJS know that I changed for example the following and reflected this change on a view?</p>
<pre><code>myobject.myproperty="new value";
</code></pre> | <p>AngularJS remembers the value and compares it to a previous value. This is basic dirty-checking. If there is a change in value, then it fires the change event.</p>
<p>The <code>$apply()</code> method, which is what you call when you are transitioning from a non-AngularJS world into an AngularJS world, calls <code>$digest()</code>. A digest is just plain old dirty-checking. It works on all browsers and is totally predictable.</p>
<p>To contrast dirty-checking (AngularJS) vs change listeners (<a href="http://en.wikipedia.org/wiki/KnockoutJS">KnockoutJS</a> and <a href="https://en.wikipedia.org/wiki/Backbone.js">Backbone.js</a>): While dirty-checking may seem simple, and even inefficient (I will address that later), it turns out that it is semantically correct all the time, while change listeners have lots of weird corner cases and need things like dependency tracking to make it more semantically correct. KnockoutJS dependency tracking is a clever feature for a problem which AngularJS does not have.</p>
<h1>Issues with change listeners:</h1>
<ul>
<li>The syntax is atrocious, since browsers do not support it natively. Yes, there are proxies, but they are not semantically correct in all cases, and of course there are no proxies on old browsers. The bottom line is that dirty-checking allows you to do <a href="http://en.wikipedia.org/wiki/Plain_Old_Java_Object">POJO</a>, whereas KnockoutJS and Backbone.js force you to inherit from their classes, and access your data through accessors.</li>
<li>Change coalescence. Suppose you have an array of items. Say you want to add items into an array, as you are looping to add, each time you add you are firing events on change, which is rendering the UI. This is very bad for performance. What you want is to update the UI only once, at the end. The change events are too fine-grained.</li>
<li>Change listeners fire immediately on a setter, which is a problem, since the change listener can further change data, which fires more change events. This is bad since on your stack you may have several change events happening at once. Suppose you have two arrays which need to be kept in sync for whatever reason. You can only add to one or the other, but each time you add you fire a change event, which now has an inconsistent view of the world. This is a very similar problem to thread locking, which JavaScript avoids since each callback executes exclusively and to completion. Change events break this since setters can have far-reaching consequences which are not intended and non obvious, which creates the thread problem all over again. It turns out that what you want to do is to delay the listener execution, and guarantee, that only one listener runs at a time, hence any code is free to change data, and it knows that no other code runs while it is doing so.</li>
</ul>
<h1>What about performance?</h1>
<p>So it may seem that we are slow, since dirty-checking is inefficient. This is where we need to look at real numbers rather than just have theoretical arguments, but first let's define some constraints.</p>
<p>Humans are:</p>
<ul>
<li><p><em>Slow</em> — Anything faster than 50 ms is imperceptible to humans and thus can be considered as "instant".</p></li>
<li><p><em>Limited</em> — You can't really show more than about 2000 pieces of information to a human on a single page. Anything more than that is really bad UI, and humans can't process this anyway.</p></li>
</ul>
<p>So the real question is this: How many comparisons can you do on a browser in 50 ms? This is a hard question to answer as many factors come into play, but here is a test case: <a href="http://jsperf.com/angularjs-digest/6">http://jsperf.com/angularjs-digest/6</a> which creates 10,000 watchers. On a modern browser this takes just under 6 ms. On <a href="http://en.wikipedia.org/wiki/Internet_Explorer_8">Internet Explorer 8</a> it takes about 40 ms. As you can see, this is not an issue even on slow browsers these days. There is a caveat: The comparisons need to be simple to fit into the time limit... Unfortunately it is way too easy to add a slow comparison into AngularJS, so it is easy to build slow applications when you don't know what you are doing. But we hope to have an answer by providing an instrumentation module, which would show you which are the slow comparisons.</p>
<p>It turns out that video games and GPUs use the dirty-checking approach, specifically because it is consistent. As long as they get over the monitor refresh rate (typically 50-60 Hz, or every 16.6-20 ms), any performance over that is a waste, so you're better off drawing more stuff, than getting FPS higher.</p> | {
"question_id": 9682092,
"question_date": "2012-03-13T10:16:37.290Z",
"question_score": 2025,
"tags": "javascript|angularjs|data-binding",
"answer_id": 9693933,
"answer_date": "2012-03-13T23:47:35.607Z",
"answer_score": 2762
} |
Please answer the following Stack Overflow question:
Title: How do I iterate over a range of numbers defined by variables in Bash?
<p>How do I iterate over a range of numbers in Bash when the range is given by a variable?</p>
<p>I know I can do this (called "sequence expression" in the Bash <a href="http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion" rel="noreferrer">documentation</a>):</p>
<pre><code> for i in {1..5}; do echo $i; done
</code></pre>
<p>Which gives:</p>
<blockquote>
<p>1 <br/>
2 <br/>
3 <br/>
4 <br/>
5</p>
</blockquote>
<p>Yet, how can I replace either of the range endpoints with a variable? This doesn't work:</p>
<pre><code>END=5
for i in {1..$END}; do echo $i; done
</code></pre>
<p>Which prints:</p>
<blockquote>
<p>{1..5}</p>
</blockquote> | <pre><code>for i in $(seq 1 $END); do echo $i; done</code></pre>
<p>edit: I prefer <code>seq</code> over the other methods because I can actually remember it ;)</p> | {
"question_id": 169511,
"question_date": "2008-10-04T01:38:43.777Z",
"question_score": 2015,
"tags": "bash|shell|for-loop|syntax",
"answer_id": 169517,
"answer_date": "2008-10-04T01:41:55.673Z",
"answer_score": 2267
} |
Please answer the following Stack Overflow question:
Title: How to replace master branch in Git, entirely, from another branch?
<p>I have two branches in my Git repository:</p>
<ol>
<li><code>master</code></li>
<li><code>seotweaks</code> (created originally from <code>master</code>)</li>
</ol>
<p>I created <code>seotweaks</code> with the intention of quickly merging it back into <code>master</code>. However, that was three months ago and the code in this branch is 13 versions ahead of <code>master</code>.</p>
<p>It has effectively become our working master branch as all the code in <code>master</code> is more or less obsolete now.</p>
<p>Very bad practice I know, lesson learned.</p>
<p>Do you know how I can replace all of the contents of the <code>master</code> branch with those in <code>seotweaks</code>?</p>
<p>I could just delete everything in <code>master</code> and merge, but this does not feel like best practice.</p> | <p>You should be able to use the "ours" merge strategy to overwrite master with seotweaks like this:</p>
<pre><code>git checkout seotweaks
git merge -s ours master
git checkout master
git merge seotweaks
</code></pre>
<p>The result should be your master is now essentially seotweaks. </p>
<p>(<code>-s ours</code> is short for <code>--strategy=ours</code>)</p>
<p>From <a href="https://git-scm.com/docs/git-merge" rel="noreferrer">the docs</a> about the 'ours' strategy:</p>
<blockquote>
<p>This resolves any number of heads, but the resulting tree of the merge is always that of the current branch head, effectively ignoring all changes from all other branches. It is meant to be used to supersede old development history of side branches. Note that this is different from the -Xours option to the recursive merge strategy.</p>
</blockquote>
<p>Update from comments: If you get fatal: <code>refusing to merge unrelated histories</code>, then change the second line to this: git <code>merge --allow-unrelated-histories -s ours master</code></p> | {
"question_id": 2862590,
"question_date": "2010-05-19T03:06:29.600Z",
"question_score": 2015,
"tags": "git|merge|git-branch",
"answer_id": 2862938,
"answer_date": "2010-05-19T04:51:31.177Z",
"answer_score": 3391
} |
Please answer the following Stack Overflow question:
Title: Preview an image before it is uploaded
<p>I want to be able to preview a file (image) before it is uploaded. The preview action should be executed all in the browser without using Ajax to upload the image.</p>
<p>How can I do this?</p> | <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>imgInp.onchange = evt => {
const [file] = imgInp.files
if (file) {
blah.src = URL.createObjectURL(file)
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form runat="server">
<input accept="image/*" type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form></code></pre>
</div>
</div>
</p> | {
"question_id": 4459379,
"question_date": "2010-12-16T09:51:32.453Z",
"question_score": 2014,
"tags": "javascript|jquery|file-upload",
"answer_id": 4459419,
"answer_date": "2010-12-16T09:55:11.127Z",
"answer_score": 3147
} |
Please answer the following Stack Overflow question:
Title: Why is using "for...in" for array iteration a bad idea?
<p>I've been told not to use <code>for...in</code> with arrays in JavaScript. Why not?</p> | <p>The reason is that one construct:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var a = []; // Create a new empty array.
a[5] = 5; // Perfectly legal JavaScript that resizes the array.
for (var i = 0; i < a.length; i++) {
// Iterate over numeric indexes from 0 to 5, as everyone expects.
console.log(a[i]);
}
/* Will display:
undefined
undefined
undefined
undefined
undefined
5
*/</code></pre>
</div>
</div>
</p>
<p>can sometimes be totally different from the other:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var a = [];
a[5] = 5;
for (var x in a) {
// Shows only the explicitly set index of "5", and ignores 0-4
console.log(x);
}
/* Will display:
5
*/</code></pre>
</div>
</div>
</p>
<p>Also consider that <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> libraries might do things like this, which will affect any array you create:</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>// Somewhere deep in your JavaScript library...
Array.prototype.foo = 1;
// Now you have no idea what the below code will do.
var a = [1, 2, 3, 4, 5];
for (var x in a){
// Now foo is a part of EVERY array and
// will show up here as a value of 'x'.
console.log(x);
}
/* Will display:
0
1
2
3
4
foo
*/</code></pre>
</div>
</div>
</p> | {
"question_id": 500504,
"question_date": "2009-02-01T09:46:38.510Z",
"question_score": 2013,
"tags": "javascript|arrays|loops|for-loop|iteration",
"answer_id": 500531,
"answer_date": "2009-02-01T10:08:34.517Z",
"answer_score": 1688
} |
Please answer the following Stack Overflow question:
Title: Why is it string.join(list) instead of list.join(string)?
<p>This has always confused me. It seems like this would be nicer:</p>
<pre><code>["Hello", "world"].join("-")
</code></pre>
<p>Than this:</p>
<pre><code>"-".join(["Hello", "world"])
</code></pre>
<p>Is there a specific reason it is like this?</p> | <p>It's because any iterable can be joined (e.g, list, tuple, dict, set), but its contents and the "joiner" <em>must be</em> strings.</p>
<p>For example:</p>
<pre><code>'_'.join(['welcome', 'to', 'stack', 'overflow'])
'_'.join(('welcome', 'to', 'stack', 'overflow'))
</code></pre>
<pre><code>'welcome_to_stack_overflow'
</code></pre>
<p>Using something other than strings will raise the following error:</p>
<blockquote>
<p>TypeError: sequence item 0: expected str instance, int found</p>
</blockquote> | {
"question_id": 493819,
"question_date": "2009-01-29T22:45:13.697Z",
"question_score": 2012,
"tags": "python|string|list",
"answer_id": 493842,
"answer_date": "2009-01-29T22:51:18.363Z",
"answer_score": 1392
} |
Please answer the following Stack Overflow question:
Title: Disable same origin policy in Chrome
<p>Is there any way to disable the <a href="https://en.wikipedia.org/wiki/Same_origin_policy" rel="noreferrer">Same-origin policy</a> on Google's <a href="http://en.wikipedia.org/wiki/Google_Chrome" rel="noreferrer">Chrome</a> browser?</p> | <p>Close chrome (or chromium) and restart with the <code>--disable-web-security</code> argument. I just tested this and verified that I can access the contents of an iframe with src="http://google.com" embedded in a page served from "localhost" (tested under chromium 5 / ubuntu). For me the exact command was:</p>
<p><strong>Note : Kill all chrome instances before running command</strong></p>
<pre><code>chromium-browser --disable-web-security --user-data-dir="[some directory here]"
</code></pre>
<p>The browser will warn you that "you are using an unsupported command line" when it first opens, which you can ignore.</p>
<p>From the chromium source:</p>
<pre><code>// Don't enforce the same-origin policy. (Used by people testing their sites.)
const wchar_t kDisableWebSecurity[] = L"disable-web-security";
</code></pre>
<hr>
<p>Before Chrome 48, you could just use:</p>
<pre><code>chromium-browser --disable-web-security
</code></pre> | {
"question_id": 3102819,
"question_date": "2010-06-23T15:00:21.823Z",
"question_score": 2011,
"tags": "javascript|ajax|google-chrome",
"answer_id": 3177718,
"answer_date": "2010-07-05T07:20:32.437Z",
"answer_score": 1228
} |
Please answer the following Stack Overflow question:
Title: Get current URL with jQuery?
<p>I am using jQuery. How do I get the path of the current URL and assign it to a variable?</p>
<p>Example URL:</p>
<pre><code>http://localhost/menuname.de?foo=bar&amp;number=0
</code></pre> | <p>To get the path, you can use:</p>
<pre><code>var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url = window.location.href; // Returns full URL (https://example.com/path/example.html)
var origin = window.location.origin; // Returns base URL (https://example.com)
</code></pre> | {
"question_id": 406192,
"question_date": "2009-01-02T06:42:54.400Z",
"question_score": 2009,
"tags": "javascript|jquery|url",
"answer_id": 406208,
"answer_date": "2009-01-02T06:57:03.373Z",
"answer_score": 2748
} |
Please answer the following Stack Overflow question:
Title: Delete an element from a dictionary
<p>How do I delete an item from a dictionary in Python?</p>
<p>Without modifying the original dictionary, how do I obtain another dict with the item removed?</p> | <p>The <a href="http://docs.python.org/reference/simple_stmts.html#the-del-statement" rel="noreferrer"><code>del</code> statement</a> removes an element:</p>
<pre><code>del d[key]
</code></pre>
<p>Note that this mutates the existing dictionary, so the contents of the dictionary changes for anybody else who has a reference to the same instance. To return a <em>new</em> dictionary, make a copy of the dictionary:</p>
<pre><code>def removekey(d, key):
r = dict(d)
del r[key]
return r
</code></pre>
<p>The <code>dict()</code> constructor makes a <em>shallow copy</em>. To make a deep copy, see the <a href="https://docs.python.org/library/copy.html" rel="noreferrer"><code>copy</code> module</a>.</p>
<hr />
<p>Note that making a copy for every dict <code>del</code>/assignment/etc. means you're going from constant time to linear time, and also using linear space. For small dicts, this is not a problem. But if you're planning to make lots of copies of large dicts, you probably want a different data structure, like a HAMT (as described in <a href="https://stackoverflow.com/a/50341031/908494">this answer</a>).</p> | {
"question_id": 5844672,
"question_date": "2011-04-30T21:20:57.930Z",
"question_score": 2007,
"tags": "python|dictionary|del",
"answer_id": 5844692,
"answer_date": "2011-04-30T21:25:39.520Z",
"answer_score": 2355
} |
Please answer the following Stack Overflow question:
Title: How do I recursively grep all directories and subdirectories?
<p>How do I recursively <code>grep</code> all directories and subdirectories?</p>
<pre><code>find . | xargs grep "texthere" *
</code></pre> | <pre><code>grep -r "texthere" .
</code></pre>
<p>The first parameter represents the regular expression to search for, while the second one represents the directory that should be searched. In this case, <code>.</code> means the current directory.</p>
<p>Note: This works for GNU grep, and on some platforms like Solaris you must specifically use GNU grep as opposed to legacy implementation. For Solaris this is the <code>ggrep</code> command. </p> | {
"question_id": 1987926,
"question_date": "2010-01-01T05:10:12.547Z",
"question_score": 2007,
"tags": "linux|unix|grep",
"answer_id": 1987928,
"answer_date": "2010-01-01T05:11:30.400Z",
"answer_score": 2933
} |
Please answer the following Stack Overflow question:
Title: Java inner class and static nested class
<p>What is the main difference between an inner class and a static nested class in Java? Does design / implementation play a role in choosing one of these?</p> | <p>From the <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html" rel="noreferrer">Java Tutorial</a>:</p>
<blockquote>
<p>Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes. </p>
</blockquote>
<p>Static nested classes are accessed using the enclosing class name:</p>
<pre><code>OuterClass.StaticNestedClass
</code></pre>
<p>For example, to create an object for the static nested class, use this syntax:</p>
<pre><code>OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
</code></pre>
<p>Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:</p>
<pre><code>class OuterClass {
...
class InnerClass {
...
}
}
</code></pre>
<p>An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.</p>
<p>To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:</p>
<pre><code>OuterClass outerObject = new OuterClass()
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
</code></pre>
<p>see: <a href="http://download.oracle.com/javase/tutorial/java/javaOO/nested.html" rel="noreferrer">Java Tutorial - Nested Classes</a></p>
<p>For completeness note that there is also such a thing as an <a href="https://stackoverflow.com/questions/20468856/is-it-true-that-every-inner-class-requires-an-enclosing-instance">inner class <em>without</em> an enclosing instance</a>:</p>
<pre><code>class A {
int t() { return 1; }
static A a = new A() { int t() { return 2; } };
}
</code></pre>
<p>Here, <code>new A() { ... }</code> is an <em>inner class defined in a static context</em> and does not have an enclosing instance.</p> | {
"question_id": 70324,
"question_date": "2008-09-16T08:22:35.727Z",
"question_score": 2007,
"tags": "java|inner-classes|static-classes",
"answer_id": 70358,
"answer_date": "2008-09-16T08:28:34.090Z",
"answer_score": 1867
} |
Please answer the following Stack Overflow question:
Title: How do I check if a variable is an array in JavaScript?
<p>How do I check if a variable is an array in JavaScript?</p>
<pre><code>if (variable.constructor == Array)
</code></pre> | <p>There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen.</p>
<pre><code>variable.constructor === Array
</code></pre>
<p>This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.</p>
<p>If you are having issues with finding out if an objects property is an array, you must first check if the property is there.</p>
<pre><code>variable.prop && variable.prop.constructor === Array
</code></pre>
<p>Some other ways are:</p>
<pre><code>Array.isArray(variable)
</code></pre>
<p><strong>Update May 23, 2019 using Chrome 75, shout out to @AnduAndrici for having me revisit this with his question</strong>
This last one is, in my opinion the ugliest, and it is one of the <s>slowest</s> fastest. <s>Running about 1/5 the speed as the first example.</s> This guy is about 2-5% slower, but it's pretty hard to tell. Solid to use! Quite impressed by the outcome. Array.prototype, is actually an array. you can read more about it here <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray</a></p>
<pre><code>variable instanceof Array
</code></pre>
<p>This method runs about <s>1/3 the speed</s> as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work as <code>variable instanceof Number</code> always returns <code>false</code>. <strong>Update: <code>instanceof</code> now goes 2/3 the speed!</strong></p>
<p><strong>So yet another update</strong></p>
<pre><code>Object.prototype.toString.call(variable) === '[object Array]';
</code></pre>
<p>This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you're looking for. However, since you're looking for an array, just use the fastest method above.</p>
<p>Also, I ran some test: <a href="http://jsperf.com/instanceof-array-vs-array-isarray/35" rel="noreferrer">http://jsperf.com/instanceof-array-vs-array-isarray/35</a> So have some fun and check it out.</p>
<p>Note: @EscapeNetscape has created another test as jsperf.com is down. <a href="http://jsben.ch/#/QgYAV" rel="noreferrer">http://jsben.ch/#/QgYAV</a> I wanted to make sure the original link stay for whenever jsperf comes back online.</p> | {
"question_id": 767486,
"question_date": "2009-04-20T09:02:59.553Z",
"question_score": 2006,
"tags": "javascript|arrays|list|variables",
"answer_id": 26633883,
"answer_date": "2014-10-29T15:07:05.927Z",
"answer_score": 1895
} |
Please answer the following Stack Overflow question:
Title: What is the effect of extern "C" in C++?
<p>What exactly does putting <code>extern "C"</code> into C++ code do?</p>
<p>For example:</p>
<pre><code>extern "C" {
void foo();
}
</code></pre> | <p><code>extern "C"</code> makes a function-name in C++ have C linkage (compiler does not mangle the name) so that client C code can link to (use) your function using a C compatible header file that contains just the declaration of your function. Your function definition is contained in a binary format (that was compiled by your C++ compiler) that the client C linker will then link to using the C name.</p>
<p>Since C++ has overloading of function names and C does not, the C++ compiler cannot just use the function name as a unique id to link to, so it mangles the name by adding information about the arguments. A C compiler does not need to mangle the name since you can not overload function names in C. When you state that a function has <code>extern "C"</code> linkage in C++, the C++ compiler does not add argument/parameter type information to the name used for linkage.</p>
<p>Just so you know, you can specify <code>extern "C"</code> linkage to each individual declaration/definition explicitly or use a block to group a sequence of declarations/definitions to have a certain linkage:</p>
<pre><code>extern "C" void foo(int);
extern "C"
{
void g(char);
int i;
}
</code></pre>
<p>If you care about the technicalities, they are listed in section 7.5 of the C++03 standard, here is a brief summary (with emphasis on <code>extern "C"</code>):</p>
<ul>
<li><code>extern "C"</code> is a linkage-specification</li>
<li>Every compiler is <em>required</em> to provide "C" linkage</li>
<li>A linkage specification shall occur only in namespace scope</li>
<li><strike>All function types, function names and variable names have a language linkage </strike> <b><a href="https://stackoverflow.com/questions/1041866/in-c-source-what-is-the-effect-of-extern-c#comment20842899_1041880">See Richard's Comment:</a></b> Only function names and variable names with external linkage have a language linkage</li>
<li>Two function types with distinct language linkages are distinct types even if otherwise identical</li>
<li>Linkage specs nest, inner one determines the final linkage</li>
<li><code>extern "C"</code> is ignored for class members</li>
<li>At most one function with a particular name can have "C" linkage (regardless of namespace)</li>
<li><strike><code>extern "C"</code> forces a function to have external linkage (cannot make it static) </strike> <b> <a href="https://stackoverflow.com/questions/1041866/what-is-the-effect-of-extern-c-in-c?rq=1#comment20842893_1041880">See Richard's comment:</a> </b> <code>static</code> inside <code>extern "C"</code> is valid; an entity so declared has internal linkage, and so does not have a language linkage</li>
<li>Linkage from C++ to objects defined in other languages and to objects defined in C++ from other languages is implementation-defined and language-dependent. Only where the object layout strategies of two language implementations are similar enough can such linkage be achieved</li>
</ul> | {
"question_id": 1041866,
"question_date": "2009-06-25T02:10:07.837Z",
"question_score": 2006,
"tags": "c++|c|linkage|name-mangling|extern-c",
"answer_id": 1041880,
"answer_date": "2009-06-25T02:12:50.233Z",
"answer_score": 1862
} |
Please answer the following Stack Overflow question:
Title: Does Java support default parameter values?
<p>I came across some Java code that had the following structure:</p>
<pre><code>public MyParameterizedFunction(String param1, int param2)
{
this(param1, param2, false);
}
public MyParameterizedFunction(String param1, int param2, boolean param3)
{
//use all three parameters here
}
</code></pre>
<p>I know that in C++ I can assign a parameter a default value. For example:</p>
<pre><code>void MyParameterizedFunction(String param1, int param2, bool param3=false);
</code></pre>
<p>Does Java support this kind of syntax? Are there any reasons why this two step syntax is preferable?</p> | <p>No, the structure you found is how Java handles it (that is, with overloading instead of default parameters).</p>
<p>For constructors, <em><a href="https://en.wikipedia.org/wiki/Joshua_Bloch#Bibliography" rel="noreferrer">See Effective Java: Programming Language Guide's</a></em> Item 1 tip (Consider static factory methods instead of constructors) if the overloading is getting complicated. For other methods, renaming some cases or using a parameter object can help. This is when you have enough complexity that differentiating is difficult. A definite case is where you have to differentiate using the order of parameters, not just number and type.</p> | {
"question_id": 997482,
"question_date": "2009-06-15T18:04:28.277Z",
"question_score": 2005,
"tags": "java|methods|parameters|overloading|default-parameters",
"answer_id": 997529,
"answer_date": "2009-06-15T18:14:29.887Z",
"answer_score": 1151
} |
Please answer the following Stack Overflow question:
Title: How do I break out of nested loops in Java?
<p>I've got a nested loop construct like this:</p>
<pre><code>for (Type type : types) {
for (Type t : types2) {
if (some condition) {
// Do something and break...
break; // Breaks out of the inner loop
}
}
}
</code></pre>
<p>Now how can I break out of both loops? I've looked at similar questions, but none concerns Java specifically. I couldn't apply these solutions because most used gotos.</p>
<p>I don't want to put the inner loop in a different method.</p>
<p>I don't want to return the loops. When breaking I'm finished with the execution of the loop block.</p> | <p>Like other answerers, I'd definitely <em>prefer</em> to put the loops in a different method, at which point you can just return to stop iterating completely. This answer just shows how the requirements in the question can be met.</p>
<p>You can use <code>break</code> with a label for the outer loop. For example:</p>
<pre><code>public class Test {
public static void main(String[] args) {
outerloop:
for (int i=0; i < 5; i++) {
for (int j=0; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
break outerloop;
}
System.out.println(i + " " + j);
}
}
System.out.println("Done");
}
}
</code></pre>
<p>This prints:</p>
<pre><code>0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
Breaking
Done
</code></pre> | {
"question_id": 886955,
"question_date": "2009-05-20T09:07:43.643Z",
"question_score": 2004,
"tags": "java|loops|nested-loops",
"answer_id": 886979,
"answer_date": "2009-05-20T09:11:22.983Z",
"answer_score": 2662
} |
Please answer the following Stack Overflow question:
Title: How to stop tracking and ignore changes to a file in Git?
<p>I have cloned a project that includes some <code>.csproj</code> files. I don't need/like my local <code>csproj</code> files being tracked by Git (or being brought up when creating a patch), but clearly they are needed in the project.</p>
<p>I have added <code>*.csproj</code> to my LOCAL <code>.gitignore</code>, but the files are already in the repo.</p>
<p>When I type git status, it shows my changes to <code>csproj</code> which I am not interested in keeping track of or submitting for patches.</p>
<p>How do I remove the "tracking of" these files from my personal repo (but keep them in the source so I can use them) so that I don't see the changes when I do a status (or create a patch)?</p>
<p>Is there a correct/canonical way to handle this situation?</p> | <p>Just calling <code>git rm --cached</code> on each of the files you want to remove from revision control should be fine. As long as your local ignore patterns are correct you won't see these files included in the output of git status.</p>
<p>Note that this solution removes the files from the repository, so all developers would need to maintain their own local (non-revision controlled) copies of the file</p>
<p>To prevent git from detecting changes in these files you should also use this command:</p>
<pre><code>git update-index --assume-unchanged [path]
</code></pre>
<p><strong>What you probably want to do:</strong> (from below <a href="https://stackoverflow.com/a/40272289/716435">@Ryan Taylor answer</a>)</p>
<blockquote>
<ol start="3">
<li>This is to tell git you want your own independent version of the file or folder. For instance, you don't want to overwrite (or delete)
production/staging config files.</li>
</ol>
<p><code>git update-index --skip-worktree <path-name></code></p>
</blockquote>
<p>The full answer is here in this URL: <a href="http://source.kohlerville.com/2009/02/untrack-files-in-git/" rel="noreferrer">http://source.kohlerville.com/2009/02/untrack-files-in-git/</a></p> | {
"question_id": 936249,
"question_date": "2009-06-01T19:08:16.037Z",
"question_score": 2003,
"tags": "git",
"answer_id": 936290,
"answer_date": "2009-06-01T19:16:19.810Z",
"answer_score": 2377
} |
Please answer the following Stack Overflow question:
Title: How to compare files from two different branches
<p>I have a script that works fine in one branch and is broken in another. I want to look at the two versions side-by-side and see what's different. Is there a way to do this?</p>
<p><strong>To be clear</strong> I'm not looking for a compare tool (I use <a href="https://en.wikipedia.org/wiki/Beyond_Compare" rel="noreferrer">Beyond Compare</a>). I'm looking for a Git diff command that will allow me to compare the master version to my current branch version to see what has changed. I'm not in the middle of a merge or anything. I just want to say something like</p>
<pre><code>git diff mybranch/myfile.cs master/myfile.cs
</code></pre> | <p><code>git diff</code> can show you the difference between two commits:</p>
<pre><code>git diff mybranch master -- myfile.cs
</code></pre>
<p>Or, equivalently:</p>
<pre><code>git diff mybranch..master -- myfile.cs
</code></pre>
<p>Note you must specify the relative path to the file. So if the file were in the src directory, you'd say <code>src/myfile.cs</code> instead of <code>myfile.cs</code>.</p>
<p>Using the latter syntax, if either side is <code>HEAD</code> it may be omitted (e.g., <code>master..</code> compares <code>master</code> to <code>HEAD</code>).</p>
<p>You may also be interested in <code>mybranch...master</code> (from <a href="https://git-scm.com/docs/git-diff" rel="noreferrer"><code>git diff</code> documentation</a>):</p>
<blockquote>
<p>This form is to view the changes on the branch containing and up to the second <code><commit></code>, starting at a common ancestor of both <code><commit></code>. <code>git diff A...B</code> is equivalent to <code>git diff $(git-merge-base A B) B</code>.</p>
</blockquote>
<p>In other words, this will give a diff of changes in <code>master</code> since it diverged from <code>mybranch</code> (but without new changes since then in <code>mybranch</code>).</p>
<hr />
<p>In all cases, the <code>--</code> separator before the file name indicates the end of command line flags. This is optional unless Git will get confused if the argument refers to a commit or a file, but including it is not a bad habit to get into. See <a href="https://stackoverflow.com/questions/13321458/meaning-of-git-checkout-double-dashes/13321491#13321491">Dietrich Epp's answer to <em>Meaning of Git checkout double dashes</em></a> for a few examples.</p>
<hr />
<p>The same arguments can be passed to <code>git difftool</code> if you have one configured.</p> | {
"question_id": 4099742,
"question_date": "2010-11-04T18:04:25.097Z",
"question_score": 2002,
"tags": "git|git-diff",
"answer_id": 4099805,
"answer_date": "2010-11-04T18:13:11.293Z",
"answer_score": 2761
} |
Please answer the following Stack Overflow question:
Title: What is move semantics?
<p>I just finished listening to the Software Engineering radio <a href="http://www.se-radio.net/2010/04/episode-159-c-0x-with-scott-meyers/" rel="noreferrer">podcast interview with Scott Meyers</a> regarding <a href="http://en.wikipedia.org/wiki/C++11" rel="noreferrer">C++0x</a>. Most of the new features made sense to me, and I am actually excited about C++0x now, with the exception of one. I still don't get <em>move semantics</em>... What is it exactly?</p> | <p>I find it easiest to understand move semantics with example code. Let's start with a very simple string class which only holds a pointer to a heap-allocated block of memory:</p>
<pre><code>#include <cstring>
#include <algorithm>
class string
{
char* data;
public:
string(const char* p)
{
size_t size = std::strlen(p) + 1;
data = new char[size];
std::memcpy(data, p, size);
}
</code></pre>
<p>Since we chose to manage the memory ourselves, we need to follow the <a href="http://en.wikipedia.org/wiki/Rule_of_three_%28C++_programming%29" rel="noreferrer">rule of three</a>. I am going to defer writing the assignment operator and only implement the destructor and the copy constructor for now:</p>
<pre><code> ~string()
{
delete[] data;
}
string(const string& that)
{
size_t size = std::strlen(that.data) + 1;
data = new char[size];
std::memcpy(data, that.data, size);
}
</code></pre>
<p>The copy constructor defines what it means to copy string objects. The parameter <code>const string& that</code> binds to all expressions of type string which allows you to make copies in the following examples:</p>
<pre><code>string a(x); // Line 1
string b(x + y); // Line 2
string c(some_function_returning_a_string()); // Line 3
</code></pre>
<p>Now comes the key insight into move semantics. Note that only in the first line where we copy <code>x</code> is this deep copy really necessary, because we might want to inspect <code>x</code> later and would be very surprised if <code>x</code> had changed somehow. Did you notice how I just said <code>x</code> three times (four times if you include this sentence) and meant the <em>exact same object</em> every time? We call expressions such as <code>x</code> "lvalues".</p>
<p>The arguments in lines 2 and 3 are not lvalues, but rvalues, because the underlying string objects have no names, so the client has no way to inspect them again at a later point in time.
rvalues denote temporary objects which are destroyed at the next semicolon (to be more precise: at the end of the full-expression that lexically contains the rvalue). This is important because during the initialization of <code>b</code> and <code>c</code>, we could do whatever we wanted with the source string, and <em>the client couldn't tell a difference</em>!</p>
<p>C++0x introduces a new mechanism called "rvalue reference" which, among other things,
allows us to detect rvalue arguments via function overloading. All we have to do is write a constructor with an rvalue reference parameter. Inside that constructor we can do <em>anything we want</em> with the source, as long as we leave it in <em>some</em> valid state:</p>
<pre><code> string(string&& that) // string&& is an rvalue reference to a string
{
data = that.data;
that.data = nullptr;
}
</code></pre>
<p>What have we done here? Instead of deeply copying the heap data, we have just copied the pointer and then set the original pointer to null (to prevent 'delete[]' from source object's destructor from releasing our 'just stolen data'). In effect, we have "stolen" the data that originally belonged to the source string. Again, the key insight is that under no circumstance could the client detect that the source had been modified. Since we don't really do a copy here, we call this constructor a "move constructor". Its job is to move resources from one object to another instead of copying them.</p>
<p>Congratulations, you now understand the basics of move semantics! Let's continue by implementing the assignment operator. If you're unfamiliar with the <a href="https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom">copy and swap idiom</a>, learn it and come back, because it's an awesome C++ idiom related to exception safety.</p>
<pre><code> string& operator=(string that)
{
std::swap(data, that.data);
return *this;
}
};
</code></pre>
<p>Huh, that's it? "Where's the rvalue reference?" you might ask. "We don't need it here!" is my answer :)</p>
<p>Note that we pass the parameter <code>that</code> <em>by value</em>, so <code>that</code> has to be initialized just like any other string object. Exactly how is <code>that</code> going to be initialized? In the olden days of <a href="http://en.wikipedia.org/wiki/C++#Standardization" rel="noreferrer">C++98</a>, the answer would have been "by the copy constructor". In C++0x, the compiler chooses between the copy constructor and the move constructor based on whether the argument to the assignment operator is an lvalue or an rvalue.</p>
<p>So if you say <code>a = b</code>, the <em>copy constructor</em> will initialize <code>that</code> (because the expression <code>b</code> is an lvalue), and the assignment operator swaps the contents with a freshly created, deep copy. That is the very definition of the copy and swap idiom -- make a copy, swap the contents with the copy, and then get rid of the copy by leaving the scope. Nothing new here.</p>
<p>But if you say <code>a = x + y</code>, the <em>move constructor</em> will initialize <code>that</code> (because the expression <code>x + y</code> is an rvalue), so there is no deep copy involved, only an efficient move.
<code>that</code> is still an independent object from the argument, but its construction was trivial,
since the heap data didn't have to be copied, just moved. It wasn't necessary to copy it because <code>x + y</code> is an rvalue, and again, it is okay to move from string objects denoted by rvalues.</p>
<p>To summarize, the copy constructor makes a deep copy, because the source must remain untouched.
The move constructor, on the other hand, can just copy the pointer and then set the pointer in the source to null. It is okay to "nullify" the source object in this manner, because the client has no way of inspecting the object again.</p>
<p>I hope this example got the main point across. There is a lot more to rvalue references and move semantics which I intentionally left out to keep it simple. If you want more details please see <a href="https://stackoverflow.com/a/11540204/179917">my supplementary answer</a>.</p> | {
"question_id": 3106110,
"question_date": "2010-06-23T22:46:46.900Z",
"question_score": 2001,
"tags": "c++|c++-faq|c++11|move-semantics",
"answer_id": 3109981,
"answer_date": "2010-06-24T12:40:47.393Z",
"answer_score": 2813
} |
Please answer the following Stack Overflow question:
Title: Easiest way to convert int to string in C++
<p>What is the easiest way to convert from <code>int</code> to equivalent <code>string</code> in C++. I am aware of two methods. Is there any easier way?</p>
<p>(1)</p>
<pre><code>int a = 10;
char *intStr = itoa(a);
string str = string(intStr);
</code></pre>
<p>(2)</p>
<pre><code>int a = 10;
stringstream ss;
ss << a;
string str = ss.str();
</code></pre> | <p>C++11 introduces <a href="http://en.cppreference.com/w/cpp/string/basic_string/stol" rel="noreferrer"><code>std::stoi</code></a> (and variants for each numeric type) and <a href="http://en.cppreference.com/w/cpp/string/basic_string/to_string" rel="noreferrer"><code>std::to_string</code></a>, the counterparts of the C <code>atoi</code> and <code>itoa</code> but expressed in term of <code>std::string</code>.</p>
<pre><code>#include <string>
std::string s = std::to_string(42);
</code></pre>
<p>is therefore the shortest way I can think of. You can even omit naming the type, using the <code>auto</code> keyword:</p>
<pre><code>auto s = std::to_string(42);
</code></pre>
<p><em>Note: see <strong>[string.conversions]</strong> (<strong>21.5</strong> in <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf" rel="noreferrer">n3242</a>)</em></p> | {
"question_id": 5590381,
"question_date": "2011-04-08T04:19:41.567Z",
"question_score": 1999,
"tags": "c++|string|int|type-conversion",
"answer_id": 5591169,
"answer_date": "2011-04-08T06:13:52.633Z",
"answer_score": 2622
} |
Please answer the following Stack Overflow question:
Title: Interfaces vs Types in TypeScript
<p>What is the difference between these statements (<code>interface</code> vs <code>type</code>) in TypeScript?</p>
<pre><code>interface X {
a: number
b: string
}
type X = {
a: number
b: string
};
</code></pre> | <p><strong>Update March 2021</strong>: The newer TypeScript Handbook (also mentioned in <a href="https://stackoverflow.com/a/65164318/52277">nju-clc
answer below</a>) has a section <a href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces" rel="noreferrer">Interfaces vs. Type Aliases</a> which explains the differences.</p>
<hr/>
<p><strong>Original Answer (2016)</strong></p>
<p>As per the <a href="https://github.com/microsoft/TypeScript/blob/master/doc/spec-ARCHIVED.md#3.10" rel="noreferrer">(now archived) TypeScript Language Specification</a>:</p>
<blockquote>
<p>Unlike an interface declaration, which always introduces a named object type, <strong>a type alias declaration</strong> can introduce a name for any kind of type, including primitive, union, and intersection types.</p>
</blockquote>
<p>The specification goes on to mention:</p>
<blockquote>
<p><strong>Interface types</strong> have many similarities to type aliases for object type
literals, but since interface types offer more capabilities they are
generally preferred to type aliases. For example, the interface type</p>
<pre><code>interface Point {
x: number;
y: number;
}
</code></pre>
<p>could be written as the type alias</p>
<pre><code>type Point = {
x: number;
y: number;
};
</code></pre>
<p>However, doing so means the following capabilities are lost:</p>
<ul>
<li><strike>An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot</strike> No longer true since TS 2.7.</li>
<li>An interface can have multiple <a href="https://www.typescriptlang.org/docs/handbook/declaration-merging.html" rel="noreferrer">merged declarations</a>, but a type alias for an object type literal cannot.</li>
</ul>
</blockquote> | {
"question_id": 37233735,
"question_date": "2016-05-15T01:53:52.903Z",
"question_score": 1999,
"tags": "typescript|interface|typescript-types",
"answer_id": 37233777,
"answer_date": "2016-05-15T02:01:28.420Z",
"answer_score": 1134
} |
Please answer the following Stack Overflow question:
Title: Find object by id in an array of JavaScript objects
<p>I've got an array:</p>
<pre><code>myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
</code></pre>
<p>I'm unable to change the structure of the array. I'm being passed an id of <code>45</code>, and I want to get <code>'bar'</code> for that object in the array. </p>
<p>How do I do this in JavaScript or using jQuery?</p> | <p>Use the <code>find()</code> method:</p>
<pre><code>myArray.find(x => x.id === '45').foo;
</code></pre>
<p>From <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find" rel="noreferrer">MDN</a>:</p>
<blockquote>
<p>The <code>find()</code> method returns the first value in the array, if an element in the array satisfies the provided testing function. Otherwise <code>undefined</code> is returned.</p>
</blockquote>
<hr />
<p>If you want to find its <em>index</em> instead, use <code>findIndex()</code>:</p>
<pre><code>myArray.findIndex(x => x.id === '45');
</code></pre>
<p>From <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex" rel="noreferrer">MDN</a>:</p>
<blockquote>
<p>The <code>findIndex()</code> method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.</p>
</blockquote>
<hr />
<p>If you want to get an array of matching elements, use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" rel="noreferrer"><code>filter()</code></a> method instead:</p>
<pre><code>myArray.filter(x => x.id === '45');
</code></pre>
<p>This will return an array of objects. If you want to get an array of <code>foo</code> properties, you can do this with the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="noreferrer"><code>map()</code></a> method:</p>
<pre><code>myArray.filter(x => x.id === '45').map(x => x.foo);
</code></pre>
<hr />
<p>Side note: methods like <code>find()</code> or <code>filter()</code>, and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions" rel="noreferrer">arrow functions</a> are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using <a href="https://babeljs.io/" rel="noreferrer">Babel</a> (with the <a href="https://babeljs.io/docs/usage/polyfill/" rel="noreferrer">polyfill</a>).</p> | {
"question_id": 7364150,
"question_date": "2011-09-09T15:42:29.343Z",
"question_score": 1998,
"tags": "javascript|arrays|javascript-objects",
"answer_id": 35398031,
"answer_date": "2016-02-14T21:11:10.690Z",
"answer_score": 1977
} |
Please answer the following Stack Overflow question:
Title: Check if a value is an object in JavaScript
<p>How do you check if a value is an object in JavaScript?</p> | <p><strong>UPDATE</strong>:</p>
<p><strong>This answer is incomplete and gives misleading results</strong>. For example, <code>null</code> is also considered of type <code>object</code> in JavaScript, not to mention several other edge cases. Follow the recommendation below and move on to other <strong><a href="https://stackoverflow.com/a/8511350/2336212">"most upvoted (and correct!) answer"</a></strong>:</p>
<pre class="lang-js prettyprint-override"><code>typeof yourVariable === 'object' && yourVariable !== null
</code></pre>
<hr />
<p><strong>Original answer</strong>:</p>
<p>Try using <code>typeof(var)</code> and/or <code>var instanceof something</code>.</p>
<p>EDIT: This answer gives an idea of how to examine variable's properties, but it is <em>not</em> a bulletproof recipe (after all there's no recipe at all!) for checking whether it's an object, far from it. Since people tend to look for something to copy from here without doing any research, I'd highly recommend that they turn to the other, most upvoted (and correct!) answer.</p> | {
"question_id": 8511281,
"question_date": "2011-12-14T20:35:47.497Z",
"question_score": 1996,
"tags": "javascript|types|javascript-objects",
"answer_id": 8511332,
"answer_date": "2011-12-14T20:39:42.177Z",
"answer_score": 905
} |
Please answer the following Stack Overflow question:
Title: Delete a column from a Pandas DataFrame
<p>To delete a column in a DataFrame, I can successfully use:</p>
<pre><code>del df['column_name']
</code></pre>
<p>But why can't I use the following?</p>
<pre><code>del df.column_name
</code></pre>
<p>Since it is possible to access the column/Series as <code>df.column_name</code>, I expected this to work.</p> | <p>As you've guessed, the right syntax is </p>
<pre><code>del df['column_name']
</code></pre>
<p>It's difficult to make <code>del df.column_name</code> work simply as the result of syntactic limitations in Python. <code>del df[name]</code> gets translated to <code>df.__delitem__(name)</code> under the covers by Python.</p> | {
"question_id": 13411544,
"question_date": "2012-11-16T06:26:40.410Z",
"question_score": 1990,
"tags": "python|pandas|dataframe",
"answer_id": 13485766,
"answer_date": "2012-11-21T03:12:31.480Z",
"answer_score": 1264
} |
Please answer the following Stack Overflow question:
Title: How to copy Docker images from one host to another without using a repository
<p>How do I transfer a Docker image from one machine to another one without using a repository, no matter private or public?</p>
<p>I create my own image in VirtualBox, and when it is finished I try to deploy to other machines to have real usage.</p>
<p>Since it is based on my own based image (like Red Hat Linux), it cannot be recreated from a Dockerfile. My dockerfile isn't easily portable.</p>
<p>Are there simple commands I can use? Or another solution?</p> | <p>You will need to save the Docker image as a tar file:</p>
<pre><code>docker save -o <path for generated tar file> <image name>
</code></pre>
<p>Then copy your image to a new system with regular file transfer tools such as <code>cp</code>, <code>scp</code> or <code>rsync</code>(preferred for big files). After that you will have to load the image into Docker:</p>
<pre><code>docker load -i <path to image tar file>
</code></pre>
<p>PS: You may need to <code>sudo</code> all commands.</p>
<p>EDIT:
You should add filename (not just directory) with -o, for example:</p>
<pre><code>docker save -o c:/myfile.tar centos:16
</code></pre> | {
"question_id": 23935141,
"question_date": "2014-05-29T13:57:18.653Z",
"question_score": 1987,
"tags": "docker",
"answer_id": 23938978,
"answer_date": "2014-05-29T17:09:52.163Z",
"answer_score": 3275
} |
Please answer the following Stack Overflow question:
Title: How do I format XML in Notepad++?
<p>I have <a href="http://en.wikipedia.org/wiki/Notepad%2B%2B" rel="noreferrer">Notepad++</a> and I got some XML code which is very long. When I pasted it in Notepad++ there was a long line of code (difficult to read and work with).</p>
<p>I want to know if there is a simple way to make the text readable (by readable I mean properly tabbed code).</p>
<p>I can do it manually, but I want a permanent solution to this as I have faced this several times. I am sure there is a way to do this as I have done it once before a couple of years back, maybe with <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio" rel="noreferrer">Visual Studio</a> or some other editor, I don't remember.</p>
<p>But can Notepad++ do it?</p> | <p>Try Plugins -> XML Tools -> Pretty Print (libXML) or (XML only - with line breaks <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Shift</kbd> + <kbd>B</kbd>)</p>
<p>You may need to install XML Tools using your plugin manager in order to get this option in your menu.</p>
<p>In my experience, libXML gives nice output but only if the file is 100% correctly formed.</p> | {
"question_id": 3961217,
"question_date": "2010-10-18T16:35:02.860Z",
"question_score": 1983,
"tags": "notepad++|code-formatting",
"answer_id": 3961326,
"answer_date": "2010-10-18T16:48:12.887Z",
"answer_score": 2790
} |
Please answer the following Stack Overflow question:
Title: Config Error: This configuration section cannot be used at this path
<p>I've encountered an error deploying a site to a server. When trying to load the home page, or access authentication on the new site in IIS, I get the error:</p>
<blockquote>
<p>Config Error: This configuration section cannot be used at this path.
This happens when the section is locked at a parent level. Locking is
either by default (overrideModeDefault="Deny"), or set explicitly by a
location tag with overrideMode="Deny" or the legacy
allowOverride="false".</p>
</blockquote>
<p>More detail can be found here, in <a href="https://docs.microsoft.com/en-gb/archive/blogs/webtopics/troubleshooting-http-500-19-errors-in-iis-7" rel="noreferrer">Scenario 7</a> matches my hex error code.</p>
<p>The solution given on the linked site above is to set <strong>Allow</strong> for overrideModeDefault in the section mentioned in my error, in the <em>applicationHost.config</em> file. In my case, under <strong>Security</strong> in <em>system.webServer</em>. But if I look at the <em>applicationHost.config</em> on my local computer, where the site is properly deployed already, that section is set to <strong>Deny</strong>.</p>
<p>If this solution is correct, how is my local instance running just fine with the same <em>web.config</em>? According to my <em>applicationHost.config</em>, that section should be locked, but it's not. I'd prefer to not change the <em>applicationHost.config</em> file, because there are many other sites running on that server. Is there another solution?</p> | <p>I had the same problem. Don't remember where I found it on the web, but here is what I did:</p>
<ul>
<li>Click "Start button"</li>
<li>in the search box, enter "Turn windows features on or off"</li>
<li>in the features window, Click: "Internet Information Services"</li>
<li>Click: "World Wide Web Services"</li>
<li>Click: "Application Development Features"</li>
<li>Check (enable) the features. I checked all but CGI.</li>
</ul>
<p>btw, I'm using Windows 7. Many comments over the years have certified this works all the way up to Windows 10 and Server 2019, as well.</p> | {
"question_id": 9794985,
"question_date": "2012-03-20T21:07:51.537Z",
"question_score": 1981,
"tags": "iis|iis-7|iis-8.5|iis-10",
"answer_id": 12867753,
"answer_date": "2012-10-12T22:06:11.817Z",
"answer_score": 3685
} |
Please answer the following Stack Overflow question:
Title: How do CSS triangles work?
<p>There're plenty of different CSS shapes over at <a href="http://css-tricks.com/examples/ShapesOfCSS/" rel="noreferrer">CSS Tricks - Shapes of CSS</a> and I'm particularly puzzled with a triangle:</p>
<p><img src="https://i.stack.imgur.com/Zcyzo.png" alt="CSS Triangle"></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>#triangle-up {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="triangle-up"></div></code></pre>
</div>
</div>
</p>
<p>How and why does it work?</p> | <h1>CSS Triangles: A Tragedy in Five Acts</h1>
<p>As <a href="https://stackoverflow.com/questions/7073484/how-does-this-css-triangle-shape-work/7073503#7073503">alex said</a>, borders of equal width butt up against each other at 45 degree angles:</p>
<p><img src="https://i.stack.imgur.com/hZefy.png" alt="borders meet at 45 degree angles, content in middle"></p>
<p>When you have no top border, it looks like this:</p>
<p><img src="https://i.stack.imgur.com/uV9Q5.png" alt="no top border"></p>
<p>Then you give it a width of 0...</p>
<p><img src="https://i.stack.imgur.com/K1A7G.png" alt="no width"></p>
<p>...and a height of 0...</p>
<p><img src="https://i.stack.imgur.com/NsmsW.png" alt="no height either"></p>
<p>...and finally, you make the two side borders transparent:</p>
<p><img src="https://i.stack.imgur.com/B42zY.png" alt="transparent side borders"></p>
<p>That results in a triangle.</p> | {
"question_id": 7073484,
"question_date": "2011-08-16T03:54:51.740Z",
"question_score": 1981,
"tags": "css|geometry|polygon|css-shapes",
"answer_id": 7073558,
"answer_date": "2011-08-16T04:11:34.070Z",
"answer_score": 2350
} |
Please answer the following Stack Overflow question:
Title: LEFT JOIN vs. LEFT OUTER JOIN in SQL Server
<p>What is the difference between <code>LEFT JOIN</code> and <code>LEFT OUTER JOIN</code>?</p> | <p>As per the documentation: <a href="http://msdn.microsoft.com/en-us/library/ms177634%28SQL.90%29.aspx" rel="noreferrer">FROM (Transact-SQL)</a>:</p>
<pre><code><join_type> ::=
[ { INNER | { { LEFT | RIGHT | FULL } [ OUTER ] } } [ <join_hint> ] ]
JOIN
</code></pre>
<p>The keyword <code>OUTER</code> is marked as optional (enclosed in square brackets). In this specific case, whether you specify <code>OUTER</code> or not makes no difference. Note that while the other elements of the join clause is also marked as optional, leaving <em>them</em> out <em>will</em> make a difference.</p>
<p>For instance, the entire type-part of the <code>JOIN</code> clause is optional, in which case the default is <code>INNER</code> if you just specify <code>JOIN</code>. In other words, this is legal:</p>
<pre><code>SELECT *
FROM A JOIN B ON A.X = B.Y
</code></pre>
<p>Here's a list of equivalent syntaxes:</p>
<pre><code>A LEFT JOIN B A LEFT OUTER JOIN B
A RIGHT JOIN B A RIGHT OUTER JOIN B
A FULL JOIN B A FULL OUTER JOIN B
A INNER JOIN B A JOIN B
</code></pre>
<p>Also take a look at the answer I left on this other SO question: <a href="https://stackoverflow.com/a/894659/267">SQL left join vs multiple tables on FROM line?</a>.</p> | {
"question_id": 406294,
"question_date": "2009-01-02T08:30:10.297Z",
"question_score": 1977,
"tags": "sql-server|tsql|left-join|outer-join",
"answer_id": 406333,
"answer_date": "2009-01-02T08:51:16.853Z",
"answer_score": 2647
} |
Please answer the following Stack Overflow question:
Title: "Debug certificate expired" error in Eclipse Android plugins
<p>I am using Eclipse Android plugins to build a project, but I am
getting this error in the console window:</p>
<pre><code>[2010-02-03 10:31:14 - androidVNC]Error generating final archive:
Debug certificate expired on 1/30/10 2:35 PM!
</code></pre>
<p>How do I fix it?</p> | <p>Delete your debug certificate under <code>~/.android/debug.keystore</code> on <strong>Linux and Mac OS X</strong>; the directory is something like <code>%USERPROFILE%/.android</code>on <strong>Windows</strong>.</p>
<p>The Eclipse plugin should then generate a new certificate when you next try to build a debug package. You may need to clean and then build to generate the certificate.</p> | {
"question_id": 2194808,
"question_date": "2010-02-03T19:26:15.243Z",
"question_score": 1977,
"tags": "android|eclipse|certificate",
"answer_id": 2196397,
"answer_date": "2010-02-03T23:50:42.300Z",
"answer_score": 2269
} |
Please answer the following Stack Overflow question:
Title: Difference between static class and singleton pattern?
<p>What real (i.e. practical) difference exists between a static class and a singleton pattern?</p>
<p>Both can be invoked without instantiation, both provide only one "Instance" and neither of them is thread-safe. Is there any other difference?</p> | <p>What makes you say that either a singleton or a static method isn't thread-safe? Usually both <em>should</em> be implemented to be thread-safe.</p>
<p>The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common, in my experience), so you can pass around the singleton as if it were "just another" implementation.</p> | {
"question_id": 519520,
"question_date": "2009-02-06T08:13:22.623Z",
"question_score": 1976,
"tags": "design-patterns|static|singleton",
"answer_id": 519530,
"answer_date": "2009-02-06T08:17:44.423Z",
"answer_score": 1377
} |
Please answer the following Stack Overflow question:
Title: Writing to files in Node.js
<p>I've been trying to find a way to write to a file when using Node.js, but with no success. How can I do that?</p> | <p>There are a lot of details in the <a href="http://nodejs.org/docs/latest/api/fs.html" rel="noreferrer">File System API</a>. The most common way is:</p>
<pre class="lang-js prettyprint-override"><code>const fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
// Or
fs.writeFileSync('/tmp/test-sync', 'Hey there!');
</code></pre> | {
"question_id": 2496710,
"question_date": "2010-03-23T00:25:02.683Z",
"question_score": 1969,
"tags": "javascript|node.js|file|express|fs",
"answer_id": 2497040,
"answer_date": "2010-03-23T01:50:15.540Z",
"answer_score": 2852
} |
Please answer the following Stack Overflow question:
Title: What is tail recursion?
<p>Whilst starting to learn lisp, I've come across the term <em>tail-recursive</em>. What does it mean exactly?</p> | <p>Consider a simple function that adds the first N natural numbers. (e.g. <code>sum(5) = 0 + 1 + 2 + 3 + 4 + 5 = 15</code>).</p>
<p>Here is a simple JavaScript implementation that uses recursion:</p>
<pre class="lang-js prettyprint-override"><code>function recsum(x) {
if (x === 0) {
return 0;
} else {
return x + recsum(x - 1);
}
}
</code></pre>
<p>If you called <code>recsum(5)</code>, this is what the JavaScript interpreter would evaluate:</p>
<pre class="lang-js prettyprint-override"><code>recsum(5)
5 + recsum(4)
5 + (4 + recsum(3))
5 + (4 + (3 + recsum(2)))
5 + (4 + (3 + (2 + recsum(1))))
5 + (4 + (3 + (2 + (1 + recsum(0)))))
5 + (4 + (3 + (2 + (1 + 0))))
5 + (4 + (3 + (2 + 1)))
5 + (4 + (3 + 3))
5 + (4 + 6)
5 + 10
15
</code></pre>
<p>Note how every recursive call has to complete before the JavaScript interpreter begins to actually do the work of calculating the sum.</p>
<p>Here's a tail-recursive version of the same function:</p>
<pre class="lang-js prettyprint-override"><code>function tailrecsum(x, running_total = 0) {
if (x === 0) {
return running_total;
} else {
return tailrecsum(x - 1, running_total + x);
}
}
</code></pre>
<p>Here's the sequence of events that would occur if you called <code>tailrecsum(5)</code>, (which would effectively be <code>tailrecsum(5, 0)</code>, because of the default second argument).</p>
<pre class="lang-js prettyprint-override"><code>tailrecsum(5, 0)
tailrecsum(4, 5)
tailrecsum(3, 9)
tailrecsum(2, 12)
tailrecsum(1, 14)
tailrecsum(0, 15)
15
</code></pre>
<p>In the tail-recursive case, with each evaluation of the recursive call, the <code>running_total</code> is updated.</p>
<p><em>Note: The original answer used examples from Python. These have been changed to JavaScript, since Python interpreters don't support <a href="https://stackoverflow.com/questions/310974/what-is-tail-call-optimization">tail call optimization</a>. However, while tail call optimization is <a href="https://www.ecma-international.org/ecma-262/6.0/#sec-tail-position-calls" rel="noreferrer">part of the ECMAScript 2015 spec</a>, most JavaScript interpreters <a href="https://kangax.github.io/compat-table/es6/#test-proper_tail_calls_(tail_call_optimisation)" rel="noreferrer">don't support it</a>.</em></p> | {
"question_id": 33923,
"question_date": "2008-08-29T03:48:03.790Z",
"question_score": 1968,
"tags": "algorithm|language-agnostic|functional-programming|recursion|tail-recursion",
"answer_id": 37010,
"answer_date": "2008-08-31T18:21:13.897Z",
"answer_score": 1997
} |
Please answer the following Stack Overflow question:
Title: Regular cast vs. static_cast vs. dynamic_cast
<p>I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e.</p>
<pre><code>MyClass *m = (MyClass *)ptr;
</code></pre>
<p>all over the place, but there seem to be two other types of casts, and I don't know the difference. What's the difference between the following lines of code?</p>
<pre><code>MyClass *m = (MyClass *)ptr;
MyClass *m = static_cast<MyClass *>(ptr);
MyClass *m = dynamic_cast<MyClass *>(ptr);
</code></pre> | <h2>static_cast</h2>
<p><code>static_cast</code> is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. <code>static_cast</code> performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example:</p>
<pre><code>void func(void *data) {
// Conversion from MyClass* -> void* is implicit
MyClass *c = static_cast<MyClass*>(data);
...
}
int main() {
MyClass c;
start_thread(&func, &c) // func(&c) will be called
.join();
}
</code></pre>
<p>In this example, you know that you passed a <code>MyClass</code> object, and thus there isn't any need for a runtime check to ensure this.</p>
<h2>dynamic_cast</h2>
<p><code>dynamic_cast</code> is useful when you don't know what the dynamic type of the object is. It returns a null pointer if the object referred to doesn't contain the type casted to as a base class (when you cast to a reference, a <code>bad_cast</code> exception is thrown in that case).</p>
<pre><code>if (JumpStm *j = dynamic_cast<JumpStm*>(&stm)) {
...
} else if (ExprStm *e = dynamic_cast<ExprStm*>(&stm)) {
...
}
</code></pre>
<p>You can <strong>not</strong> use <code>dynamic_cast</code> for downcast (casting to a derived class) <strong>if</strong> the argument type is not polymorphic. For example, the following code is not valid, because <code>Base</code> doesn't contain any virtual function:</p>
<pre><code>struct Base { };
struct Derived : Base { };
int main() {
Derived d; Base *b = &d;
dynamic_cast<Derived*>(b); // Invalid
}
</code></pre>
<p>An "up-cast" (cast to the base class) is always valid with both <code>static_cast</code> and <code>dynamic_cast</code>, and also without any cast, as an "up-cast" is an implicit conversion (assuming the base class is accessible, i.e. it's a <code>public</code> inheritance).</p>
<h2>Regular Cast</h2>
<p>These casts are also called C-style cast. A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering <code>dynamic_cast</code>. Needless to say, this is much more powerful as it combines all of <code>const_cast</code>, <code>static_cast</code> and <code>reinterpret_cast</code>, but it's also unsafe, because it does not use <code>dynamic_cast</code>.</p>
<p>In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the "equivalent" <code>static_cast</code> sequence would give you a compile-time error for that.</p>
<p>Some people prefer C-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking.</p> | {
"question_id": 28002,
"question_date": "2008-08-26T13:20:55.357Z",
"question_score": 1963,
"tags": "c++|pointers|casting",
"answer_id": 1255015,
"answer_date": "2009-08-10T13:50:45.557Z",
"answer_score": 1784
} |
Please answer the following Stack Overflow question:
Title: Make the current Git branch a master branch
<p>I have a repository in Git. I made a branch, then did some changes both to the master and to the branch.</p>
<p>Then, tens of commits later, I realized the branch is in much better state than the master, so I want the branch to "become" the master and disregard the changes on master.</p>
<p>I cannot merge it, because I don't want to keep the changes on master. What should I do?</p>
<p><em>Extra</em>: In this case, the 'old' master has already been <code>push</code>-ed to another repository such as GitHub. How does this change things?</p> | <p>The problem with the other two answers is that the new master doesn't have the old master as an ancestor, so when you push it, everyone else will get messed up. This is what you want to do:</p>
<pre><code>git checkout better_branch
git merge --strategy=ours master # keep the content of this branch, but record a merge
git checkout master
git merge better_branch # fast-forward master up to the merge
</code></pre>
<p>If you want your history to be a little clearer, I'd recommend adding some information to the merge commit message to make it clear what you've done. Change the second line to:</p>
<pre><code>git merge --strategy=ours --no-commit master
git commit # add information to the template merge message
</code></pre> | {
"question_id": 2763006,
"question_date": "2010-05-04T05:30:52.700Z",
"question_score": 1962,
"tags": "git",
"answer_id": 2763118,
"answer_date": "2010-05-04T06:00:07.817Z",
"answer_score": 2447
} |
Please answer the following Stack Overflow question:
Title: How to create an array containing 1...N
<p>I'm looking for any alternatives to the below for creating a JavaScript array containing 1 through to N where N is only known at runtime.</p>
<pre><code>var foo = [];
for (var i = 1; i <= N; i++) {
foo.push(i);
}
</code></pre>
<p>To me it feels like there should be a way of doing this without the loop.</p> | <p>If I get what you are after, you want an array of numbers <code>1..n</code> that you can later loop through.</p>
<p>If this is all you need, can you do this instead?</p>
<pre><code>var foo = new Array(45); // create an empty array with length 45
</code></pre>
<p>then when you want to use it... (un-optimized, just for example)</p>
<pre><code>for(var i = 0; i < foo.length; i++){
document.write('Item: ' + (i + 1) + ' of ' + foo.length + '<br/>');
}
</code></pre>
<p>e.g. if you don't need to <strong>store</strong> anything in the array, you just need a container of the right length that you can iterate over... this might be easier.</p>
<p>See it in action here: <a href="http://jsfiddle.net/3kcvm/" rel="noreferrer">http://jsfiddle.net/3kcvm/</a></p> | {
"question_id": 3746725,
"question_date": "2010-09-19T17:34:17.737Z",
"question_score": 1957,
"tags": "javascript|arrays|range",
"answer_id": 3746797,
"answer_date": "2010-09-19T17:54:03.547Z",
"answer_score": 540
} |
Please answer the following Stack Overflow question:
Title: How to get a Docker container's IP address from the host
<p>Is there a command I can run to get the container's IP address right from the host after a new container is created?</p>
<p>Basically, once Docker creates the container, I want to roll my own code deployment and container configuration scripts.</p> | <p>The <code>--format</code> option of <code>inspect</code> comes to the rescue.</p>
<p>Modern Docker client syntax is:</p>
<pre><code>docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id
</code></pre>
<p>Old Docker client syntax is:</p>
<pre><code>docker inspect --format '{{ .NetworkSettings.IPAddress }}' container_name_or_id
</code></pre>
<p>These commands will return the Docker container's IP address.</p>
<p>As mentioned in the comments: if you are on Windows, use double quotes <code>"</code> instead of single quotes <code>'</code> around the curly braces.</p> | {
"question_id": 17157721,
"question_date": "2013-06-17T22:10:22.410Z",
"question_score": 1953,
"tags": "docker|ip-address",
"answer_id": 20686101,
"answer_date": "2013-12-19T15:56:21.003Z",
"answer_score": 3254
} |
Please answer the following Stack Overflow question:
Title: How can I display a JavaScript object?
<p>How do I display the content of a JavaScript object in a string format like when we <code>alert</code> a variable?</p>
<p>The same formatted way I want to display an object.</p> | <p>If you want to print the object for debugging purposes, use the code:</p>
<pre><code>var obj = {
prop1: 'prop1Value',
prop2: 'prop2Value',
child: {
childProp1: 'childProp1Value',
},
}
console.log(obj)
</code></pre>
<p>will display:</p>
<p><a href="https://i.stack.imgur.com/x0Tvz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/x0Tvz.png" alt="screenshot console chrome" /></a></p>
<p><strong>Note:</strong> you must <em>only</em> log the object. For example, this won't work:</p>
<pre><code>console.log('My object : ' + obj)
</code></pre>
<p><strong>Note '</strong>: You can also use a comma in the <code>log</code> method, then the first line of the output will be the string and after that, the object will be rendered:</p>
<pre><code>console.log('My object: ', obj);
</code></pre> | {
"question_id": 957537,
"question_date": "2009-06-05T19:01:59.543Z",
"question_score": 1952,
"tags": "javascript|serialization|javascript-objects",
"answer_id": 957633,
"answer_date": "2009-06-05T19:15:48.860Z",
"answer_score": 1296
} |
Please answer the following Stack Overflow question:
Title: How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?
<p>A C# desktop application (on the Visual Studio Express/Community edition) worked, but then it didn't work 5 seconds later.</p>
<p>I tried the following:</p>
<ul>
<li>Ensure debug configuration, debug flag, and full debug information are set on all assemblies.</li>
<li>Delete all bin and obj folders and all DLL files related to the project from my entire machine.</li>
<li>Recreate projects causing the problem from scratch.</li>
<li>Reboot.</li>
</ul>
<p>I have two Windows Forms projects in the solution. One of them loads the debug information, one doesn't. They both refer to the assembly I'm trying to get debug information on in exactly the same way in the project file. Any ideas?</p>
<hr />
<p>I want to add here, mostly for myself when I come back to review this question, that symbols are not loaded until the assembly is loaded, and the assembly is not loaded until it is needed. If the breakpoint is in a library that is only used in one function in your main assembly, the symbols will not be loaded (and it will show the breakpoint as not being hit) until that function is called.</p> | <p>Start debugging, as soon as you've arrived at a breakpoint or used <code>Debug > Break All</code>, use <code>Debug > Windows > Modules</code>. You'll see a list of all the assemblies that are loaded into the process. Locate the one you want to get debug info for. Right-click it and select Symbol Load Information. You'll get a dialog that lists all the directories where it looked for the .pdb file for the assembly. Verify that list against the actual .pdb location. Make sure it doesn't find an old one.</p>
<p>In normal projects, the assembly and its .pdb file should always have been copied by the IDE into the same folder as your .exe, i.e. the bin\Debug folder of your project. Make sure you remove one from the GAC if you've been playing with it.</p> | {
"question_id": 2155930,
"question_date": "2010-01-28T16:09:10.027Z",
"question_score": 1951,
"tags": "c#|.net|visual-studio|debugging|breakpoints",
"answer_id": 2155997,
"answer_date": "2010-01-28T16:18:08.293Z",
"answer_score": 1269
} |
Please answer the following Stack Overflow question:
Title: What is the difference between an interface and abstract class?
<p>What exactly is the difference between an interface and an abstract class?</p> | <h2>Interfaces</h2>
<p>An interface is a <strong>contract</strong>: The person writing the interface says, "<em>hey, I accept things looking that way</em>", and the person using the interface says "<em>OK, the class I write looks that way</em>".</p>
<p><strong>An interface is an empty shell</strong>. There are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern.</p>
<p>For example (pseudo code):</p>
<pre class="lang-java prettyprint-override"><code>// I say all motor vehicles should look like this:
interface MotorVehicle
{
void run();
int getFuel();
}
// My team mate complies and writes vehicle looking that way
class Car implements MotorVehicle
{
int fuel;
void run()
{
print("Wrroooooooom");
}
int getFuel()
{
return this.fuel;
}
}
</code></pre>
<p>Implementing an interface consumes very little CPU, because it's not a class, just a bunch of names, and therefore there isn't any expensive look-up to do. It's great when it matters, such as in embedded devices.</p>
<hr>
<h2>Abstract classes</h2>
<p>Abstract classes, unlike interfaces, are classes. They are more expensive to use, because there is a look-up to do when you inherit from them.</p>
<p>Abstract classes look a lot like interfaces, but they have something more: You can define a behavior for them. It's more about a person saying, "<em>these classes should look like that, and they have that in common, so fill in the blanks!</em>".</p>
<p>For example:</p>
<pre class="lang-java prettyprint-override"><code>// I say all motor vehicles should look like this:
abstract class MotorVehicle
{
int fuel;
// They ALL have fuel, so lets implement this for everybody.
int getFuel()
{
return this.fuel;
}
// That can be very different, force them to provide their
// own implementation.
abstract void run();
}
// My teammate complies and writes vehicle looking that way
class Car extends MotorVehicle
{
void run()
{
print("Wrroooooooom");
}
}
</code></pre>
<hr>
<h2>Implementation</h2>
<p>While abstract classes and interfaces are supposed to be different concepts, the implementations make that statement sometimes untrue. Sometimes, they are not even what you think they are.</p>
<p>In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method declared.</p>
<p>In Python, abstract classes are more a programming trick you can get from the ABC module and is actually using metaclasses, and therefore classes. And interfaces are more related to duck typing in this language and it's a mix between conventions and special methods that call descriptors (the __method__ methods).</p>
<p>As usual with programming, there is theory, practice, and practice in another language :-)</p> | {
"question_id": 1913098,
"question_date": "2009-12-16T08:15:15.523Z",
"question_score": 1948,
"tags": "oop|interface|abstract-class",
"answer_id": 1913185,
"answer_date": "2009-12-16T08:37:12.303Z",
"answer_score": 2425
} |
Please answer the following Stack Overflow question:
Title: How do I pad a string with zeroes?
<p>How do I pad a numeric string with zeroes to the left, so that the string has a specific length?</p> | <p>To pad strings:</p>
<pre><code>>>> n = '4'
>>> print(n.zfill(3))
004
</code></pre>
<p>To pad numbers:</p>
<pre><code>>>> n = 4
>>> print(f'{n:03}') # Preferred method, python >= 3.6
004
>>> print('%03d' % n)
004
>>> print(format(n, '03')) # python >= 2.6
004
>>> print('{0:03d}'.format(n)) # python >= 2.6 + python 3
004
>>> print('{foo:03d}'.format(foo=n)) # python >= 2.6 + python 3
004
>>> print('{:03d}'.format(n)) # python >= 2.7 + python3
004
</code></pre>
<p><a href="https://docs.python.org/3/library/string.html#format-string-syntax" rel="noreferrer">String formatting documentation</a>.</p> | {
"question_id": 339007,
"question_date": "2008-12-03T22:39:51.883Z",
"question_score": 1948,
"tags": "python|string|zero-padding",
"answer_id": 339013,
"answer_date": "2008-12-03T22:42:04.750Z",
"answer_score": 3105
} |
Please answer the following Stack Overflow question:
Title: Abort Ajax requests using jQuery
<p>Is it possible that using jQuery, I <strong>cancel/abort an Ajax request</strong> that I have not yet received the response from?</p> | <p>Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use <code>abort()</code>.</p>
<p>See the documentation:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms535920%28VS.85%29.aspx" rel="noreferrer">abort Method</a> (<a href="http://en.wikipedia.org/wiki/Microsoft_Developer_Network" rel="noreferrer">MSDN</a>). Cancels the current HTTP request.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort" rel="noreferrer">abort()</a> (<a href="http://en.wikipedia.org/wiki/Mozilla_Developer_Network" rel="noreferrer">MDN</a>). If the request has been sent already, this method will abort the request.</li>
</ul>
<pre><code>var xhr = $.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
</code></pre>
<p><strong>UPDATE:</strong>
As of jQuery 1.5 the returned object is a wrapper for the native XMLHttpRequest object called jqXHR. This object appears to expose all of the native properties and methods so the above example still works. See <em><a href="http://api.jquery.com/jQuery.ajax/#jqXHR" rel="noreferrer">The jqXHR Object</a></em> (jQuery API documentation).</p>
<p><strong>UPDATE 2:</strong>
As of jQuery 3, the ajax method now returns a promise with extra methods (like abort), so the above code still works, though the object being returned is not an <code>xhr</code> any more. See the <a href="http://blog.jquery.com/2016/01/14/jquery-3-0-beta-released/" rel="noreferrer">3.0 blog here</a>. </p>
<p><strong>UPDATE 3</strong>: <code>xhr.abort()</code> still works on jQuery 3.x. Don't assume the <em>update 2</em> is correct. <a href="https://github.com/jquery/jquery/issues/2084#issuecomment-308173243" rel="noreferrer">More info on jQuery Github repository</a>.</p> | {
"question_id": 446594,
"question_date": "2009-01-15T12:45:18.527Z",
"question_score": 1948,
"tags": "javascript|jquery|ajax",
"answer_id": 446626,
"answer_date": "2009-01-15T12:56:49.923Z",
"answer_score": 1835
} |
Please answer the following Stack Overflow question:
Title: How to check if the string is empty?
<p>Does Python have something like an empty string variable where you can do:</p>
<pre><code>if myString == string.empty:
</code></pre>
<p>Regardless, what's the most elegant way to check for empty string values? I find hard coding <code>""</code> every time for checking an empty string not as good.</p> | <p>Empty strings are "falsy" (<a href="http://docs.python.org/2/library/stdtypes.html#truth-value-testing" rel="noreferrer">python 2</a> or <a href="https://docs.python.org/3/library/stdtypes.html#truth-value-testing" rel="noreferrer">python 3</a> reference), which means they are considered false in a Boolean context, so you can just do this:</p>
<pre><code>if not myString:
</code></pre>
<p>This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use:</p>
<pre><code>if myString == "":
</code></pre>
<p>See the documentation on <a href="http://docs.python.org/library/stdtypes.html#truth-value-testing" rel="noreferrer">Truth Value Testing</a> for other values that are false in Boolean contexts.</p> | {
"question_id": 9573244,
"question_date": "2012-03-05T20:09:23.927Z",
"question_score": 1947,
"tags": "python|string|comparison-operators",
"answer_id": 9573259,
"answer_date": "2012-03-05T20:10:21.147Z",
"answer_score": 2825
} |
Please answer the following Stack Overflow question:
Title: Detecting an "invalid date" Date instance in JavaScript
<p>I'd like to tell the difference between valid and invalid date objects in JS, but couldn't figure out how:</p>
<pre><code>var d = new Date("foo");
console.log(d.toString()); // shows 'Invalid Date'
console.log(typeof d); // shows 'object'
console.log(d instanceof Date); // shows 'true'
</code></pre>
<p>Any ideas for writing an <code>isValidDate</code> function?</p>
<ul>
<li>Ash recommended <code>Date.parse</code> for parsing date strings, which gives an authoritative way to check if the date string is valid.</li>
<li>What I would prefer, if possible, is have my API accept a Date instance and to be able to check/assert whether it's valid or not. Borgar's solution does that, but I need to test it across browsers. I also wonder whether there's a more elegant way.</li>
<li>Ash made me consider not having my API accept <code>Date</code> instances at all, this would be easiest to validate.</li>
<li>Borgar suggested testing for a <code>Date</code> instance, and then testing for the <code>Date</code>'s time value. If the date is invalid, the time value is <code>NaN</code>. I checked with <a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-time-values-and-time-range" rel="noreferrer">ECMA-262</a> and this behavior is in the standard, which is exactly what I'm looking for.</li>
</ul> | <p>Here's how I would do it:</p>
<pre><code>if (Object.prototype.toString.call(d) === "[object Date]") {
// it is a date
if (isNaN(d)) { // d.getTime() or d.valueOf() will also work
// date object is not valid
} else {
// date object is valid
}
} else {
// not a date object
}
</code></pre>
<p><strong>Update [2018-05-31]</strong>: If you are not concerned with Date objects from other JS contexts (external windows, frames, or iframes), this simpler form may be preferred:</p>
<pre><code>function isValidDate(d) {
return d instanceof Date && !isNaN(d);
}
</code></pre>
<p><strong>Update [2021-02-01]</strong>: Please note that there is a fundamental difference between "invalid dates" (<code>2013-13-32</code>) and "invalid date <em>objects</em>" (<code>new Date('foo')</code>). This answer <strong>does not</strong> deal with validating date input, only if a Date instance is valid.</p> | {
"question_id": 1353684,
"question_date": "2009-08-30T11:34:40.450Z",
"question_score": 1946,
"tags": "javascript|date",
"answer_id": 1353711,
"answer_date": "2009-08-30T11:48:13.917Z",
"answer_score": 1714
} |
Please answer the following Stack Overflow question:
Title: How do I auto-resize an image to fit a 'div' container?
<p>How do you auto-resize a large image so that it will fit into a smaller width div container whilst maintaining its width:height ratio?</p>
<hr>
<p>Example: stackoverflow.com - when an image is inserted onto the editor panel and the image is too large to fit onto the page, the image is automatically resized.</p> | <p>Do not apply an explicit width or height to the image tag. Instead, give it:</p>
<pre><code>max-width:100%;
max-height:100%;
</code></pre>
<p>Also, <code>height: auto;</code> if you want to specify a width only.</p>
<p>Example: <a href="http://jsfiddle.net/xwrvxser/1/" rel="noreferrer">http://jsfiddle.net/xwrvxser/1/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
max-width: 100%;
max-height: 100%;
}
.portrait {
height: 80px;
width: 30px;
}
.landscape {
height: 30px;
width: 80px;
}
.square {
height: 75px;
width: 75px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code>Portrait Div
<div class="portrait">
<img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>
Landscape Div
<div class="landscape">
<img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>
Square Div
<div class="square">
<img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div></code></pre>
</div>
</div>
</p> | {
"question_id": 3029422,
"question_date": "2010-06-12T17:00:37.277Z",
"question_score": 1945,
"tags": "html|css|image|autoresize",
"answer_id": 3029434,
"answer_date": "2010-06-12T17:03:20.607Z",
"answer_score": 2327
} |
Please answer the following Stack Overflow question:
Title: How to get screen dimensions as pixels in Android
<p>I created some custom elements, and I want to programmatically place them to the upper right corner (<code>n</code> pixels from the top edge and <code>m</code> pixels from the right edge). Therefore I need to get the screen width and screen height and then set position:</p>
<pre><code>int px = screenWidth - m;
int py = screenHeight - n;
</code></pre>
<p>How do I get <code>screenWidth</code> and <code>screenHeight</code> in the main Activity?</p> | <p>If you want the display dimensions in pixels you can use <a href="http://developer.android.com/reference/android/view/Display.html#getSize%28android.graphics.Point%29" rel="noreferrer"><code>getSize</code></a>:</p>
<pre><code>Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
</code></pre>
<p>If you're not in an <code>Activity</code> you can get the default <code>Display</code> via <code>WINDOW_SERVICE</code>:</p>
<pre><code>WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
</code></pre>
<p>If you are in a fragment and want to acomplish this just use Activity.WindowManager (in Xamarin.Android) or getActivity().getWindowManager() (in java).</p>
<p>Before <code>getSize</code> was introduced (in API level 13), you could use the <code>getWidth</code> and <code>getHeight</code> methods that are now deprecated:</p>
<pre><code>Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight(); // deprecated
</code></pre>
<p>For the use case, you're describing, however, a margin/padding in the layout seems more appropriate.</p>
<p>Another way is: <a href="http://developer.android.com/reference/android/util/DisplayMetrics.html" rel="noreferrer">DisplayMetrics</a></p>
<blockquote>
<p>A structure describing general information about a display, such as its size, density, and font scaling. To access the DisplayMetrics members, initialize an object like this:</p>
</blockquote>
<pre><code>DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
</code></pre>
<p>We can use <code>widthPixels</code> to get information for:</p>
<blockquote>
<p>"The absolute width of the display in pixels."</p>
</blockquote>
<p><strong>Example:</strong></p>
<pre><code>Log.d("ApplicationTagName", "Display width in px is " + metrics.widthPixels);
</code></pre>
<p><strong>API level 30 update</strong></p>
<pre><code>final WindowMetrics metrics = windowManager.getCurrentWindowMetrics();
// Gets all excluding insets
final WindowInsets windowInsets = metrics.getWindowInsets();
Insets insets = windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.navigationBars()
| WindowInsets.Type.displayCutout());
int insetsWidth = insets.right + insets.left;
int insetsHeight = insets.top + insets.bottom;
// Legacy size that Display#getSize reports
final Rect bounds = metrics.getBounds();
final Size legacySize = new Size(bounds.width() - insetsWidth,
bounds.height() - insetsHeight);
</code></pre> | {
"question_id": 1016896,
"question_date": "2009-06-19T08:25:57.347Z",
"question_score": 1943,
"tags": "android|layout|screen|pixel|dimensions",
"answer_id": 1016941,
"answer_date": "2009-06-19T08:41:04.510Z",
"answer_score": 3558
} |
Please answer the following Stack Overflow question:
Title: How do I append to a file?
<p>How do I append to a file instead of overwriting it?</p> | <p>Set the mode in <a href="https://docs.python.org/3/library/functions.html#open" rel="noreferrer"><code>open()</code></a> to <code>"a"</code> (append) instead of <code>"w"</code> (write):</p>
<pre class="lang-py prettyprint-override"><code>with open("test.txt", "a") as myfile:
myfile.write("appended text")
</code></pre>
<p>The <a href="https://docs.python.org/3/library/functions.html#open" rel="noreferrer">documentation</a> lists all the available modes.</p> | {
"question_id": 4706499,
"question_date": "2011-01-16T16:20:33.797Z",
"question_score": 1941,
"tags": "python|file|append",
"answer_id": 4706520,
"answer_date": "2011-01-16T16:24:05.127Z",
"answer_score": 2905
} |
Please answer the following Stack Overflow question:
Title: Static methods in Python?
<p>Can I define a <a href="https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods" rel="noreferrer">static method</a> which I can call directly on the class instance? e.g.,</p>
<pre><code>MyClass.the_static_method()
</code></pre> | <p>Yep, using the <a href="https://docs.python.org/3/library/functions.html#staticmethod" rel="noreferrer" title="staticmethod"><code>staticmethod</code></a> decorator:</p>
<pre><code>class MyClass(object):
@staticmethod
def the_static_method(x):
print(x)
MyClass.the_static_method(2) # outputs 2
</code></pre>
<p>Note that some code might use the old method of defining a static method, using <code>staticmethod</code> as a function rather than a decorator. This should only be used if you have to support ancient versions of Python (2.2 and 2.3):</p>
<pre><code>class MyClass(object):
def the_static_method(x):
print(x)
the_static_method = staticmethod(the_static_method)
MyClass.the_static_method(2) # outputs 2
</code></pre>
<p>This is entirely identical to the first example (using <code>@staticmethod</code>), just not using the nice decorator syntax.</p>
<p>Finally, use <a href="https://docs.python.org/3/library/functions.html#staticmethod" rel="noreferrer" title="staticmethod"><code>staticmethod</code></a> sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.</p>
<hr />
<p><a href="https://docs.python.org/3/library/functions.html#staticmethod" rel="noreferrer" title="staticmethod">The following is verbatim from the documentation:</a>:</p>
<blockquote>
<p>A static method does not receive an implicit first argument. To declare a static method, use this idiom:</p>
<pre><code>class C:
@staticmethod
def f(arg1, arg2, ...): ...
</code></pre>
<p>The @staticmethod form is a function <a href="https://docs.python.org/3/glossary.html#term-decorator" rel="noreferrer" title="term-decorator"><em>decorator</em></a> – see the description of function definitions in <a href="https://docs.python.org/3/reference/compound_stmts.html#function" rel="noreferrer" title="Function definitions"><em>Function definitions</em></a> for details.</p>
<p>It can be called either on the class (such as <code>C.f()</code>) or on an instance (such as <code>C().f()</code>). The instance is ignored except for its class.</p>
<p>Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see <a href="https://docs.python.org/3/library/functions.html#classmethod" rel="noreferrer" title="classmethod"><code>classmethod()</code></a>.</p>
<p>For more information on static methods, consult the documentation on the standard type hierarchy in <a href="https://docs.python.org/3/reference/datamodel.html#types" rel="noreferrer" title="types"><em>The standard type hierarchy</em></a>.</p>
<p>New in version 2.2.</p>
<p>Changed in version 2.4: Function decorator syntax added.</p>
</blockquote> | {
"question_id": 735975,
"question_date": "2009-04-09T21:23:19.477Z",
"question_score": 1939,
"tags": "python|static-methods",
"answer_id": 735978,
"answer_date": "2009-04-09T21:24:36.013Z",
"answer_score": 2207
} |
Please answer the following Stack Overflow question:
Title: How to exit from PostgreSQL command line utility: psql
<p>What command or short key can I use to exit the PostgreSQL command line utility <code>psql</code>?</p> | <p>Type <code>\q</code> and then press <code>ENTER</code> to quit <code>psql</code>.</p>
<p><strong>UPDATE: 19-OCT-2018</strong></p>
<p>As of <em>PostgreSQL 11</em>, the keywords "<code>quit</code>" and "<code>exit</code>" in the PostgreSQL command-line interface have been included to help make it easier to leave the command-line tool.</p> | {
"question_id": 9463318,
"question_date": "2012-02-27T10:17:44.657Z",
"question_score": 1937,
"tags": "postgresql|postgresql-9.1|psql",
"answer_id": 9463370,
"answer_date": "2012-02-27T10:21:48.693Z",
"answer_score": 2659
} |
Please answer the following Stack Overflow question:
Title: Can't bind to 'ngModel' since it isn't a known property of 'input'
<p>I have this simple input in my component which uses <code>[(ngModel)]</code> :</p>
<pre class="lang-html prettyprint-override"><code><input type="text" [(ngModel)]="test" placeholder="foo" />
</code></pre>
<p>And I get the following error when I launch my app, even if the component is not displayed.</p>
<blockquote>
<p>zone.js:461 Unhandled Promise rejection: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'input'.</p>
</blockquote>
<p>Here is the component.ts:</p>
<pre><code>import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { Intervention } from '../../model/intervention';
@Component({
selector: 'intervention-details',
templateUrl: 'app/intervention/details/intervention.details.html',
styleUrls: ['app/intervention/details/intervention.details.css']
})
export class InterventionDetails
{
@Input() intervention: Intervention;
public test : string = "toto";
}
</code></pre> | <p>Yes, that's it. In the <em>app.module.ts</em> file, I just added:</p>
<pre><code>import { FormsModule } from '@angular/forms';
[...]
@NgModule({
imports: [
[...]
FormsModule
],
[...]
})
</code></pre> | {
"question_id": 38892771,
"question_date": "2016-08-11T09:44:32.477Z",
"question_score": 1933,
"tags": "javascript|angular|typescript|input",
"answer_id": 38896469,
"answer_date": "2016-08-11T12:30:09.227Z",
"answer_score": 2629
} |
Please answer the following Stack Overflow question:
Title: Click through div to underlying elements
<p>I have a <code>div</code> that has <code>background:transparent</code>, along with <code>border</code>. Underneath this <code>div</code>, I have more elements.</p>
<p>Currently, I'm able to click the underlying elements when I click outside of the overlay <code>div</code>. However, I'm unable to click the underlying elements when clicking directly on the overlay <code>div</code>. </p>
<p>I want to be able to click through this <code>div</code> so that I can click on the underlying elements.</p>
<p><img src="https://i.stack.imgur.com/VDlDa.png" alt="My Problem"></p> | <p>Yes, you <strong>CAN</strong> do this. </p>
<p>Using <code>pointer-events: none</code> along with CSS conditional statements for IE11 (does not work in IE10 or below), you can get a cross browser compatible solution for this problem.</p>
<p>Using <code>AlphaImageLoader</code>, you can even put transparent <code>.PNG/.GIF</code>s in the overlay <code>div</code> and have clicks flow through to elements underneath.</p>
<p>CSS:</p>
<pre class="lang-css prettyprint-override"><code>pointer-events: none;
background: url('your_transparent.png');
</code></pre>
<p>IE11 conditional:</p>
<pre><code>filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='your_transparent.png', sizingMethod='scale');
background: none !important;
</code></pre>
<p>Here is a <a href="http://www.searchlawrence.com/click-through-a-div-to-underlying-elements.html" rel="noreferrer">basic example page</a> with all the code.</p> | {
"question_id": 3680429,
"question_date": "2010-09-09T20:42:54.743Z",
"question_score": 1932,
"tags": "css|click|mouseevent|layer",
"answer_id": 4839672,
"answer_date": "2011-01-29T21:49:17.727Z",
"answer_score": 3102
} |
Please answer the following Stack Overflow question:
Title: Undo working copy modifications of one file in Git?
<p>After the last commit, I modified a bunch of files in my working copy, but I want to undo the changes to one of those files, as in reset it to the same state as the most recent commit.</p>
<p>However, I only want to undo the working copy changes of just that one file alone, nothing else with it.</p>
<p>How do I do that?</p> | <p>You can use</p>
<pre><code>git checkout -- file
</code></pre>
<p>You can do it without the <code>--</code> (as suggested by nimrodm), but if the filename looks like a branch or tag (or other revision identifier), it may get confused, so using <code>--</code> is best.</p>
<p>You can also check out a particular version of a file:</p>
<pre><code>git checkout v1.2.3 -- file # tag v1.2.3
git checkout stable -- file # stable branch
git checkout origin/master -- file # upstream master
git checkout HEAD -- file # the version from the most recent commit
git checkout HEAD^ -- file # the version before the most recent commit
</code></pre> | {
"question_id": 692246,
"question_date": "2009-03-28T05:09:02.883Z",
"question_score": 1929,
"tags": "git|file|version-control|dvcs|undo",
"answer_id": 692329,
"answer_date": "2009-03-28T06:12:51.403Z",
"answer_score": 2561
} |
Please answer the following Stack Overflow question:
Title: How does Git handle symbolic links?
<p>If I have a file or directory that is a symbolic link and I commit it to a Git repository, what happens to it?</p>
<p>I would assume that it leaves it as a symbolic link until the file is deleted and then if you pull the file back from an old version it just creates a normal file.</p>
<p>What does it do when I delete the file it references? Does it just commit the dangling link?</p> | <p>From <a href="https://man7.org/linux/man-pages/man7/symlink.7.html" rel="noreferrer">linux symlink manual</a> (assuming you are in Linux):</p>
<blockquote>
<p>A symbolic link is a special type of file whose contents are a string that is the pathname of another file, the file to which the link refers. (The contents of a symbolic link can be read using readlink(2).)</p>
</blockquote>
<p>So a symbolic link is one more file, just as a <code>README.md</code> or a <code>Makefile</code>. Git just stores the contents of the link (i.e. the aforementioned path of the file system object that it links to) in a 'blob' just like it would for any other file. It then stores the name, mode and type (including the fact that it is a symlink) in the tree object that represents its containing directory.</p>
<p>When you checkout a tree containing the link, it restores the object as a symlink regardless of whether the target file system object exists or not.</p>
<p>If you delete the file that the symlink references it doesn't affect the Git-controlled symlink in any way. You will have a dangling reference. It is up to the user to either remove or change the link to point to something valid if needed.</p> | {
"question_id": 954560,
"question_date": "2009-06-05T06:53:33.020Z",
"question_score": 1928,
"tags": "git|version-control|symlink",
"answer_id": 954575,
"answer_date": "2009-06-05T07:01:18.993Z",
"answer_score": 1563
} |
Please answer the following Stack Overflow question:
Title: What is the difference between a process and a thread?
<p>What is the technical difference between a process and a thread?</p>
<p>I get the feeling a word like 'process' is overused and there are also hardware and software threads. How about light-weight processes in languages like <a href="http://en.wikipedia.org/wiki/Erlang_%28programming_language%29" rel="noreferrer">Erlang</a>? Is there a definitive reason to use one term over the other?</p> | <p>Both processes and threads are independent sequences of execution. The typical difference is that threads (of the same process) run in a shared memory space, while processes run in separate memory spaces.</p>
<p>I'm not sure what "hardware" vs "software" threads you might be referring to. Threads are an operating environment feature, rather than a CPU feature (though the CPU typically has operations that make threads efficient).</p>
<p>Erlang uses the term "process" because it does not expose a shared-memory multiprogramming model. Calling them "threads" would imply that they have shared memory.</p> | {
"question_id": 200469,
"question_date": "2008-10-14T09:13:24.247Z",
"question_score": 1926,
"tags": "multithreading|process|operating-system",
"answer_id": 200473,
"answer_date": "2008-10-14T09:15:58.967Z",
"answer_score": 1691
} |
Please answer the following Stack Overflow question:
Title: How do I get PHP errors to display?
<p>I have checked my PHP ini file (<code>php.ini</code>) and <code>display_errors</code> is set and also error reporting is <code>E_ALL</code>. I have restarted my Apache webserver.</p>
<p>I have even put these lines at the top of my script, and it doesn't even catch simple parse errors. For example, I declare variables with a <code>"$"</code> and I don't close statements<code>";"</code>. But all my scripts show a blank page on these errors, but I want to actually see the <strong>errors</strong> in my browser output. </p>
<pre><code>error_reporting(E_ALL);
ini_set('display_errors', 1);
</code></pre>
<p>What is left to do?</p> | <p>This always works for me:</p>
<pre><code>ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
</code></pre>
<p>However, this doesn't make PHP to show parse errors - the only way to show those errors is to modify your php.ini with this line:</p>
<pre><code>display_errors = on
</code></pre>
<p>(if you don't have access to <code>php.ini</code>, then putting this line in <code>.htaccess</code> might work too):</p>
<pre><code>php_flag display_errors 1
</code></pre> | {
"question_id": 1053424,
"question_date": "2009-06-27T19:09:59.530Z",
"question_score": 1925,
"tags": "php|error-handling|syntax-error|error-reporting",
"answer_id": 21429652,
"answer_date": "2014-01-29T11:25:17.323Z",
"answer_score": 3469
} |
Please answer the following Stack Overflow question:
Title: How to generate a random alpha-numeric string
<p>I've been looking for a <em>simple</em> Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would "likely" be unique over <code>500K+</code> generation (my needs don't really require anything much more sophisticated). </p>
<p>Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like <code>"AEYGF7K0DM1X"</code>. </p> | <h2>Algorithm</h2>
<p>To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length.</p>
<h2>Implementation</h2>
<p>Here's some fairly simple and very flexible code for generating random identifiers. <em>Read the information that follows</em> for important application notes.</p>
<pre><code>public class RandomString {
/**
* Generate a random string.
*/
public String nextString() {
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols[random.nextInt(symbols.length)];
return new String(buf);
}
public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String lower = upper.toLowerCase(Locale.ROOT);
public static final String digits = "0123456789";
public static final String alphanum = upper + lower + digits;
private final Random random;
private final char[] symbols;
private final char[] buf;
public RandomString(int length, Random random, String symbols) {
if (length < 1) throw new IllegalArgumentException();
if (symbols.length() < 2) throw new IllegalArgumentException();
this.random = Objects.requireNonNull(random);
this.symbols = symbols.toCharArray();
this.buf = new char[length];
}
/**
* Create an alphanumeric string generator.
*/
public RandomString(int length, Random random) {
this(length, random, alphanum);
}
/**
* Create an alphanumeric strings from a secure generator.
*/
public RandomString(int length) {
this(length, new SecureRandom());
}
/**
* Create session identifiers.
*/
public RandomString() {
this(21);
}
}
</code></pre>
<h2>Usage examples</h2>
<p>Create an insecure generator for 8-character identifiers:</p>
<pre><code>RandomString gen = new RandomString(8, ThreadLocalRandom.current());
</code></pre>
<p>Create a secure generator for session identifiers:</p>
<pre><code>RandomString session = new RandomString();
</code></pre>
<p>Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols:</p>
<pre><code>String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";
RandomString tickets = new RandomString(23, new SecureRandom(), easy);
</code></pre>
<h2>Use as session identifiers</h2>
<p>Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used.</p>
<p>There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand.</p>
<p>The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible.</p>
<h2>Use as object identifiers</h2>
<p>Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big.</p>
<p>Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission.</p>
<p>Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." <a href="https://en.wikipedia.org/wiki/Birthday_problem#Square_approximation" rel="noreferrer">The probability of a collision,</a> <em>p</em>, is approximately n<sup>2</sup>/(2q<sup>x</sup>), where <em>n</em> is the number of identifiers actually generated, <em>q</em> is the number of distinct symbols in the alphabet, and <em>x</em> is the length of the identifiers. This should be a very small number, like 2<sup>‑50</sup> or less.</p>
<p>Working this out shows that the chance of collision among 500k 15-character identifiers is about 2<sup>‑52</sup>, which is probably less likely than undetected errors from cosmic rays, etc.</p>
<h2>Comparison with UUIDs</h2>
<p>According to their specification, <a href="https://www.rfc-editor.org/rfc/rfc4122#section-6" rel="noreferrer">UUIDs</a> are not designed to be unpredictable, and <em>should not</em> be used as session identifiers.</p>
<p>UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters.</p>
<p>UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.</p> | {
"question_id": 41107,
"question_date": "2008-09-03T02:58:43.073Z",
"question_score": 1925,
"tags": "java|string|random|alphanumeric",
"answer_id": 41156,
"answer_date": "2008-09-03T04:04:24.647Z",
"answer_score": 1624
} |
Please answer the following Stack Overflow question:
Title: What's the difference between the atomic and nonatomic attributes?
<p>What do <code>atomic</code> and <code>nonatomic</code> mean in property declarations?</p>
<pre><code>@property(nonatomic, retain) UITextField *userName;
@property(atomic, retain) UITextField *userName;
@property(retain) UITextField *userName;
</code></pre>
<p>What is the operational difference between these three?</p> | <p>The last two are identical; "atomic" is the default behavior (<strike>note that it is not actually a keyword; it is specified only by the absence of <code>nonatomic</code></strike> -- <code>atomic</code> was added as a keyword in recent versions of llvm/clang).</p>
<p>Assuming that you are @synthesizing the method implementations, atomic vs. non-atomic changes the generated code. If you are writing your own setter/getters, atomic/nonatomic/retain/assign/copy are merely advisory. (Note: @synthesize is now the default behavior in recent versions of LLVM. There is also no need to declare instance variables; they will be synthesized automatically, too, and will have an <code>_</code> prepended to their name to prevent accidental direct access).</p>
<p>With "atomic", the synthesized setter/getter will ensure that a <em>whole</em> value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value -- an autoreleased object, most likely -- will be returned to the caller in A.</p>
<p>In <code>nonatomic</code>, no such guarantees are made. Thus, <code>nonatomic</code> is considerably faster than "atomic".</p>
<p>What "atomic" does <strong>not</strong> do is make any guarantees about thread safety. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned -- the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.</p>
<p>Ensuring data integrity -- one of the primary challenges of multi-threaded programming -- is achieved by other means.</p>
<p>Adding to this:</p>
<p><code>atomicity</code> of a single property also cannot guarantee thread safety when multiple dependent properties are in play.</p>
<p>Consider:</p>
<pre><code> @property(atomic, copy) NSString *firstName;
@property(atomic, copy) NSString *lastName;
@property(readonly, atomic, copy) NSString *fullName;
</code></pre>
<p>In this case, thread A could be renaming the object by calling <code>setFirstName:</code> and then calling <code>setLastName:</code>. In the meantime, thread B may call <code>fullName</code> in between thread A's two calls and will receive the new first name coupled with the old last name.</p>
<p>To address this, you need a <em>transactional model</em>. I.e. some other kind of synchronization and/or exclusion that allows one to exclude access to <code>fullName</code> while the dependent properties are being updated.</p> | {
"question_id": 588866,
"question_date": "2009-02-26T02:31:34.370Z",
"question_score": 1923,
"tags": "ios|objective-c|properties|atomic|nonatomic",
"answer_id": 589392,
"answer_date": "2009-02-26T06:40:50.107Z",
"answer_score": 1800
} |
Please answer the following Stack Overflow question:
Title: How can I remove a commit on GitHub?
<p>I "accidentally" pushed a commit to GitHub.</p>
<p>Is it possible to remove this commit?</p>
<p>I want to revert my GitHub repository as it was before this commit.</p> | <blockquote>
<p><strong>Note:</strong> please see an alternative to <code>git rebase -i</code> in the comments below—</p>
<p><code>git reset --soft HEAD^</code></p>
</blockquote>
<p>First, remove the commit on your local repository. You can do this using <code>git rebase -i</code>. For example, if it's your last commit, you can do <code>git rebase -i HEAD~2</code> and delete the second line within the editor window that pops up.</p>
<p>Then, force push to GitHub by using <code>git push origin +branchName --force</code></p>
<p>See <a href="http://www-cs-students.stanford.edu/%7Eblynn/gitmagic/ch05.html#_8230_and_then_some" rel="noreferrer">Git Magic Chapter 5: Lessons of History - And Then Some</a> for more information (i.e. if you want to remove older commits).</p>
<p>Oh, and if your working tree is dirty, you have to do a <code>git stash</code> first, and then a <code>git stash apply</code> after.</p> | {
"question_id": 448919,
"question_date": "2009-01-15T23:20:54.127Z",
"question_score": 1921,
"tags": "git|github|git-commit",
"answer_id": 448929,
"answer_date": "2009-01-15T23:24:03.400Z",
"answer_score": 1404
} |
Please answer the following Stack Overflow question:
Title: Detach (move) subdirectory into separate Git repository
<p>I have a <a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="noreferrer">Git</a> repository which contains a number of subdirectories. Now I have found that one of the subdirectories is unrelated to the other and should be detached to a separate repository.</p>
<p>How can I do this while keeping the history of the files within the subdirectory?</p>
<p>I guess I could make a clone and remove the unwanted parts of each clone, but I suppose this would give me the complete tree when checking out an older revision etc. This might be acceptable, but I would prefer to be able to pretend that the two repositories doesn't have a shared history.</p>
<p>Just to make it clear, I have the following structure:</p>
<pre><code>XYZ/
.git/
XY1/
ABC/
XY2/
</code></pre>
<p>But I would like this instead:</p>
<pre><code>XYZ/
.git/
XY1/
XY2/
ABC/
.git/
ABC/
</code></pre> | <p><strong>Update</strong>: This process is so common, that the git team made it much simpler with a new tool, <code>git subtree</code>. See here: <a href="https://stackoverflow.com/questions/359424/detach-subdirectory-into-separate-git-repository/17864475#17864475">Detach (move) subdirectory into separate Git repository</a></p>
<hr>
<p>You want to clone your repository and then use <code>git filter-branch</code> to mark everything but the subdirectory you want in your new repo to be garbage-collected.</p>
<ol>
<li><p>To clone your local repository:</p>
<pre><code>git clone /XYZ /ABC
</code></pre>
<p>(Note: the repository will be cloned using hard-links, but that is not a problem since the hard-linked files will not be modified in themselves - new ones will be created.)</p></li>
<li><p>Now, let us preserve the interesting branches which we want to rewrite as well, and then remove the origin to avoid pushing there and to make sure that old commits will not be referenced by the origin:</p>
<pre><code>cd /ABC
for i in branch1 br2 br3; do git branch -t $i origin/$i; done
git remote rm origin
</code></pre>
<p>or for all remote branches:</p>
<pre><code>cd /ABC
for i in $(git branch -r | sed "s/.*origin\///"); do git branch -t $i origin/$i; done
git remote rm origin
</code></pre></li>
<li><p>Now you might want to also remove tags which have no relation with the subproject; you can also do that later, but you might need to prune your repo again. I did not do so and got a <code>WARNING: Ref 'refs/tags/v0.1' is unchanged</code> for all tags (since they were all unrelated to the subproject); additionally, after removing such tags more space will be reclaimed. Apparently <code>git filter-branch</code> should be able to rewrite other tags, but I could not verify this. If you want to remove all tags, use <code>git tag -l | xargs git tag -d</code>.</p></li>
<li><p>Then use filter-branch and reset to exclude the other files, so they can be pruned. Let's also add <code>--tag-name-filter cat --prune-empty</code> to remove empty commits and to rewrite tags (note that this will have to strip their signature):</p>
<pre><code>git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter ABC -- --all
</code></pre>
<p>or alternatively, to only rewrite the HEAD branch and ignore tags and other branches:</p>
<pre><code>git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter ABC HEAD
</code></pre></li>
<li><p>Then delete the backup reflogs so the space can be truly reclaimed (although now the operation is destructive)</p>
<pre><code>git reset --hard
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
git reflog expire --expire=now --all
git gc --aggressive --prune=now
</code></pre>
<p>and now you have a local git repository of the ABC sub-directory with all its history preserved. </p></li>
</ol>
<p>Note: For most uses, <code>git filter-branch</code> should indeed have the added parameter <code>-- --all</code>. Yes that's really <kbd>-</kbd><kbd>-</kbd><kbd>space</kbd><kbd>-</kbd><kbd>-</kbd> <code>all</code>. This needs to be the last parameters for the command. As Matli discovered, this keeps the project branches and tags included in the new repo.</p>
<p>Edit: various suggestions from comments below were incorporated to make sure, for instance, that the repository is actually shrunk (which was not always the case before).</p> | {
"question_id": 359424,
"question_date": "2008-12-11T13:57:03.617Z",
"question_score": 1920,
"tags": "git|git-subtree|git-filter-branch",
"answer_id": 359759,
"answer_date": "2008-12-11T15:40:54.280Z",
"answer_score": 1266
} |
Please answer the following Stack Overflow question:
Title: How do I fix a Git detached head?
<p>I was doing some work in my repository and noticed a file had local changes. I didn't want them anymore so I deleted the file, thinking I can just checkout a fresh copy. I wanted to do the Git equivalent of</p>
<pre><code>svn up .
</code></pre>
<p>Using <code>git pull</code> didn't seem to work. Some random searching led me to a site where someone recommended doing</p>
<pre><code>git checkout HEAD^ src/
</code></pre>
<p>(<code>src</code> is the directory containing the deleted file).</p>
<p><strong>Now I find out I have a detached head. I have no idea what that is. How can I undo?</strong></p> | <p>Detached head means you are no longer on a branch, you have checked out a single commit in the history (in this case the commit previous to HEAD, i.e. HEAD^).</p>
<h2>If you want to <em>delete</em> your changes associated with the detached HEAD</h2>
<p>You only need to checkout the branch you were on, e.g.</p>
<pre><code>git checkout master
</code></pre>
<p>Next time you have changed a file and want to restore it to the state it is in the index, don't delete the file first, just do</p>
<pre><code>git checkout -- path/to/foo
</code></pre>
<p>This will restore the file foo to the state it is in the index.</p>
<h2>If you want to <em>keep</em> your changes associated with the detached HEAD</h2>
<ol>
<li>Run <code>git branch tmp</code> - this will save your changes in a new branch called <code>tmp</code>.</li>
<li>Run <code>git checkout master</code></li>
<li>If you would like to incorporate the changes you made into <code>master</code>, run <code>git merge tmp</code> from the <code>master</code> branch. You should be on the <code>master</code> branch after running <code>git checkout master</code>.</li>
</ol> | {
"question_id": 10228760,
"question_date": "2012-04-19T13:07:05.427Z",
"question_score": 1919,
"tags": "git|git-detached-head",
"answer_id": 10229202,
"answer_date": "2012-04-19T13:32:58.277Z",
"answer_score": 2762
} |
Please answer the following Stack Overflow question:
Title: Comments in Markdown
<p>How do you write a comment in Markdown, i.e. text that is not rendered in the HTML output? I found nothing on the <a href="http://daringfireball.net/projects/markdown/" rel="noreferrer">Markdown project</a>.</p> | <p>I believe that all the previously proposed solutions (apart from those that require specific implementations) result in the comments being included in the output HTML, even if they are not displayed.</p>
<p>If you want a comment that is strictly for yourself (readers of the converted document should not be able to see it, even with "view source") you could (ab)use the link labels (for use with reference style links) that are available in the core Markdown specification:</p>
<p><a href="http://daringfireball.net/projects/markdown/syntax#link" rel="noreferrer">http://daringfireball.net/projects/markdown/syntax#link</a></p>
<p>That is:</p>
<pre><code>[comment]: <> (This is a comment, it will not be included)
[comment]: <> (in the output file unless you use it in)
[comment]: <> (a reference style link.)
</code></pre>
<p>Or you could go further:</p>
<pre><code>[//]: <> (This is also a comment.)
</code></pre>
<p>To improve platform compatibility (and to save one keystroke) it is also possible to use <code>#</code> (which is a legitimate hyperlink target) instead of <code><></code>:</p>
<pre><code>[//]: # (This may be the most platform independent comment)
</code></pre>
<p>For maximum portability it is important to insert a blank line before and after this type of comments, because some Markdown parsers do not work correctly when definitions brush up against regular text. The most recent research with Babelmark shows that blank lines before and after are both important. Some parsers will output the comment if there is no blank line before, and some parsers will exclude the following line if there is no blank line after.</p>
<p>In general, this approach should work with most Markdown parsers, since it's part of the core specification. (even if the behavior when multiple links are defined, or when a link is defined but never used, is not strictly specified).</p> | {
"question_id": 4823468,
"question_date": "2011-01-28T00:18:11.507Z",
"question_score": 1918,
"tags": "syntax|comments|markdown",
"answer_id": 20885980,
"answer_date": "2014-01-02T15:18:49.543Z",
"answer_score": 1983
} |
Please answer the following Stack Overflow question:
Title: How can I count all the lines of code in a directory recursively?
<p>We've got a PHP application and want to count all the lines of code under a specific directory and its subdirectories.</p>
<p>We don't need to ignore comments, as we're just trying to get a rough idea.</p>
<pre><code>wc -l *.php
</code></pre>
<p>That command works great for a given directory, but it ignores subdirectories. I was thinking the following comment might work, but it is returning 74, which is definitely not the case...</p>
<pre><code>find . -name '*.php' | wc -l
</code></pre>
<p>What's the correct syntax to feed in all the files from a directory resursively?</p> | <p><strong>Try:</strong></p>
<pre><code>find . -name '*.php' | xargs wc -l
</code></pre>
<p>or (when file names include special characters such as spaces)</p>
<pre><code>find . -name '*.php' | sed 's/.*/"&"/' | xargs wc -l
</code></pre>
<p><strong><a href="https://dwheeler.com/sloccount/" rel="noreferrer">The SLOCCount tool</a></strong> may help as well.</p>
<p>It will give an accurate source lines of code count for whatever
hierarchy you point it at, as well as some additional stats.</p>
<p><strong>Sorted output:</strong></p>
<p><code>find . -name '*.php' | xargs wc -l | sort -nr</code></p> | {
"question_id": 1358540,
"question_date": "2009-08-31T17:42:20.160Z",
"question_score": 1916,
"tags": "bash|shell",
"answer_id": 1358573,
"answer_date": "2009-08-31T17:50:12.127Z",
"answer_score": 3098
} |
Please answer the following Stack Overflow question:
Title: How to do case insensitive search in Vim
<p>I'd like to search for an upper case word, for example COPYRIGHT in a file. I tried performing a search like:</p>
<pre><code>/copyright/i # Doesn't work
</code></pre>
<p>but it doesn't work. I know that in Perl, if I give the <code>i</code> flag into a regex it will turn the regex into a case-insensitive regex. It seems that Vim has its own way to indicate a case-insensitive regex.</p> | <p>You can use the <code>\c</code> escape sequence anywhere in the pattern. For example:</p>
<p><code>/\ccopyright</code> or <code>/copyright\c</code> or even <code>/copyri\cght</code></p>
<p>To do the inverse (case <em>sensitive</em> matching), use <code>\C</code> (capital C) instead.</p> | {
"question_id": 2287440,
"question_date": "2010-02-18T09:17:00.227Z",
"question_score": 1916,
"tags": "search|vim|case-insensitive",
"answer_id": 2287449,
"answer_date": "2010-02-18T09:18:23.693Z",
"answer_score": 2454
} |
Please answer the following Stack Overflow question:
Title: What do two question marks together mean in C#?
<p>Ran across this line of code:</p>
<pre><code>FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
</code></pre>
<p>What do the two question marks mean, is it some kind of ternary operator?
It's hard to look up in Google.</p> | <p>It's the null coalescing operator, and quite like the ternary (immediate-if) operator. See also <a href="https://docs.microsoft.com/en-in/dotnet/csharp/language-reference/operators/null-coalescing-operator" rel="noreferrer">?? Operator - MSDN</a>.</p>
<pre><code>FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
</code></pre>
<p>expands to:</p>
<pre><code>FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();
</code></pre>
<p>which further expands to:</p>
<pre><code>if(formsAuth != null)
FormsAuth = formsAuth;
else
FormsAuth = new FormsAuthenticationWrapper();
</code></pre>
<p>In English, it means "If whatever is to the left is not null, use that, otherwise use what's to the right."</p>
<p>Note that you can use any number of these in sequence. The following statement will assign the first non-null <code>Answer#</code> to <code>Answer</code> (if all Answers are null then the <code>Answer</code> is null):</p>
<pre><code>string Answer = Answer1 ?? Answer2 ?? Answer3 ?? Answer4;
</code></pre>
<hr>
<p>Also it's worth mentioning while the expansion above is conceptually equivalent, the result of each expression is only evaluated once. This is important if for example an expression is a method call with side effects. (Credit to @Joey for pointing this out.)</p> | {
"question_id": 446835,
"question_date": "2009-01-15T14:03:13.423Z",
"question_score": 1912,
"tags": "c#|null-coalescing-operator",
"answer_id": 446839,
"answer_date": "2009-01-15T14:04:33.797Z",
"answer_score": 2515
} |
Please answer the following Stack Overflow question:
Title: How to detect a mobile device using jQuery
<p>Is there a way to detect whether or not a user is using a mobile device in jQuery? Something similar to the CSS <code>@media</code> attribute? I would like to run a different script if the browser is on a handheld device.</p>
<p>The jQuery <code>$.browser</code> function is not what I am looking for.</p> | <p><strong>Editor's note:</strong> user agent detection is not a recommended technique for modern web apps. See the comments below this answer for confirmation of this fact. It is suggested to use one of the other answers using feature detection and/or media queries.</p>
<hr />
<p>Instead of using jQuery you can use simple JavaScript to detect it:</p>
<pre><code>if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
// some code..
}
</code></pre>
<p>Or you can combine them both to make it more accessible through jQuery...</p>
<pre><code>$.browser.device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));
</code></pre>
<p>Now <code>$.browser</code> will return <code>"device"</code> for all above devices</p>
<p>Note: <code>$.browser</code> removed on <a href="http://jquery.com/upgrade-guide/1.9/#jquery-browser-removed" rel="noreferrer"><strong>jQuery v1.9.1</strong></a>. But you can use this by using jQuery migration plugin <a href="https://stackoverflow.com/a/15072522/2724173"><strong>Code</strong></a></p>
<hr />
<p>A more thorough version:</p>
<pre><code>var isMobile = false; //initiate as false
// device detection
if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
|| /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))) {
isMobile = true;
}
</code></pre> | {
"question_id": 3514784,
"question_date": "2010-08-18T17:22:22.040Z",
"question_score": 1909,
"tags": "javascript|jquery|mobile|browser-detection",
"answer_id": 3540295,
"answer_date": "2010-08-22T05:26:26.297Z",
"answer_score": 2275
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.