input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: What exactly is Apache Camel?
<p>I don't understand what exactly <a href="http://camel.apache.org/index.html" rel="noreferrer">Camel</a> does.</p>
<p>If you could give in 101 words an introduction to Camel:</p>
<ul>
<li>What exactly is it? </li>
<li>How does it interact with an application written in Java? </li>
<li>Is it something that goes together with the server? </li>
<li>Is it an independent program? </li>
</ul>
<p><strong>Please explain what Camel is.</strong></p> | <p>My take to describe this in a more accessible way...</p>
<p>In order to understand what Apache Camel is, you need to understand what are <a href="https://en.wikipedia.org/wiki/Enterprise_Integration_Patterns" rel="noreferrer">Enterprise Integration Patterns</a>.</p>
<p>Let's start with what we presumably already know: The <a href="https://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">Singleton pattern</a>, the Factory pattern, etc; They are merely ways of organizing your solution to the problem, but they are not solutions themselves. These patterns were analyzed and extracted for the rest of us by the Gang of Four, when they published their book: <a href="http://en.wikipedia.org/wiki/Design_Patterns" rel="noreferrer" title="Design Patterns">Design Patterns</a>. They saved some of us tremendous effort in thinking of how to best structure our code.</p>
<p>Much like the Gang of Four, Gregor Hohpe and Bobby Woolf authored the book <a href="http://www.eaipatterns.com/" rel="noreferrer" title="Enterprise Integration Patterns book website"><em>Enterprise Integration Patterns</em></a> (EIP) in which they propose and document a set of new patterns and <em>blueprints</em> for how we could <em>best</em> design large component-based systems, where components can be running on the same process or in a different machine.</p>
<p>They basically propose that we structure our system to be <em>message</em> oriented -- where components communicate with each others using messages as inputs and outputs and absolutely nothing else. They show us a complete set of patterns that we may choose from and implement in our different components that will together form the whole system.</p>
<p><strong>So what is Apache Camel?</strong></p>
<p>Apache Camel offers you the interfaces for the EIPs, the base objects, commonly needed implementations, debugging tools, a configuration system, and many other helpers which will save you a ton of time when you want to implement your solution to follow the EIPs.</p>
<p>Take <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="noreferrer">MVC</a>. MVC is pretty simple in theory and we could implement it without any framework help. But good MVC frameworks provide us with the structure ready-to-use and have gone the extra mile and thought out all the other "side" things you need when you create a large MVC project and that's why we use them most of the time.</p>
<p>That's exactly what Apache Camel is for EIPs. <strong>It's a complete production-ready framework for people who want to implement their solution to follow the EIPs.</strong></p> | {
"question_id": 8845186,
"question_date": "2012-01-13T02:32:18.500Z",
"question_score": 1554,
"tags": "java|apache-camel|soa|enterprise-integration",
"answer_id": 11540451,
"answer_date": "2012-07-18T11:38:00.163Z",
"answer_score": 1311
} |
Please answer the following Stack Overflow question:
Title: How do I write JSON data to a file?
<p>How do I write JSON data stored in the dictionary <code>data</code> to a file?</p>
<pre><code>f = open('data.json', 'wb')
f.write(data)
</code></pre>
<p>This gives the error:</p>
<blockquote>
<p>TypeError: must be string or buffer, not dict</p>
</blockquote> | <p><code>data</code> is a Python dictionary. It needs to be encoded as JSON before writing.</p>
<p>Use this for maximum compatibility (Python 2 and 3):</p>
<pre><code>import json
with open('data.json', 'w') as f:
json.dump(data, f)
</code></pre>
<p>On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:</p>
<pre><code>import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
</code></pre>
<p>See <a href="https://docs.python.org/3/library/json.html" rel="noreferrer"><code>json</code></a> documentation.</p> | {
"question_id": 12309269,
"question_date": "2012-09-06T22:21:21.717Z",
"question_score": 1552,
"tags": "python|json",
"answer_id": 12309296,
"answer_date": "2012-09-06T22:23:14.897Z",
"answer_score": 2800
} |
Please answer the following Stack Overflow question:
Title: application/x-www-form-urlencoded or multipart/form-data?
<p>In HTTP there are two ways to POST data: <code>application/x-www-form-urlencoded</code> and <code>multipart/form-data</code>. I understand that most browsers are only able to upload files if <code>multipart/form-data</code> is used. Is there any additional guidance when to use one of the encoding types in an API context (no browser involved)? This might e.g. be based on:</p>
<ul>
<li>data size</li>
<li>existence of non-ASCII characters</li>
<li>existence on (unencoded) binary data</li>
<li>the need to transfer additional data (like filename)</li>
</ul>
<p>I basically found no formal guidance on the web regarding the use of the different content-types so far.</p> | <p><strong>TL;DR</strong></p>
<p>Summary; if you have binary (non-alphanumeric) data (or a significantly sized payload) to transmit, use <code>multipart/form-data</code>. Otherwise, use <code>application/x-www-form-urlencoded</code>.</p>
<hr>
<p>The MIME types you mention are the two <code>Content-Type</code> headers for HTTP POST requests that user-agents (browsers) must support. The purpose of both of those types of requests is to send a list of name/value pairs to the server. Depending on the type and amount of data being transmitted, one of the methods will be more efficient than the other. To understand why, you have to look at what each is doing under the covers.</p>
<p>For <code>application/x-www-form-urlencoded</code>, the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (<code>&</code>), and names are separated from values by the equals symbol (<code>=</code>). An example of this would be: </p>
<p><code>MyVariableOne=ValueOne&MyVariableTwo=ValueTwo</code></p>
<p>According to the <a href="http://www.w3.org/TR/html401/interact/forms.html" rel="noreferrer">specification</a>:</p>
<blockquote>
<p>[Reserved and] non-alphanumeric characters are replaced by `%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character</p>
</blockquote>
<p>That means that for each non-alphanumeric byte that exists in one of our values, it's going to take three bytes to represent it. For large binary files, tripling the payload is going to be highly inefficient.</p>
<p>That's where <code>multipart/form-data</code> comes in. With this method of transmitting name/value pairs, each pair is represented as a "part" in a MIME message (as described by other answers). Parts are separated by a particular string boundary (chosen specifically so that this boundary string does not occur in any of the "value" payloads). Each part has its own set of MIME headers like <code>Content-Type</code>, and particularly <code>Content-Disposition</code>, which can give each part its "name." The value piece of each name/value pair is the payload of each part of the MIME message. The MIME spec gives us more options when representing the value payload -- we can choose a more efficient encoding of binary data to save bandwidth (e.g. base 64 or even raw binary).</p>
<p>Why not use <code>multipart/form-data</code> all the time? For short alphanumeric values (like most web forms), the overhead of adding all of the MIME headers is going to significantly outweigh any savings from more efficient binary encoding.</p> | {
"question_id": 4007969,
"question_date": "2010-10-24T11:12:01.977Z",
"question_score": 1552,
"tags": "http|post|http-headers",
"answer_id": 4073451,
"answer_date": "2010-11-01T21:59:18.847Z",
"answer_score": 2301
} |
Please answer the following Stack Overflow question:
Title: How do I find out which DOM element has the focus?
<p>I would like to find out, in JavaScript, which element currently has focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this, and how?</p>
<p>The reason I was looking for this:</p>
<p>I'm trying to make keys like the arrows and <code>enter</code> navigate through a table of input elements. Tab works now, but enter, and arrows do not by default it seems. I've got the key handling part set up but now I need to figure out how to move the focus over in the event handling functions.</p> | <p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement" rel="noreferrer"><code>document.activeElement</code></a>, it is supported in all major browsers.</p>
<p>Previously, if you were trying to find out what form field has focus, you could not. To emulate detection within older browsers, add a "focus" event handler to all fields and record the last-focused field in a variable. Add a "blur" handler to clear the variable upon a blur event for the last-focused field.</p>
<p>If you need to remove the <code>activeElement</code> you can use blur; <code>document.activeElement.blur()</code>. It will change the <code>activeElement</code> to <code>body</code>.</p>
<p>Related links:</p>
<ul>
<li><a href="https://developer.mozilla.org/en/DOM/document.activeElement#Browser_compatibility" rel="noreferrer">activeElement Browser Compatibility</a></li>
<li><a href="https://stackoverflow.com/questions/3328320/jquery-alternative-for-document-activeelement">jQuery alternative for document.activeElement</a></li>
</ul> | {
"question_id": 497094,
"question_date": "2009-01-30T20:21:31.647Z",
"question_score": 1550,
"tags": "javascript|dom",
"answer_id": 497108,
"answer_date": "2009-01-30T20:24:55.960Z",
"answer_score": 1826
} |
Please answer the following Stack Overflow question:
Title: How can I rename a database column in a Ruby on Rails migration?
<p>I wrongly named a column <code>hased_password</code> instead of <code>hashed_password</code>.</p>
<p>How do I update the database schema, using migration to rename this column?</p> | <pre><code>rename_column :table, :old_column, :new_column
</code></pre>
<p>You'll probably want to create a separate migration to do this. (Rename <code>FixColumnName</code> as you will.):</p>
<pre><code>bin/rails generate migration FixColumnName
# creates db/migrate/xxxxxxxxxx_fix_column_name.rb
</code></pre>
<p>Then edit the migration to do your will:</p>
<pre><code># db/migrate/xxxxxxxxxx_fix_column_name.rb
class FixColumnName < ActiveRecord::Migration
def self.up
rename_column :table_name, :old_column, :new_column
end
def self.down
# rename back if you need or do something else or do nothing
end
end
</code></pre>
<hr />
<p>For Rails 3.1 use:</p>
<p>While, the <code>up</code> and <code>down</code> methods still apply, Rails 3.1 receives a <code>change</code> method that "knows how to migrate your database and reverse it when the migration is rolled back without the need to write a separate down method".</p>
<p>See "<a href="http://guides.rubyonrails.org/migrations.html" rel="nofollow noreferrer">Active Record Migrations</a>" for more information.</p>
<pre><code>rails g migration FixColumnName
class FixColumnName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
</code></pre>
<p>If you happen to have a whole bunch of columns to rename, or something that would have required repeating the table name over and over again:</p>
<pre><code>rename_column :table_name, :old_column1, :new_column1
rename_column :table_name, :old_column2, :new_column2
...
</code></pre>
<p>You could use <code>change_table</code> to keep things a little neater:</p>
<pre><code>class FixColumnNames < ActiveRecord::Migration
def change
change_table :table_name do |t|
t.rename :old_column1, :new_column1
t.rename :old_column2, :new_column2
...
end
end
end
</code></pre>
<p>Then just <code>db:migrate</code> as usual or however you go about your business.</p>
<hr />
<p>For Rails 4:</p>
<p>While creating a <code>Migration</code> for renaming a column, Rails 4 generates a <code>change</code> method instead of <code>up</code> and <code>down</code> as mentioned in the above section. The generated <code>change</code> method is:</p>
<pre><code>$ > rails g migration ChangeColumnName
</code></pre>
<p>which will create a migration file similar to:</p>
<pre><code>class ChangeColumnName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
</code></pre> | {
"question_id": 1992019,
"question_date": "2010-01-02T16:18:42.873Z",
"question_score": 1547,
"tags": "ruby-on-rails|ruby-on-rails-3|migration|rename|alter-table",
"answer_id": 1992045,
"answer_date": "2010-01-02T16:31:20.810Z",
"answer_score": 2455
} |
Please answer the following Stack Overflow question:
Title: How do I update the GUI from another thread?
<p>Which is the simplest way to update a <code>Label</code> from another <code>Thread</code>?</p>
<ul>
<li><p>I have a <code>Form</code> running on <code>thread1</code>, and from that I'm starting another thread (<code>thread2</code>). </p></li>
<li><p>While <code>thread2</code> is processing some files I would like to update a <code>Label</code> on the <code>Form</code> with the current status of <code>thread2</code>'s work.</p></li>
</ul>
<p>How could I do that?</p> | <p>For .NET 2.0, here's a nice bit of code I wrote that does exactly what you want, and works for any property on a <code>Control</code>:</p>
<pre><code>private delegate void SetControlPropertyThreadSafeDelegate(
Control control,
string propertyName,
object propertyValue);
public static void SetControlPropertyThreadSafe(
Control control,
string propertyName,
object propertyValue)
{
if (control.InvokeRequired)
{
control.Invoke(new SetControlPropertyThreadSafeDelegate
(SetControlPropertyThreadSafe),
new object[] { control, propertyName, propertyValue });
}
else
{
control.GetType().InvokeMember(
propertyName,
BindingFlags.SetProperty,
null,
control,
new object[] { propertyValue });
}
}
</code></pre>
<p>Call it like this:</p>
<pre><code>// thread-safe equivalent of
// myLabel.Text = status;
SetControlPropertyThreadSafe(myLabel, "Text", status);
</code></pre>
<p>If you're using .NET 3.0 or above, you could rewrite the above method as an extension method of the <code>Control</code> class, which would then simplify the call to:</p>
<pre><code>myLabel.SetPropertyThreadSafe("Text", status);
</code></pre>
<p><strong>UPDATE 05/10/2010:</strong></p>
<p>For .NET 3.0 you should use this code:</p>
<pre><code>private delegate void SetPropertyThreadSafeDelegate<TResult>(
Control @this,
Expression<Func<TResult>> property,
TResult value);
public static void SetPropertyThreadSafe<TResult>(
this Control @this,
Expression<Func<TResult>> property,
TResult value)
{
var propertyInfo = (property.Body as MemberExpression).Member
as PropertyInfo;
if (propertyInfo == null ||
[email protected]().IsSubclassOf(propertyInfo.ReflectedType) ||
@this.GetType().GetProperty(
propertyInfo.Name,
propertyInfo.PropertyType) == null)
{
throw new ArgumentException("The lambda expression 'property' must reference a valid property on this Control.");
}
if (@this.InvokeRequired)
{
@this.Invoke(new SetPropertyThreadSafeDelegate<TResult>
(SetPropertyThreadSafe),
new object[] { @this, property, value });
}
else
{
@this.GetType().InvokeMember(
propertyInfo.Name,
BindingFlags.SetProperty,
null,
@this,
new object[] { value });
}
}
</code></pre>
<p>which uses LINQ and lambda expressions to allow much cleaner, simpler and safer syntax:</p>
<pre><code>// status has to be of type string or this will fail to compile
myLabel.SetPropertyThreadSafe(() => myLabel.Text, status);
</code></pre>
<p>Not only is the property name now checked at compile time, the property's type is as well, so it's impossible to (for example) assign a string value to a boolean property, and hence cause a runtime exception.</p>
<p>Unfortunately this doesn't stop anyone from doing stupid things such as passing in another <code>Control</code>'s property and value, so the following will happily compile:</p>
<pre><code>myLabel.SetPropertyThreadSafe(() => aForm.ShowIcon, false);
</code></pre>
<p>Hence I added the runtime checks to ensure that the passed-in property does actually belong to the <code>Control</code> that the method's being called on. Not perfect, but still a lot better than the .NET 2.0 version.</p>
<p>If anyone has any further suggestions on how to improve this code for compile-time safety, please comment!</p> | {
"question_id": 661561,
"question_date": "2009-03-19T09:37:40.090Z",
"question_score": 1546,
"tags": "c#|.net|multithreading|winforms|user-interface",
"answer_id": 661706,
"answer_date": "2009-03-19T10:37:59.307Z",
"answer_score": 813
} |
Please answer the following Stack Overflow question:
Title: How do I remove a directory from a Git repository?
<p>How can I delete a single directory containing files from a Git repository?</p> | <h4>Remove directory from Git and local</h4>
<p>Checkout 'master' with both directories:</p>
<pre><code>git rm -r one-of-the-directories // This deletes from filesystem
git commit . -m "Remove duplicated directory"
git push origin <your-git-branch> (typically 'master', but not always)
</code></pre>
<h4>Remove directory from Git but NOT local</h4>
<p>To remove this directory from Git, but not delete it entirely from the filesystem (local):</p>
<pre><code>git rm -r --cached myFolder
</code></pre> | {
"question_id": 6313126,
"question_date": "2011-06-10T23:54:53.180Z",
"question_score": 1541,
"tags": "git|delete-file",
"answer_id": 6313301,
"answer_date": "2011-06-11T00:37:36.897Z",
"answer_score": 2880
} |
Please answer the following Stack Overflow question:
Title: Convert integer to string in Python
<p>How do I convert an integer to a string?</p>
<pre><code>42 ⟶ "42"
</code></pre>
<hr />
<p><sub>For the reverse, see <a href="https://stackoverflow.com/questions/379906/">How do I parse a string to a float or int?</a>. <code>float</code>s can be handled similarly, but handling the decimal points can be tricky because <a href="https://stackoverflow.com/questions/588004/">floating-point values are not precise</a>. See <a href="https://stackoverflow.com/questions/1317558">Converting a float to a string without rounding it</a> for more specific advice.</sub></p> | <pre><code>>>> str(42)
'42'
>>> int('42')
42
</code></pre>
<p>Links to the documentation:</p>
<ul>
<li><a href="https://docs.python.org/3/library/functions.html#int" rel="noreferrer"><code>int()</code></a></li>
<li><a href="https://docs.python.org/3/library/functions.html#str" rel="noreferrer"><code>str()</code></a></li>
</ul>
<p><code>str(x)</code> converts any object <code>x</code> to a string by calling <code>x.<a href="https://docs.python.org/3/reference/datamodel.html#object.__str__" rel="noreferrer">__str__()</a></code>.</p> | {
"question_id": 961632,
"question_date": "2009-06-07T10:22:38.233Z",
"question_score": 1538,
"tags": "python|string|integer",
"answer_id": 961638,
"answer_date": "2009-06-07T10:24:15.797Z",
"answer_score": 2289
} |
Please answer the following Stack Overflow question:
Title: Where to place the 'assets' folder in Android Studio?
<p>I am confused about the <code>assets</code> folder. It doesn't come auto-created in Android Studio, and almost all the forums in which this is discussed talk about Eclipse.</p>
<p>How can the Assets directory be configured in Android Studio?</p> | <p>Since Android Studio uses <a href="http://tools.android.com/tech-docs/new-build-system/user-guide" rel="noreferrer">the new Gradle-based build system</a>, you should be <a href="http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Project-Structure" rel="noreferrer">putting <code>assets/</code> inside of the source sets</a> (e.g., <code>src/main/assets/</code>).</p>
<p>In a typical Android Studio project, you will have an <code>app/</code> module, with a <code>main/</code> sourceset (<code>app/src/main/</code> off of the project root), and so your primary assets would go in <code>app/src/main/assets/</code>. However:</p>
<ul>
<li><p>If you need assets specific to a build type, such as <code>debug</code> versus <code>release</code>, you can create sourcesets for those roles (e.g,. <code>app/src/release/assets/</code>)</p>
</li>
<li><p>Your product flavors can also have sourcesets with assets (e.g., <code>app/src/googleplay/assets/</code>)</p>
</li>
<li><p>Your instrumentation tests can have an <code>androidTest</code> sourceset with custom assets (e.g., <code>app/src/androidTest/assets/</code>), though be sure to ask the <code>InstrumentationRegistry</code> for <code>getContext()</code>, not <code>getTargetContext()</code>, to access those assets</p>
</li>
</ul>
<p>Also, a quick reminder: assets are read-only at runtime. Use <a href="https://commonsware.com/blog/2014/04/07/storage-situation-internal-storage.html" rel="noreferrer">internal storage</a>, <a href="https://commonsware.com/blog/2014/04/08/storage-situation-external-storage.html" rel="noreferrer">external storage</a>, or <a href="http://developer.android.com/guide/topics/providers/document-provider.html" rel="noreferrer">the Storage Access Framework</a> for read/write content.</p> | {
"question_id": 18302603,
"question_date": "2013-08-18T18:54:46.810Z",
"question_score": 1538,
"tags": "android-studio|android-assets",
"answer_id": 18302624,
"answer_date": "2013-08-18T18:56:55.200Z",
"answer_score": 1789
} |
Please answer the following Stack Overflow question:
Title: How to Sort a List<T> by a property in the object
<p>I have a class called <code>Order</code> which has properties such as <code>OrderId</code>, <code>OrderDate</code>, <code>Quantity</code>, and <code>Total</code>. I have a list of this <code>Order</code> class:</p>
<pre><code>List<Order> objListOrder = new List<Order>();
GetOrderList(objListOrder); // fill list of orders
</code></pre>
<p>I want to sort the list based on one property of the <code>Order</code> object; for example, either by the order date or the order id.</p>
<p>How can I do this in C#?</p> | <p>The easiest way I can think of is to use Linq:</p>
<pre><code>List<Order> SortedList = objListOrder.OrderBy(o=>o.OrderDate).ToList();
</code></pre> | {
"question_id": 3309188,
"question_date": "2010-07-22T13:13:25.497Z",
"question_score": 1536,
"tags": "c#|generics|list|sorting",
"answer_id": 3309230,
"answer_date": "2010-07-22T13:16:56.877Z",
"answer_score": 2175
} |
Please answer the following Stack Overflow question:
Title: How do I get time of a Python program's execution?
<p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p> | <p>The simplest way in Python:</p>
<pre><code>import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
</code></pre>
<p>This assumes that your program takes at least a tenth of second to run.</p>
<p>Prints:</p>
<pre><code>--- 0.764891862869 seconds ---
</code></pre> | {
"question_id": 1557571,
"question_date": "2009-10-12T23:56:47.967Z",
"question_score": 1534,
"tags": "python|time|execution-time",
"answer_id": 1557584,
"answer_date": "2009-10-13T00:00:53.340Z",
"answer_score": 2659
} |
Please answer the following Stack Overflow question:
Title: What is the purpose of Node.js module.exports and how do you use it?
<p>What is the purpose of Node.js <code>module.exports</code> and how do you use it?</p>
<p>I can't seem to find any information on this, but it appears to be a rather important part of Node.js as I often see it in source code.</p>
<p>According to the <a href="http://nodejs.org/docs/v0.4.2/api/globals.html#module" rel="noreferrer">Node.js documentation</a>:</p>
<blockquote>
<p><strong>module</strong></p>
<p>A reference to the current
<code>module</code>. In particular <code>module.exports</code>
is the same as the exports object. See
<code>src/node.js</code> for more information.</p>
</blockquote>
<p>But this doesn't really help.</p>
<p>What exactly does <code>module.exports</code> do, and what would a simple example be?</p> | <p><a href="http://nodejs.org/api/modules.html#modules_module_exports" rel="noreferrer"><code>module.exports</code></a> is the object that's actually returned as the result of a <code>require</code> call.</p>
<p>The <code>exports</code> variable is initially set to that same object (i.e. it's a shorthand "alias"), so in the module code you would usually write something like this:</p>
<pre><code>let myFunc1 = function() { ... };
let myFunc2 = function() { ... };
exports.myFunc1 = myFunc1;
exports.myFunc2 = myFunc2;
</code></pre>
<p>to export (or "expose") the internally scoped functions <code>myFunc1</code> and <code>myFunc2</code>.</p>
<p>And in the calling code you would use:</p>
<pre><code>const m = require('./mymodule');
m.myFunc1();
</code></pre>
<p>where the last line shows how the result of <code>require</code> is (usually) just a plain object whose properties may be accessed.</p>
<p>NB: if you overwrite <code>exports</code> then it will no longer refer to <code>module.exports</code>. So if you wish to assign a new object (or a function reference) to <code>exports</code> then you should also assign that new object to <code>module.exports</code></p>
<hr>
<p>It's worth noting that the name added to the <code>exports</code> object does not have to be the same as the module's internally scoped name for the value that you're adding, so you could have:</p>
<pre><code>let myVeryLongInternalName = function() { ... };
exports.shortName = myVeryLongInternalName;
// add other objects, functions, as required
</code></pre>
<p>followed by:</p>
<pre><code>const m = require('./mymodule');
m.shortName(); // invokes module.myVeryLongInternalName
</code></pre> | {
"question_id": 5311334,
"question_date": "2011-03-15T11:56:10.817Z",
"question_score": 1533,
"tags": "javascript|node.js",
"answer_id": 5311377,
"answer_date": "2011-03-15T12:00:00.283Z",
"answer_score": 1673
} |
Please answer the following Stack Overflow question:
Title: 'Static readonly' vs. 'const'
<p>I've read around about <code>const</code> and <code>static readonly</code> fields. We have some classes which contain only constant values. They are used for various things around in our system. So I am wondering if my observation is correct:</p>
<p>Should these kind of constant values always be <code>static readonly</code> for everything that is public? And only use <code>const</code> for internal/protected/private values?</p>
<p>What do you recommend? Should I maybe even not use <code>static readonly</code> fields, but rather use properties maybe?</p> | <p><code>public static readonly</code> fields are a little unusual; <code>public static</code> properties (with only a <code>get</code>) would be more common (perhaps backed by a <code>private static readonly</code> field).</p>
<p><code>const</code> values are burned directly into the call-site; this is double edged:</p>
<ul>
<li>it is useless if the value is fetched at runtime, perhaps from config</li>
<li>if you change the value of a const, you need to rebuild all the clients</li>
<li>but it can be faster, as it avoids a method call...</li>
<li>...which might sometimes have been inlined by the JIT anyway</li>
</ul>
<p>If the value will <strong>never</strong> change, then const is fine - <code>Zero</code> etc make reasonable consts ;p Other than that, <code>static</code> properties are more common.</p> | {
"question_id": 755685,
"question_date": "2009-04-16T11:21:43.290Z",
"question_score": 1532,
"tags": "c#|constants",
"answer_id": 755693,
"answer_date": "2009-04-16T11:24:31.957Z",
"answer_score": 1040
} |
Please answer the following Stack Overflow question:
Title: How to add a class to a given element?
<p>I have an element that already has a class:</p>
<pre class="lang-html prettyprint-override"><code><div class="someclass">
<img ... id="image1" name="image1" />
</div>
</code></pre>
<p>Now, I want to create a JavaScript function that will add a class to the <code>div</code> (not replace, but add).</p>
<p>How can I do that?</p> | <h1>If you're only targeting modern browsers:</h1>
<p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/add" rel="noreferrer">element.classList.add</a> to add a class:</p>
<pre><code>element.classList.add("my-class");
</code></pre>
<p>And <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/remove" rel="noreferrer">element.classList.remove</a> to remove a class:</p>
<pre><code>element.classList.remove("my-class");
</code></pre>
<h1>If you need to support Internet Explorer 9 or lower:</h1>
<p>Add a space plus the name of your new class to the <code>className</code> property of the element. First, put an <code>id</code> on the element so you can easily get a reference.</p>
<pre><code><div id="div1" class="someclass">
<img ... id="image1" name="image1" />
</div>
</code></pre>
<p>Then </p>
<pre><code>var d = document.getElementById("div1");
d.className += " otherclass";
</code></pre>
<p>Note the space before <code>otherclass</code>. It's important to include the space otherwise it compromises existing classes that come before it in the class list. </p>
<p>See also <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/className" rel="noreferrer">element.className on MDN</a>.</p> | {
"question_id": 507138,
"question_date": "2009-02-03T13:54:00.210Z",
"question_score": 1531,
"tags": "javascript|dom-manipulation",
"answer_id": 507157,
"answer_date": "2009-02-03T13:58:01.480Z",
"answer_score": 2495
} |
Please answer the following Stack Overflow question:
Title: Is there a "null coalescing" operator in JavaScript?
<p>Is there a null coalescing operator in Javascript?</p>
<p>For example, in C#, I can do this:</p>
<pre><code>String someString = null;
var whatIWant = someString ?? "Cookies!";
</code></pre>
<p>The best approximation I can figure out for Javascript is using the conditional operator:</p>
<pre><code>var someString = null;
var whatIWant = someString ? someString : 'Cookies!';
</code></pre>
<p>Which is sorta icky IMHO. Can I do better?</p> | <p><strong>Update</strong></p>
<p>JavaScript now supports the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_Coalescing_Operator" rel="noreferrer">nullish coalescing operator (??)</a>. It returns its right-hand-side operand when its left-hand-side operand is <code>null</code> or <code>undefined</code>, and otherwise returns its left-hand-side operand.</p>
<p><strong>Old Answer</strong></p>
<p>Please check compatibility before using it.</p>
<hr />
<p>The JavaScript equivalent of the C# null coalescing operator (<code>??</code>) is using a logical OR (<code>||</code>):</p>
<pre><code>var whatIWant = someString || "Cookies!";
</code></pre>
<p>There are cases (clarified below) that the behaviour won't match that of C#, but this is the general, terse way of assigning default/alternative values in JavaScript.</p>
<hr />
<h2>Clarification</h2>
<p>Regardless of the type of the first operand, if casting it to a Boolean results in <code>false</code>, the assignment will use the second operand. Beware of all the cases below:</p>
<pre><code>alert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)
</code></pre>
<p>This means:</p>
<pre><code>var whatIWant = null || new ShinyObject(); // is a new shiny object
var whatIWant = undefined || "well defined"; // is "well defined"
var whatIWant = 0 || 42; // is 42
var whatIWant = "" || "a million bucks"; // is "a million bucks"
var whatIWant = "false" || "no way"; // is "false"
</code></pre> | {
"question_id": 476436,
"question_date": "2009-01-24T18:18:02.567Z",
"question_score": 1531,
"tags": "javascript|operators|null-coalescing-operator|null-coalescing",
"answer_id": 476445,
"answer_date": "2009-01-24T18:25:31.133Z",
"answer_score": 2295
} |
Please answer the following Stack Overflow question:
Title: Is null check needed before calling instanceof?
<p>Will <code>null instanceof SomeClass</code> return <code>false</code> or throw a <code>NullPointerException</code>?</p> | <p>No, a null check is not needed before using instanceof.</p>
<p>The expression <code>x instanceof SomeClass</code> is <code>false</code> if <code>x</code> is <code>null</code>.</p>
<p>The Java 11 Language Specification expresses this concisely in <a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.20.2" rel="noreferrer">section 15.20.2, "Type comparison operator instanceof"</a>. (<a href="https://docs.oracle.com/javase/specs/jls/se17/html/jls-15.html#jls-15.20.2" rel="noreferrer">Java 17 expresses this less concisely</a>, after the introduction of instanceof patternmatching.)</p>
<blockquote>
<p>"At run time, the result of the
<code>instanceof</code> operator is <code>true</code> if the
value of the <em>RelationalExpression</em> <strong>is
not <code>null</code></strong> and the reference could be
cast to the <em>ReferenceType</em>
without raising a <code>ClassCastException</code>.
Otherwise the result is <code>false</code>."</p>
</blockquote>
<p>So if the operand is null, the result is false.</p> | {
"question_id": 2950319,
"question_date": "2010-06-01T13:53:15.297Z",
"question_score": 1530,
"tags": "java|nullpointerexception|null",
"answer_id": 2950415,
"answer_date": "2010-06-01T14:05:48.570Z",
"answer_score": 2088
} |
Please answer the following Stack Overflow question:
Title: Interface vs Abstract Class (general OO)
<p>I have recently had two telephone interviews where I've been asked about the differences between an Interface and an Abstract class. I have explained every aspect of them I could think of, but it seems they are waiting for me to mention something specific, and I don't know what it is.</p>
<p>From my experience I think the following is true. If I am missing a major point please let me know.</p>
<p><strong>Interface:</strong></p>
<p>Every single Method declared in an Interface will have to be implemented in the subclass.
Only Events, Delegates, Properties (C#) and Methods can exist in an Interface. A class can implement multiple Interfaces.</p>
<p><strong>Abstract Class:</strong></p>
<p>Only Abstract methods have to be implemented by the subclass. An Abstract class can have normal methods with implementations. An Abstract class can also have class variables besides Events, Delegates, Properties and Methods. A class can implement one abstract class only due to the non-existence of Multi-inheritance in C#.</p>
<ol>
<li><p>After all that, the interviewer came up with the question "What if you had an Abstract class with only abstract methods? How would that be different from an interface?" I didn't know the answer but I think it's the inheritance as mentioned above right?</p>
</li>
<li><p>Another interviewer asked me, "What if you had a Public variable inside the interface, how would that be different than in a Abstract Class?" I insisted you can't have a public variable inside an interface. I didn't know what he wanted to hear but he wasn't satisfied either.</p>
</li>
</ol>
<p><strong>See Also</strong>:</p>
<ul>
<li><p><a href="https://stackoverflow.com/questions/479142/when-to-use-an-interface-instead-of-an-abstract-class-and-vice-versa">When to use an interface instead of an abstract class and vice versa</a></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/747517/interfaces-vs-abstract-classes">Interfaces vs. Abstract Classes</a></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/558164/how-do-you-decide-between-using-an-abstract-class-and-an-interface-closed">How do you decide between using an Abstract Class and an Interface?</a></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/1913098/what-is-the-difference-between-an-interface-and-abstract-class?rq=1">What is the difference between an interface and abstract class?</a></p>
</li>
</ul> | <p>While your question indicates it's for "general OO", it really seems to be focusing on .NET use of these terms.</p>
<p>In .NET (similar for Java):</p>
<ul>
<li>interfaces can have no state or implementation</li>
<li>a class that implements an interface must provide an implementation of all the methods of that interface</li>
<li>abstract classes may contain state (data members) and/or implementation (methods)</li>
<li>abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itself)</li>
<li>interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).</li>
</ul>
<p>As general OO terms, the differences are not necessarily well-defined. For example, there are C++ programmers who may hold similar rigid definitions (interfaces are a strict subset of abstract classes that cannot contain implementation), while some may say that an abstract class with some default implementations is still an interface or that a non-abstract class can still define an interface.</p>
<p>Indeed, there is a C++ idiom called the Non-Virtual Interface (NVI) where the public methods are non-virtual methods that 'thunk' to private virtual methods: </p>
<ul>
<li><a href="http://www.gotw.ca/publications/mill18.htm" rel="noreferrer">http://www.gotw.ca/publications/mill18.htm</a></li>
<li><a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface" rel="noreferrer">http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface</a></li>
</ul> | {
"question_id": 761194,
"question_date": "2009-04-17T16:42:38.523Z",
"question_score": 1528,
"tags": "oop|interface|abstract-class",
"answer_id": 761342,
"answer_date": "2009-04-17T17:18:40.247Z",
"answer_score": 797
} |
Please answer the following Stack Overflow question:
Title: Why is Dictionary preferred over Hashtable in C#?
<p>In most programming languages, dictionaries are preferred over hashtables.
What are the reasons behind that?</p> | <p>For what it's worth, a Dictionary <strong>is</strong> (conceptually) a hash table.</p>
<p>If you meant "why do we use the <code>Dictionary<TKey, TValue></code> class instead of the <code>Hashtable</code> class?", then it's an easy answer: <code>Dictionary<TKey, TValue></code> is a generic type, <code>Hashtable</code> is not. That means you get type safety with <code>Dictionary<TKey, TValue></code>, because you can't insert any random object into it, and you don't have to cast the values you take out.</p>
<p>Interestingly, the <code>Dictionary<TKey, TValue></code> implementation in the .NET Framework is based on the <code>Hashtable</code>, as you can tell from this comment in its source code:</p>
<blockquote>
<p>The generic Dictionary was copied from Hashtable's source</p>
</blockquote>
<p><a href="http://referencesource.microsoft.com/#mscorlib/system/collections/hashtable.cs" rel="noreferrer">Source</a> </p> | {
"question_id": 301371,
"question_date": "2008-11-19T09:24:24.877Z",
"question_score": 1528,
"tags": "c#|.net|vb.net|data-structures",
"answer_id": 301384,
"answer_date": "2008-11-19T09:28:55.367Z",
"answer_score": 1684
} |
Please answer the following Stack Overflow question:
Title: How can I change a PostgreSQL user password?
<p>How do I change the password for a PostgreSQL user?</p> | <p>To log in without a password:</p>
<pre><code>sudo -u user_name psql db_name
</code></pre>
<p>To reset the password if you have forgotten:</p>
<pre><code>ALTER USER user_name WITH PASSWORD 'new_password';
</code></pre> | {
"question_id": 12720967,
"question_date": "2012-10-04T05:45:39.323Z",
"question_score": 1525,
"tags": "postgresql|change-password",
"answer_id": 12721095,
"answer_date": "2012-10-04T05:55:58.537Z",
"answer_score": 2158
} |
Please answer the following Stack Overflow question:
Title: Convert a Unix timestamp to time in JavaScript
<p>I am storing time in a MySQL database as a Unix timestamp and that gets sent to some JavaScript code. How would I get just the time out of it?</p>
<p>For example, in <code>HH/MM/SS</code> format.</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 unix_timestamp = 1549312452
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp * 1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(formattedTime);</code></pre>
</div>
</div>
</p>
<p>For more information regarding the Date object, please refer to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" rel="noreferrer">MDN</a> or the <a href="http://ecma-international.org/ecma-262/5.1/#sec-15.9" rel="noreferrer">ECMAScript 5 specification</a>.</p> | {
"question_id": 847185,
"question_date": "2009-05-11T08:23:28.053Z",
"question_score": 1521,
"tags": "javascript|date|time|time-format",
"answer_id": 847196,
"answer_date": "2009-05-11T08:28:50.977Z",
"answer_score": 2178
} |
Please answer the following Stack Overflow question:
Title: How to reset AUTO_INCREMENT in MySQL
<p>How can I <em><strong>reset</strong></em> the <code>AUTO_INCREMENT</code> of a field?</p>
<p>I want it to start counting from <code>1</code> again.</p> | <p>You can reset the counter with:</p>
<pre><code>ALTER TABLE tablename AUTO_INCREMENT = 1
</code></pre>
<p>For <a href="https://en.wikipedia.org/wiki/InnoDB" rel="noreferrer">InnoDB</a> you cannot set the <code>auto_increment</code> value lower or equal to the highest current index. (quote from <a href="http://viralpatel.net/blogs/reseting-mysql-autoincrement-column/" rel="noreferrer">ViralPatel</a>):</p>
<blockquote>
<p>Note that you cannot reset the counter to a value less than or equal
to any that have already been used. For MyISAM, if the value is less
than or equal to the maximum value currently in the AUTO_INCREMENT
column, the value is reset to the current maximum plus one. For
InnoDB, if the value is less than the current maximum value in the
column, no error occurs and the current sequence value is not changed.</p>
</blockquote>
<p>See <em><a href="https://stackoverflow.com/questions/2410689/how-can-i-reset-an-mysql-autoincrement-using-a-max-value-from-another-table">How can I reset an MySQL AutoIncrement using a MAX value from another table?</a></em> on how to dynamically get an acceptable value.</p> | {
"question_id": 8923114,
"question_date": "2012-01-19T08:37:49.687Z",
"question_score": 1520,
"tags": "mysql|sql|auto-increment",
"answer_id": 8923132,
"answer_date": "2012-01-19T08:39:42.370Z",
"answer_score": 2449
} |
Please answer the following Stack Overflow question:
Title: Use of *args and **kwargs
<p>So I have difficulty with the concept of <code>*args</code> and <code>**kwargs</code>.</p>
<p>So far I have learned that:</p>
<ul>
<li><code>*args</code> = list of arguments - as positional arguments</li>
<li><code>**kwargs</code> = dictionary - whose keys become separate keyword arguments and the values become values of these arguments.</li>
</ul>
<p>I don't understand what programming task this would be helpful for. </p>
<p>Maybe:</p>
<p>I think to enter lists and dictionaries as arguments of a function AND at the same time as a wildcard, so I can pass ANY argument?</p>
<p>Is there a simple example to explain how <code>*args</code> and <code>**kwargs</code> are used?</p>
<p>Also the tutorial I found used just the "*" and a variable name. </p>
<p>Are <code>*args</code> and <code>**kwargs</code> just placeholders or do you use exactly <code>*args</code> and <code>**kwargs</code> in the code?</p> | <p><a href="http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists" rel="noreferrer">The syntax is the <code>*</code> and <code>**</code></a>. The names <code>*args</code> and <code>**kwargs</code> are only by convention but there's no hard requirement to use them.</p>
<p>You would use <code>*args</code> when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example:</p>
<pre><code>>>> def print_everything(*args):
for count, thing in enumerate(args):
... print( '{0}. {1}'.format(count, thing))
...
>>> print_everything('apple', 'banana', 'cabbage')
0. apple
1. banana
2. cabbage
</code></pre>
<p>Similarly, <code>**kwargs</code> allows you to handle named arguments that you have not defined in advance:</p>
<pre><code>>>> def table_things(**kwargs):
... for name, value in kwargs.items():
... print( '{0} = {1}'.format(name, value))
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit
</code></pre>
<p>You can use these along with named arguments too. The explicit arguments get values first and then everything else is passed to <code>*args</code> and <code>**kwargs</code>. The named arguments come first in the list. For example:</p>
<pre><code>def table_things(titlestring, **kwargs)
</code></pre>
<p>You can also use both in the same function definition but <code>*args</code> must occur before <code>**kwargs</code>.</p>
<p>You can also use the <code>*</code> and <code>**</code> syntax when calling a function. For example:</p>
<pre><code>>>> def print_three_things(a, b, c):
... print( 'a = {0}, b = {1}, c = {2}'.format(a,b,c))
...
>>> mylist = ['aardvark', 'baboon', 'cat']
>>> print_three_things(*mylist)
a = aardvark, b = baboon, c = cat
</code></pre>
<p>As you can see in this case it takes the list (or tuple) of items and unpacks it. By this it matches them to the arguments in the function. Of course, you could have a <code>*</code> both in the function definition and in the function call.</p> | {
"question_id": 3394835,
"question_date": "2010-08-03T08:28:07.967Z",
"question_score": 1520,
"tags": "python|args|keyword-argument",
"answer_id": 3394898,
"answer_date": "2010-08-03T08:38:45.713Z",
"answer_score": 1762
} |
Please answer the following Stack Overflow question:
Title: What is the difference between null and undefined in JavaScript?
<p>I want to know what the difference is between <code>null</code> and <code>undefined</code> in JavaScript.</p> | <p><code>undefined</code> means a variable has been declared but has not yet been assigned a value :</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 testVar;
alert(testVar); //shows undefined
alert(typeof testVar); //shows undefined</code></pre>
</div>
</div>
</p>
<p><code>null</code> is an assignment value. It can be assigned to a variable as a representation of no value :</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 testVar = null;
alert(testVar); //shows null
alert(typeof testVar); //shows object</code></pre>
</div>
</div>
</p>
<p>From the preceding examples, it is clear that <code>undefined</code> and <code>null</code> are two distinct types: <code>undefined</code> is a type itself (undefined) while <code>null</code> is an object.</p>
<p>Proof :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(null === undefined) // false (not the same type)
console.log(null == undefined) // true (but the "same value")
console.log(null === null) // true (both type and value are the same)</code></pre>
</div>
</div>
</p>
<p>and</p>
<pre><code>null = 'value' // Uncaught SyntaxError: invalid assignment left-hand side
undefined = 'value' // 'value'
</code></pre> | {
"question_id": 5076944,
"question_date": "2011-02-22T10:30:10.060Z",
"question_score": 1519,
"tags": "javascript|null|undefined",
"answer_id": 5076962,
"answer_date": "2011-02-22T10:31:56.783Z",
"answer_score": 1453
} |
Please answer the following Stack Overflow question:
Title: Hard reset of a single file
<p>How do I discard the changes to a single file and overwrite it with a fresh HEAD copy? I want to do <code>git reset --hard</code> to only a single file.</p> | <p>To reset both the working copy of <code>my-file.txt</code> and its state in the Git index to that of HEAD:</p>
<pre><code>git checkout HEAD -- my-file.txt
</code></pre>
<p><code>--</code> means <em>"treat every argument after this point as a filename"</em>. More details in <a href="https://stackoverflow.com/questions/6561142/different-between-git-checkout-filename-and-git-checkout-filename/6561160#6561160">this answer</a>. Thanks to <a href="https://stackoverflow.com/users/6309/vonc">VonC</a> for pointing this out.</p> | {
"question_id": 7147270,
"question_date": "2011-08-22T12:12:52.310Z",
"question_score": 1518,
"tags": "git",
"answer_id": 7147320,
"answer_date": "2011-08-22T12:16:21.250Z",
"answer_score": 2660
} |
Please answer the following Stack Overflow question:
Title: Determine Whether Two Date Ranges Overlap
<p>Given two date ranges, what is the simplest or most efficient way to determine whether the two date ranges overlap?</p>
<p>As an example, suppose we have ranges denoted by DateTime variables <code>StartDate1</code> to <code>EndDate1</code> <em>and</em> <code>StartDate2</code> to <code>EndDate2</code>.</p> | <p><strong>(StartA <= EndB) and (EndA >= StartB)</strong></p>
<p><em>Proof:</em><br />
Let ConditionA Mean that DateRange A Completely After DateRange B</p>
<pre><code>_ |---- DateRange A ------|
|---Date Range B -----| _
</code></pre>
<p>(True if <code>StartA > EndB</code>)</p>
<p>Let ConditionB Mean that DateRange A is Completely Before DateRange B</p>
<pre><code>|---- DateRange A -----| _
_ |---Date Range B ----|
</code></pre>
<p>(True if <code>EndA < StartB</code>)</p>
<p>Then Overlap exists if Neither A Nor B is true -<br />
(If one range is neither completely after the other,<br />
nor completely before the other,
then they must overlap.)</p>
<p>Now one of <a href="https://en.wikipedia.org/wiki/De_Morgan%27s_laws" rel="noreferrer">De Morgan's laws</a> says that:</p>
<p><code>Not (A Or B)</code> <=> <code>Not A And Not B</code></p>
<p>Which translates to: <code>(StartA <= EndB) and (EndA >= StartB)</code></p>
<hr />
<p>NOTE: This includes conditions where the edges overlap exactly. If you wish to exclude that,<br />
change the <code>>=</code> operators to <code>></code>, and <code><=</code> to <code><</code></p>
<hr />
<p>NOTE2. Thanks to @Baodad, see <a href="http://baodad.blogspot.com/2014/06/date-range-overlap.html" rel="noreferrer">this blog</a>, the actual overlap is least of:<br />
{ <code>endA-startA</code>, <code>endA - startB</code>, <code>endB-startA</code>, <code>endB - startB</code> }</p>
<p><code>(StartA <= EndB) and (EndA >= StartB)</code>
<code>(StartA <= EndB) and (StartB <= EndA)</code></p>
<hr />
<p>NOTE3. Thanks to @tomosius, a shorter version reads:<br />
<code>DateRangesOverlap = max(start1, start2) < min(end1, end2)</code><br />
This is actually a syntactical shortcut for what is a longer implementation, which includes extra checks to verify that the start dates are on or before the endDates. Deriving this from above:</p>
<p>If start and end dates can be out of order, i.e., if it is possible that <code>startA > endA</code> or <code>startB > endB</code>, then you also have to check that they are in order, so that means you have to add two additional validity rules:<br />
<code>(StartA <= EndB) and (StartB <= EndA) and (StartA <= EndA) and (StartB <= EndB)</code>
or:<br />
<code>(StartA <= EndB) and (StartA <= EndA) and (StartB <= EndA) and (StartB <= EndB)</code>
or,<br />
<code>(StartA <= Min(EndA, EndB) and (StartB <= Min(EndA, EndB))</code>
or:<br />
<code>(Max(StartA, StartB) <= Min(EndA, EndB)</code></p>
<p>But to implement <code>Min()</code> and <code>Max()</code>, you have to code, (using C ternary for terseness),:<br />
<code>(StartA > StartB? Start A: StartB) <= (EndA < EndB? EndA: EndB)</code></p> | {
"question_id": 325933,
"question_date": "2008-11-28T14:48:35.643Z",
"question_score": 1518,
"tags": "datetime|math|language-agnostic",
"answer_id": 325964,
"answer_date": "2008-11-28T15:00:40.423Z",
"answer_score": 2781
} |
Please answer the following Stack Overflow question:
Title: How can I do an UPDATE statement with JOIN in SQL Server?
<p>I need to update this table in <strong>SQL Server</strong> with data from its 'parent' table, see below:</p>
<p><strong>Table: sale</strong></p>
<pre><code>id (int)
udid (int)
assid (int)
</code></pre>
<p><strong>Table: ud</strong></p>
<pre><code>id (int)
assid (int)
</code></pre>
<p><code>sale.assid</code> contains the correct value to update <code>ud.assid</code>. </p>
<p>What query will do this? I'm thinking of a <code>join</code> but I'm not sure if it's possible.</p> | <p>Syntax strictly depends on which SQL DBMS you're using. Here are some ways to do it in ANSI/ISO (aka should work on any SQL DBMS), MySQL, SQL Server, and Oracle. Be advised that my suggested ANSI/ISO method will typically be much slower than the other two methods, but if you're using a SQL DBMS other than MySQL, SQL Server, or Oracle, then it may be the only way to go (e.g. if your SQL DBMS doesn't support <code>MERGE</code>):</p>
<p>ANSI/ISO:</p>
<pre><code>update ud
set assid = (
select sale.assid
from sale
where sale.udid = ud.id
)
where exists (
select *
from sale
where sale.udid = ud.id
);
</code></pre>
<p>MySQL:</p>
<pre><code>update ud u
inner join sale s on
u.id = s.udid
set u.assid = s.assid
</code></pre>
<p>SQL Server:</p>
<pre><code>update u
set u.assid = s.assid
from ud u
inner join sale s on
u.id = s.udid
</code></pre>
<p>PostgreSQL:</p>
<pre><code>update ud
set assid = s.assid
from sale s
where ud.id = s.udid;
</code></pre>
<p>Note that the target table must not be repeated in the <code>FROM</code> clause for Postgres.</p>
<p>Oracle:</p>
<pre><code>update
(select
u.assid as new_assid,
s.assid as old_assid
from ud u
inner join sale s on
u.id = s.udid) up
set up.new_assid = up.old_assid
</code></pre>
<p>SQLite:</p>
<pre><code>update ud
set assid = (
select sale.assid
from sale
where sale.udid = ud.id
)
where RowID in (
select RowID
from ud
where sale.udid = ud.id
);
</code></pre> | {
"question_id": 1293330,
"question_date": "2009-08-18T11:40:07.273Z",
"question_score": 1515,
"tags": "sql|sql-server|tsql|sql-server-2005|sql-update",
"answer_id": 1293347,
"answer_date": "2009-08-18T11:44:17.593Z",
"answer_score": 2720
} |
Please answer the following Stack Overflow question:
Title: Remove empty elements from an array in Javascript
<p>How do I remove empty elements from an array in JavaScript? </p>
<p>Is there a straightforward way, or do I need to loop through it and remove them manually?</p> | <p><strong>EDIT:</strong> This question was answered almost nine years ago when there were not many useful built-in methods in the <code>Array.prototype</code>.</p>
<p>Now, certainly, I would recommend you to use the <code>filter</code> method.</p>
<p>Take in mind that this method will return you <em>a new array</em> with the elements that pass the criteria of the callback function you provide to it.</p>
<p>For example, if you want to remove <code>null</code> or <code>undefined</code> values: </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 array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];
var filtered = array.filter(function (el) {
return el != null;
});
console.log(filtered);</code></pre>
</div>
</div>
</p>
<p>It will depend on what you consider to be "empty" for example, if you were dealing with strings, the above function wouldn't remove elements that are an empty string.</p>
<p>One typical pattern that I see often used is to remove elements that are <em>falsy</em>, which include an empty string <code>""</code>, <code>0</code>, <code>NaN</code>, <code>null</code>, <code>undefined</code>, and <code>false</code>.</p>
<p>You can pass to the <code>filter</code> method, the <code>Boolean</code> constructor function, or return the same element in the filter criteria function, for example:</p>
<pre><code>var filtered = array.filter(Boolean);
</code></pre>
<p>Or</p>
<pre><code>var filtered = array.filter(function(el) { return el; });
</code></pre>
<p>In both ways, this works because the <code>filter</code> method in the first case, calls the <code>Boolean</code> constructor as a function, converting the value, and in the second case, the <code>filter</code> method internally turns the return value of the callback implicitly to <code>Boolean</code>.</p>
<p>If you are working with sparse arrays, and you are trying to get rid of the "holes", you can use the <code>filter</code> method passing a callback that returns true, for example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var sparseArray = [0, , , 1, , , , , 2, , , , 3],
cleanArray = sparseArray.filter(function () { return true });
console.log(cleanArray); // [ 0, 1, 2, 3 ]</code></pre>
</div>
</div>
</p>
<p><strong>Old answer:</strong> Don't do this!</p>
<p>I use this method, extending the native Array prototype:</p>
<pre><code>Array.prototype.clean = function(deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
};
test = new Array("", "One", "Two", "", "Three", "", "Four").clean("");
test2 = [1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,];
test2.clean(undefined);
</code></pre>
<p>Or you can simply push the existing elements into other array:</p>
<pre><code>// Will remove all falsy values: undefined, null, 0, false, NaN and "" (empty string)
function cleanArray(actual) {
var newArray = new Array();
for (var i = 0; i < actual.length; i++) {
if (actual[i]) {
newArray.push(actual[i]);
}
}
return newArray;
}
cleanArray([1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,]);
</code></pre> | {
"question_id": 281264,
"question_date": "2008-11-11T15:48:54.113Z",
"question_score": 1515,
"tags": "javascript|arrays",
"answer_id": 281335,
"answer_date": "2008-11-11T16:12:59.400Z",
"answer_score": 1436
} |
Please answer the following Stack Overflow question:
Title: How can I flush the output of the print function?
<p>How do I force Python's <code>print</code> function to flush the buffered output to the screen?</p> | <p>In Python 3, <a href="https://docs.python.org/library/functions.html#print" rel="noreferrer"><code>print</code></a> can take an optional <code>flush</code> argument:</p>
<pre><code>print("Hello, World!", flush=True)
</code></pre>
<p>In Python 2, after calling <code>print</code>, do:</p>
<pre><code>import sys
sys.stdout.flush()
</code></pre>
<p>By default, <a href="https://docs.python.org/2/reference/simple_stmts.html#the-print-statement" rel="noreferrer"><code>print</code></a> prints to <a href="https://docs.python.org/2/library/sys.html#sys.stdout" rel="noreferrer"><code>sys.stdout</code></a> (see the documentation for more about <a href="https://docs.python.org/2/library/stdtypes.html#file-objects" rel="noreferrer">file objects</a>).</p> | {
"question_id": 230751,
"question_date": "2008-10-23T17:59:39.063Z",
"question_score": 1513,
"tags": "python|python-3.x|printing|flush",
"answer_id": 230774,
"answer_date": "2008-10-23T18:04:59.083Z",
"answer_score": 1783
} |
Please answer the following Stack Overflow question:
Title: How can I view a git log of just one user's commits?
<p>When using <code>git log</code>, how can I filter by user so that I see only commits from that user?</p> | <p>This works for both <code>git log</code> and <a href="https://git-scm.com/docs/gitk" rel="noreferrer">gitk</a> - the 2 most common ways of viewing history.<br />
You don't need to use the whole name:</p>
<pre><code>git log --author="Jon"
</code></pre>
<p>will match a commit made by "Jonathan Smith"</p>
<pre><code>git log --author=Jon
</code></pre>
<p>and</p>
<pre><code>git log --author=Smith
</code></pre>
<p>would also work. The quotes are optional if you don't need any spaces.</p>
<p><strong>Add <code>--all</code> if you intend to search all branches and not just the current commit's ancestors in your repo.</strong></p>
<p>You can also easily match on multiple authors as regex is the underlying mechanism for this filter. So to list commits by Jonathan or Adam, you can do this:</p>
<pre><code>git log --author="\(Adam\)\|\(Jon\)"
</code></pre>
<p>In order to exclude commits by a particular author or set of authors using regular expressions as noted <a href="https://stackoverflow.com/questions/406230/regular-expression-to-match-string-not-containing-a-word">in this question</a>, you can use a <a href="http://www.regular-expressions.info/lookaround.html" rel="noreferrer">negative lookahead</a> in combination with the <code>--perl-regexp</code> switch:</p>
<pre><code>git log --author='^(?!Adam|Jon).*$' --perl-regexp
</code></pre>
<p>Alternatively, you can exclude commits authored by Adam by using <code>bash</code> and piping:</p>
<pre><code>git log --format='%H %an' |
grep -v Adam |
cut -d ' ' -f1 |
xargs -n1 git log -1
</code></pre>
<p>If you want to exclude commits commited (but not necessarily authored) by Adam, replace <code>%an</code> with <code>%cn</code>. More details about this are in my blog post here: <a href="http://dymitruk.com/blog/2012/07/18/filtering-by-author-name/" rel="noreferrer">http://dymitruk.com/blog/2012/07/18/filtering-by-author-name/</a></p> | {
"question_id": 4259996,
"question_date": "2010-11-23T19:31:42.963Z",
"question_score": 1506,
"tags": "git|version-control|git-log",
"answer_id": 4262780,
"answer_date": "2010-11-24T01:41:29.467Z",
"answer_score": 2088
} |
Please answer the following Stack Overflow question:
Title: Use different Python version with virtualenv
<p>How do I create a virtual environment for a specified version of Python?</p> | <p><strong>NOTE:</strong> For <strong>Python 3.3+</strong>, see The Aelfinn's <a href="https://stackoverflow.com/a/39713544/1450294">answer</a> below.</p>
<hr />
<p>Use the <code>--python</code> (or short <code>-p</code>) option when creating a virtualenv instance to specify the Python executable you want to use, e.g.:</p>
<pre><code>virtualenv --python="/usr/bin/python2.6" "/path/to/new/virtualenv/"
</code></pre> | {
"question_id": 1534210,
"question_date": "2009-10-07T21:11:22.443Z",
"question_score": 1505,
"tags": "python|virtualenv|virtualenvwrapper",
"answer_id": 1534343,
"answer_date": "2009-10-07T21:33:12.773Z",
"answer_score": 1879
} |
Please answer the following Stack Overflow question:
Title: Why can't Python parse this JSON data?
<p>I have this JSON in a file:</p>
<pre class="lang-json prettyprint-override"><code>{
"maps": [
{
"id": "blabla",
"iscategorical": "0"
},
{
"id": "blabla",
"iscategorical": "0"
}
],
"masks": [
"id": "valore"
],
"om_points": "value",
"parameters": [
"id": "valore"
]
}
</code></pre>
<p>I wrote this script to print all of the JSON data:</p>
<pre class="lang-py prettyprint-override"><code>import json
from pprint import pprint
with open('data.json') as f:
data = json.load(f)
pprint(data)
</code></pre>
<p>This program raises an exception, though:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "<pyshell#1>", line 5, in <module>
data = json.load(f)
File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 13 column 13 (char 213)
</code></pre>
<p>How can I parse the JSON and extract its values?</p> | <p>Your data is not valid <a href="https://www.json.org/" rel="nofollow noreferrer">JSON</a> format. You have <code>[]</code> when you should have <code>{}</code> for the <code>"masks"</code> and <code>"parameters"</code> elements:</p>
<ul>
<li><code>[]</code> are for JSON arrays, which are called <code>list</code> in Python</li>
<li><code>{}</code> are for JSON objects, which are called <code>dict</code> in Python</li>
</ul>
<p>Here's how your JSON file should look:</p>
<pre class="lang-json prettyprint-override"><code>{
"maps": [
{
"id": "blabla",
"iscategorical": "0"
},
{
"id": "blabla",
"iscategorical": "0"
}
],
"masks": {
"id": "valore"
},
"om_points": "value",
"parameters": {
"id": "valore"
}
}
</code></pre>
<p>Then you can use your code:</p>
<pre class="lang-py prettyprint-override"><code>import json
from pprint import pprint
with open('data.json') as f:
data = json.load(f)
pprint(data)
</code></pre>
<p>With data, you can now also find values like so:</p>
<pre class="lang-py prettyprint-override"><code>data["maps"][0]["id"]
data["masks"]["id"]
data["om_points"]
</code></pre>
<p>Try those out and see if it starts to make sense.</p> | {
"question_id": 2835559,
"question_date": "2010-05-14T15:54:20.003Z",
"question_score": 1504,
"tags": "python|json|parsing",
"answer_id": 2835672,
"answer_date": "2010-05-14T16:10:15.603Z",
"answer_score": 2194
} |
Please answer the following Stack Overflow question:
Title: Create a branch in Git from another branch
<p>I have two branches: <strong>master</strong> and <strong>dev</strong></p>
<p>I want to create a "feature branch" from the <strong>dev</strong> branch.</p>
<p>Currently on the branch dev, I do:</p>
<pre><code>$ git checkout -b myfeature dev
</code></pre>
<p>... (some work)</p>
<pre><code>$ git commit -am "blablabla"
$ git push origin myfeature
</code></pre>
<p>But, after visualizing my branches, I got:</p>
<pre><code>--**master**
------0-----0-----0-----0-----0
------------------------**dev**----**myfeature**
</code></pre>
<p>I mean that the branch seems ff merged, and I don't understand why...</p>
<p>What I'm doing wrong?</p>
<p>Can you explain me please how you branch off from another branch and push back to the remote repository for the feature branch?</p>
<p>All that in a branching model like <a href="http://nvie.com/posts/a-successful-git-branching-model/" rel="noreferrer">the one described here</a>.</p> | <p>If you like the method in the link you've posted, have a look at <a href="https://github.com/nvie/gitflow" rel="noreferrer">Git Flow</a>.</p>
<p>It's a set of scripts he created for that workflow.</p>
<p>But to answer your question:</p>
<pre><code>$ git checkout -b myFeature dev
</code></pre>
<p>Creates MyFeature branch off dev. Do your work and then</p>
<pre><code>$ git commit -am "Your message"
</code></pre>
<p>Now merge your changes to dev without a fast-forward</p>
<pre><code>$ git checkout dev
$ git merge --no-ff myFeature
</code></pre>
<p>Now push changes to the server</p>
<pre><code>$ git push origin dev
$ git push origin myFeature
</code></pre>
<p>And you'll see it how you want it.</p> | {
"question_id": 4470523,
"question_date": "2010-12-17T12:39:03.007Z",
"question_score": 1502,
"tags": "git|git-branch|git-workflow|git-flow",
"answer_id": 4470822,
"answer_date": "2010-12-17T13:23:08.950Z",
"answer_score": 2083
} |
Please answer the following Stack Overflow question:
Title: How do I get the filename without the extension from a path in Python?
<p>How do I get the filename without the extension from a path in Python?</p>
<pre><code>"/path/to/some/file.txt" → "file"
</code></pre> | <p>Getting the name of the file without the extension:</p>
<pre><code>import os
print(os.path.splitext("/path/to/some/file.txt")[0])
</code></pre>
<p>Prints:</p>
<pre><code>/path/to/some/file
</code></pre>
<p><a href="https://docs.python.org/3/library/os.path.html#os.path.splitext" rel="noreferrer">Documentation for <code>os.path.splitext</code></a>.</p>
<p><em>Important Note:</em> If the filename has multiple dots, only the extension after the last one is removed. For example:</p>
<pre><code>import os
print(os.path.splitext("/path/to/some/file.txt.zip.asc")[0])
</code></pre>
<p>Prints:</p>
<pre><code>/path/to/some/file.txt.zip
</code></pre>
<p>See other answers below if you need to handle that case.</p> | {
"question_id": 678236,
"question_date": "2009-03-24T16:41:03.283Z",
"question_score": 1502,
"tags": "python|string|path",
"answer_id": 678242,
"answer_date": "2009-03-24T16:43:15.493Z",
"answer_score": 1656
} |
Please answer the following Stack Overflow question:
Title: How do I pass data between Activities in Android application?
<p>I have a scenario where, after logging in through a login page, there will be a sign-out <code>button</code> on each <code>activity</code>.</p>
<p>On clicking <code>sign-out</code>, I will be passing the <code>session id</code> of the signed in user to sign-out. Can anyone guide me on how to keep <code>session id</code> available to all <code>activities</code>?</p>
<p>Any alternative to this case </p> | <p>The easiest way to do this would be to pass the session id to the signout activity in the <code>Intent</code> you're using to start the activity:</p>
<pre><code>Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);
</code></pre>
<p>Access that intent on next activity:</p>
<pre><code>String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");
</code></pre>
<p>The <a href="http://developer.android.com/guide/topics/intents/intents-filters.html" rel="noreferrer">docs</a> for Intents has more information (look at the section titled "Extras").</p> | {
"question_id": 2091465,
"question_date": "2010-01-19T06:06:36.073Z",
"question_score": 1501,
"tags": "android|android-intent|android-activity",
"answer_id": 2091482,
"answer_date": "2010-01-19T06:12:08.557Z",
"answer_score": 1443
} |
Please answer the following Stack Overflow question:
Title: Changing image size in Markdown
<p>I just got started with Markdown. I love it, but there is one thing bugging me: How can I change the size of an image using Markdown?</p>
<p>The documentation only gives the following suggestion for an image: </p>
<pre><code>
</code></pre>
<p>If it is possible I would like the picture to also be centered. I am asking for general Markdown, not just how GitHub does it. </p> | <p>You could just use some HTML in your Markdown:</p>
<pre class="lang-html prettyprint-override"><code><img src="drawing.jpg" alt="drawing" width="200"/>
</code></pre>
<p>Or via <code>style</code> attribute (<strong>not supported by GitHub</strong>)</p>
<pre class="lang-html prettyprint-override"><code><img src="drawing.jpg" alt="drawing" style="width:200px;"/>
</code></pre>
<p>Or you could use a custom CSS file as described in this answer on <em><a href="https://stackoverflow.com/questions/255170/markdown-and-image-alignment#answer-5054055">Markdown and image alignment</a></em></p>
<pre><code>
</code></pre>
<p>CSS in another file:</p>
<pre class="lang-css prettyprint-override"><code>img[alt=drawing] { width: 200px; }
</code></pre> | {
"question_id": 14675913,
"question_date": "2013-02-03T18:42:06.110Z",
"question_score": 1499,
"tags": "image|markdown",
"answer_id": 14747656,
"answer_date": "2013-02-07T09:26:18.263Z",
"answer_score": 1578
} |
Please answer the following Stack Overflow question:
Title: How to manage a redirect request after a jQuery Ajax call
<p>I'm using <code>$.post()</code> to call a servlet using Ajax and then using the resulting HTML fragment to replace a <code>div</code> element in the user's current page. However, if the session times out, the server sends a redirect directive to send the user to the login page. In this case, jQuery is replacing the <code>div</code> element with the contents of the login page, forcing the user's eyes to witness a rare scene indeed. </p>
<p>How can I manage a redirect directive from an Ajax call with jQuery 1.2.6?</p> | <p>The solution that was eventually implemented was to use a wrapper for the callback function of the Ajax call and in this wrapper check for the existence of a specific element on the returned HTML chunk. If the element was found then the wrapper executed a redirection. If not, the wrapper forwarded the call to the actual callback function. </p>
<p>For example, our wrapper function was something like:</p>
<pre><code>function cbWrapper(data, funct){
if($("#myForm", data).length > 0)
top.location.href="login.htm";//redirection
else
funct(data);
}
</code></pre>
<p>Then, when making the Ajax call we used something like:</p>
<pre><code>$.post("myAjaxHandler",
{
param1: foo,
param2: bar
},
function(data){
cbWrapper(data, myActualCB);
},
"html"
);
</code></pre>
<p>This worked for us because all Ajax calls always returned HTML inside a DIV element that we use to replace a piece of the page. Also, we only needed to redirect to the login page.</p> | {
"question_id": 199099,
"question_date": "2008-10-13T21:29:50.063Z",
"question_score": 1498,
"tags": "javascript|jquery|ajax|redirect",
"answer_id": 484541,
"answer_date": "2009-01-27T18:10:32.743Z",
"answer_score": 105
} |
Please answer the following Stack Overflow question:
Title: Create a dictionary with comprehension
<p>Can I use list comprehension syntax to create a dictionary?</p>
<p>For example, by iterating over pairs of keys and values:</p>
<pre><code>d = {... for k, v in zip(keys, values)}
</code></pre> | <p>Use a <a href="http://www.python.org/dev/peps/pep-0274/" rel="noreferrer">dict comprehension</a> (Python 2.7 and later):</p>
<pre><code>{key: value for (key, value) in iterable}
</code></pre>
<hr />
<p>Alternatively for simpler cases or earlier version of Python, use the <a href="https://docs.python.org/3/library/stdtypes.html#typesmapping" rel="noreferrer"><code>dict</code></a> constructor, e.g.:</p>
<pre class="lang-py prettyprint-override"><code>pairs = [('a', 1), ('b', 2)]
dict(pairs) #=> {'a': 1, 'b': 2}
dict([(k, v+1) for k, v in pairs]) #=> {'a': 2, 'b': 3}
</code></pre>
<p>Given separate arrays of keys and values, use the <code>dict</code> constructor with <a href="https://docs.python.org/3/library/functions.html#zip" rel="noreferrer"><code>zip</code></a>:</p>
<pre class="lang-py prettyprint-override"><code>keys = ['a', 'b']
values = [1, 2]
dict(zip(keys, values)) #=> {'a': 1, 'b': 2}
</code></pre>
<pre><code>2) "zip'ped" from two separate iterables of keys/vals
dict(zip(list_of_keys, list_of_values))
</code></pre> | {
"question_id": 1747817,
"question_date": "2009-11-17T10:07:53.267Z",
"question_score": 1497,
"tags": "python|dictionary|list-comprehension|dictionary-comprehension",
"answer_id": 1747827,
"answer_date": "2009-11-17T10:09:32.787Z",
"answer_score": 2223
} |
Please answer the following Stack Overflow question:
Title: What are bitwise shift (bit-shift) operators and how do they work?
<p>I've been attempting to learn C in my spare time, and other languages (C#, Java, etc.) have the same concept (and often the same operators)...</p>
<p>At a core level, what does bit-shifting (<code><<</code>, <code>>></code>, <code>>>></code>) do, what problems can it help solve, and what gotchas lurk around the bend? In other words, an absolute beginner's guide to bit shifting in all its goodness.</p> | <p>The bit shifting operators do exactly what their name implies. They shift bits. Here's a brief (or not-so-brief) introduction to the different shift operators.</p>
<h2>The Operators</h2>
<ul>
<li><code>>></code> is the arithmetic (or signed) right shift operator.</li>
<li><code>>>></code> is the logical (or unsigned) right shift operator.</li>
<li><code><<</code> is the left shift operator, and meets the needs of both logical and arithmetic shifts.</li>
</ul>
<p>All of these operators can be applied to integer values (<code>int</code>, <code>long</code>, possibly <code>short</code> and <code>byte</code> or <code>char</code>). In some languages, applying the shift operators to any datatype smaller than <code>int</code> automatically resizes the operand to be an <code>int</code>.</p>
<p>Note that <code><<<</code> is not an operator, because it would be redundant.</p>
<p>Also note that <strong>C and C++ do not distinguish between the right shift operators</strong>. They provide only the <code>>></code> operator, and the right-shifting behavior is implementation defined for signed types. The rest of the answer uses the C# / Java operators.</p>
<p>(In all mainstream C and C++ implementations including GCC and Clang/LLVM, <code>>></code> on signed types is arithmetic. Some code assumes this, but it isn't something the standard guarantees. It's not <em>undefined</em>, though; the standard requires implementations to define it one way or another. However, left shifts of negative signed numbers <em>is</em> undefined behaviour (signed integer overflow). So unless you need arithmetic right shift, it's usually a good idea to do your bit-shifting with unsigned types.)</p>
<hr />
<h2>Left shift (<<)</h2>
<p>Integers are stored, in memory, as a series of bits. For example, the number 6 stored as a 32-bit <code>int</code> would be:</p>
<pre><code>00000000 00000000 00000000 00000110
</code></pre>
<p>Shifting this bit pattern to the left one position (<code>6 << 1</code>) would result in the number 12:</p>
<pre><code>00000000 00000000 00000000 00001100
</code></pre>
<p>As you can see, the digits have shifted to the left by one position, and the last digit on the right is filled with a zero. You might also note that shifting left is equivalent to multiplication by powers of 2. So <code>6 << 1</code> is equivalent to <code>6 * 2</code>, and <code>6 << 3</code> is equivalent to <code>6 * 8</code>. A good optimizing compiler will replace multiplications with shifts when possible.</p>
<h3>Non-circular shifting</h3>
<p>Please note that these are <em>not</em> circular shifts. Shifting this value to the left by one position (<code>3,758,096,384 << 1</code>):</p>
<pre><code>11100000 00000000 00000000 00000000
</code></pre>
<p>results in 3,221,225,472:</p>
<pre><code>11000000 00000000 00000000 00000000
</code></pre>
<p>The digit that gets shifted "off the end" is lost. It does not wrap around.</p>
<hr />
<h2>Logical right shift (>>>)</h2>
<p>A logical right shift is the converse to the left shift. Rather than moving bits to the left, they simply move to the right. For example, shifting the number 12:</p>
<pre><code>00000000 00000000 00000000 00001100
</code></pre>
<p>to the right by one position (<code>12 >>> 1</code>) will get back our original 6:</p>
<pre><code>00000000 00000000 00000000 00000110
</code></pre>
<p>So we see that shifting to the right is equivalent to division by powers of 2.</p>
<h3>Lost bits are gone</h3>
<p>However, a shift cannot reclaim "lost" bits. For example, if we shift this pattern:</p>
<pre><code>00111000 00000000 00000000 00000110
</code></pre>
<p>to the left 4 positions (<code>939,524,102 << 4</code>), we get 2,147,483,744:</p>
<pre><code>10000000 00000000 00000000 01100000
</code></pre>
<p>and then shifting back (<code>(939,524,102 << 4) >>> 4</code>) we get 134,217,734:</p>
<pre><code>00001000 00000000 00000000 00000110
</code></pre>
<p>We cannot get back our original value once we have lost bits.</p>
<hr />
<h1>Arithmetic right shift (>>)</h1>
<p>The arithmetic right shift is exactly like the logical right shift, except instead of padding with zero, it pads with the most significant bit. This is because the most significant bit is the <em>sign</em> bit, or the bit that distinguishes positive and negative numbers. By padding with the most significant bit, the arithmetic right shift is sign-preserving.</p>
<p>For example, if we interpret this bit pattern as a negative number:</p>
<pre><code>10000000 00000000 00000000 01100000
</code></pre>
<p>we have the number -2,147,483,552. Shifting this to the right 4 positions with the arithmetic shift (-2,147,483,552 >> 4) would give us:</p>
<pre><code>11111000 00000000 00000000 00000110
</code></pre>
<p>or the number -134,217,722.</p>
<p>So we see that we have preserved the sign of our negative numbers by using the arithmetic right shift, rather than the logical right shift. And once again, we see that we are performing division by powers of 2.</p> | {
"question_id": 141525,
"question_date": "2008-09-26T19:47:15.367Z",
"question_score": 1497,
"tags": "language-agnostic|bit-manipulation|operators|bit-shift|binary-operators",
"answer_id": 141873,
"answer_date": "2008-09-26T20:46:39.813Z",
"answer_score": 1826
} |
Please answer the following Stack Overflow question:
Title: How do I create a file and write to it?
<p>What's the simplest way to <a href="https://docs.oracle.com/javase/tutorial/essential/io/file.html" rel="noreferrer">create and write to a (text) file in Java</a>?</p> | <p><em>Note that each of the code samples below may throw <code>IOException</code>. Try/catch/finally blocks have been omitted for brevity. See <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html" rel="noreferrer">this tutorial</a> for information about exception handling.</em></p>
<p><em>Note that each of the code samples below will overwrite the file if it already exists</em></p>
<p>Creating a text file:</p>
<pre><code>PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
</code></pre>
<p>Creating a binary file:</p>
<pre><code>byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();
</code></pre>
<p><strong>Java 7+</strong> users can use the <a href="http://docs.oracle.com/javase/7/docs/api/index.html?java/nio/file/Files.html" rel="noreferrer"><code>Files</code></a> class to write to files:</p>
<p>Creating a text file:</p>
<pre><code>List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
</code></pre>
<p>Creating a binary file:</p>
<pre><code>byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);
</code></pre> | {
"question_id": 2885173,
"question_date": "2010-05-21T19:58:55.167Z",
"question_score": 1496,
"tags": "java|file-io",
"answer_id": 2885224,
"answer_date": "2010-05-21T20:06:52.207Z",
"answer_score": 1839
} |
Please answer the following Stack Overflow question:
Title: What does __all__ mean in Python?
<p>I see <code>__all__</code> in <code>__init__.py</code> files. What does it do?</p> | <p>It's a list of public objects of that module, as interpreted by <code>import *</code>. It overrides the default of hiding everything that begins with an underscore.</p> | {
"question_id": 44834,
"question_date": "2008-09-04T21:28:18.547Z",
"question_score": 1493,
"tags": "python|syntax|namespaces",
"answer_id": 44842,
"answer_date": "2008-09-04T21:30:46.213Z",
"answer_score": 815
} |
Please answer the following Stack Overflow question:
Title: JavaScript set object key by variable
<p>I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:</p>
<pre><code>var key = "happyCount";
myArray.push( { key : someValueArray } );
</code></pre>
<p>but when I try to examine my array of objects for every object the key is <code>"key"</code> instead of the value of the variable key. Is there any way to set the value of the key from a variable? </p>
<p>Fiddle for better explanation:
<a href="http://jsfiddle.net/Fr6eY/3/" rel="noreferrer">http://jsfiddle.net/Fr6eY/3/</a></p> | <p>You need to make the object first, then use <code>[]</code> to set it.</p>
<pre><code>var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
</code></pre>
<hr />
<p>UPDATE 2021:</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names" rel="noreferrer">Computed property names</a> feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.</p>
<pre><code>const yourKeyVariable = "happyCount";
const someValueArray= [...];
const obj = {
[yourKeyVariable]: someValueArray,
}
</code></pre> | {
"question_id": 11508463,
"question_date": "2012-07-16T16:24:23.647Z",
"question_score": 1492,
"tags": "javascript",
"answer_id": 11508490,
"answer_date": "2012-07-16T16:26:12.093Z",
"answer_score": 2712
} |
Please answer the following Stack Overflow question:
Title: How do I vertically align text in a div?
<p>I am trying to find the most effective way to align text with a div. I have tried a few things and none seem to work.</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>.testimonialText {
position: absolute;
left: 15px;
top: 15px;
width: 150px;
height: 309px;
vertical-align: middle;
text-align: center;
font-family: Georgia, "Times New Roman", Times, serif;
font-style: italic;
padding: 1em 0 1em 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="testimonialText">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div></code></pre>
</div>
</div>
</p> | <h3>The correct way to do this in modern browsers is to use Flexbox.</h3>
<p>See <a href="https://stackoverflow.com/a/13515693/102937">this answer</a> for details.</p>
<p>See below for some older ways that work in older browsers.</p>
<hr />
<p><strong>Vertical Centering in CSS</strong>
<br/><a href="http://www.jakpsatweb.cz/css/css-vertical-center-solution.html" rel="noreferrer">http://www.jakpsatweb.cz/css/css-vertical-center-solution.html</a></p>
<p>Article summary:</p>
<p>For a CSS 2 browser, one can use <code>display:table</code>/<code>display:table-cell</code> to center content.</p>
<p>A sample is also available at <a href="http://jsfiddle.net/SVJaK/" rel="noreferrer">JSFiddle</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>div { border:1px solid green;}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="display: table; height: 400px; overflow: hidden;">
<div style="display: table-cell; vertical-align: middle;">
<div>
everything is vertically centered in modern IE8+ and others.
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>It is possible to merge hacks for old browsers (Internet Explorer 6/7) into styles with using <code>#</code> to hide styles from newer browsers:</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>div { border:1px solid green;}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="display: table; height: 400px; #position: relative; overflow: hidden;">
<div style=
"#position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
<div style=" #position: relative; #top: -50%">
everything is vertically centered
</div>
</div>
</div></code></pre>
</div>
</div>
</p> | {
"question_id": 2939914,
"question_date": "2010-05-30T19:02:13.510Z",
"question_score": 1491,
"tags": "html|css|vertical-alignment",
"answer_id": 2939979,
"answer_date": "2010-05-30T19:29:50.253Z",
"answer_score": 901
} |
Please answer the following Stack Overflow question:
Title: You have not concluded your merge (MERGE_HEAD exists)
<p>I made a branch called 'f' and did a checkout to master. When I tried the <code>git pull</code> command I got this message:</p>
<pre><code>You have not concluded your merge (MERGE_HEAD exists).
Please, commit your changes before you can merge.
</code></pre>
<p>When I try the <code>git status</code>, it gave me the following:</p>
<pre><code>On branch master
# Your branch and 'origin/master' have diverged,
# and have 1 and 13 different commit(s) each, respectively.
#
# Changes to be committed:
#
# modified: app/assets/images/backward.png
# modified: app/assets/images/forward.png
# new file: app/assets/images/index_background.jpg
# new file: app/assets/images/loading.gif
# modified: app/assets/images/pause.png
# modified: app/assets/images/play.png
# new file: app/assets/javascripts/jquery-ui-bootstrap.js
# new file: app/assets/stylesheets/jquery-ui-bootstrap.css
# modified: app/controllers/friends_controller.rb
# modified: app/controllers/plays_controller.rb
# modified: app/mailers/invite_friends_mailer.rb
# modified: app/mailers/send_plays_mailer.rb
# modified: app/mailers/shot_chart_mailer.rb
# modified: app/views/friends/show_plays.html.erb
# modified: app/views/layouts/application.html.erb
# modified: app/views/plays/_inbox_table.html.erb
# modified: app/views/plays/show.html.erb
# modified: app/views/welcome/contact_form.html.erb
# modified: app/views/welcome/index.html.erb
# modified: log/development.log
# modified: log/restclient.log
# new file: tmp/cache/assets/C1A/C00/sprockets%2Fb7901e0813446f810e560158a1a97066
# modified: tmp/cache/assets/C64/930/sprockets%2F65aa1510292214f4fd1342280d521e4c
# new file: tmp/cache/assets/C73/C40/sprockets%2F96912377b93498914dd04bc69fa98585
# new file: tmp/cache/assets/CA9/090/sprockets%2Fa71992733a432421e67e03ff1bd441d8
# new file: tmp/cache/assets/CCD/7E0/sprockets%2F47125c2ebd0e8b29b6511b7b961152a1
# modified: tmp/cache/assets/CD5/DD0/sprockets%2F59d317902de6e0f68689899259caff26
# modified: tmp/cache/assets/CE3/080/sprockets%2F5c3b516e854760f14eda2395c4ff2581
# new file: tmp/cache/assets/CED/B20/sprockets%2F423772fde44ab6f6f861639ee71444c4
# new file: tmp/cache/assets/D0C/E10/sprockets%2F8d1f4b30c6be13017565fe1b697156ce
# new file: tmp/cache/assets/D12/290/sprockets%2F93ae21f3cdd5e24444ae4651913fd875
# new file: tmp/cache/assets/D13/FC0/sprockets%2F57aad34b9d3c9e225205237dac9b1999
# new file: tmp/cache/assets/D1D/DE0/sprockets%2F5840ff4283f6545f472be8e10ce67bb8
# new file: tmp/cache/assets/D23/BD0/sprockets%2F439d5dedcc8c54560881edb9f0456819
# new file: tmp/cache/assets/D24/570/sprockets%2Fb449db428fc674796e18b7a419924afe
# new file: tmp/cache/assets/D28/480/sprockets%2F9aeec798a04544e478806ffe57e66a51
# new file: tmp/cache/assets/D3A/ED0/sprockets%2Fcd959cbf710b366c145747eb3c062bb4
# new file: tmp/cache/assets/D3C/060/sprockets%2F363ac7c9208d3bb5d7047f11c159d7ce
# new file: tmp/cache/assets/D48/D00/sprockets%2Fe23c97b8996e7b5567a3080c285aaccb
# new file: tmp/cache/assets/D6A/900/sprockets%2Fa5cece9476b21aa4d5f46911ca96c450
# new file: tmp/cache/assets/D6C/510/sprockets%2Fb086a020de3c258cb1c67dfc9c67d546
# new file: tmp/cache/assets/D70/F30/sprockets%2Facf9a6348722adf1ee7abbb695603078
# new file: tmp/cache/assets/DA3/4A0/sprockets%2F69c26d0a9ca8ce383e20897cefe05aa4
# new file: tmp/cache/assets/DA7/2F0/sprockets%2F61da396fb86c5ecd844a2d83ac759b4b
# new file: tmp/cache/assets/DB9/C80/sprockets%2F876fbfb9685b2b8ea476fa3c67ae498b
# new file: tmp/cache/assets/DBD/7A0/sprockets%2F3640ea84a1dfaf6f91a01d1d6fbe223d
# new file: tmp/cache/assets/DC1/8D0/sprockets%2Fe5ee1f1cfba2144ec00b1dcd6773e691
# new file: tmp/cache/assets/DCC/E60/sprockets%2Fd6a95f601456c93ff9a1bb70dea3dfc0
# new file: tmp/cache/assets/DF1/130/sprockets%2Fcda4825bb42c91e2d1f1ea7b2b958bda
# new file: tmp/cache/assets/E23/DE0/sprockets%2Fb1acc25c28cd1fabafbec99d169163d3
# new file: tmp/cache/assets/E23/FD0/sprockets%2Fea3dbcd1f341008ef8be67b1ccc5a9c5
# modified: tmp/cache/assets/E4E/AD0/sprockets%2Fb930f45cfe7c6a8d0efcada3013cc4bc
# new file: tmp/cache/assets/E63/7D0/sprockets%2F77de495a665c3ebcb47befecd07baae6
# modified: tmp/pids/server.pid
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# Coachbase/
# log/development.log.orig
# log/restclient.log.orig
</code></pre>
<p>What should I do?</p> | <p>The problem is your previous pull failed to merge automatically and went to conflict state. And the conflict wasn't resolved properly before the next pull.</p>
<ol>
<li>Undo the merge and pull again.</li>
</ol>
<p>To undo a merge:</p>
<p><code>git merge --abort</code> [Since git version 1.7.4]</p>
<p><code>git reset --merge</code> [prior git versions]</p>
<ol start="2">
<li><p>Resolve the conflict.</p>
</li>
<li><p><strong>Don't forget to add and commit the merge.</strong></p>
</li>
<li><p><code>git pull</code> now should work fine.</p>
</li>
</ol> | {
"question_id": 11646107,
"question_date": "2012-07-25T08:58:17.663Z",
"question_score": 1491,
"tags": "git",
"answer_id": 11647899,
"answer_date": "2012-07-25T10:38:31.393Z",
"answer_score": 2655
} |
Please answer the following Stack Overflow question:
Title: How to directly initialize a HashMap (in a literal way)?
<p>Is there some way of initializing a Java HashMap like this?:</p>
<pre><code>Map<String,String> test =
new HashMap<String, String>{"test":"test","test":"test"};
</code></pre>
<p>What would be the correct syntax? I have not found anything regarding this. Is this possible? I am looking for the shortest/fastest way to put some "final/static" values in a map that never change and are known in advance when creating the Map.</p> | <h1>All Versions</h1>
<p>In case you happen to need just a single entry: There is <code>Collections.singletonMap("key", "value")</code>.</p>
<h1>For Java Version 9 or higher:</h1>
<p>Yes, this is possible now. In Java 9 a couple of factory methods have been added that simplify the creation of maps :</p>
<pre><code>// this works for up to 10 elements:
Map<String, String> test1 = Map.of(
"a", "b",
"c", "d"
);
// this works for any number of elements:
import static java.util.Map.entry;
Map<String, String> test2 = Map.ofEntries(
entry("a", "b"),
entry("c", "d")
);
</code></pre>
<p>In the example above both <code>test</code> and <code>test2</code> will be the same, just with different ways of expressing the Map. The <code>Map.of</code> method is defined for up to ten elements in the map, while the <code>Map.ofEntries</code> method will have no such limit.</p>
<p>Note that in this case the resulting map will be an immutable map. If you want the map to be mutable, you could copy it again, e.g. using <code>mutableMap = new HashMap<>(Map.of("a", "b"));</code></p>
<p>(See also <a href="http://openjdk.java.net/jeps/269" rel="noreferrer">JEP 269</a> and the <a href="https://docs.oracle.com/javase/9/docs/api/java/util/Map.html" rel="noreferrer">Javadoc</a>)</p>
<h1>For up to Java Version 8:</h1>
<p>No, you will have to add all the elements manually. You can use an initializer in an anonymous subclass to make the syntax a little bit shorter:</p>
<pre><code>Map<String, String> myMap = new HashMap<String, String>() {{
put("a", "b");
put("c", "d");
}};
</code></pre>
<p>However, the anonymous subclass might introduce unwanted behavior in some cases. This includes for example:</p>
<ul>
<li>It generates an additional class which increases memory consumption, disk space consumption and startup-time</li>
<li>In case of a non-static method: It holds a reference to the object the creating method was called upon. That means the object of the outer class cannot be garbage collected while the created map object is still referenced, thus blocking additional memory</li>
</ul>
<p>Using a function for initialization will also enable you to generate a map in an initializer, but avoids nasty side-effects:</p>
<pre><code>Map<String, String> myMap = createMap();
private static Map<String, String> createMap() {
Map<String,String> myMap = new HashMap<String,String>();
myMap.put("a", "b");
myMap.put("c", "d");
return myMap;
}
</code></pre> | {
"question_id": 6802483,
"question_date": "2011-07-23T18:40:33.140Z",
"question_score": 1487,
"tags": "java|dictionary|collections|initialization",
"answer_id": 6802502,
"answer_date": "2011-07-23T18:44:15.553Z",
"answer_score": 1929
} |
Please answer the following Stack Overflow question:
Title: if/else in a list comprehension
<p>How do I replace all the <code>None</code>s with empty strings, and then call some function <code>f</code>?</p>
<pre><code>[f(x) for x in xs if x is not None else '']
</code></pre> | <p>You can totally do that. It's just an ordering issue:</p>
<pre><code>[f(x) if x is not None else '' for x in xs]
</code></pre>
<p>In general,</p>
<pre><code>[f(x) if condition else g(x) for x in sequence]
</code></pre>
<p>And, for list comprehensions with <code>if</code> conditions only,</p>
<pre><code>[f(x) for x in sequence if condition]
</code></pre>
<p>Note that this actually uses a different language construct, a <a href="https://docs.python.org/3/reference/expressions.html#conditional-expressions" rel="noreferrer">conditional expression</a>, which itself is not part of the <a href="https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries" rel="noreferrer">comprehension syntax</a>, while the <code>if</code> after the <code>for…in</code> is part of list comprehensions and used to <em>filter</em> elements from the source iterable.</p>
<hr />
<p>Conditional expressions can be used in all kinds of situations where you want to choose between two expression values based on some condition. This does the same as the <a href="https://docs.python.org/3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator" rel="noreferrer">ternary operator <code>?:</code> that exists in other languages</a>. For example:</p>
<pre><code>value = 123
print(value, 'is', 'even' if value % 2 == 0 else 'odd')
</code></pre> | {
"question_id": 4260280,
"question_date": "2010-11-23T19:56:44.787Z",
"question_score": 1487,
"tags": "python|list-comprehension",
"answer_id": 4260304,
"answer_date": "2010-11-23T19:59:17.517Z",
"answer_score": 2459
} |
Please answer the following Stack Overflow question:
Title: How to add local jar files to a Maven project?
<p>How do I add local jar files (not yet part of the Maven repository) directly in my project's library sources?</p> | <p>Install the JAR into your local Maven repository (typically <code>.m2</code> in your home folder) as follows:</p>
<pre><code>mvn install:install-file \
-Dfile=<path-to-file> \
-DgroupId=<group-id> \
-DartifactId=<artifact-id> \
-Dversion=<version> \
-Dpackaging=<packaging> \
-DgeneratePom=true
</code></pre>
<p>Where each refers to:</p>
<p><code><path-to-file></code>: the path to the file to load e.g → <code>c:\kaptcha-2.3.jar</code></p>
<p><code><group-id></code>: the group that the file should be registered under e.g → <code>com.google.code</code></p>
<p><code><artifact-id></code>: the artifact name for the file e.g → <code>kaptcha</code></p>
<p><code><version></code>: the version of the file e.g → <code>2.3</code></p>
<p><code><packaging></code>: the packaging of the file e.g. → <code>jar</code></p>
<p><strong>Reference</strong></p>
<ul>
<li>Maven FAQ: <a href="http://maven.apache.org/general.html#importing-jars" rel="noreferrer">I have a jar that I want to put into my local repository. How can I copy it in?</a></li>
<li>Maven Install Plugin Usage: <a href="https://maven.apache.org/plugins/maven-install-plugin/usage.html#The_install:install-file_goal" rel="noreferrer">The <code>install:install-file</code> goal</a></li>
</ul> | {
"question_id": 4955635,
"question_date": "2011-02-10T10:03:26.430Z",
"question_score": 1487,
"tags": "java|maven|dependencies|libraries|mvn-repo",
"answer_id": 4955695,
"answer_date": "2011-02-10T10:08:29.217Z",
"answer_score": 990
} |
Please answer the following Stack Overflow question:
Title: When are you supposed to use escape instead of encodeURI / encodeURIComponent?
<p>When encoding a query string to be sent to a web server - when do you use <code>escape()</code> and when do you use <code>encodeURI()</code> or <code>encodeURIComponent()</code>:</p>
<p>Use escape:</p>
<pre><code>escape("% +&=");
</code></pre>
<p>OR</p>
<p>use encodeURI() / encodeURIComponent()</p>
<pre><code>encodeURI("http://www.google.com?var1=value1&var2=value2");
encodeURIComponent("var1=value1&var2=value2");
</code></pre> | <h1>escape()</h1>
<p>Don't use it!
<code>escape()</code> is defined in section <a href="https://www.ecma-international.org/ecma-262/9.0/index.html#sec-escape-string" rel="noreferrer">B.2.1.2 escape</a> and the <a href="https://www.ecma-international.org/ecma-262/9.0/index.html#sec-additional-ecmascript-features-for-web-browsers" rel="noreferrer">introduction text of Annex B</a> says:</p>
<blockquote>
<p>... All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. ...<br />
... Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code....</p>
</blockquote>
<p>Behaviour:</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape</a></p>
<p>Special characters are encoded with the exception of: @*_+-./</p>
<p>The hexadecimal form for characters, whose code unit value is 0xFF or less, is a two-digit escape sequence: <code>%xx</code>.</p>
<p>For characters with a greater code unit, the four-digit format <code>%uxxxx</code> is used. This is not allowed within a query string (as defined in <a href="https://www.rfc-editor.org/rfc/rfc3986#section-3.4" rel="noreferrer">RFC3986</a>):</p>
<pre><code>query = *( pchar / "/" / "?" )
pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded = "%" HEXDIG HEXDIG
sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "="
</code></pre>
<p>A percent sign is only allowed if it is directly followed by two hexdigits, percent followed by <code>u</code> is not allowed.</p>
<h1>encodeURI()</h1>
<p>Use encodeURI when you want a working URL. Make this call:</p>
<pre><code>encodeURI("http://www.example.org/a file with spaces.html")
</code></pre>
<p>to get:</p>
<pre><code>http://www.example.org/a%20file%20with%20spaces.html
</code></pre>
<p>Don't call encodeURIComponent since it would destroy the URL and return</p>
<pre><code>http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html
</code></pre>
<p>Note that encodeURI, like encodeURIComponent, does not escape the ' character.</p>
<h1>encodeURIComponent()</h1>
<p>Use encodeURIComponent when you want to encode the value of a URL parameter.</p>
<pre><code>var p1 = encodeURIComponent("http://example.org/?a=12&b=55")
</code></pre>
<p>Then you may create the URL you need:</p>
<pre><code>var url = "http://example.net/?param1=" + p1 + "&param2=99";
</code></pre>
<p>And you will get this complete URL:</p>
<p><code>http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55&param2=99</code></p>
<p>Note that encodeURIComponent does not escape the <code>'</code> character. A common bug is to use it to create html attributes such as <code>href='MyUrl'</code>, which could suffer an injection bug. If you are constructing html from strings, either use <code>"</code> instead of <code>'</code> for attribute quotes, or add an extra layer of encoding (<code>'</code> can be encoded as %27).</p>
<p>For more information on this type of encoding you can check: <a href="http://en.wikipedia.org/wiki/Percent-encoding" rel="noreferrer">http://en.wikipedia.org/wiki/Percent-encoding</a></p> | {
"question_id": 75980,
"question_date": "2008-09-16T19:24:34.730Z",
"question_score": 1486,
"tags": "javascript|encoding|query-string",
"answer_id": 3608791,
"answer_date": "2010-08-31T12:04:17.180Z",
"answer_score": 1993
} |
Please answer the following Stack Overflow question:
Title: Where can I find documentation on formatting a date in JavaScript?
<p>I noticed that JavaScript's <code>new Date()</code> function is very smart in accepting dates in several formats.</p>
<pre><code>Xmas95 = new Date("25 Dec, 1995 23:15:00")
Xmas95 = new Date("2009 06 12,12:52:39")
Xmas95 = new Date("20 09 2006,12:52:39")
</code></pre>
<p>I could not find documentation anywhere showing all the valid string formats while calling <code>new Date()</code> function.</p>
<p>This is for converting a string to a date. If we look at the opposite side, that is, converting a date object to a string, until now I was under the impression that JavaScript doesn't have a built-in API to format a date object into a string.</p>
<blockquote>
<p><strong>Editor's note:</strong> The following approach is the asker's attempt that worked on a particular browser but does <em>not</em> work in general; <strong>see the answers on this page</strong> to see some actual solutions.</p>
</blockquote>
<p>Today, I played with the <code>toString()</code> method on the date object and surprisingly it serves the purpose of formatting date to strings.</p>
<pre><code>var d1 = new Date();
d1.toString('yyyy-MM-dd'); //Returns "2009-06-29" in Internet Explorer, but not Firefox or Chrome
d1.toString('dddd, MMMM ,yyyy') //Returns "Monday, June 29,2009" in Internet Explorer, but not Firefox or Chrome
</code></pre>
<p>Also here I couldn't find any documentation on all the ways we can format the date object into a string.</p>
<p>Where is the documentation which lists the format specifiers supported by the <code>Date()</code> object?</p> | <p>I love <em><a href="https://www.webdevelopersnotes.com/10-ways-to-format-time-and-date-using-javascript" rel="noreferrer">10 ways to format time and date using JavaScript</a></em> and <em><a href="http://www.elated.com/articles/working-with-dates/" rel="noreferrer">Working with Dates</a></em>.</p>
<p>Basically, you have three methods and you have to combine the strings for yourself:</p>
<pre><code>getDate() // Returns the date
getMonth() // Returns the month
getFullYear() // Returns the year
</code></pre>
<p>Example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
console.log(curr_date + "-" + curr_month + "-" + curr_year);</code></pre>
</div>
</div>
</p> | {
"question_id": 1056728,
"question_date": "2009-06-29T05:44:03.863Z",
"question_score": 1485,
"tags": "javascript|date|datetime-format|date-format|time-format",
"answer_id": 1056730,
"answer_date": "2009-06-29T05:46:23.597Z",
"answer_score": 1117
} |
Please answer the following Stack Overflow question:
Title: How do I show my global Git configuration?
<p>I'd like to show all configured Git sections.</p>
<p>I only found <code>git config --get core.editor</code>, and I'd like to output everything that's configured globally, not only the configured default editor.</p> | <p>You can use:</p>
<pre class="lang-sh prettyprint-override"><code>git config --list
</code></pre>
<p>or look at your <code>~/.gitconfig</code> file. The local configuration will be in your repository's <code>.git/config</code> file.</p>
<p>Use:</p>
<pre class="lang-sh prettyprint-override"><code>git config --list --show-origin
</code></pre>
<p>to see where that setting is defined (global, user, repo, etc...)</p> | {
"question_id": 12254076,
"question_date": "2012-09-03T21:14:17.700Z",
"question_score": 1484,
"tags": "git",
"answer_id": 12254105,
"answer_date": "2012-09-03T21:16:39.633Z",
"answer_score": 2311
} |
Please answer the following Stack Overflow question:
Title: Passing data between view controllers
<p>I'm new to iOS and Objective-C and the whole <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="noreferrer">MVC</a> paradigm and I'm stuck with the following:</p>
<p>I have a view that acts as a data entry form and I want to give the user the option to select multiple products. The products are listed on another view with a <code>UITableViewController</code> and I have enabled multiple selections.</p>
<p>How do I transfer the data from one view to another? I will be holding the selections on the <code>UITableView</code> in an array, but how do I then pass that back to the previous data entry form view so it can be saved along with the other data to Core Data on submission of the form?</p>
<p>I have surfed around and seen some people declare an array in the app delegate. I read something about <a href="https://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">singletons</a>, but I don't understand what these are and I read something about creating a data model.</p>
<p>What would be the correct way of performing this and how would I go about it?</p> | <p>This question seems to be very popular here on Stack Overflow so I thought I would try and give a better answer to help out people starting in the world of iOS like me.</p>
<p><strong>Passing Data Forward</strong></p>
<p>Passing data forward to a view controller from another view controller. You would use this method if you wanted to pass an object/value from one view controller to another view controller that you may be pushing on to a navigation stack.</p>
<p>For this example, we will have <code>ViewControllerA</code> and <code>ViewControllerB</code></p>
<p>To pass a <code>BOOL</code> value from <code>ViewControllerA</code> to <code>ViewControllerB</code> we would do the following.</p>
<ol>
<li><p>in <code>ViewControllerB.h</code> create a property for the <code>BOOL</code></p>
<pre><code> @property (nonatomic, assign) BOOL isSomethingEnabled;
</code></pre>
</li>
<li><p>in <code>ViewControllerA</code> you need to tell it about <code>ViewControllerB</code> so use an</p>
<pre><code> #import "ViewControllerB.h"
</code></pre>
</li>
</ol>
<p>Then where you want to load the view, for example, <code>didSelectRowAtIndex</code> or some <code>IBAction</code>, you need to set the property in <code>ViewControllerB</code> before you push it onto the navigation stack.</p>
<pre><code> ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil];
viewControllerB.isSomethingEnabled = YES;
[self pushViewController:viewControllerB animated:YES];
</code></pre>
<p>This will set <code>isSomethingEnabled</code> in <code>ViewControllerB</code> to <code>BOOL</code> value <code>YES</code>.</p>
<p><strong>Passing Data Forward using Segues</strong></p>
<p>If you are using Storyboards you are most likely using segues and will need this procedure to pass data forward. This is similar to the above but instead of passing the data before you push the view controller, you use a method called</p>
<pre><code>-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
</code></pre>
<p>So to pass a <code>BOOL</code> from <code>ViewControllerA</code> to <code>ViewControllerB</code> we would do the following:</p>
<ol>
<li><p>in <code>ViewControllerB.h</code> create a property for the <code>BOOL</code></p>
<pre><code> @property (nonatomic, assign) BOOL isSomethingEnabled;
</code></pre>
</li>
<li><p>in <code>ViewControllerA</code> you need to tell it about <code>ViewControllerB</code>, so use an</p>
<pre><code> #import "ViewControllerB.h"
</code></pre>
</li>
<li><p>Create the segue from <code>ViewControllerA</code> to <code>ViewControllerB</code> on the storyboard and give it an identifier. In this example we'll call it <code>"showDetailSegue"</code></p>
</li>
<li><p>Next, we need to add the method to <code>ViewControllerA</code> that is called when any segue is performed. Because of this we need to detect which segue was called and then do something. In our example, we will check for <code>"showDetailSegue"</code> and if that's performed, we will pass our <code>BOOL</code> value to <code>ViewControllerB</code></p>
<pre><code> -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:@"showDetailSegue"]){
ViewControllerB *controller = (ViewControllerB *)segue.destinationViewController;
controller.isSomethingEnabled = YES;
}
}
</code></pre>
</li>
</ol>
<p>If you have your views embedded in a navigation controller, you need to change the method above slightly to the following</p>
<pre><code> -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:@"showDetailSegue"]){
UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
ViewControllerB *controller = (ViewControllerB *)navController.topViewController;
controller.isSomethingEnabled = YES;
}
}
</code></pre>
<p>This will set <code>isSomethingEnabled</code> in <code>ViewControllerB</code> to <code>BOOL</code> value <code>YES</code>.</p>
<p><strong>Passing Data Back</strong></p>
<p>To pass data back from <code>ViewControllerB</code> to <code>ViewControllerA</code> you need to use <em>Protocols and Delegates</em> or <em>Blocks</em>, the latter can be used as a loosely coupled mechanism for callbacks.</p>
<p>To do this we will make <code>ViewControllerA</code> a delegate of <code>ViewControllerB</code>. This allows <code>ViewControllerB</code> to send a message back to <code>ViewControllerA</code> enabling us to send data back.</p>
<p>For <code>ViewControllerA</code> to be a delegate of <code>ViewControllerB</code> it must conform to <code>ViewControllerB</code>'s protocol which we have to specify. This tells <code>ViewControllerA</code> which methods it must implement.</p>
<ol>
<li><p>In <code>ViewControllerB.h</code>, below the <code>#import</code>, but above <code>@interface</code> you specify the protocol.</p>
<pre><code> @class ViewControllerB;
@protocol ViewControllerBDelegate <NSObject>
- (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item;
@end
</code></pre>
</li>
<li><p>Next still in the <code>ViewControllerB.h</code>, you need to set up a <code>delegate</code> property and synthesize in <code>ViewControllerB.m</code></p>
<pre><code> @property (nonatomic, weak) id <ViewControllerBDelegate> delegate;
</code></pre>
</li>
<li><p>In <code>ViewControllerB</code> we call a message on the <code>delegate</code> when we pop the view controller.</p>
<pre><code> NSString *itemToPassBack = @"Pass this value back to ViewControllerA";
[self.delegate addItemViewController:self didFinishEnteringItem:itemToPassBack];
</code></pre>
</li>
<li><p>That's it for <code>ViewControllerB</code>. Now in <code>ViewControllerA.h</code>, tell <code>ViewControllerA</code> to import <code>ViewControllerB</code> and conform to its protocol.</p>
<pre><code> #import "ViewControllerB.h"
@interface ViewControllerA : UIViewController <ViewControllerBDelegate>
</code></pre>
</li>
<li><p>In <code>ViewControllerA.m</code> implement the following method from our protocol</p>
<pre><code> - (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item
{
NSLog(@"This was returned from ViewControllerB %@", item);
}
</code></pre>
</li>
<li><p>Before pushing <code>viewControllerB</code> to navigation stack we need to tell <code>ViewControllerB</code> that <code>ViewControllerA</code> is its delegate, otherwise we will get an error.</p>
<pre><code> ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil];
viewControllerB.delegate = self
[[self navigationController] pushViewController:viewControllerB animated:YES];
</code></pre>
</li>
</ol>
<hr />
<h3>References</h3>
<ol>
<li><a href="http://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/ManagingDataFlowBetweenViewControllers/ManagingDataFlowBetweenViewControllers.html#//apple_ref/doc/uid/TP40007457-CH8-SW9" rel="noreferrer">Using Delegation to Communicate With Other View Controllers</a> in the <em>View Controller Programming Guide</em></li>
<li><a href="https://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/Delegation.html" rel="noreferrer">Delegate Pattern</a></li>
</ol>
<p><strong>NSNotification center</strong></p>
<p>It's another way to pass data.</p>
<pre><code>// Add an observer in controller(s) where you want to receive data
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeepLinking:) name:@"handleDeepLinking" object:nil];
-(void) handleDeepLinking:(NSNotification *) notification {
id someObject = notification.object // Some custom object that was passed with notification fire.
}
// Post notification
id someObject;
[NSNotificationCenter.defaultCenter postNotificationName:@"handleDeepLinking" object:someObject];
</code></pre>
<p><strong>Passing Data back from one class to another</strong> (A class can be any controller, Network/session manager, UIView subclass or any other class)</p>
<p><em>Blocks are anonymous functions.</em></p>
<p>This example passes data from <strong>Controller B</strong> to <strong>Controller A</strong></p>
<p><strong>Define a block</strong></p>
<pre><code>@property void(^selectedVoucherBlock)(NSString *); // in ContollerA.h
</code></pre>
<p><strong>Add block handler (listener)</strong></p>
<p>Where you need a value (for example, you need your API response in ControllerA or you need ContorllerB data on A)</p>
<pre><code>// In ContollerA.m
- (void)viewDidLoad {
[super viewDidLoad];
__unsafe_unretained typeof(self) weakSelf = self;
self.selectedVoucherBlock = ^(NSString *voucher) {
weakSelf->someLabel.text = voucher;
};
}
</code></pre>
<p><strong>Go to Controller B</strong></p>
<pre><code>UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ControllerB *vc = [storyboard instantiateViewControllerWithIdentifier:@"ControllerB"];
vc.sourceVC = self;
[self.navigationController pushViewController:vc animated:NO];
</code></pre>
<p><strong>Fire block</strong></p>
<pre><code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath {
NSString *voucher = vouchersArray[indexPath.row];
if (sourceVC.selectVoucherBlock) {
sourceVC.selectVoucherBlock(voucher);
}
[self.navigationController popToViewController:sourceVC animated:YES];
}
</code></pre>
<p><a href="https://stackoverflow.com/a/49900404/3030400">Another Working Example for Blocks</a></p> | {
"question_id": 5210535,
"question_date": "2011-03-06T12:43:57.183Z",
"question_score": 1484,
"tags": "ios|objective-c|swift|model-view-controller|uiviewcontroller",
"answer_id": 9736559,
"answer_date": "2012-03-16T11:39:33.740Z",
"answer_score": 1746
} |
Please answer the following Stack Overflow question:
Title: How can I undo git reset --hard HEAD~1?
<p>Is it possible to undo the changes caused by the following command? If so, how?</p>
<pre><code>git reset --hard HEAD~1
</code></pre> | <p>Pat Notz is correct. You can get the commit back so long as it's been within a few days. git only garbage collects after about a month or so unless you explicitly tell it to remove newer blobs.</p>
<pre><code>$ git init
Initialized empty Git repository in .git/
$ echo "testing reset" > file1
$ git add file1
$ git commit -m 'added file1'
Created initial commit 1a75c1d: added file1
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 file1
$ echo "added new file" > file2
$ git add file2
$ git commit -m 'added file2'
Created commit f6e5064: added file2
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 file2
$ git reset --hard HEAD^
HEAD is now at 1a75c1d... added file1
$ cat file2
cat: file2: No such file or directory
$ git reflog
1a75c1d... HEAD@{0}: reset --hard HEAD^: updating HEAD
f6e5064... HEAD@{1}: commit: added file2
$ git reset --hard f6e5064
HEAD is now at f6e5064... added file2
$ cat file2
added new file
</code></pre>
<p>You can see in the example that the file2 was removed as a result of the hard reset, but was put back in place when I reset via the reflog.</p> | {
"question_id": 5473,
"question_date": "2008-08-07T23:22:51.273Z",
"question_score": 1483,
"tags": "git|version-control|git-reset",
"answer_id": 21778,
"answer_date": "2008-08-22T04:36:02.187Z",
"answer_score": 2220
} |
Please answer the following Stack Overflow question:
Title: Why don't self-closing script elements work?
<p>What is the reason browsers do not correctly recognize:</p>
<pre><code><script src="foobar.js" /> <!-- self-closing script element -->
</code></pre>
<p>Only this is recognized:</p>
<pre><code><script src="foobar.js"></script>
</code></pre>
<p>Does this break the concept of XHTML support?</p>
<p>Note: This statement is correct at least for all IE (6-8 beta 2).</p> | <p>The non-normative appendix ‘HTML Compatibility Guidelines’ of the XHTML 1 specification says:</p>
<p><a href="http://www.w3.org/TR/xhtml1/#C_3" rel="nofollow noreferrer">С.3. Element Minimization and Empty Element Content</a></p>
<blockquote>
<p>Given an empty instance of an element whose content model is not <code>EMPTY</code> (for example, an empty title or paragraph) do not use the minimized form (e.g. use <code><p> </p></code> and not <code><p /></code>).</p>
</blockquote>
<p><a href="http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict" rel="nofollow noreferrer">XHTML DTD</a> specifies script elements as:</p>
<pre><code><!-- script statements, which may include CDATA sections -->
<!ELEMENT script (#PCDATA)>
</code></pre> | {
"question_id": 69913,
"question_date": "2008-09-16T06:52:38.563Z",
"question_score": 1483,
"tags": "javascript|html|internet-explorer|xhtml",
"answer_id": 69984,
"answer_date": "2008-09-16T07:08:47.853Z",
"answer_score": 505
} |
Please answer the following Stack Overflow question:
Title: Creating a singleton in Python
<p><em>This question is not for the discussion of whether or not the <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">singleton design pattern</a> is desirable, is an anti-pattern, or for any religious wars, but to discuss how this pattern is best implemented in Python in such a way that is most pythonic. In this instance I define 'most pythonic' to mean that it follows the 'principle of least astonishment'</em>.</p>
<p>I have multiple classes which would become singletons (my use-case is for a logger, but this is not important). I do not wish to clutter several classes with added gumph when I can simply inherit or decorate.</p>
<p>Best methods:</p>
<hr />
<h2>Method 1: A decorator</h2>
<pre><code>def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@singleton
class MyClass(BaseClass):
pass
</code></pre>
<p>Pros</p>
<ul>
<li>Decorators are additive in a way that is often more intuitive than multiple inheritance.</li>
</ul>
<p>Cons</p>
<ul>
<li><p>While objects created using <code>MyClass()</code> would be true singleton objects, <code>MyClass</code> itself is a function, not a class, so you cannot call class methods from it. Also for</p>
<pre class="lang-py prettyprint-override"><code>x = MyClass();
y = MyClass();
t = type(n)();
</code></pre>
</li>
</ul>
<p>then <code>x == y</code> but <code>x != t && y != t</code></p>
<hr />
<h2>Method 2: A base class</h2>
<pre><code>class Singleton(object):
_instance = None
def __new__(class_, *args, **kwargs):
if not isinstance(class_._instance, class_):
class_._instance = object.__new__(class_, *args, **kwargs)
return class_._instance
class MyClass(Singleton, BaseClass):
pass
</code></pre>
<p>Pros</p>
<ul>
<li>It's a true class</li>
</ul>
<p>Cons</p>
<ul>
<li>Multiple inheritance - eugh! <code>__new__</code> could be overwritten during inheritance from a second base class? One has to think more than is necessary.</li>
</ul>
<hr />
<h2>Method 3: A <a href="https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">metaclass</a></h2>
<pre><code>class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
#Python2
class MyClass(BaseClass):
__metaclass__ = Singleton
#Python3
class MyClass(BaseClass, metaclass=Singleton):
pass
</code></pre>
<p>Pros</p>
<ul>
<li>It's a true class</li>
<li>Auto-magically covers inheritance</li>
<li>Uses <code>__metaclass__</code> for its proper purpose (and made me aware of it)</li>
</ul>
<p>Cons</p>
<ul>
<li>Are there any?</li>
</ul>
<hr />
<h2>Method 4: decorator returning a class with the same name</h2>
<pre><code>def singleton(class_):
class class_w(class_):
_instance = None
def __new__(class_, *args, **kwargs):
if class_w._instance is None:
class_w._instance = super(class_w,
class_).__new__(class_,
*args,
**kwargs)
class_w._instance._sealed = False
return class_w._instance
def __init__(self, *args, **kwargs):
if self._sealed:
return
super(class_w, self).__init__(*args, **kwargs)
self._sealed = True
class_w.__name__ = class_.__name__
return class_w
@singleton
class MyClass(BaseClass):
pass
</code></pre>
<p>Pros</p>
<ul>
<li>It's a true class</li>
<li>Auto-magically covers inheritance</li>
</ul>
<p>Cons</p>
<ul>
<li>Is there not an overhead for creating each new class? Here we are creating two classes for each class we wish to make a singleton. While this is fine in my case, I worry that this might not scale. Of course there is a matter of debate as to whether it aught to be too easy to scale this pattern...</li>
<li>What is the point of the <code>_sealed</code> attribute</li>
<li>Can't call methods of the same name on base classes using <code>super()</code> because they will recurse. This means you can't customize <code>__new__</code> and can't subclass a class that needs you to call up to <code>__init__</code>.</li>
</ul>
<hr />
<h2>Method 5: a module</h2>
<p>a module file <code>singleton.py</code></p>
<p>Pros</p>
<ul>
<li>Simple is better than complex</li>
</ul>
<p>Cons</p>
<ul>
<li>Not lazily instantiated</li>
</ul> | <h2>Use a Metaclass</h2>
<p>I would recommend <strong>Method #2</strong>, but you're better off using a <strong>metaclass</strong> than a base class. Here is a sample implementation:</p>
<pre><code>class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Logger(object):
__metaclass__ = Singleton
</code></pre>
<p>Or in Python3</p>
<pre><code>class Logger(metaclass=Singleton):
pass
</code></pre>
<p>If you want to run <code>__init__</code> every time the class is called, add</p>
<pre><code> else:
cls._instances[cls].__init__(*args, **kwargs)
</code></pre>
<p>to the <code>if</code> statement in <code>Singleton.__call__</code>.</p>
<p>A few words about metaclasses. A metaclass is the <strong>class of a class</strong>; that is, a class is an <strong>instance of its metaclass</strong>. You find the metaclass of an object in Python with <code>type(obj)</code>. Normal new-style classes are of type <code>type</code>. <code>Logger</code> in the code above will be of type <code>class 'your_module.Singleton'</code>, just as the (only) instance of <code>Logger</code> will be of type <code>class 'your_module.Logger'</code>. When you call logger with <code>Logger()</code>, Python first asks the metaclass of <code>Logger</code>, <code>Singleton</code>, what to do, allowing instance creation to be pre-empted. This process is the same as Python asking a class what to do by calling <code>__getattr__</code> when you reference one of it's attributes by doing <code>myclass.attribute</code>.</p>
<p>A metaclass essentially decides <strong>what the definition of a class means</strong> and how to implement that definition. See for example <a href="http://code.activestate.com/recipes/498149/" rel="noreferrer">http://code.activestate.com/recipes/498149/</a>, which essentially recreates C-style <code>struct</code>s in Python using metaclasses. The thread <a href="https://stackoverflow.com/questions/392160/what-are-your-concrete-use-cases-for-metaclasses-in-python">What are some (concrete) use-cases for metaclasses?</a> also provides some examples, they generally seem to be related to declarative programming, especially as used in ORMs.</p>
<p>In this situation, if you use your <strong>Method #2</strong>, and a subclass defines a <code>__new__</code> method, it will be <strong>executed every time</strong> you call <code>SubClassOfSingleton()</code> -- because it is responsible for calling the method that returns the stored instance. With a metaclass, it will <strong>only be called once</strong>, when the only instance is created. You want to <strong>customize what it means to call the class</strong>, which is decided by it's type.</p>
<p>In general, it <strong>makes sense</strong> to use a metaclass to implement a singleton. A singleton is special because is <strong>created only once</strong>, and a metaclass is the way you customize the <strong>creation of a class</strong>. Using a metaclass gives you <strong>more control</strong> in case you need to customize the singleton class definitions in other ways.</p>
<p>Your singletons <strong>won't need multiple inheritance</strong> (because the metaclass is not a base class), but for <strong>subclasses of the created class</strong> that use multiple inheritance, you need to make sure the singleton class is the <strong>first / leftmost</strong> one with a metaclass that redefines <code>__call__</code> This is very unlikely to be an issue. The instance dict is <strong>not in the instance's namespace</strong> so it won't accidentally overwrite it.</p>
<p>You will also hear that the singleton pattern violates the "Single Responsibility Principle" -- each class should do <strong>only one thing</strong>. That way you don't have to worry about messing up one thing the code does if you need to change another, because they are separate and encapsulated. The metaclass implementation <strong>passes this test</strong>. The metaclass is responsible for <strong>enforcing the pattern</strong> and the created class and subclasses need not be <strong>aware that they are singletons</strong>. <strong>Method #1</strong> fails this test, as you noted with "MyClass itself is a a function, not a class, so you cannot call class methods from it."</p>
<h1>Python 2 and 3 Compatible Version</h1>
<p>Writing something that works in both Python2 and 3 requires using a slightly more complicated scheme. Since metaclasses are usually subclasses of type <code>type</code>, it's possible to use one to dynamically create an intermediary base class at run time with it as its metaclass and then use <em>that</em> as the baseclass of the public <code>Singleton</code> base class. It's harder to explain than to do, as illustrated next:</p>
<pre><code># works in Python 2 & 3
class _Singleton(type):
""" A metaclass that creates a Singleton base class when called. """
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Singleton(_Singleton('SingletonMeta', (object,), {})): pass
class Logger(Singleton):
pass
</code></pre>
<p>An ironic aspect of this approach is that it's using subclassing to implement a metaclass. One possible advantage is that, unlike with a pure metaclass, <code>isinstance(inst, Singleton)</code> will return <code>True</code>.</p>
<h2>Corrections</h2>
<p>On another topic, you've probably already noticed this, but the base class implementation in your original post is wrong. <code>_instances</code> needs to be <strong>referenced on the class</strong>, you need to use <code>super()</code> or you're <strong>recursing</strong>, and <code>__new__</code> is actually a static method that you have to <strong>pass the class to</strong>, not a class method, as the actual class <strong>hasn't been created</strong> yet when it is called. All of these things will be true for a metaclass implementation as well.</p>
<pre><code>class Singleton(object):
_instances = {}
def __new__(class_, *args, **kwargs):
if class_ not in class_._instances:
class_._instances[class_] = super(Singleton, class_).__new__(class_, *args, **kwargs)
return class_._instances[class_]
class MyClass(Singleton):
pass
c = MyClass()
</code></pre>
<h2>Decorator Returning A Class</h2>
<p>I originally was writing a comment but it was too long, so I'll add this here. <strong>Method #4</strong> is better than the other decorator version, but it's more code than needed for a singleton, and it's not as clear what it does.</p>
<p>The main problems stem from the class being it's own base class. First, isn't it weird to have a class be a subclass of a nearly identical class with the same name that exists only in its <code>__class__</code> attribute? This also means that you can't define <strong>any methods that call the method of the same name on their base class</strong> with <code>super()</code> because they will recurse. This means your class can't customize <code>__new__</code>, and can't derive from any classes that need <code>__init__</code> called on them.</p>
<h2>When to use the singleton pattern</h2>
<p>Your use case is <strong>one of the better examples</strong> of wanting to use a singleton. You say in one of the comments "To me logging has always seemed a natural candidate for Singletons." You're <strong>absolutely right</strong>.</p>
<p>When people say singletons are bad, the most common reason is they are <strong>implicit shared state</strong>. While with global variables and top-level module imports are <strong>explicit</strong> shared state, other objects that are passed around are generally instantiated. This is a good point, <strong>with two exceptions</strong>.</p>
<p>The first, and one that gets mentioned in various places, is when the singletons are <strong>constant</strong>. Use of global constants, especially enums, is widely accepted, and considered sane because no matter what, <strong>none of the users can mess them up for any other user</strong>. This is equally true for a constant singleton.</p>
<p>The second exception, which get mentioned less, is the opposite -- when the singleton is <strong>only a data sink</strong>, not a data source (directly or indirectly). This is why loggers feel like a "natural" use for singletons. As the various users are <strong>not changing the loggers</strong> in ways other users will care about, there is <strong>not really shared state</strong>. This negates the primary argument against the singleton pattern, and makes them a reasonable choice because of their <strong>ease of use</strong> for the task.</p>
<p>Here is a quote from <a href="http://googletesting.blogspot.com/2008/08/root-cause-of-singletons.html" rel="noreferrer">http://googletesting.blogspot.com/2008/08/root-cause-of-singletons.html</a>:</p>
<blockquote>
<p>Now, there is one kind of Singleton which is OK. That is a singleton where all of the reachable objects are immutable. If all objects are immutable than Singleton has no global state, as everything is constant. But it is so easy to turn this kind of singleton into mutable one, it is very slippery slope. Therefore, I am against these Singletons too, not because they are bad, but because it is very easy for them to go bad. (As a side note Java enumeration are just these kind of singletons. As long as you don't put state into your enumeration you are OK, so please don't.)</p>
<p>The other kind of Singletons, which are semi-acceptable are those which don't effect the execution of your code, They have no "side effects". Logging is perfect example. It is loaded with Singletons and global state. It is acceptable (as in it will not hurt you) because your application does not behave any different whether or not a given logger is enabled. The information here flows one way: From your application into the logger. Even thought loggers are global state since no information flows from loggers into your application, loggers are acceptable. You should still inject your logger if you want your test to assert that something is getting logged, but in general Loggers are not harmful despite being full of state.</p>
</blockquote> | {
"question_id": 6760685,
"question_date": "2011-07-20T10:47:57.443Z",
"question_score": 1482,
"tags": "python|singleton|decorator|base-class|metaclass",
"answer_id": 6798042,
"answer_date": "2011-07-23T03:28:20.883Z",
"answer_score": 993
} |
Please answer the following Stack Overflow question:
Title: How do you do block comments in YAML?
<p>How do I comment a block of lines in YAML?</p> | <p>YAML supports inline comments, but does not support block comments.</p>
<p>From <a href="http://en.wikipedia.org/wiki/YAML" rel="noreferrer">Wikipedia</a>:</p>
<blockquote>
<p>Comments begin with the number sign ( <code>#</code> ), can start anywhere on a line, and continue until the end of the line</p>
</blockquote>
<p>A comparison with JSON, also from <a href="https://en.wikipedia.org/wiki/YAML#Comparison_with_JSON" rel="noreferrer">Wikipedia</a>:</p>
<blockquote>
<p>The syntax differences are subtle and seldom arise in practice: JSON allows extended charactersets like UTF-32, YAML requires a space after separators like comma, equals, and colon while JSON does not, and some non-standard implementations of JSON extend the grammar to include Javascript's <code>/* ... */</code> comments. Handling such edge cases may require light pre-processing of the JSON before parsing as in-line YAML.</p>
</blockquote>
<pre><code># If you want to write
# a block-commented Haiku
# you'll need three pound signs
</code></pre> | {
"question_id": 2276572,
"question_date": "2010-02-16T21:42:03.490Z",
"question_score": 1481,
"tags": "comments|yaml",
"answer_id": 2276604,
"answer_date": "2010-02-16T21:47:19.893Z",
"answer_score": 2444
} |
Please answer the following Stack Overflow question:
Title: Default behavior of "git push" without a branch specified
<p>I use the following command to push to my remote branch:</p>
<pre><code>git push origin sandbox
</code></pre>
<p>If I say</p>
<pre><code>git push origin
</code></pre>
<p>does that push changes in my other branches too, or does it only update my current branch? I have three branches: <code>master</code>, <code>production</code> and <code>sandbox</code>.</p>
<p>The <code>git push</code> documentation is not very clear about this, so I'd like to clarify this for good.</p>
<p>Which branches and remotes do the following <code>git push</code> commands update exactly?</p>
<pre><code>git push
git push origin
</code></pre>
<p><code>origin</code> above is a remote.</p>
<p>I understand that <code>git push [remote] [branch]</code> will push only that branch to the remote.</p> | <p>You can control the default behavior by setting push.default in your git config. From <a href="https://git-scm.com/docs/git-config#Documentation/git-config.txt-pushdefault" rel="noreferrer">the git-config(1) documentation</a>:</p>
<pre><code>push.default
</code></pre>
<p>Defines the action git push should take if no refspec is given on the command line, no refspec is configured in the remote, and no refspec is implied by any of the options given on the command line. Possible values are:</p>
<ul>
<li><p><code>nothing</code>: do not push anything</p>
</li>
<li><p><code>matching</code>: (default before Git 2.0) push all matching branches</p>
<p>All branches having the same name in both ends are considered to be matching.</p>
</li>
<li><p><code>upstream</code>: push the current branch to its upstream branch (<code>tracking</code> is a deprecated synonym for upstream)</p>
</li>
<li><p><code>current</code>: push the current branch to a branch of the same name</p>
</li>
<li><p><code>simple</code>: (new in Git 1.7.11, default since Git 2.0) like upstream, but refuses to push if the upstream branch's name is different from the local one</p>
<p>This is the safest option and is well-suited for beginners.</p>
</li>
</ul>
<blockquote>
<p>The simple, current and upstream modes are for those who want to push out a single branch after finishing work, even when the other branches are not yet ready to be pushed out</p>
</blockquote>
<p>Command line examples:</p>
<p>To view the current configuration:</p>
<pre><code>git config push.default
</code></pre>
<p>To set a new configuration:</p>
<pre><code>git config push.default current
</code></pre> | {
"question_id": 948354,
"question_date": "2009-06-04T02:45:57.310Z",
"question_score": 1481,
"tags": "git|branch|git-branch|git-push",
"answer_id": 948397,
"answer_date": "2009-06-04T03:02:57.790Z",
"answer_score": 1741
} |
Please answer the following Stack Overflow question:
Title: Read environment variables in Node.js
<p>Is there a way to read environment variables in Node.js code?</p>
<p>Like for example Python's <code>os.environ['HOME']</code>.</p> | <pre><code>process.env.ENV_VARIABLE
</code></pre>
<p>Where <code>ENV_VARIABLE</code> is the name of the variable you wish to access.</p>
<p>See <a href="https://nodejs.org/api/process.html#process_process_env" rel="noreferrer">Node.js docs for <code>process.env</code></a>.</p> | {
"question_id": 4870328,
"question_date": "2011-02-02T02:54:28.857Z",
"question_score": 1480,
"tags": "javascript|node.js|environment-variables",
"answer_id": 4870450,
"answer_date": "2011-02-02T03:14:13.450Z",
"answer_score": 2087
} |
Please answer the following Stack Overflow question:
Title: How to get GET (query string) variables in Express.js on Node.js?
<p>Can we get the variables in the query string in Node.js just like we get them in <code>$_GET</code> in PHP?</p>
<p>I know that in Node.js we can get the URL in the request. Is there a method to get the query string parameters?</p> | <p>In Express it's already done for you and you can simply use <a href="http://expressjs.com/en/api.html#req.query" rel="noreferrer">req.query</a> for that:</p>
<pre><code>var id = req.query.id; // $_GET["id"]
</code></pre>
<p>Otherwise, in NodeJS, you can access <a href="https://nodejs.org/api/http.html#http_message_url" rel="noreferrer">req.url</a> and the builtin <code>url</code> module to <a href="https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost" rel="noreferrer">url.parse</a> it manually:</p>
<pre><code>var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
</code></pre> | {
"question_id": 6912584,
"question_date": "2011-08-02T13:08:31.617Z",
"question_score": 1479,
"tags": "node.js|query-string|express",
"answer_id": 6912872,
"answer_date": "2011-08-02T13:30:16.350Z",
"answer_score": 1453
} |
Please answer the following Stack Overflow question:
Title: How to join (merge) data frames (inner, outer, left, right)
<p>Given two data frames:</p>
<pre><code>df1 = data.frame(CustomerId = c(1:6), Product = c(rep("Toaster", 3), rep("Radio", 3)))
df2 = data.frame(CustomerId = c(2, 4, 6), State = c(rep("Alabama", 2), rep("Ohio", 1)))
df1
# CustomerId Product
# 1 Toaster
# 2 Toaster
# 3 Toaster
# 4 Radio
# 5 Radio
# 6 Radio
df2
# CustomerId State
# 2 Alabama
# 4 Alabama
# 6 Ohio
</code></pre>
<p>How can I do database style, i.e., <a href="http://en.wikipedia.org/wiki/Join_%28SQL%29" rel="noreferrer">sql style, joins</a>? That is, how do I get:</p>
<ul>
<li>An <a href="http://en.wikipedia.org/wiki/Join_%28SQL%29#Inner_join" rel="noreferrer">inner join</a> of <code>df1</code> and <code>df2</code>:<br>
Return only the rows in which the left table have matching keys in the right table.</li>
<li>An <a href="http://en.wikipedia.org/wiki/Join_%28SQL%29#Outer_join" rel="noreferrer">outer join</a> of <code>df1</code> and <code>df2</code>:<br>
Returns all rows from both tables, join records from the left which have matching keys in the right table.</li>
<li>A <a href="http://en.wikipedia.org/wiki/Join_%28SQL%29#Left_outer_join" rel="noreferrer">left outer join (or simply left join)</a> of <code>df1</code> and <code>df2</code><br>
Return all rows from the left table, and any rows with matching keys from the right table.</li>
<li>A <a href="http://en.wikipedia.org/wiki/Join_%28SQL%29#Right_outer_join" rel="noreferrer">right outer join</a> of <code>df1</code> and <code>df2</code><br>
Return all rows from the right table, and any rows with matching keys from the left table.</li>
</ul>
<hr>
<p><strong>Extra credit:</strong></p>
<p>How can I do a SQL style select statement?</p> | <p>By using the <code>merge</code> function and its optional parameters:</p>
<p><strong><em>Inner join:</em></strong> <code>merge(df1, df2)</code> will work for these examples because R automatically joins the frames by common variable names, but you would most likely want to specify <code>merge(df1, df2, by = "CustomerId")</code> to make sure that you were matching on only the fields you desired. You can also use the <code>by.x</code> and <code>by.y</code> parameters if the matching variables have different names in the different data frames.</p>
<p><strong><em>Outer join:</em></strong> <code>merge(x = df1, y = df2, by = "CustomerId", all = TRUE)</code></p>
<p><strong><em>Left outer:</em></strong> <code>merge(x = df1, y = df2, by = "CustomerId", all.x = TRUE)</code></p>
<p><strong><em>Right outer:</em></strong> <code>merge(x = df1, y = df2, by = "CustomerId", all.y = TRUE)</code></p>
<p><strong><em>Cross join:</em></strong> <code>merge(x = df1, y = df2, by = NULL)</code></p>
<p><strike>Just as with the inner join, you would probably want to explicitly pass "CustomerId" to R as the matching variable.</strike> I think it's almost always best to explicitly state the identifiers on which you want to merge; it's safer if the input data.frames change unexpectedly and easier to read later on.</p>
<p>You can merge on multiple columns by giving <code>by</code> a vector, e.g., <code>by = c("CustomerId", "OrderId")</code>. </p>
<p>If the column names to merge on are not the same, you can specify, e.g., <code>by.x = "CustomerId_in_df1", by.y = "CustomerId_in_df2"</code> where <code>CustomerId_in_df1</code> is the name of the column in the first data frame and <code>CustomerId_in_df2</code> is the name of the column in the second data frame. (These can also be vectors if you need to merge on multiple columns.)</p> | {
"question_id": 1299871,
"question_date": "2009-08-19T13:18:11.250Z",
"question_score": 1477,
"tags": "r|r-faq",
"answer_id": 1300618,
"answer_date": "2009-08-19T15:15:41.570Z",
"answer_score": 1594
} |
Please answer the following Stack Overflow question:
Title: What are the differences between type() and isinstance()?
<p>What are the differences between these two code snippets?</p>
<p>Using <a href="https://docs.python.org/3/library/functions.html#type" rel="noreferrer"><code>type</code></a>:</p>
<pre><code>import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
</code></pre>
<p>Using <a href="https://docs.python.org/3/library/functions.html#isinstance" rel="noreferrer"><code>isinstance</code></a>:</p>
<pre><code>if isinstance(a, dict):
do_something()
if isinstance(b, str) or isinstance(b, unicode):
do_something_else()
</code></pre> | <p>To summarize the contents of other (already good!) answers, <code>isinstance</code> caters for inheritance (an instance of a derived class <em>is an</em> instance of a base class, too), while checking for equality of <code>type</code> does not (it demands identity of types and rejects instances of subtypes, AKA subclasses).</p>
<p>Normally, in Python, you want your code to support inheritance, of course (since inheritance is so handy, it would be bad to stop code using yours from using it!), so <code>isinstance</code> is less bad than checking identity of <code>type</code>s because it seamlessly supports inheritance.</p>
<p>It's not that <code>isinstance</code> is <em>good</em>, mind you—it's just <em>less bad</em> than checking equality of types. The normal, Pythonic, preferred solution is almost invariably "duck typing": try using the argument <em>as if</em> it was of a certain desired type, do it in a <code>try</code>/<code>except</code> statement catching all exceptions that could arise if the argument was not in fact of that type (or any other type nicely duck-mimicking it;-), and in the <code>except</code> clause, try something else (using the argument "as if" it was of some other type).</p>
<p><code>basestring</code> <strong>is</strong>, however, quite a special case—a builtin type that exists <strong>only</strong> to let you use <code>isinstance</code> (both <code>str</code> and <code>unicode</code> subclass <code>basestring</code>). Strings are sequences (you could loop over them, index them, slice them, ...), but you generally want to treat them as "scalar" types—it's somewhat incovenient (but a reasonably frequent use case) to treat all kinds of strings (and maybe other scalar types, i.e., ones you can't loop on) one way, all containers (lists, sets, dicts, ...) in another way, and <code>basestring</code> plus <code>isinstance</code> helps you do that—the overall structure of this idiom is something like:</p>
<pre><code>if isinstance(x, basestring)
return treatasscalar(x)
try:
return treatasiter(iter(x))
except TypeError:
return treatasscalar(x)
</code></pre>
<p>You could say that <code>basestring</code> is an <em>Abstract Base Class</em> ("ABC")—it offers no concrete functionality to subclasses, but rather exists as a "marker", mainly for use with <code>isinstance</code>. The concept is obviously a growing one in Python, since <a href="http://www.python.org/dev/peps/pep-3119/" rel="noreferrer">PEP 3119</a>, which introduces a generalization of it, was accepted and has been implemented starting with Python 2.6 and 3.0.</p>
<p>The PEP makes it clear that, while ABCs can often substitute for duck typing, there is generally no big pressure to do that (see <a href="http://www.python.org/dev/peps/pep-3119/#abcs-vs-duck-typing" rel="noreferrer">here</a>). ABCs as implemented in recent Python versions do however offer extra goodies: <code>isinstance</code> (and <code>issubclass</code>) can now mean more than just "[an instance of] a derived class" (in particular, any class can be "registered" with an ABC so that it will show as a subclass, and its instances as instances of the ABC); and ABCs can also offer extra convenience to actual subclasses in a very natural way via Template Method design pattern applications (see <a href="http://en.wikipedia.org/wiki/Template_method_pattern" rel="noreferrer">here</a> and <a href="http://www.catonmat.net/blog/learning-python-design-patterns-through-video-lectures/" rel="noreferrer">here</a> [[part II]] for more on the TM DP, in general and specifically in Python, independent of ABCs).</p>
<p>For the underlying mechanics of ABC support as offered in Python 2.6, see <a href="http://docs.python.org/library/abc.html" rel="noreferrer">here</a>; for their 3.1 version, very similar, see <a href="http://docs.python.org/3.1/library/abc.html" rel="noreferrer">here</a>. In both versions, standard library module <a href="http://docs.python.org/3.1/library/collections.html#module-collections" rel="noreferrer">collections</a> (that's the 3.1 version—for the very similar 2.6 version, see <a href="http://docs.python.org/library/collections.html#module-collections" rel="noreferrer">here</a>) offers several useful ABCs.</p>
<p>For the purpose of this answer, the key thing to retain about ABCs (beyond an arguably more natural placement for TM DP functionality, compared to the classic Python alternative of mixin classes such as <a href="http://docs.python.org/library/userdict.html?highlight=userdict#UserDict.DictMixin" rel="noreferrer">UserDict.DictMixin</a>) is that they make <code>isinstance</code> (and <code>issubclass</code>) much more attractive and pervasive (in Python 2.6 and going forward) than they used to be (in 2.5 and before), and therefore, by contrast, make checking type equality an even worse practice in recent Python versions than it already used to be.</p> | {
"question_id": 1549801,
"question_date": "2009-10-11T03:50:54.997Z",
"question_score": 1476,
"tags": "python|oop|inheritance|types",
"answer_id": 1549854,
"answer_date": "2009-10-11T04:31:57.393Z",
"answer_score": 1458
} |
Please answer the following Stack Overflow question:
Title: How can I select an element by name with jQuery?
<p>I have a table column I’m trying to expand and hide. jQuery seems to hide the <code><td></code> elements when I select it by <code>class</code> but not by the element’s <code>name</code>.</p>
<p>For example:</p>
<pre class="lang-js prettyprint-override"><code>$(".bold").hide(); // Selecting by class works.
$("tcol1").hide(); // Selecting by name does not work.
</code></pre>
<p>Note the HTML below. The second column has the same <code>name</code> for all rows. How could I create this collection using the <code>name</code> attribute?</p>
<pre class="lang-html prettyprint-override"><code><tr>
<td>data1</td>
<td name="tcol1" class="bold"> data2</td>
</tr>
<tr>
<td>data1</td>
<td name="tcol1" class="bold"> data2</td>
</tr>
<tr>
<td>data1</td>
<td name="tcol1" class="bold"> data2</td>
</tr>
</code></pre> | <p>You can use the <a href="https://api.jquery.com/category/selectors/attribute-selectors/" rel="noreferrer">jQuery attribute selector</a>:</p>
<pre class="lang-js prettyprint-override"><code>$('td[name="tcol1"]') // Matches exactly 'tcol1'
$('td[name^="tcol"]' ) // Matches those that begin with 'tcol'
$('td[name$="tcol"]' ) // Matches those that end with 'tcol'
$('td[name*="tcol"]' ) // Matches those that contain 'tcol'
</code></pre> | {
"question_id": 1107220,
"question_date": "2009-07-10T01:05:38.733Z",
"question_score": 1473,
"tags": "javascript|jquery|html|dom|jquery-selectors",
"answer_id": 1107264,
"answer_date": "2009-07-10T01:21:08.113Z",
"answer_score": 2620
} |
Please answer the following Stack Overflow question:
Title: Does JavaScript have a method like "range()" to generate a range within the supplied bounds?
<p>In PHP, you can do...</p>
<pre><code>range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")
</code></pre>
<p>That is, there is a function that lets you get a range of numbers or characters by passing the upper and lower bounds.</p>
<p>Is there anything built-in to JavaScript natively for this? If not, how would I implement it?</p> | <p>It works for characters and numbers, going forwards or backwards with an optional step.</p>
<pre><code>var range = function(start, end, step) {
var range = [];
var typeofStart = typeof start;
var typeofEnd = typeof end;
if (step === 0) {
throw TypeError("Step cannot be zero.");
}
if (typeofStart == "undefined" || typeofEnd == "undefined") {
throw TypeError("Must pass start and end arguments.");
} else if (typeofStart != typeofEnd) {
throw TypeError("Start and end arguments must be of same type.");
}
typeof step == "undefined" && (step = 1);
if (end < start) {
step = -step;
}
if (typeofStart == "number") {
while (step > 0 ? end >= start : end <= start) {
range.push(start);
start += step;
}
} else if (typeofStart == "string") {
if (start.length != 1 || end.length != 1) {
throw TypeError("Only strings with one character are supported.");
}
start = start.charCodeAt(0);
end = end.charCodeAt(0);
while (step > 0 ? end >= start : end <= start) {
range.push(String.fromCharCode(start));
start += step;
}
} else {
throw TypeError("Only string and number types are supported");
}
return range;
}
</code></pre>
<p><a href="http://jsfiddle.net/ZaZAZ/" rel="noreferrer">jsFiddle</a>.</p>
<p>If augmenting native types is your thing, then assign it to <code>Array.range</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var range = function(start, end, step) {
var range = [];
var typeofStart = typeof start;
var typeofEnd = typeof end;
if (step === 0) {
throw TypeError("Step cannot be zero.");
}
if (typeofStart == "undefined" || typeofEnd == "undefined") {
throw TypeError("Must pass start and end arguments.");
} else if (typeofStart != typeofEnd) {
throw TypeError("Start and end arguments must be of same type.");
}
typeof step == "undefined" && (step = 1);
if (end < start) {
step = -step;
}
if (typeofStart == "number") {
while (step > 0 ? end >= start : end <= start) {
range.push(start);
start += step;
}
} else if (typeofStart == "string") {
if (start.length != 1 || end.length != 1) {
throw TypeError("Only strings with one character are supported.");
}
start = start.charCodeAt(0);
end = end.charCodeAt(0);
while (step > 0 ? end >= start : end <= start) {
range.push(String.fromCharCode(start));
start += step;
}
} else {
throw TypeError("Only string and number types are supported");
}
return range;
}
console.log(range("A", "Z", 1));
console.log(range("Z", "A", 1));
console.log(range("A", "Z", 3));
console.log(range(0, 25, 1));
console.log(range(0, 25, 5));
console.log(range(20, 5, 5));</code></pre>
</div>
</div>
</p> | {
"question_id": 3895478,
"question_date": "2010-10-09T02:37:29.520Z",
"question_score": 1468,
"tags": "javascript|arrays|functional-programming",
"answer_id": 3895521,
"answer_date": "2010-10-09T02:54:09.763Z",
"answer_score": 82
} |
Please answer the following Stack Overflow question:
Title: How to check if a value exists in an array in Ruby
<p>I have a value <code>'Dog'</code> and an array <code>['Cat', 'Dog', 'Bird']</code>. </p>
<p>How do I check if it exists in the array without looping through it? Is there a simple way of checking if the value exists, nothing more?</p> | <p>You're looking for <a href="http://ruby-doc.org/core-2.3.1/Array.html#method-i-include-3F" rel="noreferrer"><code>include?</code></a>:</p>
<pre><code>>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true
</code></pre> | {
"question_id": 1986386,
"question_date": "2009-12-31T17:49:03.317Z",
"question_score": 1468,
"tags": "ruby|arrays",
"answer_id": 1986398,
"answer_date": "2009-12-31T17:51:19.863Z",
"answer_score": 2162
} |
Please answer the following Stack Overflow question:
Title: echo that outputs to stderr
<p>Is there a standard Bash tool that acts like echo but outputs to stderr rather than stdout?</p>
<p>I know I can do <code>echo foo 1>&2</code> but it's kinda ugly and, I suspect, error prone (e.g. more likely to get edited wrong when things change). </p> | <p>You could do this, which facilitates reading:</p>
<pre><code>>&2 echo "error"
</code></pre>
<p><code>>&2</code> copies file descriptor #2 to file descriptor #1. Therefore, after this redirection is performed, both file descriptors will refer to the same file: the one file descriptor #2 was <strong>originally</strong> referring to. For more information see the <a href="http://wiki.bash-hackers.org/howto/redirection_tutorial" rel="noreferrer">Bash Hackers Illustrated Redirection Tutorial</a>.</p> | {
"question_id": 2990414,
"question_date": "2010-06-07T14:36:16.647Z",
"question_score": 1468,
"tags": "bash",
"answer_id": 23550347,
"answer_date": "2014-05-08T18:59:47.240Z",
"answer_score": 1906
} |
Please answer the following Stack Overflow question:
Title: What is the best way to add options to a select from a JavaScript object with jQuery?
<p>What is the best method for adding options to a <code><select></code> from a JavaScript object using jQuery?</p>
<p>I'm looking for something that I don't need a plugin to do, but I would also be interested in the plugins that are out there.</p>
<p>This is what I did:</p>
<pre><code>selectValues = { "1": "test 1", "2": "test 2" };
for (key in selectValues) {
if (typeof (selectValues[key] == 'string') {
$('#mySelect').append('<option value="' + key + '">' + selectValues[key] + '</option>');
}
}
</code></pre>
<p><strong>A clean/simple solution:</strong></p>
<p>This is a cleaned up and simplified <a href="https://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from-an-array-with-jquery/171007#171007">version of matdumsa's</a>:</p>
<pre><code>$.each(selectValues, function(key, value) {
$('#mySelect')
.append($('<option>', { value : key })
.text(value));
});
</code></pre>
<p>Changes from matdumsa's: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().</p> | <p>The same as other answers, in a jQuery fashion:</p>
<pre><code>$.each(selectValues, function(key, value) {
$('#mySelect')
.append($("<option></option>")
.attr("value", key)
.text(value));
});
</code></pre> | {
"question_id": 170986,
"question_date": "2008-10-04T20:58:46.400Z",
"question_score": 1464,
"tags": "javascript|jquery|html-select",
"answer_id": 171007,
"answer_date": "2008-10-04T21:12:02.037Z",
"answer_score": 1462
} |
Please answer the following Stack Overflow question:
Title: How can I check for NaN values?
<p><code>float('nan')</code> represents NaN (not a number). But how do I check for it?</p> | <p>Use <a href="http://docs.python.org/library/math.html#math.isnan" rel="noreferrer"><code>math.isnan</code></a>:</p>
<pre><code>>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True
</code></pre> | {
"question_id": 944700,
"question_date": "2009-06-03T13:19:54.927Z",
"question_score": 1463,
"tags": "python|math",
"answer_id": 944733,
"answer_date": "2009-06-03T13:24:37.010Z",
"answer_score": 1864
} |
Please answer the following Stack Overflow question:
Title: Using Git with Visual Studio
<p>As a long-time <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_SourceSafe" rel="noreferrer">Visual SourceSafe</a> user (and hater) I was discussing switching to <a href="http://en.wikipedia.org/wiki/Apache_Subversion" rel="noreferrer">SVN</a> with a colleague; he suggested using <a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="noreferrer">Git</a> instead. Since, apparently, it can be used as peer-to-peer without a central server (we are a 3-developer team). </p>
<p>I have not been able to find anything about tools that integrate Git with Visual Studio, though - does such a thing exist? </p>
<p>What are the technologies available for using Git with Visual Studio? And what do I need to know about how they differ before I begin?</p> | <p>In Jan 2013, Microsoft <a href="https://devblogs.microsoft.com/bharry/git-init-vs/" rel="nofollow noreferrer">announced</a> that they are adding full Git support into all their ALM products. They have <a href="http://visualstudiogallery.msdn.microsoft.com/abafc7d6-dcaa-40f4-8a5e-d6724bdb980c" rel="nofollow noreferrer">published a plugin</a> for Visual Studio 2012 that adds Git source control integration.</p>
<p>Alternatively, there is a project called <a href="http://gitextensions.github.io/" rel="nofollow noreferrer">Git Extensions</a> that includes add-ins for Visual Studio 2005, 2008, 2010 and 2012, as well as Windows Explorer integration. It's regularly updated and having used it on a couple of projects, I've found it very useful.</p>
<p>Another option is <a href="http://gitscc.codeplex.com/" rel="nofollow noreferrer">Git Source Control Provider</a>.</p> | {
"question_id": 507343,
"question_date": "2009-02-03T14:46:19.010Z",
"question_score": 1463,
"tags": "visual-studio|git",
"answer_id": 507453,
"answer_date": "2009-02-03T15:07:20.700Z",
"answer_score": 1072
} |
Please answer the following Stack Overflow question:
Title: How can I "add existing frameworks" in Xcode 4?
<p>I can't find the good old "Add existing frameworks" option. How do I do this?</p>
<p>We're talking about Xcode 4 DP2 (in the context of iPhone development, as far as it matters...).</p> | <p><a href="https://developer.apple.com/library/ios/#recipes/xcode_help-project_editor/Articles/AddingaLibrarytoaTarget.html%23//apple_ref/doc/uid/TP40010155-CH17-SW1" rel="noreferrer">As per Apple's documentation:</a></p>
<ol>
<li>In the project navigator, select
your project. </li>
<li>Select your target.</li>
<li>Select the "<em>Build Phases</em>" tab.</li>
<li>Open "<em>Link Binaries With Libraries</em>"
expander.</li>
<li>Click the <kbd>+</kbd> button.</li>
<li>Select your framework.</li>
<li><em>(optional)</em> Drag and drop the added
framework to the "<em>Frameworks</em>" group.</li>
</ol> | {
"question_id": 3352664,
"question_date": "2010-07-28T12:12:20.567Z",
"question_score": 1462,
"tags": "xcode|frameworks|xcode4",
"answer_id": 3377682,
"answer_date": "2010-07-31T10:20:46.760Z",
"answer_score": 1743
} |
Please answer the following Stack Overflow question:
Title: How does the 'Access-Control-Allow-Origin' header work?
<p>Apparently, I have completely misunderstood its semantics. I thought of something like this:</p>
<ol>
<li>A client downloads JavaScript code MyCode.js from <code>http://siteA</code> - <strong>the origin</strong>.</li>
<li>The response header of MyCode.js contains <strong>Access-Control-Allow-Origin: <code>http://siteB</code></strong>, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.</li>
<li>The client triggers some functionality of MyCode.js, which in turn make requests to <code>http://siteB</code>, which should be fine, despite being cross-origin requests.</li>
</ol>
<p>Well, I am wrong. It does not work like this at all. So, I have read <em><a href="http://en.wikipedia.org/wiki/Cross-origin_resource_sharing" rel="nofollow noreferrer">Cross-origin resource sharing</a></em> and attempted to read <em><a href="http://www.w3.org/TR/cors/" rel="nofollow noreferrer">Cross-Origin Resource Sharing in w3c recommendation</a></em>.</p>
<p>One thing is sure - I still do not understand how I am supposed to use this header.</p>
<p>I have full control of both site A and site B. How do I enable the JavaScript code downloaded from the site A to access resources on the site B using this header?</p>
<p>P.S.: I do not want to utilize <a href="https://en.wikipedia.org/wiki/JSONP" rel="nofollow noreferrer">JSONP</a>.</p> | <p><em>Access-Control-Allow-Origin</em> is a <a href="http://www.html5rocks.com/en/tutorials/cors/" rel="noreferrer">CORS (cross-origin resource sharing) header</a>.</p>
<p>When Site A tries to fetch content from Site B, Site B can send an <em>Access-Control-Allow-Origin</em> response header to tell the browser that the content of this page is accessible to certain origins. (An <em>origin</em> is a <a href="https://stackoverflow.com/a/19542686/710446">domain, plus a scheme and port number</a>.) By default, Site B's pages are <a href="https://en.wikipedia.org/wiki/Same-origin_policy" rel="noreferrer">not accessible to any other origin</a>; using the <em>Access-Control-Allow-Origin</em> header opens a door for cross-origin access by specific requesting origins.</p>
<p>For each resource/page that Site B wants to make accessible to Site A, Site B should serve its pages with the response header:</p>
<pre class="lang-none prettyprint-override"><code>Access-Control-Allow-Origin: http://siteA.com
</code></pre>
<p>Modern browsers will not block cross-domain requests outright. If Site A requests a page from Site B, the browser will actually fetch the requested page <em>on the network level</em> and check if the response headers list Site A as a permitted requester domain. If Site B has not indicated that Site A is allowed to access this page, the browser will trigger the <code>XMLHttpRequest</code>'s <code>error</code> event and deny the response data to the requesting JavaScript code.</p>
<h3>Non-simple requests</h3>
<p>What happens on the network level can be <em>slightly</em> more complex than explained above. If the request is a <a href="http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request" rel="noreferrer">"non-simple" request</a>, the browser first sends a data-less "preflight" OPTIONS request, to verify that the server will accept the request. A request is non-simple when either (or both):</p>
<ul>
<li>using an HTTP verb other than GET or POST (e.g. PUT, DELETE)</li>
<li>using non-simple request headers; the only simple requests headers are:</li>
<li><code>Accept</code></li>
<li><code>Accept-Language</code></li>
<li><code>Content-Language</code></li>
<li><code>Content-Type</code> (this is only simple when its value is <code>application/x-www-form-urlencoded</code>, <code>multipart/form-data</code>, or <code>text/plain</code>)</li>
</ul>
<p>If the server responds to the OPTIONS preflight with appropriate response headers (<code>Access-Control-Allow-Headers</code> for non-simple headers, <code>Access-Control-Allow-Methods</code> for non-simple verbs) that match the non-simple verb and/or non-simple headers, then the browser sends the actual request.</p>
<p>Supposing that Site A wants to send a PUT request for <code>/somePage</code>, with a non-simple <code>Content-Type</code> value of <code>application/json</code>, the browser would first send a preflight request:</p>
<pre class="lang-none prettyprint-override"><code>OPTIONS /somePage HTTP/1.1
Origin: http://siteA.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Content-Type
</code></pre>
<p>Note that <code>Access-Control-Request-Method</code> and <code>Access-Control-Request-Headers</code> are added by the browser automatically; you do not need to add them. This OPTIONS preflight gets the successful response headers:</p>
<pre class="lang-none prettyprint-override"><code>Access-Control-Allow-Origin: http://siteA.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type
</code></pre>
<p>When sending the actual request (after preflight is done), the behavior is identical to how a simple request is handled. In other words, a non-simple request whose preflight is successful is treated the same as a simple request (i.e., the server must still send <code>Access-Control-Allow-Origin</code> again for the actual response).</p>
<p>The browsers sends the actual request:</p>
<pre class="lang-none prettyprint-override"><code>PUT /somePage HTTP/1.1
Origin: http://siteA.com
Content-Type: application/json
{ "myRequestContent": "JSON is so great" }
</code></pre>
<p>And the server sends back an <code>Access-Control-Allow-Origin</code>, just as it would for a simple request:</p>
<pre class="lang-none prettyprint-override"><code>Access-Control-Allow-Origin: http://siteA.com
</code></pre>
<p>See <em><a href="https://stackoverflow.com/a/13400954/710446">Understanding XMLHttpRequest over CORS</a></em> for a little more information about non-simple requests.</p> | {
"question_id": 10636611,
"question_date": "2012-05-17T13:23:54.107Z",
"question_score": 1458,
"tags": "javascript|cross-domain|cors",
"answer_id": 10636765,
"answer_date": "2012-05-17T13:33:26.440Z",
"answer_score": 1770
} |
Please answer the following Stack Overflow question:
Title: Merge/flatten an array of arrays
<p>I have a JavaScript array like:</p>
<pre><code>[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
</code></pre>
<p>How would I go about merging the separate inner arrays into one like:</p>
<pre><code>["$6", "$12", "$25", ...]
</code></pre> | <p>You can use <code>concat</code> to merge arrays:</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 arrays = [
["$6"],
["$12"],
["$25"],
["$25"],
["$18"],
["$22"],
["$10"]
];
var merged = [].concat.apply([], arrays);
console.log(merged);</code></pre>
</div>
</div>
</p>
<p>Using the <code>apply</code> method of <code>concat</code> will just take the second parameter as an array, so the last line is identical to this:</p>
<pre><code>var merged2 = [].concat(["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]);
</code></pre>
<hr>
<p>There is also the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat" rel="noreferrer"><code>Array.prototype.flat()</code></a> method (introduced in ES2019) which you could use to flatten the arrays, although <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat#Browser_compatibility" rel="noreferrer">it is only available in Node.js starting with version 11, and not at all in Internet Explorer</a>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arrays = [
["$6"],
["$12"],
["$25"],
["$25"],
["$18"],
["$22"],
["$10"]
];
const merge3 = arrays.flat(1); //The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.
console.log(merge3);
</code></pre>
</div>
</div>
</p> | {
"question_id": 10865025,
"question_date": "2012-06-02T18:53:46.603Z",
"question_score": 1458,
"tags": "javascript|arrays|multidimensional-array|flatten",
"answer_id": 10865042,
"answer_date": "2012-06-02T18:56:33.400Z",
"answer_score": 2396
} |
Please answer the following Stack Overflow question:
Title: What is the difference between match_parent and fill_parent?
<p>I'm a little confused about two XML properties: <code>match_parent</code> and <code>fill_parent</code>. It seems that both are the same. Is there any difference between them?</p> | <p>They're the same thing (in API Level 8+). Use <code>match_parent</code>.</p>
<blockquote>
<p>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which means that the view wants to be as big as its parent (minus padding)</p>
<p>...</p>
<p><code>fill_parent</code>: The view should be as big as its parent (minus padding). This constant is deprecated starting from API Level 8 and is replaced by <code>match_parent</code>.</p>
</blockquote>
<p><a href="http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html" rel="noreferrer">http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html</a></p> | {
"question_id": 5761960,
"question_date": "2011-04-23T03:31:10.040Z",
"question_score": 1458,
"tags": "android|android-layout",
"answer_id": 5761970,
"answer_date": "2011-04-23T03:33:49.243Z",
"answer_score": 1266
} |
Please answer the following Stack Overflow question:
Title: How do I check if directory exists in Python?
<p>How do I check if a directory exists?</p> | <p>Use <a href="http://docs.python.org/dev/library/os.path.html#os.path.isdir" rel="noreferrer"><strong><code>os.path.isdir</code></strong></a> for directories only:</p>
<pre><code>>>> import os
>>> os.path.isdir('new_folder')
True
</code></pre>
<p>Use <a href="http://docs.python.org/dev/library/os.path.html#os.path.exists" rel="noreferrer"><strong><code>os.path.exists</code></strong></a> for both files and directories:</p>
<pre><code>>>> import os
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False
</code></pre>
<p>Alternatively, you can use <a href="https://docs.python.org/dev/library/pathlib.html" rel="noreferrer"><strong><code>pathlib</code></strong></a>:</p>
<pre><code> >>> from pathlib import Path
>>> Path('new_folder').is_dir()
True
>>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
False
</code></pre> | {
"question_id": 8933237,
"question_date": "2012-01-19T21:03:20.267Z",
"question_score": 1457,
"tags": "python|directory",
"answer_id": 8933290,
"answer_date": "2012-01-19T21:07:25.167Z",
"answer_score": 2141
} |
Please answer the following Stack Overflow question:
Title: Safely turning a JSON string into an object
<p>Given a string of JSON data, how can I safely turn that string into a JavaScript object?</p>
<p>Obviously I can do this unsafely with something like:</p>
<pre><code>var obj = eval("(" + json + ')');
</code></pre>
<p>but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval.</p> | <p><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse" rel="noreferrer"><code>JSON.parse(jsonString)</code></a> is a pure JavaScript approach so long as you can guarantee a reasonably modern browser.</p> | {
"question_id": 45015,
"question_date": "2008-09-05T00:12:01.570Z",
"question_score": 1456,
"tags": "javascript|json|parsing",
"answer_id": 5686237,
"answer_date": "2011-04-16T11:45:21.977Z",
"answer_score": 2086
} |
Please answer the following Stack Overflow question:
Title: How do you get a list of the names of all files present in a directory in Node.js?
<p>I'm trying to get a list of the names of all the files present in a directory using Node.js. I want output that is an array of filenames. How can I do this?</p> | <p>You can use the <a href="https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback" rel="noreferrer"><code>fs.readdir</code></a> or <a href="https://nodejs.org/api/fs.html#fs_fs_readdirsync_path_options" rel="noreferrer"><code>fs.readdirSync</code></a> methods. <code>fs</code> is included in Node.js core, so there's no need to install anything.</p>
<p><strong>fs.readdir</strong></p>
<pre><code>const testFolder = './tests/';
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
files.forEach(file => {
console.log(file);
});
});
</code></pre>
<p><strong>fs.readdirSync</strong></p>
<pre><code>const testFolder = './tests/';
const fs = require('fs');
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
});
</code></pre>
<p>The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.</p>
<p>The second is synchronous, it will return the file name array, but it will stop any further execution of your code until the read process ends.</p> | {
"question_id": 2727167,
"question_date": "2010-04-28T06:10:16.873Z",
"question_score": 1456,
"tags": "javascript|node.js|directory-listing",
"answer_id": 2727191,
"answer_date": "2010-04-28T06:15:23.210Z",
"answer_score": 1960
} |
Please answer the following Stack Overflow question:
Title: Sort (order) data frame rows by multiple columns
<p>I want to sort a data frame by multiple columns. For example, with the data frame below I would like to sort by column 'z' (descending) then by column 'b' (ascending):</p>
<pre><code>dd <- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"),
levels = c("Low", "Med", "Hi"), ordered = TRUE),
x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
z = c(1, 1, 1, 2))
dd
b x y z
1 Hi A 8 1
2 Med D 3 1
3 Hi A 9 1
4 Low C 9 2
</code></pre> | <p>You can use the <a href="http://stat.ethz.ch/R-manual/R-devel/library/base/html/order.html" rel="noreferrer"><code>order()</code></a> function directly without resorting to add-on tools -- see this simpler answer which uses a trick right from the top of the <code>example(order)</code> code:</p>
<pre><code>R> dd[with(dd, order(-z, b)), ]
b x y z
4 Low C 9 2
2 Med D 3 1
1 Hi A 8 1
3 Hi A 9 1
</code></pre>
<p><em>Edit some 2+ years later:</em> It was just asked how to do this by column index. The answer is to simply pass the desired sorting column(s) to the <code>order()</code> function:</p>
<pre><code>R> dd[order(-dd[,4], dd[,1]), ]
b x y z
4 Low C 9 2
2 Med D 3 1
1 Hi A 8 1
3 Hi A 9 1
R>
</code></pre>
<p>rather than using the name of the column (and <code>with()</code> for easier/more direct access).</p> | {
"question_id": 1296646,
"question_date": "2009-08-18T21:33:18.473Z",
"question_score": 1454,
"tags": "r|sorting|dataframe|r-faq",
"answer_id": 1296745,
"answer_date": "2009-08-18T21:51:22.273Z",
"answer_score": 1760
} |
Please answer the following Stack Overflow question:
Title: UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
<p>I'm having problems dealing with unicode characters from text fetched from different web pages (on different sites). I am using BeautifulSoup. </p>
<p>The problem is that the error is not always reproducible; it sometimes works with some pages, and sometimes, it barfs by throwing a <code>UnicodeEncodeError</code>. I have tried just about everything I can think of, and yet I have not found anything that works consistently without throwing some kind of Unicode-related error.</p>
<p>One of the sections of code that is causing problems is shown below:</p>
<pre><code>agent_telno = agent.find('div', 'agent_contact_number')
agent_telno = '' if agent_telno is None else agent_telno.contents[0]
p.agent_info = str(agent_contact + ' ' + agent_telno).strip()
</code></pre>
<p>Here is a stack trace produced on SOME strings when the snippet above is run:</p>
<pre><code>Traceback (most recent call last):
File "foobar.py", line 792, in <module>
p.agent_info = str(agent_contact + ' ' + agent_telno).strip()
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
</code></pre>
<p>I suspect that this is because some pages (or more specifically, pages from some of the sites) may be encoded, whilst others may be unencoded. All the sites are based in the UK and provide data meant for UK consumption - so there are no issues relating to internalization or dealing with text written in anything other than English.</p>
<p>Does anyone have any ideas as to how to solve this so that I can CONSISTENTLY fix this problem?</p> | <p>Read the Python <a href="https://docs.python.org/2.7/howto/unicode.html" rel="nofollow noreferrer">Unicode HOWTO</a>. This error is the <a href="https://docs.python.org/2.7/howto/unicode.html#the-unicode-type" rel="nofollow noreferrer">very first example</a>.</p>
<p>Do not use <code>str()</code> to convert from unicode to encoded text / bytes.</p>
<p>Instead, use <a href="http://docs.python.org/library/stdtypes.html#str.encode" rel="nofollow noreferrer"><code>.encode()</code></a> to encode the string:</p>
<pre><code>p.agent_info = u' '.join((agent_contact, agent_telno)).encode('utf-8').strip()
</code></pre>
<p>or work entirely in unicode.</p> | {
"question_id": 9942594,
"question_date": "2012-03-30T12:06:41.353Z",
"question_score": 1453,
"tags": "python|unicode|beautifulsoup|python-2.x|python-unicode",
"answer_id": 9942822,
"answer_date": "2012-03-30T12:21:31.160Z",
"answer_score": 1492
} |
Please answer the following Stack Overflow question:
Title: Activity restart on rotation Android
<p>In my Android application, when I rotate the device (slide out the keyboard) then my <code>Activity</code> is restarted (<code>onCreate</code> is called). Now, this is probably how it's supposed to be, but I do a lot of initial setting up in the <code>onCreate</code> method, so I need either:</p>
<ol>
<li>Put all the initial setting up in another function so it's not all lost on device rotation or</li>
<li>Make it so <code>onCreate</code> is not called again and the layout just adjusts or</li>
<li>Limit the app to just portrait so that <code>onCreate</code> is not called.</li>
</ol> | <p><strong>Using the Application Class</strong></p>
<p>Depending on what you're doing in your initialization you could consider creating a new class that extends <code>Application</code> and moving your initialization code into an overridden <code>onCreate</code> method within that class.</p>
<pre><code>public class MyApplicationClass extends Application {
@Override
public void onCreate() {
super.onCreate();
// TODO Put your application initialization code here.
}
}
</code></pre>
<p>The <code>onCreate</code> in the application class is only called when the entire application is created, so the Activity restarts on orientation or keyboard visibility changes won't trigger it.</p>
<p>It's good practice to expose the instance of this class as a singleton and exposing the application variables you're initializing using getters and setters.</p>
<p><em>NOTE: You'll need to specify the name of your new Application class in the manifest for it to be registered and used:</em></p>
<pre><code><application
android:name="com.you.yourapp.MyApplicationClass"
</code></pre>
<p><strong>Reacting to Configuration Changes</strong> <em>[UPDATE: this is deprecated since API 13; <a href="http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html" rel="noreferrer">see the recommended alternative</a>]</em></p>
<p>As a further alternative, you can have your application listen for events that would cause a restart – like orientation and keyboard visibility changes – and handle them within your Activity.</p>
<p>Start by adding the <code>android:configChanges</code> node to your Activity's manifest node</p>
<pre><code> <activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
</code></pre>
<p>or for <a href="https://stackoverflow.com/a/9550231/2291">Android 3.2 (API level 13) and newer</a>:</p>
<pre><code><activity android:name=".MyActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name">
</code></pre>
<p>Then within the Activity override the <code>onConfigurationChanged</code> method and call <code>setContentView</code> to force the GUI layout to be re-done in the new orientation.</p>
<pre><code>@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.myLayout);
}
</code></pre> | {
"question_id": 456211,
"question_date": "2009-01-19T00:28:29.657Z",
"question_score": 1449,
"tags": "android|rotation|android-activity",
"answer_id": 456918,
"answer_date": "2009-01-19T08:47:59.960Z",
"answer_score": 994
} |
Please answer the following Stack Overflow question:
Title: Check synchronously if file/directory exists in Node.js
<p>How can I synchronously check, using <strong>node.js</strong>, if a file or directory exists?</p> | <p>The answer to this question has changed over the years. The <em>current</em> answer is here at the top, followed by the various answers over the years in chronological order:</p>
<h2>Current Answer</h2>
<p>You can use <a href="http://nodejs.org/api/fs.html#fs_fs_existssync_path" rel="noreferrer"><code>fs.existsSync()</code></a>:</p>
<pre><code>const fs = require("fs"); // Or `import fs from "fs";` with ESM
if (fs.existsSync(path)) {
// Do something
}
</code></pre>
<p>It was deprecated for several years, but no longer is. From the docs:</p>
<blockquote>
<p>Note that <code>fs.exists()</code> is deprecated, but <code>fs.existsSync()</code> is not. (The
callback parameter to <code>fs.exists()</code> accepts parameters that are
inconsistent with other Node.js callbacks. <code>fs.existsSync()</code> does not
use a callback.)</p>
</blockquote>
<p>You've specifically asked for a <em>synchronous</em> check, but if you can use an <em>asynchronous</em> check instead (usually best with I/O), use <a href="https://nodejs.org/api/fs.html#fs_fspromises_access_path_mode" rel="noreferrer"><code>fs.promises.access</code></a> if you're using <code>async</code> functions or <a href="https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback" rel="noreferrer"><code>fs.access</code></a> (since <a href="http://nodejs.org/api/fs.html#fs_fs_exists_path_callback" rel="noreferrer"><code>exists</code> is deprecated</a>) if not:</p>
<p>In an <code>async</code> function:</p>
<pre><code>try {
await fs.promises.access("somefile");
// The check succeeded
} catch (error) {
// The check failed
}
</code></pre>
<p>Or with a callback:</p>
<pre><code>fs.access("somefile", error => {
if (!error) {
// The check succeeded
} else {
// The check failed
}
});
</code></pre>
<hr>
<h2>Historical Answers</h2>
<p>Here are the historical answers in chronological order:</p>
<ul>
<li><strong>Original answer from 2010</strong>
<br>(<code>stat</code>/<code>statSync</code> or <code>lstat</code>/<code>lstatSync</code>)</li>
<li><strong>Update September 2012</strong>
<br>(<code>exists</code>/<code>existsSync</code>)</li>
<li><strong>Update February 2015</strong>
<br>(Noting impending deprecation of <code>exists</code>/<code>existsSync</code>, so we're probably back to <code>stat</code>/<code>statSync</code> or <code>lstat</code>/<code>lstatSync</code>)</li>
<li><strong>Update December 2015</strong>
<br>(There's also <code>fs.access(path, fs.F_OK, function(){})</code> / <code>fs.accessSync(path, fs.F_OK)</code>, but note that if the file/directory doesn't exist, it's an error; docs for <code>fs.stat</code> recommend using <code>fs.access</code> if you need to check for existence without opening)</li>
<li><strong>Update December 2016</strong>
<br><code>fs.exists()</code> is still deprecated but <code>fs.existsSync()</code> is no longer deprecated. So you can safely use it now.</li>
</ul>
<h3>Original answer from 2010:</h3>
<p>You can use <code>statSync</code> or <code>lstatSync</code> (<a href="http://nodejs.org/api/fs.html#fs_fs_lstatsync_path" rel="noreferrer">docs link</a>), which give you an <a href="http://nodejs.org/api/fs.html#fs_class_fs_stats" rel="noreferrer"><code>fs.Stats</code> object</a>. In general, if a synchronous version of a function is available, it will have the same name as the async version with <code>Sync</code> at the end. So <code>statSync</code> is the synchronous version of <code>stat</code>; <code>lstatSync</code> is the synchronous version of <code>lstat</code>, etc.</p>
<p><code>lstatSync</code> tells you both whether something exists, and if so, whether it's a file or a directory (or in some file systems, a symbolic link, block device, character device, etc.), e.g. if you need to know if it exists and is a directory:</p>
<pre><code>var fs = require('fs');
try {
// Query the entry
stats = fs.lstatSync('/the/path');
// Is it a directory?
if (stats.isDirectory()) {
// Yes it is
}
}
catch (e) {
// ...
}
</code></pre>
<p>...and similarly, if it's a file, there's <code>isFile</code>; if it's a block device, there's <code>isBlockDevice</code>, etc., etc. Note the <code>try/catch</code>; it throws an error if the entry doesn't exist at all.</p>
<p><s>If you don't care what the entry <em>is</em> and only want to know whether it exists, you can use <a href="http://nodejs.org/api/path.html#path_path_existssync_p" rel="noreferrer"><code>path.existsSync</code></a> (or with latest, <code>fs.existsSync</code>) as <a href="https://stackoverflow.com/a/5008295/157247">noted by user618408</a>:</p>
<pre><code>var path = require('path');
if (path.existsSync("/the/path")) { // or fs.existsSync
// ...
}
</code></pre>
<p>It doesn't require a <code>try/catch</code> but gives you no information about what the thing is, just that it's there.</s> <code>path.existsSync</code> was deprecated long ago.</p>
<hr>
<p>Side note: You've expressly asked how to check <em>synchronously</em>, so I've used the <code>xyzSync</code> versions of the functions above. But wherever possible, with I/O, it really is best to avoid synchronous calls. Calls into the I/O subsystem take significant time from a CPU's point of view. Note how easy it is to call <a href="http://nodejs.org/api/fs.html#fs_fs_lstat_path_callback" rel="noreferrer"><code>lstat</code></a> rather than <code>lstatSync</code>:</p>
<pre><code>// Is it a directory?
lstat('/the/path', function(err, stats) {
if (!err && stats.isDirectory()) {
// Yes it is
}
});
</code></pre>
<p>But if you need the synchronous version, it's there.</p>
<h3>Update September 2012</h3>
<p>The below answer from a couple of years ago is now a bit out of date. The current way is to use <a href="http://nodejs.org/api/fs.html#fs_fs_existssync_path" rel="noreferrer"><code>fs.existsSync</code></a> to do a synchronous check for file/directory existence (or of course <a href="http://nodejs.org/api/fs.html#fs_fs_exists_path_callback" rel="noreferrer"><code>fs.exists</code></a> for an asynchronous check), rather than the <code>path</code> versions below.</p>
<p>Example:</p>
<pre><code>var fs = require('fs');
if (fs.existsSync(path)) {
// Do something
}
// Or
fs.exists(path, function(exists) {
if (exists) {
// Do something
}
});
</code></pre>
<h3>Update February 2015</h3>
<p>And here we are in 2015 and the Node docs now say that <code>fs.existsSync</code> (and <code>fs.exists</code>) "will be deprecated". (Because the Node folks think it's dumb to check whether something exists before opening it, which it is; but that's not the only reason for checking whether something exists!)</p>
<p>So we're probably back to the various <code>stat</code> methods... Until/unless this changes yet again, of course.</p>
<h3>Update December 2015</h3>
<p>Don't know how long it's been there, but there's also <a href="https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback" rel="noreferrer"><code>fs.access(path, fs.F_OK, ...)</code> / <code>fs.accessSync(path, fs.F_OK)</code></a>. And at least as of October 2016, the <a href="https://nodejs.org/api/fs.html#fs_fs_stat_path_callback" rel="noreferrer"><code>fs.stat</code> documentation</a> recommends using <code>fs.access</code> to do existence checks (<em>"To check if a file exists without manipulating it afterwards, <code>fs.access()</code> is recommended."</em>). But note that the access not being available is considered an <em>error</em>, so this would probably be best if you're expecting the file to be accessible:</p>
<pre><code>var fs = require('fs');
try {
fs.accessSync(path, fs.F_OK);
// Do something
} catch (e) {
// It isn't accessible
}
// Or
fs.access(path, fs.F_OK, function(err) {
if (!err) {
// Do something
} else {
// It isn't accessible
}
});
</code></pre>
<h3>Update December 2016</h3>
<p>You can use <a href="http://nodejs.org/api/fs.html#fs_fs_existssync_path" rel="noreferrer"><code>fs.existsSync()</code></a>:</p>
<pre><code>if (fs.existsSync(path)) {
// Do something
}
</code></pre>
<p>It was deprecated for several years, but no longer is. From the docs:</p>
<blockquote>
<p>Note that <code>fs.exists()</code> is deprecated, but <code>fs.existsSync()</code> is not. (The
callback parameter to <code>fs.exists()</code> accepts parameters that are
inconsistent with other Node.js callbacks. <code>fs.existsSync()</code> does not
use a callback.)</p>
</blockquote> | {
"question_id": 4482686,
"question_date": "2010-12-19T11:19:43.613Z",
"question_score": 1447,
"tags": "node.js|fs",
"answer_id": 4482701,
"answer_date": "2010-12-19T11:26:29.353Z",
"answer_score": 2590
} |
Please answer the following Stack Overflow question:
Title: How to fix npm throwing error without sudo
<p>I just installed node and npm through the package on nodejs.org, and whenever I try to search or install something with npm, it throws the following error unless I sudo the command. I have a feeling this is a permissions issue? I am already the admin.</p>
<pre class="lang-none prettyprint-override"><code>npm ERR! Error: EACCES, open '/Users/chietala/.npm/-/all/.cache.json'
npm ERR! { [Error: EACCES, open '/Users/chietala/.npm/-/all/.cache.json']
npm ERR! errno: 3,
npm ERR! code: 'EACCES',
npm ERR! path: '/Users/chietala/.npm/-/all/.cache.json' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.
npm ERR! System Darwin 12.2.0
npm ERR! command "node" "/usr/local/bin/npm" "search" "bower"
npm ERR! cwd /Users/chietala
npm ERR! node -v v0.10.4
npm ERR! npm -v 1.2.18
npm ERR! path /Users/chietala/.npm/-/all/.cache.json
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, open '/Users/chietala/.npm/-/all/.cache.json'
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /Users/chietala/npm-debug.log
npm ERR! not ok code 0
</code></pre> | <p>This looks like a permissions issue in your home directory. To reclaim ownership of the <strong>.npm</strong> directory execute:</p>
<pre class="lang-bash prettyprint-override"><code>sudo chown -R $(whoami) ~/.npm
</code></pre> | {
"question_id": 16151018,
"question_date": "2013-04-22T15:35:37.163Z",
"question_score": 1442,
"tags": "node.js|unix|permissions|npm|sudo",
"answer_id": 16151707,
"answer_date": "2013-04-22T16:11:27.590Z",
"answer_score": 2419
} |
Please answer the following Stack Overflow question:
Title: How do function pointers in C work?
<p>I had some experience lately with function pointers in C.</p>
<p>So going on with the tradition of answering your own questions, I decided to make a small summary of the very basics, for those who need a quick dive-in to the subject.</p> | <h1>Function pointers in C</h1>
<p>Let's start with a basic function which we will be <em>pointing to</em>:</p>
<pre><code>int addInt(int n, int m) {
return n+m;
}
</code></pre>
<p>First thing, let's define a pointer to a function which receives 2 <code>int</code>s and returns an <code>int</code>:</p>
<pre><code>int (*functionPtr)(int,int);
</code></pre>
<p>Now we can safely point to our function:</p>
<pre><code>functionPtr = &addInt;
</code></pre>
<p>Now that we have a pointer to the function, let's use it:</p>
<pre><code>int sum = (*functionPtr)(2, 3); // sum == 5
</code></pre>
<p>Passing the pointer to another function is basically the same:</p>
<pre><code>int add2to3(int (*functionPtr)(int, int)) {
return (*functionPtr)(2, 3);
}
</code></pre>
<p>We can use function pointers in return values as well (try to keep up, it gets messy):</p>
<pre><code>// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
printf("Got parameter %d", n);
int (*functionPtr)(int,int) = &addInt;
return functionPtr;
}
</code></pre>
<p>But it's much nicer to use a <code>typedef</code>:</p>
<pre><code>typedef int (*myFuncDef)(int, int);
// note that the typedef name is indeed myFuncDef
myFuncDef functionFactory(int n) {
printf("Got parameter %d", n);
myFuncDef functionPtr = &addInt;
return functionPtr;
}
</code></pre> | {
"question_id": 840501,
"question_date": "2009-05-08T15:49:17.003Z",
"question_score": 1438,
"tags": "c|function-pointers",
"answer_id": 840504,
"answer_date": "2009-05-08T15:49:59.090Z",
"answer_score": 1670
} |
Please answer the following Stack Overflow question:
Title: What is the difference between gravity and layout_gravity in Android?
<p>I know we can set the following values to the <strong><code>android:gravity</code></strong> and <strong><code>android:layout_gravity</code></strong> properties:</p>
<ol>
<li><code>center</code></li>
<li><code>center_vertical</code></li>
<li><code>center_horizontal</code>, etc.</li>
</ol>
<p>But I am confused regarding both of these.</p>
<p>What is the difference between the usage of <code>android:gravity</code> and <code>android:layout_gravity</code>?</p> | <p>Their names should help you:</p>
<ul>
<li><code>android:gravity</code> sets the gravity of the contents (i.e. its subviews) of the <code>View</code> it's used on. </li>
<li><code>android:layout_gravity</code> sets the gravity of the <code>View</code> or <code>Layout</code> relative to its parent. </li>
</ul>
<p>And an example is <a href="http://thinkandroid.wordpress.com/2010/01/14/how-to-position-views-properly-in-layouts/" rel="noreferrer">here</a>.</p> | {
"question_id": 3482742,
"question_date": "2010-08-14T09:28:02.810Z",
"question_score": 1438,
"tags": "android|android-layout|android-gravity",
"answer_id": 3482757,
"answer_date": "2010-08-14T09:31:49.493Z",
"answer_score": 1440
} |
Please answer the following Stack Overflow question:
Title: Relative imports for the billionth time
<p>I've been here:</p>
<ul>
<li><a href="http://www.python.org/dev/peps/pep-0328/" rel="noreferrer">http://www.python.org/dev/peps/pep-0328/</a></li>
<li><a href="http://docs.python.org/2/tutorial/modules.html#packages" rel="noreferrer">http://docs.python.org/2/tutorial/modules.html#packages</a></li>
<li><a href="https://stackoverflow.com/questions/10059002/python-packages-relative-imports">Python packages: relative imports</a></li>
<li><a href="https://stackoverflow.com/questions/9123062/python-relative-import-example-code-does-not-work">python relative import example code does not work</a></li>
<li><a href="https://stackoverflow.com/questions/8299270/ultimate-answer-to-relative-python-imports">Relative imports in python 2.5</a></li>
<li><a href="https://stackoverflow.com/questions/4175534/relative-imports-in-python">Relative imports in Python</a></li>
<li><a href="https://stackoverflow.com/questions/13233931/python-disabling-relative-import?rq=1">Python: Disabling relative import</a></li>
</ul>
<p>and plenty of URLs that I did not copy, some on SO, some on other sites, back when I thought I'd have the solution quickly.</p>
<p>The forever-recurring question is this: how do I solve this "Attempted relative import in non-package" message?</p>
<pre><code>ImportError: attempted relative import with no known parent package
</code></pre>
<p>I built an exact replica of the package on pep-0328:</p>
<pre><code>package/
__init__.py
subpackage1/
__init__.py
moduleX.py
moduleY.py
subpackage2/
__init__.py
moduleZ.py
moduleA.py
</code></pre>
<p>The imports were done from the console.</p>
<p>I did make functions named spam and eggs in their appropriate modules. Naturally, it didn't work. The answer is apparently in the 4th URL I listed, but it's all alumni to me. There was this response on one of the URLs I visited:</p>
<blockquote>
<p>Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.</p>
</blockquote>
<p>The above response looks promising, but it's all hieroglyphs to me. So my question, how do I make Python not return to me "Attempted relative import in non-package"? has an answer that involves -m, supposedly.</p>
<p>Can somebody please tell me why Python gives that error message, what it means by "non-package", why and how do you define a 'package', and <em>the precise answer put in terms easy enough for a kindergartener to understand</em>.</p> | <p><strong>Script vs. Module</strong></p>
<p>Here's an explanation. The short version is that there is a big difference between directly running a Python file, and importing that file from somewhere else. <strong>Just knowing what directory a file is in does not determine what package Python thinks it is in.</strong> That depends, additionally, on how you load the file into Python (by running or by importing).</p>
<p>There are two ways to load a Python file: as the top-level script, or as a
module. A file is loaded as the top-level script if you execute it directly, for instance by typing <code>python myfile.py</code> on the command line. It is loaded as a module when an <code>import</code> statement is encountered inside some other file. There can only be one top-level script at a time; the top-level script is the Python file you ran to start things off.</p>
<p><strong>Naming</strong></p>
<p>When a file is loaded, it is given a name (which is stored in its <code>__name__</code> attribute).</p>
<ul>
<li>If it was loaded as the top-level script, its name is <code>__main__</code>.</li>
<li>If it was loaded as a module, its name is [ the filename, preceded by the names of any packages/subpackages of which it is a part, separated by dots ], for example, <code>package.subpackage1.moduleX</code>.</li>
</ul>
<p>But be aware, if you load <code>moduleX</code> as a module from shell command line using something like <code>python -m package.subpackage1.moduleX</code>, the <code>__name__</code> will still be <code>__main__</code>.</p>
<p>So for instance in your example:</p>
<pre><code>package/
__init__.py
subpackage1/
__init__.py
moduleX.py
moduleA.py
</code></pre>
<p>if you imported <code>moduleX</code> (note: <em>imported</em>, not directly executed), its name would be <code>package.subpackage1.moduleX</code>. If you imported <code>moduleA</code>, its name would be <code>package.moduleA</code>. However, if you <em>directly run</em> <code>moduleX</code> from the command line, its name will instead be <code>__main__</code>, and if you directly run <code>moduleA</code> from the command line, its name will be <code>__main__</code>. When a module is run as the top-level script, it loses its normal name and its name is instead <code>__main__</code>.</p>
<p><strong>Accessing a module NOT through its containing package</strong></p>
<p>There is an additional wrinkle: the module's name depends on whether it was imported "directly" from the directory it is in or imported via a package. This only makes a difference if you run Python in a directory, and try to import a file in that same directory (or a subdirectory of it). For instance, if you start the Python interpreter in the directory <code>package/subpackage1</code> and then do <code>import moduleX</code>, the name of <code>moduleX</code> will just be <code>moduleX</code>, and not <code>package.subpackage1.moduleX</code>. This is because Python adds the current directory to its search path when the interpreter is entered interactively; if it finds the to-be-imported module in the current directory, it will not know that that directory is part of a package, and the package information will not become part of the module's name.</p>
<p>A special case is if you run the interpreter interactively (e.g., just type <code>python</code> and start entering Python code on the fly). In this case, the name of that interactive session is <code>__main__</code>.</p>
<p>Now here is the crucial thing for your error message: <strong>if a module's name has no dots, it is not considered to be part of a package</strong>. It doesn't matter where the file actually is on disk. All that matters is what its name is, and its name depends on how you loaded it.</p>
<p>Now look at the quote you included in your question:</p>
<blockquote>
<p>Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top-level module, regardless of where the module is actually located on the file system.</p>
</blockquote>
<p><strong>Relative imports...</strong></p>
<p>Relative imports use the module's <em>name</em> to determine where it is in a package. When you use a relative import like <code>from .. import foo</code>, the dots indicate to step up some number of levels in the package hierarchy. For instance, if your current module's name is <code>package.subpackage1.moduleX</code>, then <code>..moduleA</code> would mean <code>package.moduleA</code>. For a <code>from .. import</code> to work, the module's name must have at least as many dots as there are in the <code>import</code> statement.</p>
<p><strong>... are only relative in a package</strong></p>
<p>However, if your module's name is <code>__main__</code>, it is not considered to be in a package. Its name has no dots, and therefore you cannot use <code>from .. import</code> statements inside it. If you try to do so, you will get the "relative-import in non-package" error.</p>
<p><strong>Scripts can't import relative</strong></p>
<p>What you probably did is you tried to run <code>moduleX</code> or the like from the command line. When you did this, its name was set to <code>__main__</code>, which means that relative imports within it will fail, because its name does not reveal that it is in a package. Note that this will also happen if you run Python from the same directory where a module is, and then try to import that module, because, as described above, Python will find the module in the current directory "too early" without realizing it is part of a package.</p>
<p>Also remember that when you run the interactive interpreter, the "name" of that interactive session is always <code>__main__</code>. Thus <strong>you cannot do relative imports directly from an interactive session</strong>. Relative imports are only for use within module files.</p>
<p><strong>Two solutions:</strong></p>
<ol>
<li><p>If you really do want to run <code>moduleX</code> directly, but you still want it to be considered part of a package, you can do <code>python -m package.subpackage1.moduleX</code>. The <code>-m</code> tells Python to load it as a module, not as the top-level script.</p>
</li>
<li><p>Or perhaps you don't actually want to <em>run</em> <code>moduleX</code>, you just want to run some other script, say <code>myfile.py</code>, that <em>uses</em> functions inside <code>moduleX</code>. If that is the case, put <code>myfile.py</code> <em>somewhere else</em> – <em>not</em> inside the <code>package</code> directory – and run it. If inside <code>myfile.py</code> you do things like <code>from package.moduleA import spam</code>, it will work fine.</p>
</li>
</ol>
<p><strong>Notes</strong></p>
<ul>
<li><p>For either of these solutions, the package directory (<code>package</code> in your example) must be accessible from the Python module search path (<code>sys.path</code>). If it is not, you will not be able to use anything in the package reliably at all.</p>
</li>
<li><p>Since Python 2.6, the module's "name" for package-resolution purposes is determined not just by its <code>__name__</code> attributes but also by the <code>__package__</code> attribute. That's why I'm avoiding using the explicit symbol <code>__name__</code> to refer to the module's "name". Since Python 2.6 a module's "name" is effectively <code>__package__ + '.' + __name__</code>, or just <code>__name__</code> if <code>__package__</code> is <code>None</code>.)</p>
</li>
</ul> | {
"question_id": 14132789,
"question_date": "2013-01-03T03:50:40.633Z",
"question_score": 1436,
"tags": "python|import|relative-path|python-packaging|relative-import",
"answer_id": 14132912,
"answer_date": "2013-01-03T04:06:37.593Z",
"answer_score": 1877
} |
Please answer the following Stack Overflow question:
Title: Check if element exists in jQuery
<p>How do I check if an element exists if the element is created by <code>.append()</code> method?
<code>$('elemId').length</code> doesn't work for me.</p> | <blockquote>
<p><code>$('elemId').length</code> doesn't work for
me.</p>
</blockquote>
<p>You need to put <code>#</code> before element id:</p>
<pre><code>$('#elemId').length
---^
</code></pre>
<hr>
<p>With vanilla JavaScript, you don't need the hash (<code>#</code>) e.g. <code>document.getElementById('id_here')</code> , however when using jQuery, you do need to put hash to target elements based on <code>id</code> just like CSS.</p> | {
"question_id": 4592493,
"question_date": "2011-01-04T10:15:11.323Z",
"question_score": 1435,
"tags": "javascript|jquery",
"answer_id": 4592511,
"answer_date": "2011-01-04T10:17:43.120Z",
"answer_score": 1960
} |
Please answer the following Stack Overflow question:
Title: What's a quick way to comment/uncomment lines in Vim?
<p>I have a Ruby code file open in vi, there are lines commented out with <code>#</code>:</p>
<pre><code>class Search < ActiveRecord::Migration
def self.up
# create_table :searches do |t|
# t.integer :user_id
# t.string :name
# t.string :all_of
# t.string :any_of
# t.string :none_of
# t.string :exact_phrase
#
# t.timestamps
# end
end
def self.down
# drop_table :searches
end
end
</code></pre>
<p>Say I want to uncomment all the lines in the first <code>def ... end</code> section. What's an efficient way to do that in Vim?</p>
<p>In general, I'm looking for an easy and fluid way to comment and uncomment lines. Here I'm dealing with Ruby code, but it could be JavaScript (<code>//</code>) or Haml (<code>-#</code>).</p> | <p>I use the <a href="http://www.vim.org/scripts/script.php?script_id=1218" rel="noreferrer">NERD Commenter script</a>. It lets you easily comment, uncomment or toggle comments in your code.</p>
<p>As mentioned in the <a href="https://stackoverflow.com/questions/1676632/whats-a-quick-way-to-comment-uncomment-lines-in-vim/1676775#comment63316440_1676775">comments</a>:</p>
<blockquote>
<p>for anyone who is confused by the usage, default leader is "\" so 10\cc will comment ten lines and 10\cu will uncomment those ten lines</p>
</blockquote> | {
"question_id": 1676632,
"question_date": "2009-11-04T21:06:32.723Z",
"question_score": 1435,
"tags": "vim|comments",
"answer_id": 1676775,
"answer_date": "2009-11-04T21:33:56.520Z",
"answer_score": 194
} |
Please answer the following Stack Overflow question:
Title: Ignoring directories in Git repositories on Windows
<p>How can I ignore directories or folders in Git using msysgit on Windows?</p> | <p>Create a file named <code>.gitignore</code> in your project's directory. Ignore directories by entering the directory name into the file (with a slash appended):</p>
<pre><code>dir_to_ignore/
</code></pre>
<p>More information is <a href="http://git-scm.com/docs/gitignore" rel="noreferrer">here</a>.</p> | {
"question_id": 343646,
"question_date": "2008-12-05T12:17:28.657Z",
"question_score": 1434,
"tags": "windows|git|gitignore|git-bash|msysgit",
"answer_id": 343734,
"answer_date": "2008-12-05T12:54:10.407Z",
"answer_score": 2030
} |
Please answer the following Stack Overflow question:
Title: How can I revert multiple Git commits?
<p>I have a Git repository that looks like this:</p>
<pre><code>A <- B <- C <- D <- HEAD
</code></pre>
<p>I want the head of the branch to point to A, i.e., I want B, C, D, and HEAD to disappear and I want head to be synonymous with A.</p>
<p>It sounds like I can either try to rebase (doesn't apply, since I've pushed changes in between), or revert. But how do I revert multiple commits? Do I revert one at a time? Is the order important?</p> | <p><em>Expanding what I wrote in a comment</em></p>
<p>The general rule is that you should not rewrite (change) history that you have published, because somebody might have based their work on it. If you rewrite (change) history, you would make problems with merging their changes and with updating for them.</p>
<p>So the solution is to create a <em>new commit</em> which <strong>reverts changes</strong> that you want to get rid of. You can do this using <a href="http://www.kernel.org/pub/software/scm/git/docs/git-revert.html" rel="noreferrer" title="git-revert(1) Manual Page - Revert an existing commit">git revert</a> command.</p>
<p>You have the following situation:</p>
<pre>
A <-- B <-- C <-- D <-- master <-- HEAD
</pre>
<p>(arrows here refers to the direction of the pointer: the "parent" reference in the case of commits, the top commit in the case of branch head (branch ref), and the name of branch in the case of HEAD reference).</p>
<p>What you need to create is the following:</p>
<pre>
A <-- B <-- C <-- D <-- [(BCD)<sup>-1</sup>] <-- master <-- HEAD
</pre>
<p>where <code>[(BCD)^-1]</code> means the commit that reverts changes in commits B, C, D. Mathematics tells us that (BCD)<sup>-1</sup> = D<sup>-1</sup> C<sup>-1</sup> B<sup>-1</sup>, so you can get the required situation using the following commands:</p>
<pre><code>$ git revert --no-commit D
$ git revert --no-commit C
$ git revert --no-commit B
$ git commit -m "the commit message for all of them"
</code></pre>
<p>Works for everything except merge commits.</p>
<hr />
<p>Alternate solution would be to <a href="http://git-scm.com/docs/git-checkout" rel="noreferrer" title="git-checkout(1) Manual Page - Checkout a branch or paths to the working tree">checkout</a> <em>contents</em> of commit A, and commit this state. Also works with merge commits. Added files will not be deleted, however. If you have any local changes <code>git stash</code> them first:</p>
<pre><code>$ git checkout -f A -- . # checkout that revision over the top of local files
$ git commit -a
</code></pre>
<p>Then you would have the following situation:</p>
<pre>
A <-- B <-- C <-- D <-- A' <-- master <-- HEAD
</pre>
<p>The commit A' has the same contents as commit A, but is a different commit (commit message, parents, commit date).</p>
<hr />
<p>Alternate <a href="https://stackoverflow.com/questions/1463340/revert-multiple-git-commits/1463390#comment1312779_1463390">solution by Jeff Ferland, modified by Charles Bailey</a> builds upon the same idea, but uses <a href="https://www.kernel.org/pub/software/scm/git/docs/git-reset.html" rel="noreferrer" title="git-reset(1) Manual Page - Reset current HEAD to the specified state">git reset</a>. Here it is slightly modified, this way WORKS FOR EVERYTHING:</p>
<pre><code>$ git reset --hard A
$ git reset --soft D # (or ORIG_HEAD or @{1} [previous location of HEAD]), all of which are D
$ git commit
</code></pre> | {
"question_id": 1463340,
"question_date": "2009-09-23T00:27:14.353Z",
"question_score": 1434,
"tags": "git|commit|git-revert",
"answer_id": 1470452,
"answer_date": "2009-09-24T08:44:40.757Z",
"answer_score": 1867
} |
Please answer the following Stack Overflow question:
Title: Check if checkbox is checked with jQuery
<p>How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?</p>
<p>I am using the following code, but it always returns the count of checked checkboxes regardless of id.</p>
<pre class="lang-js prettyprint-override"><code>function isCheckedById(id) {
alert(id);
var checked = $("input[@id=" + id + "]:checked").length;
alert(checked);
if (checked == 0) {
return false;
} else {
return true;
}
}
</code></pre> | <p>IDs must be unique in your document, meaning that you <strong>shouldn't</strong> do this:</p>
<pre><code><input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />
</code></pre>
<p>Instead, drop the ID, and then select them by name, or by a containing element:</p>
<pre><code><fieldset id="checkArray">
<input type="checkbox" name="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>
</code></pre>
<p>And now the jQuery:</p>
<pre><code>var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector
// or, without the container:
var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;
</code></pre> | {
"question_id": 2204250,
"question_date": "2010-02-05T00:23:20.760Z",
"question_score": 1433,
"tags": "javascript|jquery|html|checkbox",
"answer_id": 2204275,
"answer_date": "2010-02-05T00:31:16.250Z",
"answer_score": 775
} |
Please answer the following Stack Overflow question:
Title: Virtual member call in a constructor
<p>I'm getting a warning from ReSharper about a call to a virtual member from my objects constructor. </p>
<p>Why would this be something not to do?</p> | <p>When an object written in C# is constructed, what happens is that the initializers run in order from the most derived class to the base class, and then constructors run in order from the base class to the most derived class (<a href="https://docs.microsoft.com/en-us/archive/blogs/ericlippert/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two" rel="noreferrer">see Eric Lippert's blog for details as to why this is</a>).</p>
<p>Also in .NET objects do not change type as they are constructed, but start out as the most derived type, with the method table being for the most derived type. This means that virtual method calls always run on the most derived type.</p>
<p>When you combine these two facts you are left with the problem that if you make a virtual method call in a constructor, and it is not the most derived type in its inheritance hierarchy, that it will be called on a class whose constructor has not been run, and therefore may not be in a suitable state to have that method called. </p>
<p>This problem is, of course, mitigated if you mark your class as sealed to ensure that it is the most derived type in the inheritance hierarchy - in which case it is perfectly safe to call the virtual method.</p> | {
"question_id": 119506,
"question_date": "2008-09-23T07:11:30.337Z",
"question_score": 1431,
"tags": "c#|constructor|warnings|resharper|virtual-functions",
"answer_id": 119543,
"answer_date": "2008-09-23T07:21:13.747Z",
"answer_score": 1243
} |
Please answer the following Stack Overflow question:
Title: Deleting array elements in JavaScript - delete vs splice
<p>What is the difference between using <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/delete" rel="noreferrer">the <code>delete</code> operator</a> on the array element as opposed to using <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice" rel="noreferrer">the <code>Array.splice</code> method</a>? </p>
<p>For example:</p>
<pre><code>myArray = ['a', 'b', 'c', 'd'];
delete myArray[1];
// or
myArray.splice (1, 1);
</code></pre>
<p>Why even have the splice method if I can delete array elements like I can with objects?</p> | <p><code>delete</code> will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:</p>
<pre><code>> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> delete myArray[0]
true
> myArray[0]
undefined
</code></pre>
<p>Note that it is not in fact set to the value <code>undefined</code>, rather the property is removed from the array, making it <em>appear</em> undefined. The Chrome dev tools make this distinction clear by printing <code>empty</code> when logging the array.</p>
<pre><code>> myArray[0]
undefined
> myArray
[empty, "b", "c", "d"]
</code></pre>
<p><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice" rel="noreferrer"><code>myArray.splice(start, deleteCount)</code></a> actually removes the element, reindexes the array, and changes its length.</p>
<pre><code>> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> myArray.splice(0, 2)
["a", "b"]
> myArray
["c", "d"]
</code></pre> | {
"question_id": 500606,
"question_date": "2009-02-01T11:11:16.420Z",
"question_score": 1430,
"tags": "javascript|arrays|element|delete-operator|array-splice",
"answer_id": 500617,
"answer_date": "2009-02-01T11:16:23.257Z",
"answer_score": 1801
} |
Please answer the following Stack Overflow question:
Title: String formatting: % vs. .format vs. f-string literal
<p>There are various string formatting methods:</p>
<ul>
<li>Python <2.6: <code>"Hello %s" % name</code></li>
<li>Python 2.6+: <code>"Hello {}".format(name)</code> (uses <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow noreferrer"><code>str.format</code></a>)</li>
<li>Python 3.6+: <code>f"{name}"</code> (uses f-strings)</li>
</ul>
<p>Which is better, and for what situations?</p>
<hr />
<ol>
<li><p>The following methods have the same outcome, so what is the difference?</p>
<pre><code>name = "Alice"
"Hello %s" % name
"Hello {0}".format(name)
f"Hello {name}"
# Using named arguments:
"Hello %(kwarg)s" % {'kwarg': name}
"Hello {kwarg}".format(kwarg=name)
f"Hello {name}"
</code></pre>
</li>
<li><p>When does string formatting run, and how do I avoid a runtime performance penalty?</p>
</li>
</ol>
<hr />
<p><sub>If you are trying to close a duplicate question that is just looking for a way to format a string, please use <a href="https://stackoverflow.com/questions/2960772">How do I put a variable’s value inside a string?</a>.</sub></p> | <p>To answer your first question... <code>.format</code> just seems more sophisticated in many ways. An annoying thing about <code>%</code> is also how it can either take a variable or a tuple. You'd think the following would always work:</p>
<pre><code>"Hello %s" % name
</code></pre>
<p>yet, if <code>name</code> happens to be <code>(1, 2, 3)</code>, it will throw a <code>TypeError</code>. To guarantee that it always prints, you'd need to do</p>
<pre><code>"Hello %s" % (name,) # supply the single argument as a single-item tuple
</code></pre>
<p>which is just ugly. <code>.format</code> doesn't have those issues. Also in the second example you gave, the <code>.format</code> example is much cleaner looking.</p>
<p>Only use it for backwards compatibility with Python 2.5.</p>
<hr />
<p>To answer your second question, string formatting happens at the same time as any other operation - when the string formatting expression is evaluated. And Python, not being a lazy language, evaluates expressions before calling functions, so the expression <code>log.debug("some debug info: %s" % some_info)</code> will first evaluate the string to, e.g. <code>"some debug info: roflcopters are active"</code>, then that string will be passed to <code>log.debug()</code>.</p> | {
"question_id": 5082452,
"question_date": "2011-02-22T18:46:42.453Z",
"question_score": 1430,
"tags": "python|performance|string-formatting|f-string",
"answer_id": 5082482,
"answer_date": "2011-02-22T18:49:21.347Z",
"answer_score": 979
} |
Please answer the following Stack Overflow question:
Title: What is setup.py?
<p>What is <code>setup.py</code> and how can it be configured or used?</p> | <p><code>setup.py</code> is a python file, the presence of which is an indication that the module/package you are about to install has likely been packaged and distributed with Distutils, which is the standard for distributing Python Modules.<br></p>
<p>This allows you to easily install Python packages. Often it's enough to write:</p>
<pre><code>$ pip install .
</code></pre>
<p><code>pip</code> will use <code>setup.py</code> to install your module. Avoid calling <code>setup.py</code> directly.</p>
<p><a href="https://docs.python.org/3/installing/index.html#installing-index" rel="noreferrer">https://docs.python.org/3/installing/index.html#installing-index</a></p> | {
"question_id": 1471994,
"question_date": "2009-09-24T14:16:52.613Z",
"question_score": 1430,
"tags": "python|pypi|setup.py|python-packaging",
"answer_id": 1472014,
"answer_date": "2009-09-24T14:19:35.300Z",
"answer_score": 1047
} |
Please answer the following Stack Overflow question:
Title: What is the difference between a field and a property?
<p>In C#, what makes a field different from a property, and when should a field be used instead of a property?</p> | <p>Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.</p>
<pre><code>public class MyClass
{
// this is a field. It is private to your class and stores the actual data.
private string _myField;
// this is a property. When accessed it uses the underlying field,
// but only exposes the contract, which will not be affected by the underlying field
public string MyProperty
{
get
{
return _myField;
}
set
{
_myField = value;
}
}
// This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax
// used to generate a private field for you
public int AnotherProperty { get; set; }
}
</code></pre>
<p>@Kent points out that Properties are not required to encapsulate fields, they could do a calculation on other fields, or serve other purposes.</p>
<p>@GSS points out that you can also do other logic, such as validation, when a property is accessed, another useful feature.</p> | {
"question_id": 295104,
"question_date": "2008-11-17T08:41:38.037Z",
"question_score": 1428,
"tags": "c#|oop|properties|field",
"answer_id": 295109,
"answer_date": "2008-11-17T08:44:18.813Z",
"answer_score": 1242
} |
Please answer the following Stack Overflow question:
Title: Path.Combine for URLs?
<p><a href="https://msdn.microsoft.com/en-us/library/system.io.path.combine%28v=vs.110%29.aspx" rel="noreferrer">Path.Combine</a> is handy, but is there a similar function in the .NET framework for <a href="http://en.wikipedia.org/wiki/Uniform_resource_locator" rel="noreferrer">URLs</a>?</p>
<p>I'm looking for syntax like this:</p>
<pre><code>Url.Combine("http://MyUrl.com/", "/Images/Image.jpg")
</code></pre>
<p>which would return:</p>
<p><code>"http://MyUrl.com/Images/Image.jpg"</code></p> | <p>There <a href="https://stackoverflow.com/questions/372865/path-combine-for-urls/43582421#comment33212350_372865">is a Todd Menier's comment above</a> that <a href="https://flurl.dev/" rel="nofollow noreferrer">Flurl</a> includes a <code>Url.Combine</code>.</p>
<p>More details:</p>
<blockquote>
<p>Url.Combine is basically a Path.Combine for URLs, ensuring one
and only one separator character between parts:</p>
</blockquote>
<pre><code>var url = Url.Combine(
"http://MyUrl.com/",
"/too/", "/many/", "/slashes/",
"too", "few?",
"x=1", "y=2"
// result: "http://www.MyUrl.com/too/many/slashes/too/few?x=1&y=2"
</code></pre>
<p>Get <a href="https://www.nuget.org/packages/Flurl.Http/" rel="nofollow noreferrer">Flurl.Http on NuGet</a>:</p>
<p>PM> Install-Package Flurl.Http</p>
<p>Or <a href="https://www.nuget.org/packages/Flurl/" rel="nofollow noreferrer">get the stand-alone URL builder</a> without the HTTP features:</p>
<p>PM> Install-Package Flurl</p> | {
"question_id": 372865,
"question_date": "2008-12-16T21:42:26.937Z",
"question_score": 1428,
"tags": "c#|.net|asp.net|url|path",
"answer_id": 49810235,
"answer_date": "2018-04-13T06:00:13.173Z",
"answer_score": 124
} |
Please answer the following Stack Overflow question:
Title: What is the "right" JSON date format?
<p>I've seen so many different standards for the JSON date format:</p>
<pre><code>"\"\\/Date(1335205592410)\\/\"" .NET JavaScriptSerializer
"\"\\/Date(1335205592410-0500)\\/\"" .NET DataContractJsonSerializer
"2012-04-23T18:25:43.511Z" JavaScript built-in JSON object
"2012-04-21T18:25:43-05:00" ISO 8601
</code></pre>
<p>Which one is the right one? Or best? Is there any sort of standard on this?</p> | <p><a href="http://json.org/" rel="noreferrer" title="JSON definition">JSON</a> itself <strong>does not</strong> specify how dates should be represented, but JavaScript does.</p>
<p>You <em>should</em> use the format emitted by <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" rel="noreferrer" title="MDN documentation for JavaScript Date"><code>Date</code></a>'s <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON" rel="noreferrer" title="MDN documentation for toJSON()"><code>toJSON</code></a> method:</p>
<p><code>2012-04-23T18:25:43.511Z</code></p>
<p>Here's why:</p>
<ol>
<li><p>It's human readable but also succinct</p>
</li>
<li><p>It sorts correctly</p>
</li>
<li><p>It includes fractional seconds, which can help re-establish chronology</p>
</li>
<li><p>It conforms to <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer" title="ISO8601 on Wikipedia">ISO 8601</a></p>
</li>
<li><p>ISO 8601 has been well-established internationally for more than a decade</p>
</li>
<li><p>ISO 8601 is endorsed by <a href="http://www.w3.org/TR/NOTE-datetime" rel="noreferrer" title="W3C datetime">W3C</a>, <a href="https://www.rfc-editor.org/rfc/rfc3339" rel="noreferrer" title="RFC3339 on IETF">RFC3339</a>, and <a href="http://xkcd.com/1179/" rel="noreferrer" title="XKCD comic about ISO8601">XKCD</a></p>
</li>
</ol>
<p><strong>That being said</strong>, every date library ever written can understand "milliseconds since 1970". So for easy portability, <a href="https://stackoverflow.com/a/10286228/1850609">ThiefMaster</a> is right.</p> | {
"question_id": 10286204,
"question_date": "2012-04-23T18:32:32.077Z",
"question_score": 1427,
"tags": "javascript|json",
"answer_id": 15952652,
"answer_date": "2013-04-11T15:20:43.507Z",
"answer_score": 2305
} |
Please answer the following Stack Overflow question:
Title: Can I concatenate multiple MySQL rows into one field?
<p>Using <code>MySQL</code>, I can do something like:</p>
<pre><code>SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;
</code></pre>
<p><strong>My Output:</strong></p>
<pre><code>shopping
fishing
coding
</code></pre>
<p>but instead I just want 1 row, 1 col:</p>
<p><strong>Expected Output:</strong></p>
<pre><code>shopping, fishing, coding
</code></pre>
<p>The reason is that I'm selecting multiple values from multiple tables, and after all the joins I've got a lot more rows than I'd like.</p>
<p>I've looked for a function on <a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws" rel="noreferrer">MySQL Doc</a> and it doesn't look like the <code>CONCAT</code> or <code>CONCAT_WS</code> functions accept result sets.</p>
<p>So does anyone here know how to do this?</p> | <p>You can use <a href="https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat" rel="noreferrer"><code>GROUP_CONCAT</code></a>:</p>
<pre><code>SELECT person_id,
GROUP_CONCAT(hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
</code></pre>
<p>As Ludwig stated in <a href="https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field#comment14513101_276949">his comment,</a> you can add the <code>DISTINCT</code> operator to avoid duplicates:</p>
<pre><code>SELECT person_id,
GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
</code></pre>
<p>As Jan stated in <a href="https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field#comment72475644_276949">their comment,</a> you can also sort the values before imploding it using <code>ORDER BY</code>:</p>
<pre><code>SELECT person_id,
GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
</code></pre>
<p>As Dag stated in <a href="https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field/276949#comment12638055_276949">his comment,</a> there is a 1024 byte limit on the result. To solve this, run this query before your query:</p>
<pre><code>SET group_concat_max_len = 2048;
</code></pre>
<p>Of course, you can change <code>2048</code> according to your needs. To calculate and assign the value:</p>
<pre><code>SET group_concat_max_len = CAST(
(SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')
FROM peoples_hobbies
GROUP BY person_id) AS UNSIGNED);
</code></pre> | {
"question_id": 276927,
"question_date": "2008-11-10T02:34:26.463Z",
"question_score": 1427,
"tags": "mysql|sql|concat|group-concat",
"answer_id": 276949,
"answer_date": "2008-11-10T02:48:11.677Z",
"answer_score": 2022
} |
Please answer the following Stack Overflow question:
Title: What is Gradle in Android Studio?
<p>Gradle is a bit confusing to me, and also for any new Android developer. Can anyone explain what Gradle in Android Studio is and what its purpose is? Why is it included in Android Studio?</p> | <h3>Short Answer</h3>
<p>Gradle is a build system.</p>
<h3>Long Answer</h3>
<p>Before Android Studio you were using <a href="https://en.wikipedia.org/wiki/Eclipse_%28software%29" rel="noreferrer">Eclipse</a> for your development purposes, and, chances are, you didn't know how to build your Android <a href="https://en.wikipedia.org/wiki/APK_%28file_format%29" rel="noreferrer">APK</a> without Eclipse.</p>
<p>You can do this on the command line, but you have to learn what each tool (<a href="https://stackoverflow.com/tags/dx/info">dx</a> and <a href="https://developer.android.com/studio/command-line/aapt2" rel="noreferrer">AAPT</a>) does in the SDK.
Eclipse saved us all from these low-level, but important, fundamental details by giving us their own build system.</p>
<p>Now, have you ever wondered why the <code>res</code> folder is in the same directory as your <code>src</code> folder?</p>
<p>This is where the build system enters the picture. The build system automatically takes all the source files (<code>.java</code> or <code>.xml</code>), then applies the appropriate tool (e.g., takes <code>.java</code> class files and converts them to <code>.dex</code> files), and groups all of them into one compressed file - our beloved APK.</p>
<p>This build system uses some conventions: an example of one is to specify the directory containing the source files (in Eclipse it is <code>\src</code> folder) or resources files (in Eclipse it is <code>\res</code> folder).</p>
<p>Now, in order to automate all these tasks, there has to be a script; you can write your own build system using shell scripting in Linux or batch files syntax in Windows. Got it?</p>
<p>Gradle is another <strong>build system</strong> that takes the best features from other build systems and combines them into one. It is improved based off of their shortcomings. It is a <strong>JVM-based build system</strong>. That means you can write your own script in Java, which Android Studio makes use of.</p>
<p>One cool thing about Gradle is that it is a <strong>plugin-based system</strong>. This means if you have your own programming language and you want to automate the task of building some package (output like a <a href="https://en.wikipedia.org/wiki/JAR_%28file_format%29" rel="noreferrer">JAR</a> file for Java) from sources, then you can write a complete plugin in Java or <a href="https://en.wikipedia.org/wiki/Groovy_%28programming_language%29" rel="noreferrer">Groovy</a> (or <a href="https://en.wikipedia.org/wiki/Kotlin_(programming_language)" rel="noreferrer">Kotlin</a>, see <a href="https://blog.gradle.org/kotlin-meets-gradle" rel="noreferrer">here</a>), and distribute it to the rest of the world.</p>
<h3>Why did Google use it?</h3>
<p>Google saw one of the most advanced build systems on the market and realized that you could write scripts of your own with little-to-no learning curve, and without learning Groovy or any other new language. So they wrote the Android plugin for Gradle.</p>
<p>You must have seen <code>build.gradle</code> file(s) in your project. That is where you can write scripts to automate your tasks. The code you saw in these files is Groovy code. If you write <code>System.out.println("Hello Gradle!");</code> then it will print on your console.</p>
<h3>What can you do in a build script?</h3>
<p>A simple example is that you have to copy some files from one directory to another before the actual build process happens. A Gradle build script can do this.</p> | {
"question_id": 16754643,
"question_date": "2013-05-25T22:53:38.523Z",
"question_score": 1427,
"tags": "android-studio|gradle|android-gradle-plugin|build-automation",
"answer_id": 24828666,
"answer_date": "2014-07-18T15:27:41.113Z",
"answer_score": 1644
} |
Please answer the following Stack Overflow question:
Title: Turning off auto indent when pasting text into vim
<p>I am making the effort to learn Vim.</p>
<p>When I paste code into my document from the clipboard, I get extra spaces at the start of each new line:</p>
<pre><code>line
line
line
</code></pre>
<p>I know you can turn off auto indent but I can't get it to work because I have some other settings conflicting or something (which look pretty obvious in my .vimrc but don't seem to matter when I take them out). </p>
<p>How do I turn off auto indenting when I paste code but still have vim auto indent when I am writing code? Here is my <code>.vimrc</code> file:</p>
<pre><code>set expandtab
set tabstop=2
set shiftwidth=2
set autoindent
set smartindent
set bg=dark
set nowrap
</code></pre> | <p><strong>Update:</strong> Better answer here: <a href="https://stackoverflow.com/a/38258720/62202">https://stackoverflow.com/a/38258720/62202</a></p>
<p>To turn off autoindent when you paste code, there's a special "paste" mode.</p>
<p>Type </p>
<pre><code>:set paste
</code></pre>
<p>Then paste your code. Note that the text in the tooltip now says <code>-- INSERT (paste) --</code>.</p>
<p>After you pasted your code, turn off the paste-mode, so that auto-indenting when you type works correctly again.</p>
<pre><code>:set nopaste
</code></pre>
<p>However, I always found that cumbersome. That's why I map <code><F3></code> such that it can switch between paste and nopaste modes <em>while editing the text!</em> I add this to <code>.vimrc</code></p>
<pre><code>set pastetoggle=<F3>
</code></pre> | {
"question_id": 2514445,
"question_date": "2010-03-25T09:52:47.883Z",
"question_score": 1426,
"tags": "vim|configuration|editor|indentation|auto-indent",
"answer_id": 2514520,
"answer_date": "2010-03-25T10:02:14.307Z",
"answer_score": 2488
} |
Please answer the following Stack Overflow question:
Title: How to put the legend outside the plot
<p>I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced.</p>
<ol>
<li>I want to keep the legend box outside the plot area (I want the legend to be outside at the right side of the plot area).</li>
<li>Is there a way that I reduce the font size of the text inside the legend box, so that the size of the legend box will be small?</li>
</ol> | <ul>
<li>You can make the legend text smaller by specifying <code>set_size</code> of <code>FontProperties</code>.</li>
<li>Resources:
<ul>
<li><a href="https://matplotlib.org/tutorials/intermediate/legend_guide.html#legend-guide" rel="nofollow noreferrer">Legend guide</a></li>
<li><a href="https://matplotlib.org/api/legend_api.html" rel="nofollow noreferrer"><code>matplotlib.legend</code></a></li>
<li><a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html#matplotlib.pyplot.legend" rel="nofollow noreferrer"><code>matplotlib.pyplot.legend</code></a></li>
<li><a href="https://matplotlib.org/3.3.1/api/font_manager_api.html" rel="nofollow noreferrer"><code>matplotlib.font_manager</code></a>
<ul>
<li><a href="https://matplotlib.org/3.3.1/api/font_manager_api.html#matplotlib.font_manager.FontProperties.set_size" rel="nofollow noreferrer"><code>set_size(self, size)</code></a></li>
<li>Valid font size are <em>xx-small</em>, <em>x-small</em>, <em>small</em>, <em>medium</em>, <em>large</em>, <em>x-large</em>, <em>xx-large</em>, <em>larger</em>, <em>smaller</em>, and <em>None</em>.</li>
</ul>
</li>
<li><a href="https://realpython.com/python-matplotlib-guide/" rel="nofollow noreferrer">Real Python: Python Plotting With Matplotlib (Guide)</a></li>
</ul>
</li>
</ul>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
fontP = FontProperties()
fontP.set_size('xx-small')
p1, = plt.plot([1, 2, 3], label='Line 1')
p2, = plt.plot([3, 2, 1], label='Line 2')
plt.legend(handles=[p1, p2], title='title', bbox_to_anchor=(1.05, 1), loc='upper left', prop=fontP)
</code></pre>
<p><a href="https://i.stack.imgur.com/OMgiC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OMgiC.png" alt="Enter image description here" /></a></p>
<ul>
<li><code>fontsize='xx-small'</code> also works, without importing <code>FontProperties</code>.</li>
</ul>
<pre class="lang-py prettyprint-override"><code>plt.legend(handles=[p1, p2], title='title', bbox_to_anchor=(1.05, 1), loc='upper left', fontsize='xx-small')
</code></pre> | {
"question_id": 4700614,
"question_date": "2011-01-15T16:10:03.023Z",
"question_score": 1425,
"tags": "python|matplotlib|seaborn|legend",
"answer_id": 4700674,
"answer_date": "2011-01-15T16:21:37.470Z",
"answer_score": 181
} |
Please answer the following Stack Overflow question:
Title: Proper MIME media type for PDF files
<p>When working with PDFs, I've run across the MIME types <code>application/pdf</code> and <code>application/x-pdf</code> among others. </p>
<p>Is there a difference between these two types, and if so what is it? Is one preferred over the other?</p>
<p>I'm working on a web app which must deliver huge amounts of PDFs and I want to do it the correct way, if there is one.</p> | <p>The standard Media Type (formerly known as MIME types) is <code>application/pdf</code>. The assignment is defined in <a href="http://www.rfc-editor.org/rfc/rfc3778.txt" rel="noreferrer" title="RFC 3778">RFC 3778, The application/pdf Media Type</a>, referenced from the <a href="http://www.iana.org/assignments/media-types/" rel="noreferrer" title="IANA | MIME Media Types">Media Types registry</a>.</p>
<p>Media Types are controlled by a standards body, The <a href="http://www.iana.org/" rel="noreferrer" title="IANA">Internet Assigned Numbers Authority</a> (IANA). This is the same organization that manages the root name servers and the IP address space.</p>
<p>The use of <code>x-pdf</code> predates the standardization of the Media Type for PDF. Media Types in the <code>x-</code> namespace are considered experimental, just as those in the <code>vnd.</code> namespace are considered vendor-specific. <code>x-pdf</code> might be used for compatibility with old software.</p> | {
"question_id": 312230,
"question_date": "2008-11-23T06:49:08.497Z",
"question_score": 1425,
"tags": "pdf|http-headers|content-type|mime",
"answer_id": 312258,
"answer_date": "2008-11-23T07:22:44.950Z",
"answer_score": 1869
} |
Please answer the following Stack Overflow question:
Title: What is the difference between concurrency and parallelism?
<p>What is the difference between concurrency and parallelism?</p> | <p><strong>Concurrency</strong> is when two or more tasks can start, run, and complete in overlapping time <strong>periods</strong>. It doesn't necessarily mean they'll ever both be running <strong>at the same instant</strong>. For example, <em>multitasking</em> on a single-core machine.</p>
<p><strong>Parallelism</strong> is when tasks <em>literally</em> run at the same time, e.g., on a multicore processor.</p>
<hr>
<p>Quoting <a href="http://docs.oracle.com/cd/E19455-01/806-5257/6je9h032b/index.html" rel="noreferrer">Sun's <em>Multithreaded Programming Guide</em></a>:</p>
<ul>
<li><p>Concurrency: A condition that exists when at least two threads are making progress. A more generalized form of parallelism that can include time-slicing as a form of virtual parallelism.</p></li>
<li><p>Parallelism: A condition that arises when at least two threads are executing simultaneously.</p></li>
</ul> | {
"question_id": 1050222,
"question_date": "2009-06-26T17:18:02.243Z",
"question_score": 1425,
"tags": "language-agnostic|concurrency|parallel-processing",
"answer_id": 1050257,
"answer_date": "2009-06-26T17:24:20.503Z",
"answer_score": 1642
} |
Please answer the following Stack Overflow question:
Title: How to change the href attribute for a hyperlink using jQuery
<p>How can you change the <code>href</code> attribute (link target) for a hyperlink using jQuery?</p> | <p>Using</p>
<pre><code>$("a").attr("href", "http://www.google.com/")
</code></pre>
<p>will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags:</p>
<pre><code><a name="MyLinks"></a>
<a href="http://www.codeproject.com/">The CodeProject</a>
</code></pre>
<p>...Then you probably don't want to accidentally add <code>href</code> attributes to them. For safety then, we can specify that our selector will only match <code><a></code> tags with an existing <code>href</code> attribute:</p>
<pre><code>$("a[href]") //...
</code></pre>
<p>Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing <code>href</code>, you might use something like this:</p>
<pre><code>$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')
</code></pre>
<p>This will find links where the <code>href</code> exactly matches the string <code>http://www.google.com/</code>. A more involved task might be matching, then updating only part of the <code>href</code>:</p>
<pre><code>$("a[href^='http://stackoverflow.com']")
.each(function()
{
this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/,
"http://stackoverflow.com");
});
</code></pre>
<p>The first part selects only links where the href <em>starts</em> with <code>http://stackoverflow.com</code>. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.</p> | {
"question_id": 179713,
"question_date": "2008-10-07T18:17:33.977Z",
"question_score": 1424,
"tags": "javascript|html|jquery|hyperlink",
"answer_id": 179717,
"answer_date": "2008-10-07T18:19:42.817Z",
"answer_score": 2024
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.