input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: OR is not supported with CASE Statement in SQL Server
<p>The <code>OR</code> operator in the <code>WHEN</code> clause of a <code>CASE</code> statement is not supported. How can I do this?</p>
<pre><code>CASE ebv.db_no
WHEN 22978 OR 23218 OR 23219 THEN 'WECS 9500'
ELSE 'WECS 9520'
END as wecs_system
</code></pre> | <p>That format requires you to use either:</p>
<pre><code>CASE ebv.db_no
WHEN 22978 THEN 'WECS 9500'
WHEN 23218 THEN 'WECS 9500'
WHEN 23219 THEN 'WECS 9500'
ELSE 'WECS 9520'
END as wecs_system
</code></pre>
<p>Otherwise, use:</p>
<pre><code>CASE
WHEN ebv.db_no IN (22978, 23218, 23219) THEN 'WECS 9500'
ELSE 'WECS 9520'
END as wecs_system
</code></pre> | {
"question_id": 5487892,
"question_date": "2011-03-30T14:45:11.100Z",
"question_score": 598,
"tags": "sql|sql-server|tsql|case|case-when",
"answer_id": 5487936,
"answer_date": "2011-03-30T14:47:54.507Z",
"answer_score": 1109
} |
Please answer the following Stack Overflow question:
Title: How to update the value stored in Dictionary in C#?
<p>How to update value for a specific key in a dictionary <code>Dictionary<string, int></code>?</p> | <p>Just point to the dictionary at given key and assign a new value:</p>
<pre><code>myDictionary[myKey] = myNewValue;
</code></pre> | {
"question_id": 1243717,
"question_date": "2009-08-07T09:02:11.787Z",
"question_score": 598,
"tags": "c#|dictionary",
"answer_id": 1243724,
"answer_date": "2009-08-07T09:04:27.240Z",
"answer_score": 965
} |
Please answer the following Stack Overflow question:
Title: How to use SharedPreferences in Android to store, fetch and edit values
<p>I want to store a time value and need to retrieve and edit it. How can I use <code>SharedPreferences</code> to do this?</p> | <p>To obtain shared preferences, use the following method
In your activity:</p>
<pre><code>SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
</code></pre>
<p>To read preferences:</p>
<pre><code>String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
</code></pre>
<p>To edit and save preferences</p>
<pre><code>Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
</code></pre>
<p>The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:</p>
<pre><code><android-sdk-home>/samples/android-<platformversion>/ApiDemos directory
</code></pre>
<p><strong>Edit==></strong></p>
<p>I noticed, it is important to write difference between <code>commit()</code> and <code>apply()</code> here as well.</p>
<p><strong><code>commit()</code></strong> return <code>true</code> if value saved successfully otherwise <code>false</code>. It save values to SharedPreferences <strong>synchronously</strong>.</p>
<p><strong><code>apply()</code></strong> was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an <strong>asynchronous</strong> commit.
More detail is <a href="http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()" rel="noreferrer">here</a>.</p> | {
"question_id": 3624280,
"question_date": "2010-09-02T06:26:52.897Z",
"question_score": 598,
"tags": "android|sharedpreferences",
"answer_id": 3624358,
"answer_date": "2010-09-02T06:42:15.013Z",
"answer_score": 861
} |
Please answer the following Stack Overflow question:
Title: How can I tell if I'm running in 64-bit JVM or 32-bit JVM (from within a program)?
<p>How can I tell if the JVM in which my application runs is 32 bit or 64-bit? Specifically, what functions or properties I can used to detect this within the program?</p> | <p>You retrieve the <a href="https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html" rel="noreferrer">system property</a> that marks the bitness of this JVM with:</p>
<pre><code>System.getProperty("sun.arch.data.model");
</code></pre>
<p>Possible results are:</p>
<ul>
<li><code>"32"</code> – 32-bit JVM</li>
<li><code>"64"</code> – 64-bit JVM</li>
<li><code>"unknown"</code> – Unknown JVM</li>
</ul>
<p>As described in the <a href="https://www.oracle.com/technetwork/java/hotspotfaq-138619.html#64bit_detection" rel="noreferrer">HotSpot FAQ</a>:</p>
<blockquote>
<p><strong>When writing Java code, how do I distinguish between 32 and 64-bit operation?</strong></p>
<p>There's no public API that allows you to distinguish between 32 and 64-bit operation. Think of 64-bit as just another platform in the write once, run anywhere tradition. However, if you'd like to write code which is platform specific (shame on you), the system property sun.arch.data.model has the value "32", "64", or "unknown".</p>
</blockquote>
<p>An example where this could be necessary is if your Java code depends on native libraries, and you need to determine whether to load the 32- or 64-bit version of the libraries on startup.</p> | {
"question_id": 2062020,
"question_date": "2010-01-14T03:38:29.823Z",
"question_score": 598,
"tags": "java|jvm|java-native-interface|64-bit|32-bit",
"answer_id": 2062036,
"answer_date": "2010-01-14T03:44:31.513Z",
"answer_score": 334
} |
Please answer the following Stack Overflow question:
Title: CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue
<p>Suppose you have some style and the markup:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul
{
white-space: nowrap;
overflow-x: visible;
overflow-y: hidden;
/* added width so it would work in the snippet */
width: 100px;
}
li
{
display: inline-block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<ul>
<li>1</li> <li>2</li> <li>3</li>
<li>4</li> <li>5</li> <li>6</li>
<li>7</li> <li>8</li> <li>9</li>
<li>1</li> <li>2</li> <li>3</li>
<li>4</li> <li>5</li> <li>6</li>
<li>7</li> <li>8</li> <li>9</li>
<li>1</li> <li>2</li> <li>3</li>
<li>4</li> <li>5</li> <li>6</li>
<li>7</li> <li>8</li> <li>9</li>
</ul>
</div></code></pre>
</div>
</div>
</p>
<p>When you view this. The <code><ul></code> has a scroll bar at the bottom even though I've specified visible and hidden values for overflow x/y.</p>
<p>(observed on Chrome 11 and opera (?))</p>
<p>I'm guessing there must be some w3c spec or something telling this to happen but for the life of me I can't work out why.</p>
<p><a href="http://jsfiddle.net/3xv6A/" rel="noreferrer">JSFiddle</a></p>
<p><strong>UPDATE:-</strong> I found a way to achieve the same result by adding another element wrapped around the <code>ul</code>. <a href="http://jsfiddle.net/3xv6A/9/" rel="noreferrer">Check it out.</a></p> | <p>After some serious searching it seems i've found the answer to my question:</p>
<p>from: <a href="http://www.brunildo.org/test/Overflowxy2.html" rel="noreferrer">http://www.brunildo.org/test/Overflowxy2.html</a></p>
<blockquote>
<p>In Gecko, Safari, Opera, ‘visible’
becomes ‘auto’ also when combined with
‘hidden’ (in other words: ‘visible’
becomes ‘auto’ when combined with
anything else different from
‘visible’). Gecko 1.8, Safari 3, Opera
9.5 are pretty consistent among them.</p>
</blockquote>
<p>also the <a href="http://www.w3.org/TR/css3-box/#overflow-x" rel="noreferrer">W3C spec</a> says:</p>
<blockquote>
<p>The computed values of ‘overflow-x’
and ‘overflow-y’ are the same as their
specified values, except that some
combinations with ‘visible’ are not
possible: if one is specified as
‘visible’ and the other is ‘scroll’ or
‘auto’, then ‘visible’ is set to
‘auto’. The computed value of
‘overflow’ is equal to the computed
value of ‘overflow-x’ if ‘overflow-y’
is the same; otherwise it is the pair
of computed values of ‘overflow-x’ and
‘overflow-y’.</p>
</blockquote>
<p><strong>Short Version:</strong></p>
<p>If you are using <code>visible</code> for either <code>overflow-x</code> or <code>overflow-y</code> and something other than <code>visible</code> for the other, the <code>visible</code> value is interpreted as <code>auto</code>.</p> | {
"question_id": 6421966,
"question_date": "2011-06-21T07:45:06.340Z",
"question_score": 598,
"tags": "html|css|overflow",
"answer_id": 6433475,
"answer_date": "2011-06-22T00:13:54.077Z",
"answer_score": 861
} |
Please answer the following Stack Overflow question:
Title: How can I find the method that called the current method?
<p>When logging in C#, how can I learn the name of the method that called the current method? I know all about <code>System.Reflection.MethodBase.GetCurrentMethod()</code>, but I want to go one step beneath this in the stack trace. I've considered parsing the stack trace, but I am hoping to find a cleaner more explicit way, something like <code>Assembly.GetCallingAssembly()</code> but for methods.</p> | <p>Try this:</p>
<pre><code>using System.Diagnostics;
// Get call stack
StackTrace stackTrace = new StackTrace();
// Get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
</code></pre>
<p>one-liner:</p>
<pre><code>(new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name
</code></pre>
<p>It is from <em><a href="http://www.csharp-examples.net/reflection-calling-method-name/" rel="noreferrer">Get Calling Method using Reflection [C#]</a></em>.</p> | {
"question_id": 171970,
"question_date": "2008-10-05T13:28:41.797Z",
"question_score": 598,
"tags": "c#|.net|logging|stack-trace|system.diagnostics",
"answer_id": 171974,
"answer_date": "2008-10-05T13:33:34.003Z",
"answer_score": 614
} |
Please answer the following Stack Overflow question:
Title: Why Is `Export Default Const` invalid?
<p>I see that the following is fine:</p>
<pre><code>const Tab = connect( mapState, mapDispatch )( Tabs );
export default Tab;
</code></pre>
<p>However, this is incorrect:</p>
<pre><code>export default const Tab = connect( mapState, mapDispatch )( Tabs );
</code></pre>
<p>Yet this is fine:</p>
<pre><code>export default Tab = connect( mapState, mapDispatch )( Tabs );
</code></pre>
<p>Can this be explained please why <code>const</code> is invalid with <code>export default</code>? Is it an unnecessary addition & anything declared as <code>export default</code> is presumed a <code>const</code> or such? </p> | <p><code>const</code> is like <code>let</code>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-let-and-const-declarations" rel="noreferrer"><strong>it is a <em>LexicalDeclaration</em></strong></a> (<em>VariableStatement, Declaration</em>) used to define an identifier in your block.</p>
<p>You are trying to mix this with the <code>default</code> keyword, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-exports-static-semantics-boundnames" rel="noreferrer"><strong>which expects a <em>HoistableDeclaration, ClassDeclaration</em> or <em>AssignmentExpression</em></strong></a> to follow it.</p>
<p>Therefore it is a <em>SyntaxError</em>.</p>
<hr />
<p>If you want to <code>const</code> something you need to provide the identifier and not use <code>default</code>.</p>
<p><code>export</code> by itself accepts a <em>VariableStatement</em> or <em>Declaration</em> to its right.</p>
<hr />
<blockquote>
<p>The following is fine<code>export default Tab;</code></p>
</blockquote>
<p><code>Tab</code> becomes an <em>AssignmentExpression</em> as it's given the name <em>default</em> <sup>?</sup></p>
<blockquote>
<p><code>export default Tab = connect( mapState, mapDispatch )( Tabs );</code> is fine</p>
</blockquote>
<p>Here <code>Tab = connect( mapState, mapDispatch )( Tabs );</code> is an <em>AssignmentExpression</em>.</p>
<hr />
<p><strong>Update:</strong> A different way to imagine the problem</p>
<p>If you're trying to conceptually understand this and the spec-reasoning above is not helping, think of it as <em>"if <code>default</code> was a legal identifier and not a reserved token, what would be a different way to write <code>export default Foo;</code> and <code>export default const Foo = 1;</code> ?"</em></p>
<p>In this situation, the expanded way to write it would be</p>
<pre class="lang-js prettyprint-override"><code>// pseudocode, this thought experiment is not valid JS
export default Foo;
// would be like
export const default = Foo;
export default const Foo = 1;
// would be like
export const default const Foo = 1;
// so would the following line make sense?
const bar const Foo = 1;
</code></pre>
<p>There is a valid argument the expansion <em>should</em> be something like</p>
<pre class="lang-js prettyprint-override"><code>// pseudocode, this thought experiment is not valid JS
export default const Foo = 1;
// would be like
const Foo = 1;
export const default = Foo;
</code></pre>
<p>However, this then would become ambiguous per <a href="https://stackoverflow.com/questions/36261225/why-is-export-default-const-invalid/36261387?noredirect=1#comment80008351_36261387">Sergey's comment</a>, so it makes more sense to write this pattern explicitly instead.</p> | {
"question_id": 36261225,
"question_date": "2016-03-28T11:16:20.387Z",
"question_score": 598,
"tags": "javascript|scope|export|constants|default",
"answer_id": 36261387,
"answer_date": "2016-03-28T11:26:59.157Z",
"answer_score": 451
} |
Please answer the following Stack Overflow question:
Title: Why do I need an IoC container as opposed to straightforward DI code?
<p>I've been using <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer">Dependency Injection</a> (DI) for a while, injecting either in a constructor, property, or method. I've never felt a need to use an <a href="http://en.wikipedia.org/wiki/Inversion_of_control" rel="noreferrer">Inversion of Control</a> (IoC) container. However, the more I read, the more pressure I feel from the community to use an IoC container.</p>
<p>I played with .NET containers like <a href="http://docs.structuremap.net" rel="noreferrer">StructureMap</a>, <a href="http://www.ninject.org" rel="noreferrer">NInject</a>, <a href="http://unity.codeplex.com" rel="noreferrer">Unity</a>, and <a href="http://funq.codeplex.com" rel="noreferrer">Funq</a>. I still fail to see how an IoC container is going to benefit / improve my code.</p>
<p>I'm also afraid to start using a container at work because many of my co-workers will see code which they don't understand. Many of them may be reluctant to learn new technology.</p>
<p>Please, convince me that I need to use an IoC container. I'm going to use these arguments when I talk to my fellow developers at work.</p> | <p>Wow, can't believe that Joel would favor this:</p>
<pre class="lang-cs prettyprint-override"><code>var svc = new ShippingService(new ProductLocator(),
new PricingService(), new InventoryService(),
new TrackingRepository(new ConfigProvider()),
new Logger(new EmailLogger(new ConfigProvider())));
</code></pre>
<p>over this:</p>
<pre class="lang-cs prettyprint-override"><code>var svc = IoC.Resolve<IShippingService>();
</code></pre>
<p>Many folks don't realize that your dependencies chain can become nested, and it quickly becomes unwieldy to wire them up manually. Even with factories, the duplication of your code is just not worth it.</p>
<p>IoC containers can be complex, yes. But for this simple case I've shown it's incredibly easy.</p>
<hr>
<p>Okay, let's justify this even more. Let's say you have some entities or model objects that you want to bind to a smart UI. This smart UI (we'll call it Shindows Morms) wants you to implement INotifyPropertyChanged so that it can do change tracking & update the UI accordingly.</p>
<p>"OK, that doesn't sound so hard" so you start writing.</p>
<p>You start with this: </p>
<pre class="lang-cs prettyprint-override"><code>public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime CustomerSince { get; set; }
public string Status { get; set; }
}
</code></pre>
<p>..and end up with <strong>this</strong>:</p>
<pre class="lang-cs prettyprint-override"><code>public class UglyCustomer : INotifyPropertyChanged
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
string oldValue = _firstName;
_firstName = value;
if(oldValue != value)
OnPropertyChanged("FirstName");
}
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set
{
string oldValue = _lastName;
_lastName = value;
if(oldValue != value)
OnPropertyChanged("LastName");
}
}
private DateTime _customerSince;
public DateTime CustomerSince
{
get { return _customerSince; }
set
{
DateTime oldValue = _customerSince;
_customerSince = value;
if(oldValue != value)
OnPropertyChanged("CustomerSince");
}
}
private string _status;
public string Status
{
get { return _status; }
set
{
string oldValue = _status;
_status = value;
if(oldValue != value)
OnPropertyChanged("Status");
}
}
protected virtual void OnPropertyChanged(string property)
{
var propertyChanged = PropertyChanged;
if(propertyChanged != null)
propertyChanged(this, new PropertyChangedEventArgs(property));
}
public event PropertyChangedEventHandler PropertyChanged;
}
</code></pre>
<p>That's disgusting plumbing code, and I maintain that if you're writing code like that by hand <strong>you're stealing from your client</strong>. There are better, smarter way of working.</p>
<p>Ever hear that term, work smarter, not harder?</p>
<p>Well imagine some smart guy on your team came up and said: "Here's an easier way"</p>
<p>If you make your properties virtual (calm down, it's not that big of a deal) then we can <em>weave</em> in that property behavior automatically. (This is called AOP, but don't worry about the name, focus on what it's going to do for you)</p>
<p>Depending on which IoC tool you're using, you could do something that looks like this:</p>
<pre class="lang-cs prettyprint-override"><code>var bindingFriendlyInstance = IoC.Resolve<Customer>(new NotifyPropertyChangedWrapper());
</code></pre>
<p><strong>Poof!</strong> All of that manual INotifyPropertyChanged BS is now automatically generated for you, on every virtual property setter of the object in question.</p>
<p>Is this magic? <strong>YES</strong>! If you can trust the fact that this code does its job, then you can safely skip all of that property wrapping mumbo-jumbo. You've got business problems to solve.</p>
<p>Some other interesting uses of an IoC tool to do AOP:</p>
<ul>
<li>Declarative & nested database transactions</li>
<li>Declarative & nested Unit of work</li>
<li>Logging</li>
<li>Pre/Post conditions (Design by Contract)</li>
</ul> | {
"question_id": 871405,
"question_date": "2009-05-16T01:06:18.070Z",
"question_score": 598,
"tags": "dependency-injection|inversion-of-control|ioc-container",
"answer_id": 1532254,
"answer_date": "2009-10-07T15:10:50.297Z",
"answer_score": 441
} |
Please answer the following Stack Overflow question:
Title: moving changed files to another branch for check-in
<p>This often happens to me: I write some code, go to check in my changes, and then realize I'm not in the proper branch to check in those changes. However I can't switch to another branch without my changes reverting. Is there a way to move changes to another branch to be checked in there?</p> | <p><code>git stash</code> is your friend.</p>
<p>If you have not made the commit yet, just run <code>git stash</code>. This will save away all of your changes.</p>
<p>Switch to the branch you want the changes on and run <code>git stash pop</code>.</p>
<p>There are lots of uses for git stash. This is certainly one of the more useful reasons.</p>
<p>An example:</p>
<pre><code># work on some code
git stash
git checkout correct-branch
git stash pop
</code></pre>
<hr />
<p>Update: No need to use <code>stash</code> command. uncommitted changes do not belong to any branch so just use <code>git checkout -b <new-branch></code></p> | {
"question_id": 7217894,
"question_date": "2011-08-27T22:51:17.270Z",
"question_score": 598,
"tags": "git",
"answer_id": 7218106,
"answer_date": "2011-08-27T23:46:14.830Z",
"answer_score": 1076
} |
Please answer the following Stack Overflow question:
Title: What does the @ symbol before a variable name mean in C#?
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/91817/whats-the-use-meaning-of-the-character-in-variable-names-in-c">What's the use/meaning of the @ character in variable names in C#?</a> </p>
</blockquote>
<p>I understand that the @ symbol can be used before a string literal to change how the compiler parses the string. But what does it mean when a variable name is prefixed with the @ symbol?</p> | <p>The @ symbol allows you to use reserved word. For example:</p>
<pre><code>int @class = 15;
</code></pre>
<p>The above works, when the below wouldn't:</p>
<pre><code>int class = 15;
</code></pre> | {
"question_id": 429529,
"question_date": "2009-01-09T20:10:42Z",
"question_score": 598,
"tags": "c#|variables|naming|specifications|reserved-words",
"answer_id": 429534,
"answer_date": "2009-01-09T20:12:58.063Z",
"answer_score": 762
} |
Please answer the following Stack Overflow question:
Title: Find a value in an array of objects in Javascript
<p>I know similar questions have been asked before, but this one is a little different. I have an array of unnamed objects, which contain an array of named objects, and I need to get the object where "name" is "string 1". Here is an example array.</p>
<pre><code>var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
</code></pre>
<p><strong>Update:</strong> I should have said this earlier, but once I find it, I want to replace it with an edited object.</p> | <p>You can loop over the array and test for that property:</p>
<pre><code>function search(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
var resultObject = search("string 1", array);
</code></pre> | {
"question_id": 12462318,
"question_date": "2012-09-17T15:19:51.683Z",
"question_score": 597,
"tags": "javascript|arrays",
"answer_id": 12462387,
"answer_date": "2012-09-17T15:23:36.437Z",
"answer_score": 312
} |
Please answer the following Stack Overflow question:
Title: Fastest way to check if a file exists using standard C++/C++11,14,17/C?
<p>I would like to find the fastest way to check if a file exists in standard C++11, 14, 17, or C. I have thousands of files and before doing something on them I need to check if all of them exist. What can I write instead of <code>/* SOMETHING */</code> in the following function?</p>
<pre><code>inline bool exist(const std::string& name)
{
/* SOMETHING */
}
</code></pre> | <p>Well I threw together a test program that ran each of these methods 100,000 times, half on files that existed and half on files that didn't.</p>
<pre><code>#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <fstream>
inline bool exists_test0 (const std::string& name) {
ifstream f(name.c_str());
return f.good();
}
inline bool exists_test1 (const std::string& name) {
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else {
return false;
}
}
inline bool exists_test2 (const std::string& name) {
return ( access( name.c_str(), F_OK ) != -1 );
}
inline bool exists_test3 (const std::string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
</code></pre>
<p>Results for total time to run the 100,000 calls averaged over 5 runs,</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Method</th>
<th style="text-align: left;">Time</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;"><code>exists_test0</code> (ifstream)</td>
<td style="text-align: left;"><strong>0.485s</strong></td>
</tr>
<tr>
<td style="text-align: left;"><code>exists_test1</code> (FILE fopen)</td>
<td style="text-align: left;"><strong>0.302s</strong></td>
</tr>
<tr>
<td style="text-align: left;"><code>exists_test2</code> (posix access())</td>
<td style="text-align: left;"><strong>0.202s</strong></td>
</tr>
<tr>
<td style="text-align: left;"><code>exists_test3</code> (posix stat())</td>
<td style="text-align: left;"><strong>0.134s</strong></td>
</tr>
</tbody>
</table>
</div>
<p>The <code>stat()</code> function provided the best performance on my system (Linux, compiled with <code>g++</code>), with a standard <code>fopen</code> call being your best bet if you for some reason refuse to use POSIX functions.</p> | {
"question_id": 12774207,
"question_date": "2012-10-08T01:10:11.103Z",
"question_score": 597,
"tags": "c++|c|file|stream",
"answer_id": 12774387,
"answer_date": "2012-10-08T01:43:22.110Z",
"answer_score": 974
} |
Please answer the following Stack Overflow question:
Title: Testing if a checkbox is checked with jQuery
<p>If the checkbox is checked, then I only need to get the value as 1; otherwise, I need to get it as 0. How do I do this using jQuery?</p>
<p><code>$("#ans").val()</code> will always give me one right in this case:</p>
<pre><code><input type="checkbox" id="ans" value="1" />
</code></pre> | <p>Use <code>.is(':checked')</code> to determine whether or not it's checked, and then set your value accordingly.</p>
<p><a href="http://jquery-howto.blogspot.com/2008/12/how-to-check-if-checkbox-is-checked.html" rel="noreferrer">More information here.</a></p> | {
"question_id": 4813219,
"question_date": "2011-01-27T05:59:52.833Z",
"question_score": 597,
"tags": "javascript|jquery|checkbox|jquery-selectors",
"answer_id": 4813235,
"answer_date": "2011-01-27T06:03:59.067Z",
"answer_score": 1013
} |
Please answer the following Stack Overflow question:
Title: How to retrieve an element from a set without removing it?
<p>Suppose the following:</p>
<pre><code>>>> s = set([1, 2, 3])
</code></pre>
<p>How do I get a value (any value) out of <code>s</code> without doing <code>s.pop()</code>? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.</p>
<p>Quick and dirty:</p>
<pre><code>>>> elem = s.pop()
>>> s.add(elem)
</code></pre>
<p>But do you know of a better way? Ideally in constant time.</p> | <p>Two options that don't require copying the whole set:</p>
<pre><code>for e in s:
break
# e is now an element from s
</code></pre>
<p>Or...</p>
<pre><code>e = next(iter(s))
</code></pre>
<p>But in general, sets don't support indexing or slicing.</p> | {
"question_id": 59825,
"question_date": "2008-09-12T19:58:33.403Z",
"question_score": 597,
"tags": "python|set",
"answer_id": 59841,
"answer_date": "2008-09-12T20:08:10.167Z",
"answer_score": 759
} |
Please answer the following Stack Overflow question:
Title: Multi-line string with extra space (preserved indentation)
<p>I want to write some pre-defined texts to a file with the following:</p>
<pre><code>text="this is line one\n
this is line two\n
this is line three"
echo -e $text > filename
</code></pre>
<p>I'm expecting something like this:</p>
<pre><code>this is line one
this is line two
this is line three
</code></pre>
<p>But got this:</p>
<pre><code>this is line one
this is line two
this is line three
</code></pre>
<p>I'm positive that there is no space after each <code>\n</code>, but how does the extra space come out?</p> | <p>Heredoc sounds more convenient for this purpose. It is used to send multiple commands to a command interpreter program like <em>ex</em> or <em>cat</em></p>
<pre><code>cat << EndOfMessage
This is line 1.
This is line 2.
Line 3.
EndOfMessage
</code></pre>
<p>The string after <code><<</code> indicates where to stop.</p>
<p>To send these lines to a file, use:</p>
<pre><code>cat > $FILE <<- EOM
Line 1.
Line 2.
EOM
</code></pre>
<p>You could also store these lines to a variable:</p>
<pre><code>read -r -d '' VAR << EOM
This is line 1.
This is line 2.
Line 3.
EOM
</code></pre>
<p>This stores the lines to the variable named <code>VAR</code>.</p>
<p>When printing, remember the quotes around the variable otherwise you won't see the newline characters.</p>
<pre><code>echo "$VAR"
</code></pre>
<p>Even better, you can use indentation to make it stand out more in your code. This time just add a <code>-</code> after <code><<</code> to stop the tabs from appearing.</p>
<pre><code>read -r -d '' VAR <<- EOM
This is line 1.
This is line 2.
Line 3.
EOM
</code></pre>
<p>But then you must use tabs, not spaces, for indentation in your code.</p> | {
"question_id": 23929235,
"question_date": "2014-05-29T08:44:38.660Z",
"question_score": 597,
"tags": "string|bash|shell|echo",
"answer_id": 23930212,
"answer_date": "2014-05-29T09:37:12.190Z",
"answer_score": 914
} |
Please answer the following Stack Overflow question:
Title: Why is there no SortedList in Java?
<p>In Java there are the <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/SortedSet.html" rel="noreferrer"><code>SortedSet</code></a> and <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/SortedMap.html" rel="noreferrer"><code>SortedMap</code></a> interfaces. Both belong to the <a href="https://en.wikipedia.org/wiki/Java_collections_framework" rel="noreferrer">Java Collections framework</a> and provide a sorted way to access the elements. </p>
<p>However, in my understanding there is no <code>SortedList</code> in Java. You can use <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collections.html#sort(java.util.List)" rel="noreferrer"><code>java.util.Collections.sort()</code></a> to sort a list.</p>
<p>Any idea why it is designed like that?</p> | <p>List iterators guarantee first and foremost that you get the list's elements in the internal order of the list (aka. <em>insertion order</em>). More specifically it is in the order you've inserted the elements or on how you've manipulated the list. Sorting can be seen as a manipulation of the data structure, and there are several ways to sort the list.</p>
<p>I'll order the ways in the order of <em>usefulness</em> as I personally see it:</p>
<h2>1. Consider using <code>Set</code> or <code>Bag</code> collections instead</h2>
<p><strong>NOTE:</strong> I put this option at the top because this is what you normally want to do anyway.</p>
<p>A sorted set <strong>automatically sorts the collection at insertion</strong>, meaning that it does the sorting while you add elements into the collection. It also means you don't need to manually sort it.</p>
<p>Furthermore if you are sure that you don't need to worry about (or have) duplicate elements then you can use the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/TreeSet.html" rel="noreferrer"><code>TreeSet<T></code></a> instead. It implements <code>SortedSet</code> and <code>NavigableSet</code> interfaces and works as you'd probably expect from a list:</p>
<pre><code>TreeSet<String> set = new TreeSet<String>();
set.add("lol");
set.add("cat");
// automatically sorts natural order when adding
for (String s : set) {
System.out.println(s);
}
// Prints out "cat" and "lol"
</code></pre>
<p>If you don't want the natural ordering you can use the constructor parameter that takes a <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html" rel="noreferrer"><code>Comparator<T></code></a>.</p>
<p>Alternatively, you can use <strong><a href="https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Multiset.html" rel="noreferrer">Multisets</a> (also known as <em>Bags</em>)</strong>, that is a <code>Set</code> that allows duplicate elements, instead and there are third-party implementations of them. Most notably from the <a href="http://code.google.com/p/guava-libraries/" rel="noreferrer">Guava libraries</a> there is a <a href="https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/TreeMultiset.html" rel="noreferrer"><code>TreeMultiset</code></a>, that works a lot like the <code>TreeSet</code>.</p>
<h2>2. Sort your list with <code>Collections.sort()</code></h2>
<p>As mentioned above, sorting of <code>List</code>s is a manipulation of the data structure. So for situations where you need "one source of truth" that will be sorted in a variety of ways then sorting it manually is the way to go.</p>
<p>You can sort your list with the <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List)" rel="noreferrer"><code>java.util.Collections.sort()</code></a> method. Here is a code sample on how:</p>
<pre><code>List<String> strings = new ArrayList<String>()
strings.add("lol");
strings.add("cat");
Collections.sort(strings);
for (String s : strings) {
System.out.println(s);
}
// Prints out "cat" and "lol"
</code></pre>
<h3>Using comparators</h3>
<p>One clear benefit is that you may use <a href="https://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html" rel="noreferrer"><code>Comparator</code></a> in the <code>sort</code> method. Java also provides some implementations for the <code>Comparator</code> such as the <a href="https://docs.oracle.com/javase/6/docs/api/java/text/Collator.html" rel="noreferrer"><code>Collator</code></a> which is useful for locale sensitive sorting strings. Here is one example:</p>
<pre><code>Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY); // ignores casing
Collections.sort(strings, usCollator);
</code></pre>
<h3>Sorting in concurrent environments</h3>
<p>Do note though that using the <code>sort</code> method is not friendly in concurrent environments, since the collection instance will be manipulated, and you should consider using immutable collections instead. This is something Guava provides in the <a href="https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/collect/Ordering.html" rel="noreferrer"><code>Ordering</code></a> class and is a simple one-liner:</p>
<pre><code>List<string> sorted = Ordering.natural().sortedCopy(strings);
</code></pre>
<h2>3. Wrap your list with <code>java.util.PriorityQueue</code></h2>
<p>Though there is no sorted list in Java there is however a sorted queue which would probably work just as well for you. It is the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/PriorityQueue.html" rel="noreferrer"><code>java.util.PriorityQueue</code></a> class.</p>
<p>Nico Haase linked in the comments to a <a href="https://stackoverflow.com/questions/416266/sorted-collection-in-java">related question</a> that also answers this.</p>
<p>In a sorted collection <strong>you most likely don't want to manipulate</strong> the internal data structure which is why PriorityQueue doesn't implement the List interface (because that would give you direct access to its elements). </p>
<h3>Caveat on the <code>PriorityQueue</code> iterator</h3>
<p>The <code>PriorityQueue</code> class implements the <code>Iterable<E></code> and <code>Collection<E></code> interfaces so it can be iterated as usual. However, the iterator is not guaranteed to return elements in the sorted order. Instead (as Alderath points out in the comments) you need to <code>poll()</code> the queue until empty.</p>
<p>Note that you can convert a list to a priority queue via the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/PriorityQueue.html#PriorityQueue%28java.util.Collection%29" rel="noreferrer">constructor that takes any collection</a>:</p>
<pre><code>List<String> strings = new ArrayList<String>()
strings.add("lol");
strings.add("cat");
PriorityQueue<String> sortedStrings = new PriorityQueue(strings);
while(!sortedStrings.isEmpty()) {
System.out.println(sortedStrings.poll());
}
// Prints out "cat" and "lol"
</code></pre>
<h2>4. Write your own <code>SortedList</code> class</h2>
<p><strong>NOTE:</strong> You shouldn't have to do this.</p>
<p>You can write your own List class that sorts each time you add a new element. This can get rather computation heavy depending on your implementation <strong>and is pointless</strong>, unless you want to do it as an exercise, because of two main reasons: </p>
<ol>
<li>It breaks the contract that <code>List<E></code> interface has because the <code>add</code> methods should ensure that the element will reside in the index that the user specifies.</li>
<li>Why reinvent the wheel? You should be using the TreeSet or Multisets instead as pointed out in the first point above.</li>
</ol>
<p>However, if you want to do it as an exercise here is a code sample to get you started, it uses the <code>AbstractList</code> abstract class: </p>
<pre><code>public class SortedList<E> extends AbstractList<E> {
private ArrayList<E> internalList = new ArrayList<E>();
// Note that add(E e) in AbstractList is calling this one
@Override
public void add(int position, E e) {
internalList.add(e);
Collections.sort(internalList, null);
}
@Override
public E get(int i) {
return internalList.get(i);
}
@Override
public int size() {
return internalList.size();
}
}
</code></pre>
<p>Note that if you haven't overridden the methods you need, then the default implementations from <code>AbstractList</code> will throw <code>UnsupportedOperationException</code>s.</p> | {
"question_id": 8725387,
"question_date": "2012-01-04T10:35:53.513Z",
"question_score": 597,
"tags": "java|sorting|collections",
"answer_id": 8725470,
"answer_date": "2012-01-04T10:41:01.557Z",
"answer_score": 777
} |
Please answer the following Stack Overflow question:
Title: Automatically accept all SDK licences
<p>Since gradle android plugins <a href="https://sites.google.com/a/android.com/tools/tech-docs/new-build-system" rel="noreferrer">2.2-alpha4</a>:</p>
<blockquote>
<p>Gradle will attempt to download missing SDK packages that a project
depends on</p>
</blockquote>
<p>Which is amazingly cool and was know to be a <a href="https://github.com/JakeWharton/sdk-manager-plugin" rel="noreferrer">JakeWharton project</a>.</p>
<p>But, to download the SDK library you need to: accept the license agreements or gradle tells you:</p>
<blockquote>
<p>You have not accepted the license agreements of the following SDK
components: [Android SDK Build-Tools 24, Android SDK Platform 24].
Before building your project, you need to accept the license
agreements and complete the installation of the missing components
using the Android Studio SDK Manager. Alternatively, to learn how to
transfer the license agreements from one workstation to another, go to
<a href="http://d.android.com/r/studio-ui/export-licenses.html" rel="noreferrer">http://d.android.com/r/studio-ui/export-licenses.html</a></p>
</blockquote>
<p>And this is a problem because I would love to install all sdk dependencies while doing a <code>gradle build</code>.</p>
<p>I am looking for a solution to automatically accept all licenses. Maybe a gradle script ?
Do you have any ideas ?</p> | <p><strong>UPDATE 2021</strong>
<a href="https://stackoverflow.com/a/65372165/1155507">This</a> should be the accepted answer as its easy and upto date</p>
<hr>
<p>AndroidSDK can finally accept licenses.</p>
<p>Go to <code>Android\sdk\tools\bin</code></p>
<pre><code>yes | sdkmanager --licenses
</code></pre>
<p>EDIT:</p>
<p>as pointed out in the comments by @MoOx, on macOS, you can do</p>
<p><code>yes | sudo ~/Library/Android/sdk/tools/bin/sdkmanager --licenses</code></p>
<p>as pointed out in the comments by @pho, @mikebridge and @ Noitidart on Windows, you can do</p>
<p><code>cmd.exe /C"%ANDROID_HOME%\tools\bin\sdkmanager.bat --licenses" </code></p>
<p>be sure to install java before</p> | {
"question_id": 38096225,
"question_date": "2016-06-29T09:56:41.827Z",
"question_score": 597,
"tags": "android|gradle|sdk|android-gradle-plugin|android-sdk-tools",
"answer_id": 45782695,
"answer_date": "2017-08-20T13:33:03.390Z",
"answer_score": 523
} |
Please answer the following Stack Overflow question:
Title: Using jQuery to test if an input has focus
<p>On the front page of a site I am building, several <code><div></code>s use the CSS <code>:hover</code> pseudo-class to add a border when the mouse is over them. One of the <code><div></code>s contains a <code><form></code> which, using jQuery, will keep the border if an input within it has focus. This works perfectly except that IE6 does not support <code>:hover</code> on any elements other than <code><a></code>s. So, for this browser only we are using jQuery to mimic CSS <code>:hover</code> using the <code>$(#element).hover()</code> method. The only problem is, now that jQuery handles both the form <code>focus()</code> <em>and</em> <code>hover()</code>, when an input has focus then the user moves the mouse in and out, the border goes away.</p>
<p>I was thinking we could use some kind of conditional to stop this behavior. For instance, if we tested on mouse out if any of the inputs had focus, we could stop the border from going away. AFAIK, there is no <code>:focus</code> selector in jQuery, so I'm not sure how to make this happen. Any ideas?</p> | <h2>jQuery 1.6+</h2>
<p>jQuery added a <a href="http://api.jquery.com/focus-selector/" rel="noreferrer"><code>:focus</code></a> selector so we no longer need to add it ourselves. Just use <code>$("..").is(":focus")</code></p>
<h2>jQuery 1.5 and below</h2>
<p><strong>Edit:</strong> As times change, we find better methods for testing focus, the new favorite is <a href="https://gist.github.com/450017" rel="noreferrer">this gist from Ben Alman</a>:</p>
<pre><code>jQuery.expr[':'].focus = function( elem ) {
return elem === document.activeElement && ( elem.type || elem.href );
};
</code></pre>
<p>Quoted from Mathias Bynens <a href="https://stackoverflow.com/questions/967096/using-jquery-to-test-if-an-input-has-focus/5391608#5391608">here</a>:</p>
<blockquote>
<p>Note that the <code>(elem.type || elem.href)</code> test was added to filter out false positives like body. This way, we make sure to filter out all elements except form controls and hyperlinks.</p>
</blockquote>
<p>You're defining a new selector. See <a href="http://docs.jquery.com/Plugins/Authoring" rel="noreferrer">Plugins/Authoring</a>. Then you can do:</p>
<pre><code>if ($("...").is(":focus")) {
...
}
</code></pre>
<p>or:</p>
<pre><code>$("input:focus").doStuff();
</code></pre>
<h2>Any jQuery</h2>
<p>If you just want to figure out which element has focus, you can use </p>
<pre><code>$(document.activeElement)
</code></pre>
<p>If you aren't sure if the version will be 1.6 or lower, you can add the <code>:focus</code> selector if it is missing:</p>
<pre><code>(function ( $ ) {
var filters = $.expr[":"];
if ( !filters.focus ) {
filters.focus = function( elem ) {
return elem === document.activeElement && ( elem.type || elem.href );
};
}
})( jQuery );
</code></pre> | {
"question_id": 967096,
"question_date": "2009-06-08T21:21:01.407Z",
"question_score": 597,
"tags": "javascript|jquery|jquery-events|jquery-on",
"answer_id": 2684561,
"answer_date": "2010-04-21T16:04:18.013Z",
"answer_score": 987
} |
Please answer the following Stack Overflow question:
Title: SQLAlchemy ORDER BY DESCENDING?
<p>How can I use ORDER BY <code>descending</code> in a SQLAlchemy query like the following?</p>
<p>This query works, but returns them in ascending order:</p>
<pre class="lang-py prettyprint-override"><code>query = (model.Session.query(model.Entry)
.join(model.ClassificationItem)
.join(model.EnumerationValue)
.filter_by(id=c.row.id)
.order_by(model.Entry.amount) # This row :)
)
</code></pre>
<p>If I try:</p>
<pre><code>.order_by(desc(model.Entry.amount))
</code></pre>
<p>then I get: <code>NameError: global name 'desc' is not defined</code>.</p> | <pre><code>from sqlalchemy import desc
someselect.order_by(desc(table1.mycol))
</code></pre>
<p><a href="http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.desc" rel="noreferrer">Usage</a> from @jpmc26</p> | {
"question_id": 4186062,
"question_date": "2010-11-15T15:47:42.107Z",
"question_score": 597,
"tags": "python|sqlalchemy",
"answer_id": 4186078,
"answer_date": "2010-11-15T15:49:04.167Z",
"answer_score": 417
} |
Please answer the following Stack Overflow question:
Title: How to reset Django admin password?
<p>I am using Django (version 1.3) and have forgotten both admin username and password. How to reset both?</p>
<p>And is it possible to make a normal user into admin, and then remove admin status?</p> | <pre><code>python manage.py changepassword <user_name>
</code></pre>
<p><a href="https://docs.djangoproject.com/en/stable/topics/auth/default/#changing-passwords" rel="noreferrer">see docs</a> </p> | {
"question_id": 6358030,
"question_date": "2011-06-15T13:00:02.103Z",
"question_score": 597,
"tags": "django|authentication|permissions|passwords|django-admin",
"answer_id": 6358121,
"answer_date": "2011-06-15T13:07:14.370Z",
"answer_score": 1066
} |
Please answer the following Stack Overflow question:
Title: In practice, what are the main uses for the "yield from" syntax in Python 3.3?
<p>I'm having a hard time wrapping my brain around <a href="http://www.python.org/dev/peps/pep-0380/" rel="noreferrer">PEP 380</a>.</p>
<ol>
<li>What are the situations where <code>yield from</code> is useful?</li>
<li>What is the classic use case?</li>
<li>Why is it compared to micro-threads?</li>
</ol>
<p>So far I have used generators, but never really used coroutines (introduced by <a href="http://www.python.org/dev/peps/pep-0342/" rel="noreferrer">PEP-342</a>). Despite some similarities, generators and coroutines are basically two different concepts. Understanding coroutines (not only generators) is the key to understanding the new syntax.</p>
<p>IMHO <strong>coroutines are the most obscure Python feature</strong>, most books make it look useless and uninteresting.</p>
<hr />
<p>Thanks for the great answers, but special thanks to <a href="https://stackoverflow.com/users/500584/agf">agf</a> and his comment linking to <a href="http://www.dabeaz.com/coroutines/" rel="noreferrer">David Beazley presentations</a>.</p> | <p>Let's get one thing out of the way first. The explanation that <code>yield from g</code> is equivalent to <code>for v in g: yield v</code> <strong>does not even begin to do justice</strong> to what <code>yield from</code> is all about. Because, let's face it, if all <code>yield from</code> does is expand the <code>for</code> loop, then it does not warrant adding <code>yield from</code> to the language and preclude a whole bunch of new features from being implemented in Python 2.x.</p>
<p>What <code>yield from</code> does is it <strong><em>establishes a transparent bidirectional connection between the caller and the sub-generator</em></strong>:</p>
<ul>
<li><p>The connection is "transparent" in the sense that it will propagate everything correctly too, not just the elements being generated (e.g. exceptions are propagated).</p></li>
<li><p>The connection is "bidirectional" in the sense that data can be both sent <em>from</em> and <em>to</em> a generator.</p></li>
</ul>
<p>(<em>If we were talking about TCP, <code>yield from g</code> might mean "now temporarily disconnect my client's socket and reconnect it to this other server socket".</em>)</p>
<p>BTW, if you are not sure what <em>sending data to a generator</em> even means, you need to drop everything and read about <em>coroutines</em> first—they're very useful (contrast them with <em>subroutines</em>), but unfortunately lesser-known in Python. <a href="http://dabeaz.com/coroutines/" rel="noreferrer">Dave Beazley's Curious Course on Coroutines</a> is an excellent start. <a href="http://dabeaz.com/coroutines/Coroutines.pdf" rel="noreferrer">Read slides 24-33</a> for a quick primer.</p>
<h2>Reading data from a generator using yield from</h2>
<pre><code>def reader():
"""A generator that fakes a read from a file, socket, etc."""
for i in range(4):
yield '<< %s' % i
def reader_wrapper(g):
# Manually iterate over data produced by reader
for v in g:
yield v
wrap = reader_wrapper(reader())
for i in wrap:
print(i)
# Result
<< 0
<< 1
<< 2
<< 3
</code></pre>
<p>Instead of manually iterating over <code>reader()</code>, we can just <code>yield from</code> it.</p>
<pre><code>def reader_wrapper(g):
yield from g
</code></pre>
<p>That works, and we eliminated one line of code. And probably the intent is a little bit clearer (or not). But nothing life changing.</p>
<h2>Sending data to a generator (coroutine) using yield from - Part 1</h2>
<p>Now let's do something more interesting. Let's create a coroutine called <code>writer</code> that accepts data sent to it and writes to a socket, fd, etc.</p>
<pre><code>def writer():
"""A coroutine that writes data *sent* to it to fd, socket, etc."""
while True:
w = (yield)
print('>> ', w)
</code></pre>
<p>Now the question is, how should the wrapper function handle sending data to the writer, so that any data that is sent to the wrapper is <em>transparently</em> sent to the <code>writer()</code>?</p>
<pre><code>def writer_wrapper(coro):
# TBD
pass
w = writer()
wrap = writer_wrapper(w)
wrap.send(None) # "prime" the coroutine
for i in range(4):
wrap.send(i)
# Expected result
>> 0
>> 1
>> 2
>> 3
</code></pre>
<p>The wrapper needs to <em>accept</em> the data that is sent to it (obviously) and should also handle the <code>StopIteration</code> when the for loop is exhausted. Evidently just doing <code>for x in coro: yield x</code> won't do. Here is a version that works.</p>
<pre><code>def writer_wrapper(coro):
coro.send(None) # prime the coro
while True:
try:
x = (yield) # Capture the value that's sent
coro.send(x) # and pass it to the writer
except StopIteration:
pass
</code></pre>
<p>Or, we could do this.</p>
<pre><code>def writer_wrapper(coro):
yield from coro
</code></pre>
<p>That saves 6 lines of code, make it much much more readable and it just works. Magic!</p>
<h2>Sending data to a generator yield from - Part 2 - Exception handling</h2>
<p>Let's make it more complicated. What if our writer needs to handle exceptions? Let's say the <code>writer</code> handles a <code>SpamException</code> and it prints <code>***</code> if it encounters one.</p>
<pre><code>class SpamException(Exception):
pass
def writer():
while True:
try:
w = (yield)
except SpamException:
print('***')
else:
print('>> ', w)
</code></pre>
<p>What if we don't change <code>writer_wrapper</code>? Does it work? Let's try</p>
<pre><code># writer_wrapper same as above
w = writer()
wrap = writer_wrapper(w)
wrap.send(None) # "prime" the coroutine
for i in [0, 1, 2, 'spam', 4]:
if i == 'spam':
wrap.throw(SpamException)
else:
wrap.send(i)
# Expected Result
>> 0
>> 1
>> 2
***
>> 4
# Actual Result
>> 0
>> 1
>> 2
Traceback (most recent call last):
... redacted ...
File ... in writer_wrapper
x = (yield)
__main__.SpamException
</code></pre>
<p>Um, it's not working because <code>x = (yield)</code> just raises the exception and everything comes to a crashing halt. Let's make it work, but manually handling exceptions and sending them or throwing them into the sub-generator (<code>writer</code>)</p>
<pre><code>def writer_wrapper(coro):
"""Works. Manually catches exceptions and throws them"""
coro.send(None) # prime the coro
while True:
try:
try:
x = (yield)
except Exception as e: # This catches the SpamException
coro.throw(e)
else:
coro.send(x)
except StopIteration:
pass
</code></pre>
<p>This works.</p>
<pre><code># Result
>> 0
>> 1
>> 2
***
>> 4
</code></pre>
<p>But so does this!</p>
<pre><code>def writer_wrapper(coro):
yield from coro
</code></pre>
<p>The <code>yield from</code> transparently handles sending the values or throwing values into the sub-generator.</p>
<p>This still does not cover all the corner cases though. What happens if the outer generator is closed? What about the case when the sub-generator returns a value (yes, in Python 3.3+, generators can return values), how should the return value be propagated? <a href="https://www.python.org/dev/peps/pep-0380/#formal-semantics" rel="noreferrer">That <code>yield from</code> transparently handles all the corner cases is really impressive</a>. <code>yield from</code> just magically works and handles all those cases.</p>
<p>I personally feel <code>yield from</code> is a poor keyword choice because it does not make the <em>two-way</em> nature apparent. There were other keywords proposed (like <code>delegate</code> but were rejected because adding a new keyword to the language is much more difficult than combining existing ones.</p>
<p>In summary, it's best to think of <code>yield from</code> as a <strong><code>transparent two way channel</code></strong> between the caller and the sub-generator.</p>
<p>References:</p>
<ol>
<li><a href="http://www.python.org/dev/peps/pep-0380/" rel="noreferrer">PEP 380</a> - Syntax for delegating to a sub-generator (Ewing) [v3.3, 2009-02-13]</li>
<li><a href="http://www.python.org/dev/peps/pep-0342/" rel="noreferrer">PEP 342</a> -
Coroutines via Enhanced Generators (GvR, Eby) [v2.5, 2005-05-10]</li>
</ol> | {
"question_id": 9708902,
"question_date": "2012-03-14T19:33:41.833Z",
"question_score": 597,
"tags": "python|yield",
"answer_id": 26109157,
"answer_date": "2014-09-29T21:22:57.877Z",
"answer_score": 884
} |
Please answer the following Stack Overflow question:
Title: SQLAlchemy: What's the difference between flush() and commit()?
<p>What the difference is between <code>flush()</code> and <code>commit()</code> in SQLAlchemy?</p>
<p>I've read the docs, but am none the wiser - they seem to assume a pre-understanding that I don't have.</p>
<p>I'm particularly interested in their impact on memory usage. I'm loading some data into a database from a series of files (around 5 million rows in total) and my session is occasionally falling over - it's a large database and a machine with not much memory. </p>
<p>I'm wondering if I'm using too many <code>commit()</code> and not enough <code>flush()</code> calls - but without really understanding what the difference is, it's hard to tell!</p> | <p>A Session object is basically an ongoing transaction of changes to a database (update, insert, delete). These operations aren't persisted to the database until they are committed (if your program aborts for some reason in mid-session transaction, any uncommitted changes within are lost).</p>
<p>The session object registers transaction operations with <code>session.add()</code>, but doesn't yet communicate them to the database until <code>session.flush()</code> is called. </p>
<p><code>session.flush()</code> communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction. The changes aren't persisted permanently to disk, or visible to other transactions until the database receives a COMMIT for the current transaction (which is what <code>session.commit()</code> does).</p>
<p><code>session.commit()</code> commits (persists) those changes to the database.</p>
<p><code>flush()</code> is <em>always</em> called as part of a call to <code>commit()</code> (<a href="http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#committing" rel="noreferrer">1</a>).</p>
<p>When you use a Session object to query the database, the query will return results both from the database and from the flushed parts of the uncommitted transaction it holds. By default, Session objects <code>autoflush</code> their operations, but this can be disabled.</p>
<p>Hopefully this example will make this clearer:</p>
<pre><code>#---
s = Session()
s.add(Foo('A')) # The Foo('A') object has been added to the session.
# It has not been committed to the database yet,
# but is returned as part of a query.
print 1, s.query(Foo).all()
s.commit()
#---
s2 = Session()
s2.autoflush = False
s2.add(Foo('B'))
print 2, s2.query(Foo).all() # The Foo('B') object is *not* returned
# as part of this query because it hasn't
# been flushed yet.
s2.flush() # Now, Foo('B') is in the same state as
# Foo('A') was above.
print 3, s2.query(Foo).all()
s2.rollback() # Foo('B') has not been committed, and rolling
# back the session's transaction removes it
# from the session.
print 4, s2.query(Foo).all()
#---
Output:
1 [<Foo('A')>]
2 [<Foo('A')>]
3 [<Foo('A')>, <Foo('B')>]
4 [<Foo('A')>]
</code></pre> | {
"question_id": 4201455,
"question_date": "2010-11-17T04:20:20.037Z",
"question_score": 597,
"tags": "python|sqlalchemy",
"answer_id": 4202016,
"answer_date": "2010-11-17T06:25:24.477Z",
"answer_score": 766
} |
Please answer the following Stack Overflow question:
Title: String comparison in Python: is vs. ==
<p>I noticed a Python script I was writing was acting squirrelly, and traced it to an infinite loop, where the loop condition was <code>while line is not ''</code>. Running through it in the debugger, it turned out that line was in fact <code>''</code>. When I changed it to <code>!=''</code> rather than <code>is not ''</code>, it worked fine. </p>
<p>Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values? I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id.</p> | <blockquote>
<p>For all built-in Python objects (like
strings, lists, dicts, functions,
etc.), if x is y, then x==y is also
True.</p>
</blockquote>
<p>Not always. NaN is a counterexample. But <em>usually</em>, identity (<code>is</code>) implies equality (<code>==</code>). The converse is not true: Two distinct objects can have the same value.</p>
<blockquote>
<p>Also, is it generally considered better to just use '==' by default, even
when comparing int or Boolean values?</p>
</blockquote>
<p>You use <code>==</code> when comparing values and <code>is</code> when comparing identities.</p>
<p>When comparing ints (or immutable types in general), you pretty much always want the former. There's an optimization that allows small integers to be compared with <code>is</code>, but don't rely on it.</p>
<p>For boolean values, you shouldn't be doing comparisons at all. Instead of:</p>
<pre><code>if x == True:
# do something
</code></pre>
<p>write:</p>
<pre><code>if x:
# do something
</code></pre>
<p>For comparing against <code>None</code>, <code>is None</code> is preferred over <code>== None</code>.</p>
<blockquote>
<p>I've always liked to use 'is' because
I find it more aesthetically pleasing
and pythonic (which is how I fell into
this trap...), but I wonder if it's
intended to just be reserved for when
you care about finding two objects
with the same id.</p>
</blockquote>
<p>Yes, that's exactly what it's for.</p> | {
"question_id": 2988017,
"question_date": "2010-06-07T08:31:49.237Z",
"question_score": 596,
"tags": "python|string|comparison|equality",
"answer_id": 2988117,
"answer_date": "2010-06-07T08:53:45.950Z",
"answer_score": 657
} |
Please answer the following Stack Overflow question:
Title: Smooth scrolling when clicking an anchor link
<p>I have a couple of hyperlinks on my page. A FAQ that users will read when they visit my help section.</p>
<p>Using Anchor links, I can make the page scroll towards the anchor and guide the users there.</p>
<p>Is there a way to make that scrolling smooth?</p>
<p>But notice that he's using a custom JavaScript library. Maybe jQuery offers somethings like this baked in?</p> | <p>No need any js just use scroll-behavior: smooth at html tag Thats it</p>
<pre><code>html{
scroll-behavior: smooth;
}
</code></pre> | {
"question_id": 7717527,
"question_date": "2011-10-10T19:19:34.713Z",
"question_score": 596,
"tags": "javascript|jquery|scroll|hyperlink|anchor",
"answer_id": 71674163,
"answer_date": "2022-03-30T08:45:41.163Z",
"answer_score": 12
} |
Please answer the following Stack Overflow question:
Title: What are CN, OU, DC in an LDAP search?
<p>I have a search query in LDAP like this. What exactly does this query mean?</p>
<pre><code>("CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com");
</code></pre> | <ul>
<li><code>CN</code> = Common Name</li>
<li><code>OU</code> = Organizational Unit</li>
<li><code>DC</code> = Domain Component</li>
</ul>
<p>These are all parts of the X.500 Directory Specification, which defines nodes in a LDAP directory.</p>
<p>You can also read up on <a href="http://en.wikipedia.org/wiki/LDAP_Data_Interchange_Format" rel="noreferrer">LDAP data Interchange Format (<code>LDIF</code>)</a>, which is an alternate format.</p>
<p>You read it from right to left, the right-most component is the root of the tree, and the left most component is the node (or leaf) you want to reach.</p>
<p>Each <code>=</code> pair is a search criteria.</p>
<p>With your example query</p>
<pre><code>("CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com");
</code></pre>
<p>In effect the query is:</p>
<p>From the <code>com</code> Domain Component, find the <code>google</code> Domain Component, and then inside it the <code>gl</code> Domain Component and then inside it the <code>gp</code> Domain Component.</p>
<p>In the <code>gp</code> Domain Component, find the Organizational Unit called <code>Distribution Groups</code> and then find the object that has a common name of <code>Dev-India</code>.</p> | {
"question_id": 18756688,
"question_date": "2013-09-12T06:16:06.253Z",
"question_score": 596,
"tags": "active-directory|ldap|ldap-query",
"answer_id": 18756876,
"answer_date": "2013-09-12T06:27:13.483Z",
"answer_score": 984
} |
Please answer the following Stack Overflow question:
Title: How to wrap text in LaTeX tables?
<p>I am creating a report in LaTeX which involves a few tables. I'm stuck on that as my cell data in the table is exceeding the width of the page. Can I somehow wrap the text so that it falls into the next line in the same cell of the table?</p>
<p>Is it somehow related to the table's width? But as it's overshooting the page's width, will it make a difference?</p> | <p>Use p{width} for your column specifiers instead of l/r/c.</p>
<pre><code>\begin{tabular}{|p{1cm}|p{3cm}|}
This text will be wrapped & Some more text \\
\end{tabular}
</code></pre>
<hr />
<p>EDIT: (based on the comments)</p>
<pre><code>\begin{table}[ht]
\centering
\begin{tabular}{p{0.35\linewidth} | p{0.6\linewidth}}
Column 1 & Column2 \\ \hline
This text will be wrapped & Some more text \\
Some text here & This text maybe wrapped here if its tooooo long \\
\end{tabular}
\caption{Caption}
\label{tab:my_label}
\end{table}
</code></pre>
<p>we get:</p>
<p><a href="https://i.stack.imgur.com/XHn2Z.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XHn2Z.png" alt="enter image description here" /></a></p> | {
"question_id": 790932,
"question_date": "2009-04-26T14:26:47.683Z",
"question_score": 596,
"tags": "text|latex|word-wrap",
"answer_id": 790944,
"answer_date": "2009-04-26T14:32:46.517Z",
"answer_score": 708
} |
Please answer the following Stack Overflow question:
Title: Parse (split) a string in C++ using string delimiter (standard C++)
<p>I am parsing a string in C++ using the following:</p>
<pre><code>using namespace std;
string parsed,input="text to be parsed";
stringstream input_stringstream(input);
if (getline(input_stringstream,parsed,' '))
{
// do some processing.
}
</code></pre>
<p>Parsing with a single char delimiter is fine. But what if I want to use a string as delimiter.</p>
<p>Example: I want to split:</p>
<pre><code>scott>=tiger
</code></pre>
<p>with <code>>=</code> as delimiter so that I can get scott and tiger. </p> | <p>You can use the <a href="http://en.cppreference.com/w/cpp/string/basic_string/find"><code>std::string::find()</code></a> function to find the position of your string delimiter, then use <a href="http://en.cppreference.com/w/cpp/string/basic_string/substr"><code>std::string::substr()</code></a> to get a token.</p>
<p>Example:</p>
<pre><code>std::string s = "scott>=tiger";
std::string delimiter = ">=";
std::string token = s.substr(0, s.find(delimiter)); // token is "scott"
</code></pre>
<ul>
<li><p>The <code>find(const string& str, size_t pos = 0)</code> function returns the position of the first occurrence of <code>str</code> in the string, or <a href="http://en.cppreference.com/w/cpp/string/basic_string/npos"><code>npos</code></a> if the string is not found.</p></li>
<li><p>The <code>substr(size_t pos = 0, size_t n = npos)</code> function returns a substring of the object, starting at position <code>pos</code> and of length <code>npos</code>.</p></li>
</ul>
<hr>
<p>If you have multiple delimiters, after you have extracted one token, you can remove it (delimiter included) to proceed with subsequent extractions (if you want to preserve the original string, just use <code>s = s.substr(pos + delimiter.length());</code>):</p>
<pre><code>s.erase(0, s.find(delimiter) + delimiter.length());
</code></pre>
<p>This way you can easily loop to get each token.</p>
<h2> Complete Example </h2>
<pre><code>std::string s = "scott>=tiger>=mushroom";
std::string delimiter = ">=";
size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << token << std::endl;
s.erase(0, pos + delimiter.length());
}
std::cout << s << std::endl;
</code></pre>
<p>Output:</p>
<pre><code>scott
tiger
mushroom
</code></pre> | {
"question_id": 14265581,
"question_date": "2013-01-10T19:16:43.900Z",
"question_score": 595,
"tags": "c++|parsing|split|token|tokenize",
"answer_id": 14266139,
"answer_date": "2013-01-10T19:53:17.483Z",
"answer_score": 884
} |
Please answer the following Stack Overflow question:
Title: Get screen width and height in Android
<p>How can I get the screen width and height and use this value in:</p>
<pre><code>@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
Log.e(TAG, "onMeasure" + widthSpecId);
setMeasuredDimension(SCREEN_WIDTH, SCREEN_HEIGHT -
game.findViewById(R.id.flag).getHeight());
}
</code></pre> | <p>Using this code, you can get the runtime display's width & height:</p>
<pre><code>DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
</code></pre>
<hr>
<p>In a view you need to do something like this: </p>
<pre><code>((Activity) getContext()).getWindowManager()
.getDefaultDisplay()
.getMetrics(displayMetrics);
</code></pre>
<hr>
<p>In some scenarios, where devices have a navigation bar, you have to check at runtime:</p>
<pre><code>public boolean showNavigationBar(Resources resources)
{
int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
return id > 0 && resources.getBoolean(id);
}
</code></pre>
<p>If the device has a navigation bar, then count its height:</p>
<pre><code>private int getNavigationBarHeight() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int usableHeight = metrics.heightPixels;
getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
int realHeight = metrics.heightPixels;
if (realHeight > usableHeight)
return realHeight - usableHeight;
else
return 0;
}
return 0;
}
</code></pre>
<p>So the final height of the device is:</p>
<pre><code>int height = displayMetrics.heightPixels + getNavigationBarHeight();
</code></pre> | {
"question_id": 4743116,
"question_date": "2011-01-20T03:17:00.677Z",
"question_score": 595,
"tags": "android",
"answer_id": 4744499,
"answer_date": "2011-01-20T07:28:15.463Z",
"answer_score": 1188
} |
Please answer the following Stack Overflow question:
Title: Replace Line Breaks in a String C#
<p>How can I replace Line Breaks within a string in C#?</p> | <p>Use replace with <code>Environment.NewLine</code></p>
<pre><code>myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ;
</code></pre>
<p>As mentioned in other posts, if the string comes from another environment (OS) then you'd need to replace that particular environments implementation of <a href="http://en.wikipedia.org/wiki/Newline" rel="noreferrer">new line control characters</a>.</p> | {
"question_id": 238002,
"question_date": "2008-10-26T13:20:10.757Z",
"question_score": 595,
"tags": "c#|.net|string",
"answer_id": 238020,
"answer_date": "2008-10-26T13:38:57.723Z",
"answer_score": 798
} |
Please answer the following Stack Overflow question:
Title: Expansion of variables inside single quotes in a command in Bash
<p>I want to run a command from a <em>bash script</em> which has single quotes and some other commands inside the single quotes and a variable.</p>
<p>e.g. <code>repo forall -c '....$variable'</code></p>
<p>In this format, <code>$</code> is escaped and the variable is not expanded.</p>
<p>I tried the following variations but they were rejected:</p>
<pre><code>repo forall -c '...."$variable" '
repo forall -c " '....$variable' "
" repo forall -c '....$variable' "
repo forall -c "'" ....$variable "'"
</code></pre>
<p>If I substitute the value in place of the variable the command is executed just fine.</p>
<p>Please tell me where am I going wrong.</p> | <p>Inside single quotes everything is preserved literally, without exception.</p>
<p>That means you have to close the quotes, insert something, and then re-enter again.</p>
<pre><code>'before'"$variable"'after'
'before'"'"'after'
'before'\''after'
</code></pre>
<p>Word concatenation is simply done by juxtaposition. As you can verify, each of the above lines is a single word to the shell. Quotes (single or double quotes, depending on the situation) don't isolate words. They are only used to disable interpretation of various special characters, like whitespace, <code>$</code>, <code>;</code>... For a good tutorial on quoting see Mark Reed's answer. Also relevant: <a href="https://stackoverflow.com/questions/15783701/which-characters-need-to-be-escaped-in-bash-how-do-we-know-it/20053121">Which characters need to be escaped in bash?</a></p>
<h2>Do not concatenate strings interpreted by a shell</h2>
<p>You should absolutely avoid building shell commands by concatenating variables. This is a bad idea similar to concatenation of SQL fragments (SQL injection!).</p>
<p>Usually it is possible to have placeholders in the command, and to supply the command together with variables so that the callee can receive them from the invocation arguments list.</p>
<p>For example, the following is very unsafe. DON'T DO THIS</p>
<pre><code>script="echo \"Argument 1 is: $myvar\""
/bin/sh -c "$script"
</code></pre>
<p>If the contents of <code>$myvar</code> is untrusted, here is an exploit:</p>
<pre><code>myvar='foo"; echo "you were hacked'
</code></pre>
<p>Instead of the above invocation, use positional arguments. The following invocation is better -- it's not exploitable:</p>
<pre><code>script='echo "arg 1 is: $1"'
/bin/sh -c "$script" -- "$myvar"
</code></pre>
<p>Note the use of single ticks in the assignment to <code>script</code>, which means that it's taken literally, without variable expansion or any other form of interpretation.</p> | {
"question_id": 13799789,
"question_date": "2012-12-10T11:10:13.903Z",
"question_score": 595,
"tags": "bash|shell|variables|quotes",
"answer_id": 13802438,
"answer_date": "2012-12-10T14:00:30.803Z",
"answer_score": 911
} |
Please answer the following Stack Overflow question:
Title: Insert new item in array on any position in PHP
<p>How can I insert a new item into an array on any position, for example in the middle of array?</p> | <p>You may find this a little more intuitive. It only requires one function call to <a href="http://www.php.net/manual/en/function.array-splice.php" rel="noreferrer"><code>array_splice</code></a>:</p>
<pre><code>$original = array( 'a', 'b', 'c', 'd', 'e' );
$inserted = array( 'x' ); // not necessarily an array, see manual quote
array_splice( $original, 3, 0, $inserted ); // splice in at position 3
// $original is now a b c x d e
</code></pre>
<blockquote>
<p>If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL.</p>
</blockquote>
<blockquote>
<p>RETURN VALUE: To be noted that the function does <em>not</em> return the desired substitution. The <code>$original</code> is passed by reference and edited in place. See the expression <code>array &$array</code> with <code>&</code> in the <a href="https://www.php.net/manual/en/function.array-splice.php" rel="noreferrer"><code>parameters list</code></a> .</p>
</blockquote> | {
"question_id": 3797239,
"question_date": "2010-09-26T09:39:22.293Z",
"question_score": 595,
"tags": "php|arrays|insert",
"answer_id": 3797526,
"answer_date": "2010-09-26T11:14:51.820Z",
"answer_score": 1131
} |
Please answer the following Stack Overflow question:
Title: View's getWidth() and getHeight() returns 0
<p>I am creating all of the elements in my android project dynamically. I am trying to get the width and height of a button so that I can rotate that button around. I am just trying to learn how to work with the android language. However, it returns 0. </p>
<p>I did some research and I saw that it needs to be done somewhere other than in the <code>onCreate()</code> method. If someone can give me an example of how to do it, that would be great. </p>
<p>Here is my current code:</p>
<pre><code>package com.animation;
import android.app.Activity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
public class AnimateScreen extends Activity {
//Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 0);
Button bt = new Button(this);
bt.setText(String.valueOf(bt.getWidth()));
RotateAnimation ra = new RotateAnimation(0,360,bt.getWidth() / 2,bt.getHeight() / 2);
ra.setDuration(3000L);
ra.setRepeatMode(Animation.RESTART);
ra.setRepeatCount(Animation.INFINITE);
ra.setInterpolator(new LinearInterpolator());
bt.startAnimation(ra);
ll.addView(bt,layoutParams);
setContentView(ll);
}
</code></pre>
<p>Any help is appreciated.</p> | <p>You are calling <code>getWidth()</code> too early. The UI has not been sized and laid out on the screen yet.</p>
<p>I doubt you want to be doing what you are doing, anyway -- widgets being animated do not change their clickable areas, and so the button will still respond to clicks in the original orientation regardless of how it has rotated.</p>
<p>That being said, you can use a <a href="http://developer.android.com/guide/topics/resources/more-resources.html#Dimension" rel="noreferrer">dimension resource</a> to define the button size, then reference that dimension resource from your layout file and your source code, to avoid this problem.</p> | {
"question_id": 3591784,
"question_date": "2010-08-28T17:47:02.127Z",
"question_score": 595,
"tags": "java|android|android-layout|getter",
"answer_id": 3594216,
"answer_date": "2010-08-29T09:26:59.843Z",
"answer_score": 222
} |
Please answer the following Stack Overflow question:
Title: What's the difference between 'git merge' and 'git rebase'?
<p>What's the difference between <code>git merge</code> and <code>git rebase</code>?</p> | <p>Suppose originally there were 3 commits, <code>A</code>,<code>B</code>,<code>C</code>:</p>
<p><img src="https://i.stack.imgur.com/lJRq7.png" alt="A-B-C"></p>
<p>Then developer Dan created commit <code>D</code>, and developer Ed created commit <code>E</code>:</p>
<p><img src="https://i.stack.imgur.com/pK7Zb.png" alt="A-B-C-D-E"></p>
<p>Obviously, this conflict should be resolved somehow. For this, there are 2 ways:</p>
<p><strong>MERGE</strong>:</p>
<p><img src="https://i.stack.imgur.com/9Ul5w.png" alt="A-B-C-D-E-M"></p>
<p>Both commits <code>D</code> and <code>E</code> are still here, but we create merge commit <code>M</code> that inherits changes from both <code>D</code> and <code>E</code>. However, this creates <em>diamond</em> shape, which many people find very confusing.</p>
<p><strong>REBASE</strong>:</p>
<p><img src="https://i.stack.imgur.com/TvXuJ.png" alt="A-B-C-D-E-R"></p>
<p>We create commit <code>R</code>, which actual file content is identical to that of merge commit <code>M</code> above. But, we get rid of commit <code>E</code>, like it never existed (denoted by dots - vanishing line). Because of this obliteration, <code>E</code> should be local to developer Ed and should have never been pushed to any other repository. Advantage of rebase is that <em>diamond</em> shape is avoided, and history stays nice straight line - most developers love that!</p> | {
"question_id": 16666089,
"question_date": "2013-05-21T09:06:09.130Z",
"question_score": 595,
"tags": "git|merge|git-merge|rebase|git-rebase",
"answer_id": 16666418,
"answer_date": "2013-05-21T09:22:05.143Z",
"answer_score": 973
} |
Please answer the following Stack Overflow question:
Title: How to colorize diff on the command line
<p>When I have a diff, how can I colorize it so that it looks good?</p>
<p>I want it for the command line, so please no GUI solutions.</p> | <p>Man pages for <code>diff</code> suggest no solution for colorization from within itself. Please consider using <code>colordiff</code>. It's a wrapper around <code>diff</code> that produces the same output as diff, except that it augments the output using colored syntax highlighting to increase readability:</p>
<pre><code>diff old new | colordiff
</code></pre>
<p>or just:</p>
<pre><code>colordiff old new
</code></pre>
<hr>
<p>Installation:</p>
<ul>
<li>Ubuntu/Debian: <code>sudo apt-get install colordiff</code></li>
<li>OS X: <code>brew install colordiff</code> or <code>port install colordiff</code></li>
</ul> | {
"question_id": 8800578,
"question_date": "2012-01-10T08:49:10.107Z",
"question_score": 595,
"tags": "unix|command-line|colors|diff",
"answer_id": 8800636,
"answer_date": "2012-01-10T08:54:58.900Z",
"answer_score": 688
} |
Please answer the following Stack Overflow question:
Title: C# "internal" access modifier when doing unit testing
<p>I'm new to unit testing and I'm trying to figure out if I should start using more of <code>internal</code> access modifier. I know that if we use <code>internal</code> and set the assembly variable <code>InternalsVisibleTo</code>, we can test functions that we don't want to declare public from the testing project. This makes me think that I should just always use <code>internal</code> because at least each project (should?) have its own testing project. Can you guys tell me why I shouldn't do this? When should I use <code>private</code>?</p> | <p>Internal classes need to be tested and there is an assembly attribute:</p>
<pre><code>using System.Runtime.CompilerServices;
[assembly:InternalsVisibleTo("MyTests")]
</code></pre>
<p>Add this to the project info file, e.g. <code>Properties\AssemblyInfo.cs</code>, for the project under test. In this case "MyTests" is the test project.</p> | {
"question_id": 358196,
"question_date": "2008-12-11T01:20:30.163Z",
"question_score": 595,
"tags": "c#|.net|unit-testing|tdd",
"answer_id": 1809482,
"answer_date": "2009-11-27T15:53:54.033Z",
"answer_score": 1413
} |
Please answer the following Stack Overflow question:
Title: Iterator invalidation rules for C++ containers
<p>What are the iterator invalidation rules for C++ containers?</p>
<sub>
(<strong>Note:</strong> This Q&A is an entry in <a href="https://stackoverflow.com/questions/tagged/c++-faq">Stack Overflow's C++ FAQ</a>. Meta-discussion about the question itself should be posted on <a href="https://meta.stackexchange.com/questions/68647/setting-up-a-faq-for-the-c-tag">the Meta question that started all of this</a>, not here.)
</sub> | <p><strong>C++17</strong> (All references are from the final working draft of CPP17 - <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4659.pdf" rel="noreferrer">n4659</a>)</p>
<hr />
<h1>Insertion</h1>
<p><em>Sequence Containers</em></p>
<ul>
<li><p><code>vector</code>: The functions <code>insert</code>, <code>emplace_back</code>, <code>emplace</code>, <code>push_back</code> cause reallocation if the new size is greater than the old capacity. Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. If no reallocation
happens, all the iterators and references before the insertion point remain valid. [26.3.11.5/1]<br />
With respect to the <code>reserve</code> function, reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. No reallocation shall take place during insertions that happen after a call to <code>reserve()</code> until the time when an insertion would make the size of the vector greater than the value of <code>capacity()</code>. [26.3.11.3/6]</p>
</li>
<li><p><code>deque</code>: An insertion in the middle of the deque invalidates all the iterators and references to elements of the deque. An insertion at either end of the deque invalidates all the iterators to the deque, but has no effect on the validity of references to elements of the deque. [26.3.8.4/1]</p>
</li>
<li><p><code>list</code>: Does not affect the validity of iterators and references. If an exception is thrown there are no effects. [26.3.10.4/1].<br />
The <code>insert</code>, <code>emplace_front</code>, <code>emplace_back</code>, <code>emplace</code>, <code>push_front</code>, <code>push_back</code> functions are covered under this rule.</p>
</li>
<li><p><code>forward_list</code>: None of the overloads of <code>insert_after</code> shall affect the validity of iterators and references [26.3.9.5/1]</p>
</li>
<li><p><code>array</code>: <a href="https://en.cppreference.com/w/cpp/container/array#Iterator_invalidation" rel="noreferrer">As a rule</a>, iterators to an array are never invalidated throughout the lifetime of the array. One should take note, however, that during swap, the iterator will continue to point to the same array element, and will thus change its value.</p>
</li>
</ul>
<p><em>Associative Containers</em></p>
<ul>
<li><code>All Associative Containers</code>: The <code>insert</code> and <code>emplace</code> members shall not affect the validity of iterators and references to the container [26.2.6/9]</li>
</ul>
<p><em>Unordered Associative Containers</em></p>
<ul>
<li><p><code>All Unordered Associative Containers</code>: Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. [26.2.7/9]<br />
The <code>insert</code> and <code>emplace</code> members shall not affect the validity of references to container elements, but may invalidate all iterators to the container. [26.2.7/14]<br />
The <code>insert</code> and <code>emplace</code> members shall not affect the validity of iterators if <code>(N+n) <= z * B</code>, where <code>N</code> is the number of elements in the container prior to the insert operation, <code>n</code> is the number of elements inserted, <code>B</code> is the container’s bucket count, and <code>z</code> is the container’s maximum load factor. [26.2.7/15]</p>
</li>
<li><p><code>All Unordered Associative Containers</code>: In case of a merge operation (e.g., <code>a.merge(a2)</code>), iterators referring to the transferred elements and all iterators referring to <code>a</code> will be invalidated, but iterators to elements remaining in <code>a2</code> will remain valid. (Table 91 — Unordered associative container requirements)</p>
</li>
</ul>
<p><em>Container Adaptors</em></p>
<ul>
<li><code>stack</code>: inherited from underlying container</li>
<li><code>queue</code>: inherited from underlying container</li>
<li><code>priority_queue</code>: inherited from underlying container</li>
</ul>
<hr />
<h1>Erasure</h1>
<p><em>Sequence Containers</em></p>
<ul>
<li><p><code>vector</code>: The functions <code>erase</code> and <code>pop_back</code> invalidate iterators and references at or after the point of the erase. [26.3.11.5/3]</p>
</li>
<li><p><code>deque</code>: An erase operation that erases the last element of a <code>deque</code> invalidates only the past-the-end iterator and all iterators and references to the erased elements. An erase operation that erases the first element of a <code>deque</code> but not the last element invalidates only iterators and references to the erased elements. An erase operation that erases neither the first element nor the last element of a <code>deque</code> invalidates the past-the-end iterator and all iterators and references to all the elements of the <code>deque</code>.
[ Note: <code>pop_front</code> and <code>pop_back</code> are erase operations. —end note ] [26.3.8.4/4]</p>
</li>
<li><p><code>list</code>: Invalidates only the iterators and references to the erased elements. [26.3.10.4/3]. This applies to <code>erase</code>, <code>pop_front</code>, <code>pop_back</code>, <code>clear</code> functions.<br />
<code>remove</code> and <code>remove_if</code> member functions: Erases all the elements in the list referred by a list iterator <code>i</code> for which the following conditions hold: <code>*i == value</code>, <code>pred(*i) != false</code>. Invalidates only the iterators and references to the erased elements [26.3.10.5/15].<br />
<code>unique</code> member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator <code>i</code> in the range <code>[first + 1, last)</code> for which <code>*i == *(i-1)</code> (for the version of unique with no arguments) or <code>pred(*i, *(i - 1))</code> (for the version of unique with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.10.5/19]</p>
</li>
<li><p><code>forward_list</code>: <code>erase_after</code> shall invalidate only iterators and references to the erased elements. [26.3.9.5/1].<br />
<code>remove</code> and <code>remove_if</code> member functions - Erases all the elements in the list referred by a list iterator i for which the following conditions hold: <code>*i == value</code> (for <code>remove()</code>), <code>pred(*i)</code> is true (for <code>remove_if()</code>). Invalidates only the iterators and references to the erased elements. [26.3.9.6/12].<br />
<code>unique</code> member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which <code>*i == *(i-1)</code> (for the version with no arguments) or <code>pred(*i, *(i - 1))</code> (for the version with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.9.6/16]</p>
</li>
<li><p><code>All Sequence Containers</code>: <code>clear</code> invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator (Table 87 — Sequence container requirements). But for <code>forward_list</code>, <code>clear</code> does not invalidate past-the-end iterators. [26.3.9.5/32]</p>
</li>
<li><p><code>All Sequence Containers</code>: <code>assign</code> invalidates all references, pointers and
iterators referring to the elements of the container. For <code>vector</code> and <code>deque</code>, also invalidates the past-the-end iterator. (Table 87 — Sequence container requirements)</p>
</li>
</ul>
<p><em>Associative Containers</em></p>
<ul>
<li><p><code>All Associative Containers</code>: The <code>erase</code> members shall invalidate only iterators and references to the erased elements [26.2.6/9]</p>
</li>
<li><p><code>All Associative Containers</code>: The <code>extract</code> members invalidate only iterators to the removed element; pointers and references to the removed element remain valid [26.2.6/10]</p>
</li>
</ul>
<p><em>Container Adaptors</em></p>
<ul>
<li><code>stack</code>: inherited from underlying container</li>
<li><code>queue</code>: inherited from underlying container</li>
<li><code>priority_queue</code>: inherited from underlying container</li>
</ul>
<hr />
<p><strong>General container requirements relating to iterator invalidation:</strong></p>
<ul>
<li><p>Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [26.2.1/12]</p>
</li>
<li><p>no <code>swap()</code> function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] [26.2.1/(11.6)]</p>
</li>
</ul>
<p><em>As examples of the above requirements:</em></p>
<ul>
<li><p><code>transform</code> algorithm: The <code>op</code> and <code>binary_op</code> functions shall not invalidate iterators or subranges, or modify elements in the ranges [28.6.4/1]</p>
</li>
<li><p><code>accumulate</code> algorithm: In the range [first, last], <code>binary_op</code> shall neither modify elements nor invalidate iterators or subranges [29.8.2/1]</p>
</li>
<li><p><code>reduce</code> algorithm: binary_op shall neither invalidate iterators or subranges, nor modify elements in the range [first, last]. [29.8.3/5]</p>
</li>
</ul>
<p>and so on...</p> | {
"question_id": 6438086,
"question_date": "2011-06-22T10:01:49.870Z",
"question_score": 595,
"tags": "c++|iterator|c++-standard-library|c++-faq",
"answer_id": 54004916,
"answer_date": "2019-01-02T10:44:35.680Z",
"answer_score": 175
} |
Please answer the following Stack Overflow question:
Title: How can I make a weak protocol reference in 'pure' Swift (without @objc)
<p><code>weak</code> references don't seem to work in Swift unless a <code>protocol</code> is declared as <code>@objc</code>, which I don't want in a pure Swift app.</p>
<p>This code gives a compile error (<code>weak</code> cannot be applied to non-class type <code>MyClassDelegate</code>):</p>
<pre><code>class MyClass {
weak var delegate: MyClassDelegate?
}
protocol MyClassDelegate {
}
</code></pre>
<p>I need to prefix the protocol with <code>@objc</code>, then it works.</p>
<p>Question: What is the 'pure' Swift way to accomplish a <code>weak</code> <code>delegate</code>?</p> | <p>You need to declare the type of the protocol as <code>AnyObject</code>.</p>
<pre><code>protocol ProtocolNameDelegate: AnyObject {
// Protocol stuff goes here
}
class SomeClass {
weak var delegate: ProtocolNameDelegate?
}
</code></pre>
<p>Using <code>AnyObject</code> you say that only classes can conform to this protocol, whereas structs or enums can't.</p> | {
"question_id": 24066304,
"question_date": "2014-06-05T17:16:54.740Z",
"question_score": 595,
"tags": "swift|delegates|swift-protocols",
"answer_id": 24104371,
"answer_date": "2014-06-08T08:35:30.417Z",
"answer_score": 1119
} |
Please answer the following Stack Overflow question:
Title: How to find elements by class
<p>I'm having trouble parsing HTML elements with "class" attribute using Beautifulsoup. The code looks like this</p>
<pre><code>soup = BeautifulSoup(sdata)
mydivs = soup.findAll('div')
for div in mydivs:
if (div["class"] == "stylelistrow"):
print div
</code></pre>
<p>I get an error on the same line "after" the script finishes. </p>
<pre><code>File "./beautifulcoding.py", line 130, in getlanguage
if (div["class"] == "stylelistrow"):
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 599, in __getitem__
return self._getAttrMap()[key]
KeyError: 'class'
</code></pre>
<p>How do I get rid of this error?</p> | <p>You can refine your search to only find those divs with a given class using BS3:</p>
<pre class="lang-py prettyprint-override"><code>mydivs = soup.find_all("div", {"class": "stylelistrow"})
</code></pre> | {
"question_id": 5041008,
"question_date": "2011-02-18T11:58:10.443Z",
"question_score": 594,
"tags": "python|html|web-scraping|beautifulsoup",
"answer_id": 5041056,
"answer_date": "2011-02-18T12:04:10.833Z",
"answer_score": 952
} |
Please answer the following Stack Overflow question:
Title: Working copy XXX locked and cleanup failed in SVN
<p>I get this error when I do an <code>svn update</code>:</p>
<blockquote>
<p>Working copy XXXXXXXX locked Please
execute "Cleanup" command</p>
</blockquote>
<p>When I run cleanup, I get</p>
<blockquote>
<p>Cleanup failed to process the
following paths: XXXXXXXX</p>
</blockquote>
<p>How do I get out of this loop?</p> | <p>One approach would be to:</p>
<ol>
<li>Copy edited items to another location.</li>
<li>Delete the folder containing the problem path.</li>
<li>Update the containing folder through Subversion.</li>
<li>Copy your files back or merge changes as needed.</li>
<li>Commit</li>
</ol>
<p>Another option would be to delete the top level folder and check out again. Hopefully it doesn't come to that though.</p> | {
"question_id": 127932,
"question_date": "2008-09-24T15:37:37.943Z",
"question_score": 594,
"tags": "svn|tortoisesvn",
"answer_id": 127980,
"answer_date": "2008-09-24T15:47:13.240Z",
"answer_score": 523
} |
Please answer the following Stack Overflow question:
Title: How to add multiple classes to a ReactJS Component?
<p>I am new to ReactJS and JSX and I am having a little problem with the code below. </p>
<p>I am trying to add multiple classes to the <code>className</code> attribute on each <code>li</code>:</p>
<pre class="lang-html prettyprint-override"><code><li key={index} className={activeClass, data.class, "main-class"}></li>
</code></pre>
<p>My React component is:</p>
<pre class="lang-jsx prettyprint-override"><code>var AccountMainMenu = React.createClass({
getInitialState: function() {
return { focused: 0 };
},
clicked: function(index) {
this.setState({ focused: index });
},
render: function() {
var self = this;
var accountMenuData = [
{
name: "My Account",
icon: "icon-account"
},
{
name: "Messages",
icon: "icon-message"
},
{
name: "Settings",
icon: "icon-settings"
}
/*{
name:"Help &amp; Support &nbsp; <span class='font-awesome icon-support'></span>(888) 664.6261",
listClass:"no-mobile last help-support last"
}*/
];
return (
<div className="acc-header-wrapper clearfix">
<ul className="acc-btns-container">
{accountMenuData.map(function(data, index) {
var activeClass = "";
if (self.state.focused == index) {
activeClass = "active";
}
return (
<li
key={index}
className={activeClass}
onClick={self.clicked.bind(self, index)}
>
<a href="#" className={data.icon}>
{data.name}
</a>
</li>
);
})}
</ul>
</div>
);
}
});
ReactDOM.render(<AccountMainMenu />, document.getElementById("app-container"));
</code></pre> | <p>I use <a href="https://github.com/JedWatson/classnames" rel="noreferrer">classnames</a> when there is a fair amount of logic required for deciding the classes to (not) use. An <strong>overly simple example</strong>:</p>
<pre><code>...
var liClasses = classNames({
'main-class': true,
'activeClass': self.state.focused === index
});
return (<li className={liClasses}>{data.name}</li>);
...
</code></pre>
<p>That said, if you don't want to include a dependency then there are better answers below.</p> | {
"question_id": 34521797,
"question_date": "2015-12-30T01:44:21.507Z",
"question_score": 594,
"tags": "javascript|css|reactjs|ecmascript-6",
"answer_id": 34521945,
"answer_date": "2015-12-30T02:02:24.310Z",
"answer_score": 293
} |
Please answer the following Stack Overflow question:
Title: TypeScript getting error TS2304: cannot find name ' require'
<p>I am trying to get my first TypeScript and DefinitelyTyped Node.js application up and running, and running into some errors.</p>
<p>I am getting the error "TS2304: Cannot find name 'require' " when I attempt to transpile a simple TypeScript Node.js page. I have read through several other occurrences of this error on Stack Overflow, and I do not think I have similar issues.
I am running at the shell prompt the command:</p>
<pre><code>tsc movie.server.model.ts.
</code></pre>
<p>The contents of this file are:</p>
<pre><code>'use strict';
/// <reference path="typings/tsd.d.ts" />
/* movie.server.model.ts - definition of movie schema */
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var foo = 'test';
</code></pre>
<p>The error is thrown on the <code>var mongoose=require('mongoose')</code> line.</p>
<p>The contents of the typings/tsd.d.ts file are:</p>
<pre><code>/// <reference path="node/node.d.ts" />
/// <reference path="requirejs/require.d.ts" />
</code></pre>
<p>The .d.ts file references were placed in the appropriate folders and added to typings/tsd.d.ts by the commands:</p>
<pre><code>tsd install node --save
tsd install require --save
</code></pre>
<p>The produced .js file seems to work fine, so I could ignore the error. But I would appreciate knowing why this error occurs and what I am doing wrong.</p> | <h2>Quick and Dirty</h2>
<p>If you just have one file using require, or you're doing this for demo purposes you can define require at the top of your TypeScript file.</p>
<pre><code>declare var require: any
</code></pre>
<h2>TypeScript 2.x</h2>
<p>If you are using TypeScript 2.x you no longer need to have Typings or Definitely Typed installed. Simply install the following package.</p>
<pre><code>npm install @types/node --save-dev
</code></pre>
<p><a href="https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/" rel="noreferrer">The Future of Declaration Files (6/15/2016)</a></p>
<blockquote>
<p>Tools like Typings and tsd will continue to work, and we’ll be working
alongside those communities to ensure a smooth transition.</p>
</blockquote>
<p>Verify or Edit your <strong>src</strong>/tsconfig.app.json so that it contains the following:</p>
<pre><code>...
"types": [ "node" ],
"typeRoots": [ "../node_modules/@types" ]
...
</code></pre>
<p>Make sure is the file in the <strong>src</strong> folder and no the one on the root app folder.</p>
<p>By default, any package under @types is already included in your build <strong>unless</strong> you've specified either of these options. <a href="https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types" rel="noreferrer">Read more</a></p>
<h2>TypeScript 1.x</h2>
<p>Using typings (DefinitelyTyped's replacement) you can specify a definition directly from a GitHub repository.</p>
<p>Install typings</p>
<pre><code>npm install typings -g --save-dev
</code></pre>
<p>Install the requireJS type definition from DefinitelyType's repo</p>
<pre><code>typings install dt~node --save --global
</code></pre>
<h2>Webpack</h2>
<p>If you are using Webpack as your build tool you can include the Webpack types.</p>
<pre><code>npm install --save-dev @types/webpack-env
</code></pre>
<p>Update your <code>tsconfig.json</code> with the following under <code>compilerOptions</code>:</p>
<pre><code>"types": [
"webpack-env"
]
</code></pre>
<p>This allows you to do <code>require.ensure</code> and other Webpack specific functions.</p>
<h2>Angular CLI</h2>
<p>With CLI you can follow the Webpack step above and add the "types" block to your <code>tsconfig.app.json</code>.</p>
<p>Alternatively, you could use the preinstalled <code>node</code> types. Keep in mind this will include additional types to your client-side code that are not really available.</p>
<pre><code>"compilerOptions": {
// other options
"types": [
"node"
]
}
</code></pre> | {
"question_id": 31173738,
"question_date": "2015-07-02T00:21:40.093Z",
"question_score": 594,
"tags": "node.js|typescript|definitelytyped",
"answer_id": 35961176,
"answer_date": "2016-03-12T17:46:00.513Z",
"answer_score": 902
} |
Please answer the following Stack Overflow question:
Title: Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley
<p>Two-part question from an iOS developer learning Android, working on an Android project that will make a variety of requests from JSON to image to streaming download of audio and video:</p>
<ol>
<li><p>On iOS I have used the <a href="https://github.com/AFNetworking/AFNetworking" rel="nofollow noreferrer">AFNetworking</a> project extensively. Is there an equivalent library for Android?</p>
</li>
<li><p>I've read up on <a href="http://square.github.io/okhttp/" rel="nofollow noreferrer">OkHTTP</a> and <a href="http://square.github.io/retrofit/" rel="nofollow noreferrer">Retrofit</a> by Square, as well as <a href="https://developers.google.com/live/shows/474338138" rel="nofollow noreferrer">Volley</a> but dont yet have experience developing with them. I'm hoping someone can provide some concrete examples of best use cases for each. From what I've read, seems like OkHTTP is the most robust of the three, and could handle the requirements of this project (mentioned above).</p>
</li>
</ol> | <blockquote>
<p>I'm hoping someone can provide some concrete examples of best use cases for each.</p>
</blockquote>
<p>Use Retrofit if you are communicating with a Web service. Use the peer library Picasso if you are downloading images. Use OkHTTP if you need to do HTTP operations that lie outside of Retrofit/Picasso.</p>
<p>Volley roughly competes with Retrofit + Picasso. On the plus side, it is one library. On the minus side, it is <strike>one undocumented,</strike> an unsupported, "throw the code over the wall and do an I|O presentation on it" library.</p>
<p>EDIT - Volley is now officially supported by Google. Kindly refer <a href="https://developer.android.com/training/volley/index.html" rel="noreferrer">Google Developer Guide</a></p>
<blockquote>
<p>From what I've read, seems like OkHTTP is the most robust of the 3</p>
</blockquote>
<p>Retrofit uses OkHTTP automatically if available. There is a <a href="https://gist.github.com/JakeWharton/5616899" rel="noreferrer">Gist from Jake Wharton</a> that connects Volley to OkHTTP.</p>
<blockquote>
<p>and could handle the requirements of this project (mentioned above).</p>
</blockquote>
<p>Probably you will use none of them for "streaming download of audio and video", by the conventional definition of "streaming". Instead, Android's media framework will handle those HTTP requests for you.</p>
<p>That being said, if you are going to attempt to do your own HTTP-based streaming, OkHTTP should handle that scenario; I don't recall how well Volley would handle that scenario. Neither Retrofit nor Picasso are designed for that.</p> | {
"question_id": 16902716,
"question_date": "2013-06-03T17:47:04.673Z",
"question_score": 594,
"tags": "android|networking|retrofit|android-networking",
"answer_id": 16903205,
"answer_date": "2013-06-03T18:18:03.980Z",
"answer_score": 661
} |
Please answer the following Stack Overflow question:
Title: Is there anything like .NET's NotImplementedException in Java?
<p>Is there anything like .NET's <code>NotImplementedException</code> in Java?</p> | <p><a href="http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/NotImplementedException.html" rel="noreferrer">Commons Lang</a> has it. Or you could throw an <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/UnsupportedOperationException.html" rel="noreferrer"><code>UnsupportedOperationException</code></a>.</p> | {
"question_id": 2329358,
"question_date": "2010-02-24T20:44:28.530Z",
"question_score": 594,
"tags": "java|.net|exception",
"answer_id": 2329389,
"answer_date": "2010-02-24T20:48:04.030Z",
"answer_score": 569
} |
Please answer the following Stack Overflow question:
Title: Bind a function to Twitter Bootstrap Modal Close
<p>I am using the Twitter Bootstrap lib on a new project and I want for part of the page to refresh and retrieve the latest json data on modal close. I dont see this anywhere in the documentation can someone point it out to me or suggest a solution.</p>
<p>Two problems with using the documented methods</p>
<pre><code> $('#my-modal').bind('hide', function () {
// do something ...
});
</code></pre>
<p>I attach a "hide" class to the modal already so it does not display on page load so that would load twice</p>
<p>even if I remove the hide class and set the element id to <code>display:none</code> and add <code>console.log("THE MODAL CLOSED");</code> to the function above when I hit close nothing happens.</p> | <h2>Bootstrap 3 & 4</h2>
<pre><code>$('#myModal').on('hidden.bs.modal', function () {
// do something…
});
</code></pre>
<p>Bootstrap 3: <a href="https://getbootstrap.com/javascript/#modals-events" rel="noreferrer">getbootstrap.com/javascript/#modals-events</a></p>
<p>Bootstrap 4: <a href="https://getbootstrap.com/docs/4.1/components/modal/#events" rel="noreferrer">getbootstrap.com/docs/4.1/components/modal/#events</a></p>
<h2>Bootstrap 2.3.2</h2>
<pre><code>$('#myModal').on('hidden', function () {
// do something…
});
</code></pre>
<p>See <a href="https://getbootstrap.com/2.3.2/javascript.html#modals" rel="noreferrer">getbootstrap.com/2.3.2/javascript.html#modals</a> → Events</p> | {
"question_id": 8363802,
"question_date": "2011-12-02T23:06:25.617Z",
"question_score": 593,
"tags": "jquery|modal-dialog|twitter-bootstrap",
"answer_id": 13201843,
"answer_date": "2012-11-02T19:31:54.973Z",
"answer_score": 1244
} |
Please answer the following Stack Overflow question:
Title: How to properly assert that an exception gets raised in pytest?
<h2>Code:</h2>
<pre><code># coding=utf-8
import pytest
def whatever():
return 9/0
def test_whatever():
try:
whatever()
except ZeroDivisionError as exc:
pytest.fail(exc, pytrace=True)
</code></pre>
<h2>Output:</h2>
<pre><code>================================ test session starts =================================
platform linux2 -- Python 2.7.3 -- py-1.4.20 -- pytest-2.5.2
plugins: django, cov
collected 1 items
pytest_test.py F
====================================== FAILURES ======================================
___________________________________ test_whatever ____________________________________
def test_whatever():
try:
whatever()
except ZeroDivisionError as exc:
> pytest.fail(exc, pytrace=True)
E Failed: integer division or modulo by zero
pytest_test.py:12: Failed
============================== 1 failed in 1.16 seconds ==============================
</code></pre>
<p>How to make pytest print traceback, so I would see where in the <code>whatever</code> function an exception was raised?</p> | <p><a href="https://docs.pytest.org/en/stable/reference.html?highlight=raises#pytest.raises" rel="noreferrer"><code>pytest.raises(Exception)</code></a> is what you need.</p>
<p><strong>Code</strong></p>
<pre><code>import pytest
def test_passes():
with pytest.raises(Exception) as e_info:
x = 1 / 0
def test_passes_without_info():
with pytest.raises(Exception):
x = 1 / 0
def test_fails():
with pytest.raises(Exception) as e_info:
x = 1 / 1
def test_fails_without_info():
with pytest.raises(Exception):
x = 1 / 1
# Don't do this. Assertions are caught as exceptions.
def test_passes_but_should_not():
try:
x = 1 / 1
assert False
except Exception:
assert True
# Even if the appropriate exception is caught, it is bad style,
# because the test result is less informative
# than it would be with pytest.raises(e)
# (it just says pass or fail.)
def test_passes_but_bad_style():
try:
x = 1 / 0
assert False
except ZeroDivisionError:
assert True
def test_fails_but_bad_style():
try:
x = 1 / 1
assert False
except ZeroDivisionError:
assert True
</code></pre>
<p><strong>Output</strong></p>
<pre><code>============================================================================================= test session starts ==============================================================================================
platform linux2 -- Python 2.7.6 -- py-1.4.26 -- pytest-2.6.4
collected 7 items
test.py ..FF..F
=================================================================================================== FAILURES ===================================================================================================
__________________________________________________________________________________________________ test_fails __________________________________________________________________________________________________
def test_fails():
with pytest.raises(Exception) as e_info:
> x = 1 / 1
E Failed: DID NOT RAISE
test.py:13: Failed
___________________________________________________________________________________________ test_fails_without_info ____________________________________________________________________________________________
def test_fails_without_info():
with pytest.raises(Exception):
> x = 1 / 1
E Failed: DID NOT RAISE
test.py:17: Failed
___________________________________________________________________________________________ test_fails_but_bad_style ___________________________________________________________________________________________
def test_fails_but_bad_style():
try:
x = 1 / 1
> assert False
E assert False
test.py:43: AssertionError
====================================================================================== 3 failed, 4 passed in 0.02 seconds ======================================================================================
</code></pre>
<p>Note that <code>e_info</code> saves the exception object so you can extract details from it. For example, if you want to check the exception call stack or another nested exception inside. </p> | {
"question_id": 23337471,
"question_date": "2014-04-28T09:33:45.357Z",
"question_score": 593,
"tags": "python|unit-testing|testing|pytest",
"answer_id": 29855337,
"answer_date": "2015-04-24T18:52:57Z",
"answer_score": 681
} |
Please answer the following Stack Overflow question:
Title: Can one AngularJS controller call another?
<p>Is it possible to have one controller use another?</p>
<p>For example:</p>
<p>This HTML document simply prints a message delivered by the <code>MessageCtrl</code> controller in the <code>messageCtrl.js</code> file.</p>
<pre><code><html xmlns:ng="http://angularjs.org/">
<head>
<meta charset="utf-8" />
<title>Inter Controller Communication</title>
</head>
<body>
<div ng:controller="MessageCtrl">
<p>{{message}}</p>
</div>
<!-- Angular Scripts -->
<script src="http://code.angularjs.org/angular-0.9.19.js" ng:autobind></script>
<script src="js/messageCtrl.js" type="text/javascript"></script>
</body>
</html>
</code></pre>
<p>The controller file contains the following code:</p>
<pre><code>function MessageCtrl()
{
this.message = function() {
return "The current date is: " + new Date().toString();
};
}
</code></pre>
<p>Which simply prints the current date;</p>
<p>If I were to add another controller, <code>DateCtrl</code> which handed the date in a specific format back to <code>MessageCtrl</code>, how would one go about doing this? The DI framework seems to be concerned with <code>XmlHttpRequests</code> and accessing services.</p> | <p>There are multiple ways how to communicate between controllers.</p>
<p>The best one is probably sharing a service:</p>
<pre><code>function FirstController(someDataService)
{
// use the data service, bind to template...
// or call methods on someDataService to send a request to server
}
function SecondController(someDataService)
{
// has a reference to the same instance of the service
// so if the service updates state for example, this controller knows about it
}
</code></pre>
<p>Another way is emitting an event on scope:</p>
<pre><code>function FirstController($scope)
{
$scope.$on('someEvent', function(event, args) {});
// another controller or even directive
}
function SecondController($scope)
{
$scope.$emit('someEvent', args);
}
</code></pre>
<p>In both cases, you can communicate with any directive as well.</p> | {
"question_id": 9293423,
"question_date": "2012-02-15T12:31:20.860Z",
"question_score": 593,
"tags": "javascript|html|angularjs",
"answer_id": 9407953,
"answer_date": "2012-02-23T05:59:47.110Z",
"answer_score": 710
} |
Please answer the following Stack Overflow question:
Title: CSS hide scroll bar if not needed
<p>I am trying to figure out how I can hide the <code>overflow-y:scroll;</code> if not needed. What I mean is that I am building a website and I have a main area which posts will be displayed and I want to hide the scroll bar if content does not exceed the current width.</p>
<p>Also, my second question. I want to make it so when the posts exceed the current width, the width will increase automatically and the content won't go out of the box.</p>
<p>Does anyone have a clue how to do this?</p>
<p>Posts area:</p>
<pre><code>.content {
height: 600px;
border-left: 1px solid;
border-right: 1px solid;
border-bottom: 1px solid;
font-size: 15px;
text-align: justify;
line-height: 19px;
overflow-y:scroll;
}
</code></pre>
<p>Main website container:</p>
<pre><code>.container {
margin: 0 auto;
width: 757px;
margin-top: 30px;
text-align: center;
}
</code></pre> | <p>Set <code>overflow-y</code> property to <code>auto</code>, or remove the property altogether if it is not inherited.</p> | {
"question_id": 18716863,
"question_date": "2013-09-10T10:46:43.333Z",
"question_score": 593,
"tags": "html|css",
"answer_id": 18716885,
"answer_date": "2013-09-10T10:47:55.030Z",
"answer_score": 1056
} |
Please answer the following Stack Overflow question:
Title: What is the non-jQuery equivalent of '$(document).ready()'?
<p>What is the non-jQuery equivalent of <code>$(document).ready()</code>?</p> | <p><em>This does not answer the question nor does it show any non-jQuery code. See @ sospedra's answer below.</em></p>
<p>The nice thing about <code>$(document).ready()</code> is that it fires before <code>window.onload</code>. The load function waits until everything is loaded, including external assets and images. <code>$(document).ready</code>, however, fires when the DOM tree is complete and can be manipulated. If you want to acheive DOM ready, without jQuery, you might check into this library. Someone extracted just the <code>ready</code> part from jQuery. Its nice and small and you might find it useful:</p>
<p><a href="https://code.google.com/archive/p/domready/" rel="nofollow noreferrer">domready at Google Code</a></p> | {
"question_id": 2304941,
"question_date": "2010-02-21T05:40:52.267Z",
"question_score": 593,
"tags": "javascript|jquery",
"answer_id": 2305001,
"answer_date": "2010-02-21T06:01:54.487Z",
"answer_score": 32
} |
Please answer the following Stack Overflow question:
Title: Set the value of an input field
<p>How would you set the default value of a form <code><input></code> text field in JavaScript?</p> | <p>This is one way of doing it:</p>
<pre><code>document.getElementById("nameofid").value = "My value";
</code></pre> | {
"question_id": 7609130,
"question_date": "2011-09-30T10:32:00.500Z",
"question_score": 592,
"tags": "javascript|html|forms|input|html-input",
"answer_id": 7609144,
"answer_date": "2011-09-30T10:33:16.733Z",
"answer_score": 1042
} |
Please answer the following Stack Overflow question:
Title: How do I resize an image using PIL and maintain its aspect ratio?
<p>Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.</p> | <p>Define a maximum size.
Then, compute a resize ratio by taking <code>min(maxwidth/width, maxheight/height)</code>.</p>
<p>The proper size is <code>oldsize*ratio</code>.</p>
<p>There is of course also a library method to do this: the method <code>Image.thumbnail</code>.<br />
Below is an (edited) example from the <a href="https://pillow.readthedocs.io/en/stable/reference/Image.html?highlight=thumbnail#PIL.Image.Image.thumbnail" rel="noreferrer">PIL documentation</a>.</p>
<pre><code>import os, sys
import Image
size = 128, 128
for infile in sys.argv[1:]:
outfile = os.path.splitext(infile)[0] + ".thumbnail"
if infile != outfile:
try:
im = Image.open(infile)
im.thumbnail(size, Image.ANTIALIAS)
im.save(outfile, "JPEG")
except IOError:
print "cannot create thumbnail for '%s'" % infile
</code></pre> | {
"question_id": 273946,
"question_date": "2008-11-07T23:08:04.197Z",
"question_score": 592,
"tags": "python|image|python-imaging-library|thumbnails",
"answer_id": 273962,
"answer_date": "2008-11-07T23:15:37.973Z",
"answer_score": 594
} |
Please answer the following Stack Overflow question:
Title: How can I view HTTP headers in Google Chrome?
<p>Till 9.x, the headers were under the resources in the Developer Tools, but now I can't find it anywhere.</p> | <p>I'm not sure about your exact version, but Chrome has a tab "Network" with several items and when I click on them I can see the headers on the right in a tab.</p>
<p>Press <kbd>F12</kbd> on windows or <kbd>⌥⌘I</kbd> on a mac to bring up the Chrome developer tools.</p>
<p><a href="https://i.stack.imgur.com/1dolH.png"><img src="https://i.stack.imgur.com/1dolH.png" alt="Chrome developer tools headers tab"></a></p> | {
"question_id": 4423061,
"question_date": "2010-12-12T17:58:13.733Z",
"question_score": 592,
"tags": "http-headers|google-chrome-devtools",
"answer_id": 4423097,
"answer_date": "2010-12-12T18:05:30.063Z",
"answer_score": 872
} |
Please answer the following Stack Overflow question:
Title: How do I convert a string to enum in TypeScript?
<p>I have defined the following enum in TypeScript:</p>
<pre><code>enum Color{
Red, Green
}
</code></pre>
<p>Now in my function I receive color as a string. I have tried the following code:</p>
<pre><code>var green= "Green";
var color : Color = <Color>green; // Error: can't convert string to enum
</code></pre>
<p>How can I convert that value to an enum?</p> | <p>Enums in TypeScript 0.9 are string+number based. You should not need type assertion for simple conversions: </p>
<pre><code>enum Color{
Red, Green
}
// To String
var green: string = Color[Color.Green];
// To Enum / number
var color : Color = Color[green];
</code></pre>
<p><a href="http://www.typescriptlang.org/Playground/#src=enum%20Color%7B%0D%0A%20%20%20%20Red%2C%20Green%0D%0A%7D%0D%0A%0D%0A%2F%2F%20To%20String%0D%0A%20var%20green%3A%20string%20%3D%20Color%5BColor.Green%5D%3B%0D%0A%0D%0A%2F%2F%20To%20Enum%0D%0Avar%20color%20%3A%20Color%20%3D%20Color%5Bgreen%5D%3B%0D%0A%0D%0A" rel="noreferrer">Try it online</a></p>
<p>I have documention about this and other Enum patterns in my OSS book : <a href="https://basarat.gitbook.io/typescript/type-system/enums" rel="noreferrer">https://basarat.gitbook.io/typescript/type-system/enums</a></p> | {
"question_id": 17380845,
"question_date": "2013-06-29T13:45:41.213Z",
"question_score": 592,
"tags": "typescript",
"answer_id": 17381004,
"answer_date": "2013-06-29T14:04:00.847Z",
"answer_score": 653
} |
Please answer the following Stack Overflow question:
Title: Java 8 Lambda function that throws exception?
<p>I know how to create a reference to a method that has a <code>String</code> parameter and returns an <code>int</code>, it's:</p>
<pre><code>Function<String, Integer>
</code></pre>
<p>However, this doesn't work if the function throws an exception, say it's defined as:</p>
<pre><code>Integer myMethod(String s) throws IOException
</code></pre>
<p>How would I define this reference?</p> | <p>You'll need to do one of the following.</p>
<ul>
<li><p>If it's your code, then define your own functional interface that declares the checked exception:</p>
<pre><code>@FunctionalInterface
public interface CheckedFunction<T, R> {
R apply(T t) throws IOException;
}
</code></pre>
<p>and use it:</p>
<pre><code>void foo (CheckedFunction f) { ... }
</code></pre></li>
<li><p>Otherwise, wrap <code>Integer myMethod(String s)</code> in a method that doesn't declare a checked exception:</p>
<pre><code>public Integer myWrappedMethod(String s) {
try {
return myMethod(s);
}
catch(IOException e) {
throw new UncheckedIOException(e);
}
}
</code></pre>
<p>and then:</p>
<pre><code>Function<String, Integer> f = (String t) -> myWrappedMethod(t);
</code></pre>
<p>or:</p>
<pre><code>Function<String, Integer> f =
(String t) -> {
try {
return myMethod(t);
}
catch(IOException e) {
throw new UncheckedIOException(e);
}
};
</code></pre></li>
</ul> | {
"question_id": 18198176,
"question_date": "2013-08-12T23:16:36.183Z",
"question_score": 592,
"tags": "java|lambda|java-8",
"answer_id": 18198349,
"answer_date": "2013-08-12T23:33:18.980Z",
"answer_score": 524
} |
Please answer the following Stack Overflow question:
Title: How to do relative imports in Python?
<p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/" rel="noreferrer">PEP 366</a> (thanks John B)</p> | <p>Everyone seems to want to tell you what you should be doing rather than just answering the question.</p>
<p>The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.</p>
<p>From <a href="http://www.python.org/dev/peps/pep-0328/" rel="noreferrer">PEP 328</a>:</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>In Python 2.6, they're adding the ability to reference modules relative to the main module. <a href="http://python.org/dev/peps/pep-0366/" rel="noreferrer">PEP 366</a> describes the change.</p>
<p><strong>Update</strong>: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.</p> | {
"question_id": 72852,
"question_date": "2008-09-16T14:24:02.330Z",
"question_score": 592,
"tags": "python|python-import|python-module",
"answer_id": 73149,
"answer_date": "2008-09-16T14:48:56.873Z",
"answer_score": 370
} |
Please answer the following Stack Overflow question:
Title: Staging Deleted files
<p>Say I have a file in my git repository called <code>foo</code>.</p>
<p>Suppose it has been deleted with <code>rm</code> (not <code>git rm</code>). Then git status will show:</p>
<pre><code>Changes not staged for commit:
deleted: foo
</code></pre>
<p>How do I stage this individual file deletion?</p>
<p>If I try:</p>
<pre><code>git add foo
</code></pre>
<p>It says:</p>
<pre><code>'foo' did not match any files.
</code></pre>
<p><strong>Update (9 years later, lol):</strong></p>
<p>This looks like it has been fixed in git 2.x:</p>
<pre><code>$ git --version
git version 2.25.1
$ mkdir repo
$ cd repo
$ git init .
Initialized empty Git repository in repo/.git/
$ touch foo bar baz
$ git add foo bar baz
$ git commit -m "initial commit"
[master (root-commit) 79c736b] initial commit
3 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 bar
create mode 100644 baz
create mode 100644 foo
$ rm foo
$ git status
On branch master
Changes not staged for commit:
deleted: foo
$ git add foo
$ git status
On branch master
Changes to be committed:
deleted: foo
</code></pre> | <p>Since Git 2.0.0, <code>git add</code> will also stage file deletions.</p>
<p><a href="https://git-scm.com/docs/git-add/2.0.0" rel="noreferrer">Git 2.0.0 Docs - git-add</a></p>
<blockquote>
<p>< pathspec >…</p>
<p>Files to add content from. Fileglobs (e.g. *.c) can be given to add all
matching files. Also a leading directory name (e.g. dir to add dir/file1 and dir/file2) can be given to update the index to match the current state of the directory as a whole (e.g. specifying dir will record not just a file dir/file1 modified in the working tree, a file dir/file2 added to the working tree, but also a file dir/file3 removed from the working tree. <strong>Note that older versions of Git used to ignore removed files; use --no-all option if you want to add modified or new files but ignore removed ones.</strong></p>
</blockquote> | {
"question_id": 12373733,
"question_date": "2012-09-11T16:01:03.350Z",
"question_score": 592,
"tags": "git|git-add|git-rm|git-stage",
"answer_id": 43056286,
"answer_date": "2017-03-27T20:52:11.853Z",
"answer_score": 49
} |
Please answer the following Stack Overflow question:
Title: Can I delete data from the iOS DeviceSupport directory?
<p>After going through and cleaning my disk with old things that I didn't need anymore, I came across the <code>iOS DeviceSupport</code> folder in <code>~/Library/Developer/Xcode</code> which was taking nearly 20 GB.</p>
<p>A similar question <a href="https://stackoverflow.com/questions/5302789/can-i-remove-previous-versions-of-iphone-support-in-devicesupport-folder-in-xcod/">has been asked before</a>, but since then many things have changed and I would like an up-to-date answer.</p>
<p>As long as I have the version I use for testing, can I delete the older/unused versions without breaking anything?</p>
<p><img src="https://i.stack.imgur.com/YE3u3.png" alt="iOS DeviceSupport contents" /></p> | <p>The <code>~/Library/Developer/Xcode/iOS DeviceSupport</code> folder is basically only needed to symbolicate crash logs.</p>
<p>You could completely purge the entire folder. Of course the next time you connect one of your devices, Xcode would redownload the symbol data from the device.</p>
<p>I clean out that folder once a year or so by deleting folders for versions of iOS I no longer support or expect to ever have to symbolicate a crash log for.</p> | {
"question_id": 29930198,
"question_date": "2015-04-28T21:24:23.827Z",
"question_score": 592,
"tags": "xcode|xcode8|delete-file|temporary-files",
"answer_id": 29931912,
"answer_date": "2015-04-28T23:50:07.910Z",
"answer_score": 903
} |
Please answer the following Stack Overflow question:
Title: Python error "ImportError: No module named"
<p>Python is installed in a local directory. </p>
<p>My directory tree looks like this:</p>
<pre><code>(local directory)/site-packages/toolkit/interface.py
</code></pre>
<p>My code is in here:</p>
<pre><code>(local directory)/site-packages/toolkit/examples/mountain.py
</code></pre>
<p>To run the example, I write <code>python mountain.py</code>, and in the code I have:</p>
<pre><code>from toolkit.interface import interface
</code></pre>
<p>And I get the error:</p>
<pre><code>Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code></pre>
<p>I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>. Also, I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p>
<p>I do not know why Python cannot find the file when it is in <code>sys.path</code>. Any ideas? Can it be a permissions problem? Do I need some execution permission?</p> | <p>Based on your comments to orip's post, I guess this is what happened:</p>
<ol>
<li>You edited <code>__init__.py</code> on windows.</li>
<li>The windows editor added something non-printing, perhaps a carriage-return (end-of-line in Windows is CR/LF; in unix it is LF only), or perhaps a CTRL-Z (windows end-of-file).</li>
<li>You used WinSCP to copy the file to your unix box.</li>
<li>WinSCP thought: "This has something that's not basic text; I'll put a .bin extension to indicate binary data."</li>
<li>The missing <code>__init__.py</code> (now called <code>__init__.py.bin</code>) means python doesn't understand toolkit as a package.</li>
<li>You create <code>__init__.py</code> in the appropriate directory and everything works... ?</li>
</ol> | {
"question_id": 338768,
"question_date": "2008-12-03T21:26:28.253Z",
"question_score": 591,
"tags": "python|importerror|python-import",
"answer_id": 339220,
"answer_date": "2008-12-04T00:17:40.203Z",
"answer_score": 322
} |
Please answer the following Stack Overflow question:
Title: usr/bin/ld: cannot find -l<nameOfTheLibrary>
<p>I'm trying to compile my program and it returns this error :</p>
<pre><code>usr/bin/ld: cannot find -l<nameOfTheLibrary>
</code></pre>
<p>in my makefile I use the command <code>g++</code> and link to my library which is a symbolic link to my library located on an other directory.</p>
<p>Is there an option to add to make it work please?</p> | <p>If your library name is say <code>libxyz.so</code> and it is located on path say:</p>
<pre><code>/home/user/myDir
</code></pre>
<p>then to link it to your program:</p>
<pre><code>g++ -L/home/user/myDir -lxyz myprog.cpp -o myprog
</code></pre> | {
"question_id": 16710047,
"question_date": "2013-05-23T09:20:39.733Z",
"question_score": 591,
"tags": "c++|linux|g++",
"answer_id": 16710346,
"answer_date": "2013-05-23T09:33:31.203Z",
"answer_score": 244
} |
Please answer the following Stack Overflow question:
Title: Python: Checking if a 'Dictionary' is empty doesn't seem to work
<p>I am trying to check if a dictionary is empty but it doesn't behave properly. It just skips it and displays <strong>ONLINE</strong> without anything except of display the message. Any ideas why ?</p>
<pre><code>def isEmpty(self, dictionary):
for element in dictionary:
if element:
return True
return False
def onMessage(self, socket, message):
if self.isEmpty(self.users) == False:
socket.send("Nobody is online, please use REGISTER command" \
" in order to register into the server")
else:
socket.send("ONLINE " + ' ' .join(self.users.keys()))
</code></pre> | <p>Empty dictionaries <a href="https://docs.python.org/2/library/stdtypes.html#truth-value-testing" rel="noreferrer">evaluate to <code>False</code></a> in Python:</p>
<pre><code>>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>
</code></pre>
<p>Thus, your <code>isEmpty</code> function is unnecessary. All you need to do is:</p>
<pre><code>def onMessage(self, socket, message):
if not self.users:
socket.send("Nobody is online, please use REGISTER command" \
" in order to register into the server")
else:
socket.send("ONLINE " + ' ' .join(self.users.keys()))
</code></pre> | {
"question_id": 23177439,
"question_date": "2014-04-20T01:29:19.210Z",
"question_score": 591,
"tags": "python|dictionary",
"answer_id": 23177452,
"answer_date": "2014-04-20T01:31:06.830Z",
"answer_score": 1048
} |
Please answer the following Stack Overflow question:
Title: How to enter a multi-line command
<p>Is it possible to split a PowerShell command line over multiple lines?</p>
<p>In Visual Basic I can use the underscore (<code>_</code>) to continue the command in the next line.</p> | <p>You can use a space followed by the grave accent (backtick):</p>
<pre><code>Get-ChildItem -Recurse `
-Filter *.jpg `
| Select LastWriteTime
</code></pre>
<p>However, this is only ever necessary in such cases as shown above. Usually you get automatic line continuation when a command cannot syntactically be complete at that point. This includes starting a new pipeline element:</p>
<pre><code>Get-ChildItem |
Select Name,Length
</code></pre>
<p>will work without problems since after the <code>|</code> the command cannot be complete since it's missing another pipeline element. Also opening curly braces or any other kind of parentheses will allow line continuation directly:</p>
<pre><code>$x=1..5
$x[
0,3
] | % {
"Number: $_"
}
</code></pre>
<p>Similar to the <code>|</code> a comma will also work in some contexts:</p>
<pre><code>1,
2
</code></pre>
<p>Keep in mind, though, similar to JavaScript's <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion" rel="noreferrer">Automatic Semicolon Insertion</a>, there are some things that are similarly broken because the line break occurs at a point where it <em>is</em> preceded by a valid statement:</p>
<pre><code>return
5
</code></pre>
<p>will not work.</p>
<p>Finally, strings (in all varieties) may also extend beyond a single line:</p>
<pre><code>'Foo
bar'
</code></pre>
<p>They include the line breaks within the string, then.</p> | {
"question_id": 3235850,
"question_date": "2010-07-13T09:36:16.803Z",
"question_score": 591,
"tags": "powershell|multiline",
"answer_id": 3235993,
"answer_date": "2010-07-13T09:52:44.637Z",
"answer_score": 835
} |
Please answer the following Stack Overflow question:
Title: How to permanently add a private key with ssh-add on Ubuntu?
<p>I have a private key protected with a password to access a server via SSH. </p>
<p>I have 2 linux (ubuntu 10.04) machines and the behavior of ssh-add command is different in both of them. </p>
<p>In one machine, once I use "ssh-add .ssh/identity" and entered my password, the key was added permanently, i.e., every time I shutdown the computer and login again, the key is already added.</p>
<p>In the other one, I have to add the key every time I login. </p>
<p>As far as I remember, I did the same thing on both. The only difference is that the key was created on the one that is added permanently.</p>
<p>Does anyone know how to add it permanently to the other machine as well?</p> | <p>A solution would be to force the key files to be kept permanently, by adding them in your <code>~/.ssh/config</code> file:</p>
<pre><code>IdentityFile ~/.ssh/gitHubKey
IdentityFile ~/.ssh/id_rsa_buhlServer
</code></pre>
<p>If you do not have a 'config' file in the ~/.ssh directory, then you should create one. It does not need root rights, so simply:</p>
<pre><code>nano ~/.ssh/config
</code></pre>
<p>...and enter the lines above as per your requirements.</p>
<p>For this to work the file needs to have chmod 600. You can use the command <code>chmod 600 ~/.ssh/config</code>.</p>
<p>If you want all users on the computer to use the key put these lines into <code>/etc/ssh/ssh_config</code> and the key in a folder accessible to all.</p>
<p>Additionally if you want to set the key specific to one host, you can do the following in your ~/.ssh/config :</p>
<pre><code>Host github.com
User git
IdentityFile ~/.ssh/githubKey
</code></pre>
<p>This has the advantage when you have many identities that a server doesn't reject you because you tried the wrong identities first. Only the specific identity will be tried. </p> | {
"question_id": 3466626,
"question_date": "2010-08-12T10:13:38.130Z",
"question_score": 591,
"tags": "ubuntu|ssh|key|ssh-agent",
"answer_id": 4246809,
"answer_date": "2010-11-22T15:08:59.043Z",
"answer_score": 846
} |
Please answer the following Stack Overflow question:
Title: Drop unused factor levels in a subsetted data frame
<p>I have a data frame containing a <code>factor</code>. When I create a subset of this dataframe using <code>subset</code> or another indexing function, a new data frame is created. However, the <code>factor</code> variable retains all of its original levels, even when/if they do not exist in the new dataframe.</p>
<p>This causes problems when doing faceted plotting or using functions that rely on factor levels.</p>
<p>What is the most succinct way to remove levels from a factor in the new dataframe?</p>
<p>Here's an example:</p>
<pre><code>df <- data.frame(letters=letters[1:5],
numbers=seq(1:5))
levels(df$letters)
## [1] "a" "b" "c" "d" "e"
subdf <- subset(df, numbers <= 3)
## letters numbers
## 1 a 1
## 2 b 2
## 3 c 3
# all levels are still there!
levels(subdf$letters)
## [1] "a" "b" "c" "d" "e"
</code></pre> | <p>All you should have to do is to apply factor() to your variable again after subsetting:</p>
<pre><code>> subdf$letters
[1] a b c
Levels: a b c d e
subdf$letters <- factor(subdf$letters)
> subdf$letters
[1] a b c
Levels: a b c
</code></pre>
<p><strong>EDIT</strong></p>
<p>From the factor page example:</p>
<pre><code>factor(ff) # drops the levels that do not occur
</code></pre>
<p>For dropping levels from all factor columns in a dataframe, you can use:</p>
<pre><code>subdf <- subset(df, numbers <= 3)
subdf[] <- lapply(subdf, function(x) if(is.factor(x)) factor(x) else x)
</code></pre> | {
"question_id": 1195826,
"question_date": "2009-07-28T18:21:47.503Z",
"question_score": 591,
"tags": "r|dataframe|r-factor|r-faq",
"answer_id": 1197154,
"answer_date": "2009-07-28T22:41:31.177Z",
"answer_score": 451
} |
Please answer the following Stack Overflow question:
Title: What's the best way to break from nested loops in JavaScript?
<p>What's the best way to break from nested loops in Javascript?</p>
<pre><code>//Write the links to the page.
for (var x = 0; x < Args.length; x++)
{
for (var Heading in Navigation.Headings)
{
for (var Item in Navigation.Headings[Heading])
{
if (Args[x] == Navigation.Headings[Heading][Item].Name)
{
document.write("<a href=\""
+ Navigation.Headings[Heading][Item].URL + "\">"
+ Navigation.Headings[Heading][Item].Name + "</a> : ");
break; // <---HERE, I need to break out of two loops.
}
}
}
}
</code></pre> | <p>Just like Perl,</p>
<pre><code>loop1:
for (var i in set1) {
loop2:
for (var j in set2) {
loop3:
for (var k in set3) {
break loop2; // breaks out of loop3 and loop2
}
}
}
</code></pre>
<p>as defined in EMCA-262 section 12.12. <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/label" rel="noreferrer">[MDN Docs]</a></p>
<p>Unlike C, these labels can only be used for <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/continue" rel="noreferrer"><code>continue</code></a> and <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/break" rel="noreferrer"><code>break</code></a>, as Javascript does not have <code>goto</code>.</p> | {
"question_id": 183161,
"question_date": "2008-10-08T14:47:25.100Z",
"question_score": 591,
"tags": "javascript|loops|nested-loops|break",
"answer_id": 183197,
"answer_date": "2008-10-08T14:53:40.720Z",
"answer_score": 1346
} |
Please answer the following Stack Overflow question:
Title: Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?
<p>A while ago I came across some code that marked a member variable of a class with the <code>mutable</code> keyword. As far as I can see it simply allows you to modify a variable in a <code>const</code> method:</p>
<pre><code>class Foo
{
private:
mutable bool done_;
public:
void doSomething() const { ...; done_ = true; }
};
</code></pre>
<p>Is this the only use of this keyword or is there more to it than meets the eye? I have since used this technique in a class, marking a <code>boost::mutex</code> as mutable allowing <code>const</code> functions to lock it for thread-safety reasons, but, to be honest, it feels like a bit of a hack.</p> | <p>It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result. </p>
<p>Since c++11 <code>mutable</code> can be used on a lambda to denote that things captured by value are modifiable (they aren't by default):</p>
<pre><code>int x = 0;
auto f1 = [=]() mutable {x = 42;}; // OK
auto f2 = [=]() {x = 42;}; // Error: a by-value capture cannot be modified in a non-mutable lambda
</code></pre> | {
"question_id": 105014,
"question_date": "2008-09-19T19:58:05.613Z",
"question_score": 591,
"tags": "c++|keyword|mutable",
"answer_id": 105061,
"answer_date": "2008-09-19T20:04:14.100Z",
"answer_score": 408
} |
Please answer the following Stack Overflow question:
Title: Using a dispatch_once singleton model in Swift
<p>I'm trying to work out an appropriate singleton model for usage in Swift. So far, I've been able to get a non-thread safe model working as:</p>
<pre><code>class var sharedInstance: TPScopeManager {
get {
struct Static {
static var instance: TPScopeManager? = nil
}
if !Static.instance {
Static.instance = TPScopeManager()
}
return Static.instance!
}
}
</code></pre>
<p>Wrapping the singleton instance in the Static struct should allow a single instance that doesn't collide with singleton instances without complex naming schemings, and it should make things fairly private. Obviously though, this model isn't thread-safe. So I tried to add <code>dispatch_once</code> to the whole thing:</p>
<pre><code>class var sharedInstance: TPScopeManager {
get {
struct Static {
static var instance: TPScopeManager? = nil
static var token: dispatch_once_t = 0
}
dispatch_once(Static.token) { Static.instance = TPScopeManager() }
return Static.instance!
}
}
</code></pre>
<p>But I get a compiler error on the <code>dispatch_once</code> line:</p>
<blockquote>
<p>Cannot convert the expression's type 'Void' to type '()'</p>
</blockquote>
<p>I've tried several different variants of the syntax, but they all seem to have the same results:</p>
<pre><code>dispatch_once(Static.token, { Static.instance = TPScopeManager() })
</code></pre>
<p>What is the proper usage of <code>dispatch_once</code> using Swift? I initially thought the problem was with the block due to the <code>()</code> in the error message, but the more I look at it, the more I think it may be a matter of getting the <code>dispatch_once_t</code> correctly defined.</p> | <p><em>tl;dr: Use the <strong>class constant</strong> approach if you are using Swift 1.2 or above and the <strong>nested struct</strong> approach if you need to support earlier versions.</em></p>
<p>From my experience with Swift there are three approaches to implement the Singleton pattern that support lazy initialization and thread safety.</p>
<h1>Class constant</h1>
<pre><code>class Singleton {
static let sharedInstance = Singleton()
}
</code></pre>
<p>This approach supports lazy initialization because Swift lazily initializes class constants (and variables), and is thread safe by the definition of <code>let</code>. This is now <a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-ID14">officially recommended way</a> to instantiate a singleton.</p>
<p>Class constants were introduced in Swift 1.2. If you need to support an earlier version of Swift, use the nested struct approach below or a global constant.</p>
<h1>Nested struct</h1>
<pre><code>class Singleton {
class var sharedInstance: Singleton {
struct Static {
static let instance: Singleton = Singleton()
}
return Static.instance
}
}
</code></pre>
<p>Here we are using the static constant of a nested struct as a class constant. This is a workaround for the lack of static class constants in Swift 1.1 and earlier, and still works as a workaround for the lack of static constants and variables in functions.</p>
<h1>dispatch_once</h1>
<p>The traditional Objective-C approach ported to Swift. I'm fairly certain there's no advantage over the nested struct approach but I'm putting it here anyway as I find the differences in syntax interesting.</p>
<pre><code>class Singleton {
class var sharedInstance: Singleton {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: Singleton? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = Singleton()
}
return Static.instance!
}
}
</code></pre>
<p>See this <a href="https://github.com/hpique/SwiftSingleton">GitHub</a> project for unit tests.</p> | {
"question_id": 24024549,
"question_date": "2014-06-03T20:41:12.367Z",
"question_score": 591,
"tags": "swift|singleton|dispatch",
"answer_id": 24147830,
"answer_date": "2014-06-10T17:57:53.583Z",
"answer_score": 726
} |
Please answer the following Stack Overflow question:
Title: How to use radio on change event?
<p>I have two radio button
on change event i want change button How it is possible?
My Code </p>
<pre><code><input type="radio" name="bedStatus" id="allot" checked="checked" value="allot">Allot
<input type="radio" name="bedStatus" id="transfer" value="transfer">Transfer
</code></pre>
<p>Script</p>
<pre><code><script>
$(document).ready(function () {
$('input:radio[name=bedStatus]:checked').change(function () {
if ($("input[name='bedStatus']:checked").val() == 'allot') {
alert("Allot Thai Gayo Bhai");
}
if ($("input[name='bedStatus']:checked").val() == 'transfer') {
alert("Transfer Thai Gayo");
}
});
});
</script>
</code></pre> | <p>You can use <code>this</code> which refers to the current <code>input</code> element.</p>
<pre><code>$('input[type=radio][name=bedStatus]').change(function() {
if (this.value == 'allot') {
// ...
}
else if (this.value == 'transfer') {
// ...
}
});
</code></pre>
<p><a href="http://jsfiddle.net/4gZAT/" rel="noreferrer">http://jsfiddle.net/4gZAT/</a></p>
<p>Note that you are comparing the value against <code>allot</code> in both if statements and <code>:radio</code> selector is deprecated.</p>
<p>In case that you are not using jQuery, you can use the <code>document.querySelectorAll</code> and <code>HTMLElement.addEventListener</code> methods:</p>
<pre><code>var radios = document.querySelectorAll('input[type=radio][name="bedStatus"]');
function changeHandler(event) {
if ( this.value === 'allot' ) {
console.log('value', 'allot');
} else if ( this.value === 'transfer' ) {
console.log('value', 'transfer');
}
}
Array.prototype.forEach.call(radios, function(radio) {
radio.addEventListener('change', changeHandler);
});
</code></pre> | {
"question_id": 13152927,
"question_date": "2012-10-31T07:09:53.890Z",
"question_score": 590,
"tags": "jquery|jquery-ui",
"answer_id": 13152970,
"answer_date": "2012-10-31T07:13:26.520Z",
"answer_score": 1149
} |
Please answer the following Stack Overflow question:
Title: How to do a logical OR operation for integer comparison in shell scripting?
<p>I am trying to do a simple condition check, but it doesn't seem to work.</p>
<p>If <code>$#</code> is equal to <code>0</code> or is greater than <code>1</code> then say hello.</p>
<p>I have tried the following syntax with no success:</p>
<pre><code>if [ "$#" == 0 -o "$#" > 1 ] ; then
echo "hello"
fi
if [ "$#" == 0 ] || [ "$#" > 1 ] ; then
echo "hello"
fi
</code></pre> | <p>This should work:</p>
<pre><code>#!/bin/bash
if [ "$#" -eq 0 ] || [ "$#" -gt 1 ] ; then
echo "hello"
fi
</code></pre>
<p>I'm not sure if this is different in other shells but if you wish to use <, >, you need to put them inside double parenthesis like so: </p>
<pre><code>if (("$#" > 1))
...
</code></pre> | {
"question_id": 4111475,
"question_date": "2010-11-06T01:48:33.717Z",
"question_score": 590,
"tags": "bash|unix|if-statement|sh",
"answer_id": 4111510,
"answer_date": "2010-11-06T02:03:12.633Z",
"answer_score": 1025
} |
Please answer the following Stack Overflow question:
Title: “Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL
<p>I'm developing a page that pulls images from Flickr and Panoramio via jQuery's AJAX support.</p>
<p>The Flickr side is working fine, but when I try to <code>$.get(url, callback)</code> from Panoramio, I see an error in Chrome's console:</p>
<blockquote>
<p>XMLHttpRequest cannot load <a href="http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&callback=processImages&minx=-30&miny=0&maxx=0&maxy=150" rel="noreferrer">http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&callback=processImages&minx=-30&miny=0&maxx=0&maxy=150</a>. Origin null is not allowed by Access-Control-Allow-Origin.</p>
</blockquote>
<p>If I query that URL from a browser directly it works fine. What is going on, and can I get around this? Am I composing my query incorrectly, or is this something that Panoramio does to hinder what I'm trying to do?</p>
<p>Google didn't turn up any useful matches on the <a href="http://www.google.co.uk/search?q=%22Origin+null+is+not+allowed+by+Access-Control-Allow-Origin%22" rel="noreferrer">error message</a>.</p>
<p><strong>EDIT</strong></p>
<p>Here's some sample code that shows the problem:</p>
<pre><code>$().ready(function () {
var url = 'http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&callback=processImages&minx=-30&miny=0&maxx=0&maxy=150';
$.get(url, function (jsonp) {
var processImages = function (data) {
alert('ok');
};
eval(jsonp);
});
});
</code></pre>
<p>You can <a href="http://jsfiddle.net/ZfvKm/" rel="noreferrer">run the example online</a>.</p>
<p><strong>EDIT 2</strong></p>
<p>Thanks to Darin for his help with this. <strong>THE ABOVE CODE IS WRONG.</strong> Use this instead:</p>
<pre><code>$().ready(function () {
var url = 'http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&minx=-30&miny=0&maxx=0&maxy=150&callback=?';
$.get(url, function (data) {
// can use 'data' in here...
});
});
</code></pre> | <p>For the record, as far as I can tell, you had two problems:</p>
<ol>
<li><p>You weren't passing a "jsonp" type specifier to your <code>$.get</code>, so it was using an ordinary XMLHttpRequest. However, your browser supported CORS (Cross-Origin Resource Sharing) to allow cross-domain XMLHttpRequest if the server OKed it. That's where the <code>Access-Control-Allow-Origin</code> header came in.</p></li>
<li><p>I believe you mentioned you were running it from a file:// URL. There are two ways for CORS headers to signal that a cross-domain XHR is OK. One is to send <code>Access-Control-Allow-Origin: *</code> (which, if you were reaching Flickr via <code>$.get</code>, they must have been doing) while the other was to echo back the contents of the <code>Origin</code> header. However, <code>file://</code> URLs produce a null <code>Origin</code> which can't be authorized via echo-back.</p></li>
</ol>
<p>The first was solved in a roundabout way by Darin's suggestion to use <code>$.getJSON</code>. It does a little magic to change the request type from its default of "json" to "jsonp" if it sees the substring <code>callback=?</code> in the URL.</p>
<p>That solved the second by no longer trying to perform a CORS request from a <code>file://</code> URL.</p>
<p>To clarify for other people, here are the simple troubleshooting instructions:</p>
<ol>
<li>If you're trying to use JSONP, make sure one of the following is the case:
<ul>
<li>You're using <code>$.get</code> and set <a href="http://api.jquery.com/jQuery.get/" rel="noreferrer"><code>dataType</code></a> to <code>jsonp</code>.</li>
<li>You're using <code>$.getJSON</code> and included <code>callback=?</code> in the URL.</li>
</ul></li>
<li>If you're trying to do a cross-domain XMLHttpRequest via CORS...
<ol>
<li>Make sure you're testing via <code>http://</code>. Scripts running via <code>file://</code> have limited support for CORS.</li>
<li>Make sure the browser <a href="http://caniuse.com/cors" rel="noreferrer">actually supports CORS</a>. (Opera and Internet Explorer are late to the party)</li>
</ol></li>
</ol> | {
"question_id": 3595515,
"question_date": "2010-08-29T16:12:40.617Z",
"question_score": 590,
"tags": "javascript|jquery|xmlhttprequest|cors|jsonp",
"answer_id": 3744697,
"answer_date": "2010-09-19T06:06:38.870Z",
"answer_score": 439
} |
Please answer the following Stack Overflow question:
Title: Android: Go back to previous activity
<p>I want to do something simple on android app.
How is it possible to go back to a previous activity. </p>
<p>What code do I need to go back to previous activity</p> | <p>Android activities are stored in the activity stack. Going back to a previous activity could mean two things.</p>
<ol>
<li><p>You opened the new activity from another activity with <strong>startActivityForResult</strong>. In that case you can just call the <strong>finishActivity()</strong> function from your code and it'll take you back to the previous activity.</p></li>
<li><p>Keep track of the activity stack. Whenever you start a new activity with an intent you can specify an intent flag like <code>FLAG_ACTIVITY_REORDER_TO_FRONT</code> or <code>FLAG_ACTIVITY_PREVIOUS_IS_TOP</code>. You can use this to shuffle between the activities in your application. Haven't used them much though. Have a look at the flags here: <a href="http://developer.android.com/reference/android/content/Intent.html" rel="noreferrer">http://developer.android.com/reference/android/content/Intent.html</a></p></li>
</ol>
<p>As mentioned in the comments, if the activity is opened with <code>startActivity()</code> then one can close it with <code>finish()</code>.
If you wish to use the Up button you can catch that in <code>onOptionsSelected(MenuItem item)</code> method with checking the item ID against <code>android.R.id.home</code> unlike <code>R.id.home</code> as mentioned in the comments.</p> | {
"question_id": 4038479,
"question_date": "2010-10-27T23:13:54.750Z",
"question_score": 590,
"tags": "android|android-intent|android-activity",
"answer_id": 4038637,
"answer_date": "2010-10-27T23:49:39.990Z",
"answer_score": 537
} |
Please answer the following Stack Overflow question:
Title: Import a file from a subdirectory?
<p>I have a file called <code>tester.py</code>, located on <code>/project</code>.</p>
<p><code>/project</code> has a subdirectory called <code>lib</code>, with a file called <code>BoxTime.py</code>:</p>
<pre class="lang-none prettyprint-override"><code>/project/tester.py
/project/lib/BoxTime.py
</code></pre>
<p>I want to import <code>BoxTime</code> from <code>tester</code>. I have tried this:</p>
<pre><code>import lib.BoxTime
</code></pre>
<p>Which resulted:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "./tester.py", line 3, in <module>
import lib.BoxTime
ImportError: No module named lib.BoxTime
</code></pre>
<p>Any ideas how to import <code>BoxTime</code> from the subdirectory?</p>
<p><strong>EDIT</strong></p>
<p>The <code>__init__.py</code> was the problem, but don't forget to refer to <code>BoxTime</code> as <code>lib.BoxTime</code>, or use:</p>
<pre><code>import lib.BoxTime as BT
...
BT.bt_function()
</code></pre> | <p>Take a look at the <strong><a href="https://docs.python.org/3/tutorial/modules.html#packages" rel="noreferrer">Packages documentation (Section 6.4)</a></strong>.</p>
<p>In short, you need to put a blank file named</p>
<pre><code>__init__.py
</code></pre>
<p>in the <code>lib</code> directory.</p> | {
"question_id": 1260792,
"question_date": "2009-08-11T14:39:05.467Z",
"question_score": 590,
"tags": "python|python-import",
"answer_id": 1260813,
"answer_date": "2009-08-11T14:42:10.267Z",
"answer_score": 655
} |
Please answer the following Stack Overflow question:
Title: Is there a Max function in SQL Server that takes two values like Math.Max in .NET?
<p>I want to write a query like this:</p>
<pre><code>SELECT o.OrderId, MAX(o.NegotiatedPrice, o.SuggestedPrice)
FROM Order o
</code></pre>
<p>But this isn't how the <code>MAX</code> function works, right? It is an aggregate function so it expects a single parameter and then returns the MAX of all rows. </p>
<p>Does anyone know how to do it my way?</p> | <p>You'd need to make a <code>User-Defined Function</code> if you wanted to have syntax similar to your example, but could you do what you want to do, inline, fairly easily with a <code>CASE</code> statement, as the others have said.</p>
<p>The <code>UDF</code> could be something like this:</p>
<pre><code>create function dbo.InlineMax(@val1 int, @val2 int)
returns int
as
begin
if @val1 > @val2
return @val1
return isnull(@val2,@val1)
end
</code></pre>
<p>... and you would call it like so ...</p>
<pre><code>SELECT o.OrderId, dbo.InlineMax(o.NegotiatedPrice, o.SuggestedPrice)
FROM Order o
</code></pre> | {
"question_id": 124417,
"question_date": "2008-09-23T22:52:03.837Z",
"question_score": 590,
"tags": "sql|sql-server|max",
"answer_id": 124474,
"answer_date": "2008-09-23T23:03:06.697Z",
"answer_score": 184
} |
Please answer the following Stack Overflow question:
Title: How to turn off word wrapping in HTML?
<p>I feel silly for not being able to figure this out, but how do I turn off wordwrap? the css <code>word-wrap</code> property can be forced on with <code>break-word</code>, but cannot be forced <em>off</em> (only can be left alone with <code>normal</code> value).</p>
<p>How do I force word wrap <em>off</em>?</p> | <p>You need to use the CSS <a href="http://www.impressivewebs.com/css-white-space/" rel="noreferrer"><code>white-space</code></a> attribute.</p>
<p>In particular, <code>white-space: nowrap</code> and <code>white-space: pre</code> are the most commonly used values. The first one seems to be what you 're after.</p> | {
"question_id": 4652654,
"question_date": "2011-01-10T23:19:32.980Z",
"question_score": 590,
"tags": "html|css|word-wrap",
"answer_id": 4652666,
"answer_date": "2011-01-10T23:21:08.663Z",
"answer_score": 968
} |
Please answer the following Stack Overflow question:
Title: 'git' is not recognized as an internal or external command
<p>I have an installation of Git for Windows, but when I try to use the <code>git</code> command in Command Prompt, I get the following error:</p>
<pre class="lang-none prettyprint-override"><code>'git' is not recognized as an internal or external command,
operable program or batch file.
</code></pre>
<p>How do I fix this problem?</p> | <p>Have you correctly set your <code>PATH</code> to point at your Git installation?</p>
<p>You need to add the following paths to <code>PATH</code>:</p>
<ul>
<li><code>C:\Program Files\Git\bin\</code></li>
<li><code>C:\Program Files\Git\cmd\</code></li>
</ul>
<p>And check that these paths are correct – you may have Git installed on a different drive, or under <code>Program Files (x86)</code>. Correct the paths if necessary.</p>
<hr>
<p>Modifying <code>PATH</code> on Windows 10:</p>
<ol>
<li>In the Start Menu or taskbar search, search for "environment variable".</li>
<li>Select "Edit the system environment variables".</li>
<li>Click the "Environment Variables" button at the bottom.</li>
<li>Double-click the "Path" entry under "System variables".</li>
<li>With the "New" button in the PATH editor, add <code>C:\Program Files\Git\bin\</code> and <code>C:\Program Files\Git\cmd\</code> to the end of the list.</li>
<li>Close and re-open your console.</li>
</ol>
<p>Modifying <code>PATH</code> on Windows 7:</p>
<ol>
<li>Right-click "Computer" on the Desktop or Start Menu.</li>
<li>Select "Properties".</li>
<li>On the very far left, click the "Advanced system settings" link.</li>
<li>Click the "Environment Variables" button at the bottom.</li>
<li>Double-click the "Path" entry under "System variables".</li>
<li>At the end of "Variable value", insert a <code>;</code> if there is not already one, and then <code>C:\Program Files\Git\bin\;C:\Program Files\Git\cmd\</code>. Do not put a space between <code>;</code> and the entry.</li>
<li>Close and re-open your console.</li>
</ol>
<p>If these instructions weren't helpful, feel free to look at some others:</p>
<ul>
<li><a href="https://www.computerhope.com/issues/ch000549.htm" rel="noreferrer">How to set the path and environment variables in Windows</a> (Computer Hope)</li>
<li><a href="https://www.howtogeek.com/118594/how-to-edit-your-system-path-for-easy-command-line-access/" rel="noreferrer">How to edit your system PATH for easy command line access in Windows</a> (How-To Geek)</li>
<li><a href="https://www.addictivetips.com/windows-tips/set-path-environment-variables-in-windows-10/" rel="noreferrer">How to set Path environment variables in Windows 10</a> (Addictive Tips)</li>
<li><a href="https://superuser.com/questions/284342/what-are-path-and-other-environment-variables-and-how-can-i-set-or-use-them">What are PATH and other environment variables, and how can I set or use them?</a> (Super User)</li>
</ul> | {
"question_id": 4492979,
"question_date": "2010-12-20T19:13:31.960Z",
"question_score": 589,
"tags": "windows|git|path|environment-variables|command-prompt",
"answer_id": 4493004,
"answer_date": "2010-12-20T19:16:10.293Z",
"answer_score": 787
} |
Please answer the following Stack Overflow question:
Title: Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?
<p>I know I've done this before years ago, but I can't remember the syntax, and I can't find it anywhere due to pulling up tons of help docs and articles about "bulk imports".</p>
<p>Here's what I want to do, but the syntax is not exactly right... please, someone who has done this before, help me out :)</p>
<pre><code>INSERT INTO dbo.MyTable (ID, Name)
VALUES (123, 'Timmy'),
(124, 'Jonny'),
(125, 'Sally')
</code></pre>
<p>I know that this is <em>close</em> to the right syntax. I might need the word "BULK" in there, or something, I can't remember. Any idea?</p>
<p>I need this for a SQL Server 2005 database. I've tried this code, to no avail:</p>
<pre><code>DECLARE @blah TABLE
(
ID INT NOT NULL PRIMARY KEY,
Name VARCHAR(100) NOT NULL
)
INSERT INTO @blah (ID, Name)
VALUES (123, 'Timmy')
VALUES (124, 'Jonny')
VALUES (125, 'Sally')
SELECT * FROM @blah
</code></pre>
<p>I'm getting <code>Incorrect syntax near the keyword 'VALUES'.</code></p> | <pre><code>INSERT INTO dbo.MyTable (ID, Name)
SELECT 123, 'Timmy'
UNION ALL
SELECT 124, 'Jonny'
UNION ALL
SELECT 125, 'Sally'
</code></pre>
<p>For SQL Server 2008, can do it in one VALUES clause <em>exactly</em> as per the statement in your question (you just need to add a comma to separate each values statement)...</p> | {
"question_id": 2624713,
"question_date": "2010-04-12T19:18:48.600Z",
"question_score": 589,
"tags": "sql-server|tsql|sql-server-2005|insert",
"answer_id": 2624754,
"answer_date": "2010-04-12T19:23:17.453Z",
"answer_score": 345
} |
Please answer the following Stack Overflow question:
Title: What is "not assignable to parameter of type never" error in TypeScript?
<p>Code is:</p>
<pre><code>const foo = (foo: string) => {
const result = []
result.push(foo)
}
</code></pre>
<p>I get the following TS error:</p>
<blockquote>
<p>[ts] Argument of type 'string' is not assignable to parameter of type 'never'.</p>
</blockquote>
<p>What am I doing wrong? Is this a bug?</p> | <p>All you have to do is define your <code>result</code> as a string array, like the following: </p>
<pre><code>const result : string[] = [];
</code></pre>
<p>Without defining the array type, it by default will be <code>never</code>. So when you tried to add a string to it, it was a type mismatch, and so it threw the error you saw.</p> | {
"question_id": 52423842,
"question_date": "2018-09-20T11:13:28Z",
"question_score": 589,
"tags": "typescript",
"answer_id": 52423919,
"answer_date": "2018-09-20T11:17:38.717Z",
"answer_score": 807
} |
Please answer the following Stack Overflow question:
Title: Does Java have support for multiline strings?
<p>Coming from Perl, I sure am missing the "here-document" means of creating a multi-line string in source code:</p>
<pre><code>$string = <<"EOF" # create a three-line string
text
text
text
EOF
</code></pre>
<p>In Java, I have to have cumbersome quotes and plus signs on every line as I concatenate my multiline string from scratch.</p>
<p>What are some better alternatives? Define my string in a properties file?</p>
<p><strong>Edit</strong>: Two answers say StringBuilder.append() is preferable to the plus notation. Could anyone elaborate as to why they think so? It doesn't look more preferable to me at all. I'm looking for a way around the fact that multiline strings are not a first-class language construct, which means I definitely don't want to replace a first-class language construct (string concatenation with plus) with method calls.</p>
<p><strong>Edit</strong>: To clarify my question further, I'm not concerned about performance at all. I'm concerned about maintainability and design issues.</p> | <p>Stephen Colebourne has created a <a href="http://blog.joda.org/2008/01/java-7-multi-line-string-literals_594.html" rel="noreferrer">proposal</a> for adding multi-line strings in Java 7.</p>
<p>Also, Groovy already has support for <a href="http://groovy-lang.org/syntax.html#_triple_single_quoted_string" rel="noreferrer">multi-line strings</a>.</p> | {
"question_id": 878573,
"question_date": "2009-05-18T16:28:47.287Z",
"question_score": 589,
"tags": "java|string|multiline",
"answer_id": 878958,
"answer_date": "2009-05-18T17:47:24.820Z",
"answer_score": 122
} |
Please answer the following Stack Overflow question:
Title: AngularJS passing data to $http.get request
<p>I have a function which does a http POST request. The code is specified below. This works fine.</p>
<pre><code> $http({
url: user.update_path,
method: "POST",
data: {user_id: user.id, draft: true}
});
</code></pre>
<p>I have another function for http GET and I want to send data to that request. But I don't have that option in get.</p>
<pre><code> $http({
url: user.details_path,
method: "GET",
data: {user_id: user.id}
});
</code></pre>
<p>The syntax for <code>http.get</code> is</p>
<p><strong>get(url, config)</strong></p> | <p>An HTTP GET request can't contain data to be posted to the server. However, you can add a query string to the request. </p>
<p>angular.http provides an option for it called <code>params</code>.</p>
<pre><code>$http({
url: user.details_path,
method: "GET",
params: {user_id: user.id}
});
</code></pre>
<p>See: <a href="http://docs.angularjs.org/api/ng.$http#get" rel="noreferrer">http://docs.angularjs.org/api/ng.$http#get</a> and <a href="https://docs.angularjs.org/api/ng/service/$http#usage" rel="noreferrer">https://docs.angularjs.org/api/ng/service/$http#usage</a> (shows the <code>params</code> param)</p> | {
"question_id": 13760070,
"question_date": "2012-12-07T09:16:20.300Z",
"question_score": 589,
"tags": "javascript|angularjs|javascript-framework",
"answer_id": 13760360,
"answer_date": "2012-12-07T09:34:11.507Z",
"answer_score": 957
} |
Please answer the following Stack Overflow question:
Title: How to replace all occurrences of a character in string?
<p>What is the effective way to replace all occurrences of a character with another character in <code>std::string</code>?</p> | <p><code>std::string</code> doesn't contain such function but you could use stand-alone <code>replace</code> function from <code>algorithm</code> header.</p>
<pre><code>#include <algorithm>
#include <string>
void some_func() {
std::string s = "example string";
std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}
</code></pre> | {
"question_id": 2896600,
"question_date": "2010-05-24T11:30:25.167Z",
"question_score": 589,
"tags": "c++|algorithm|str-replace|stdstring",
"answer_id": 2896627,
"answer_date": "2010-05-24T11:33:32.460Z",
"answer_score": 899
} |
Please answer the following Stack Overflow question:
Title: Enabling HTTPS on express.js
<p>I'm trying to get HTTPS working on express.js for node, and I can't figure it out.</p>
<p>This is my <code>app.js</code> code.</p>
<pre><code>var express = require('express');
var fs = require('fs');
var privateKey = fs.readFileSync('sslcert/server.key');
var certificate = fs.readFileSync('sslcert/server.crt');
var credentials = {key: privateKey, cert: certificate};
var app = express.createServer(credentials);
app.get('/', function(req,res) {
res.send('hello');
});
app.listen(8000);
</code></pre>
<p>When I run it, it seems to only respond to HTTP requests.</p>
<p>I wrote simple vanilla <code>node.js</code> based HTTPS app:</p>
<pre><code>var fs = require("fs"),
http = require("https");
var privateKey = fs.readFileSync('sslcert/server.key').toString();
var certificate = fs.readFileSync('sslcert/server.crt').toString();
var credentials = {key: privateKey, cert: certificate};
var server = http.createServer(credentials,function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
server.listen(8000);
</code></pre>
<p>And when I run this app, it <em>does</em> respond to HTTPS requests. Note that I don't think the toString() on the fs result matters, as I've used combinations of both and still no es bueno.</p>
<hr />
<p>EDIT TO ADD:</p>
<p>For production systems, you're probably better off using Nginx or HAProxy to proxy requests to your nodejs app. You can set up nginx to handle the ssl requests and just speak http to your node app.js.</p>
<p>EDIT TO ADD (4/6/2015)</p>
<p>For systems on using AWS, you are better off using EC2 Elastic Load Balancers to handle SSL Termination, and allow regular HTTP traffic to your EC2 web servers. For further security, setup your security group such that only the ELB is allowed to send HTTP traffic to the EC2 instances, which will prevent external unencrypted HTTP traffic from hitting your machines.</p>
<hr /> | <p>In express.js (since version 3) you should use that syntax:</p>
<pre class="lang-js prettyprint-override"><code>var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey = fs.readFileSync('sslcert/server.key', 'utf8');
var certificate = fs.readFileSync('sslcert/server.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();
// your express configuration here
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
httpServer.listen(8080);
httpsServer.listen(8443);
</code></pre>
<p>In that way you provide express middleware to the native http/https server</p>
<p>If you want your app running on ports below 1024, you will need to use <code>sudo</code> command (not recommended) or use a reverse proxy (e.g. nginx, haproxy).</p> | {
"question_id": 11744975,
"question_date": "2012-07-31T16:40:16.153Z",
"question_score": 589,
"tags": "node.js|https|express",
"answer_id": 11745114,
"answer_date": "2012-07-31T16:48:09.360Z",
"answer_score": 881
} |
Please answer the following Stack Overflow question:
Title: jQuery find events handlers registered with an object
<p>I need to find which event handlers are registered over an object.</p>
<p>For example:</p>
<pre><code>$("#el").click(function() {...});
$("#el").mouseover(function() {...});
</code></pre>
<p><code>$("#el")</code> has <em>click</em> and <em>mouseover</em> registered.</p>
<p>Is there a function to find out that, and possibly iterate over the event handlers?</p>
<p>If it is not possible on a jQuery object through proper methods, is it possible on a plain DOM object?</p> | <p>As of jQuery 1.8, the event data is no longer available from the "public API" for data. Read <a href="http://blog.jquery.com/2011/11/08/building-a-slimmer-jquery/" rel="noreferrer">this jQuery blog post</a>. You should now use this instead:</p>
<pre><code>jQuery._data( elem, "events" );
</code></pre>
<p><code>elem</code> should be an HTML Element, not a jQuery object, or selector.</p>
<p>Please note, that this is an internal, 'private' structure, and shouldn't be modified. Use this for debugging purposes only.</p>
<p>In older versions of jQuery, you might have to use the old method which is:</p>
<pre><code>jQuery( elem ).data( "events" );
</code></pre> | {
"question_id": 2518421,
"question_date": "2010-03-25T18:47:08.343Z",
"question_score": 589,
"tags": "jquery|events|dom",
"answer_id": 2518441,
"answer_date": "2010-03-25T18:50:43.653Z",
"answer_score": 725
} |
Please answer the following Stack Overflow question:
Title: How to update nested state properties in React
<p>I'm trying to organize my state by using nested property like this:</p>
<pre><code>this.state = {
someProperty: {
flag:true
}
}
</code></pre>
<p>But updating state like this,</p>
<pre><code>this.setState({ someProperty.flag: false });
</code></pre>
<p>doesn't work. How can this be done correctly?</p> | <p>In order to <code>setState</code> for a nested object you can follow the below approach as I think setState doesn't handle nested updates.</p>
<pre><code>var someProperty = {...this.state.someProperty}
someProperty.flag = true;
this.setState({someProperty})
</code></pre>
<p>The idea is to create a dummy object perform operations on it and then replace the component's state with the updated object</p>
<p>Now, the spread operator creates only one level nested copy of the object. If your state is highly nested like:</p>
<pre><code>this.state = {
someProperty: {
someOtherProperty: {
anotherProperty: {
flag: true
}
..
}
...
}
...
}
</code></pre>
<p>You could setState using spread operator at each level like</p>
<pre><code>this.setState(prevState => ({
...prevState,
someProperty: {
...prevState.someProperty,
someOtherProperty: {
...prevState.someProperty.someOtherProperty,
anotherProperty: {
...prevState.someProperty.someOtherProperty.anotherProperty,
flag: false
}
}
}
}))
</code></pre>
<p>However the above syntax get every ugly as the state becomes more and more nested and hence I recommend you to use <a href="https://github.com/kolodny/immutability-helper" rel="noreferrer"><code>immutability-helper</code></a> package to update the state.</p>
<p>See <a href="https://stackoverflow.com/questions/41949387/how-to-use-immutability-helper-to-update-a-nested-object-within-an-array/41949486#41949486">this answer</a> on how to update state with <code>immutability-helper</code>.</p> | {
"question_id": 43040721,
"question_date": "2017-03-27T07:51:38Z",
"question_score": 589,
"tags": "javascript|reactjs|ecmascript-6|setstate",
"answer_id": 43041334,
"answer_date": "2017-03-27T08:25:38.323Z",
"answer_score": 656
} |
Please answer the following Stack Overflow question:
Title: How to hide underbar in EditText
<p>How can I hide the EditText underbar (the prompt line with little serifs at the ends)?</p>
<p>There might be a better way to do what I want: I have a layout with an EditText. Normally, this displays fine where the user can tap on it and begin entering or editing text.</p>
<p>Sometimes, however, I would like to use the same layout (simplifies other logic) to display the same data in a read-only manner. I want the presentation to be similar - it should have the same height and same font, but not have the underbar.</p>
<p>As a stop-gap measure, I'm going to implement this by removing the EditText and substituting a TextView. I think that will give the desired results, but it seems like a roundabout an expensive way to do something that ought to be easy to do by changing attributes.</p> | <p>You can set the <code>EditText</code> to have a custom transparent drawable or just use </p>
<pre><code>android:background="@android:color/transparent"
</code></pre>
<p>or</p>
<pre><code>android:background="@null"
</code></pre>
<p>or Programmatically</p>
<pre><code>editText.setBackgroundResource(android.R.color.transparent);
</code></pre> | {
"question_id": 13975528,
"question_date": "2012-12-20T15:36:14.343Z",
"question_score": 589,
"tags": "android|textview|android-edittext",
"answer_id": 13975575,
"answer_date": "2012-12-20T15:38:19.220Z",
"answer_score": 1236
} |
Please answer the following Stack Overflow question:
Title: What is "runtime"?
<p>I have heard about things like "C Runtime", "Visual C++ 2008 Runtime", ".NET Common Language Runtime", etc.</p>
<ul>
<li>What is "<strong>runtime</strong>" exactly?</li>
<li>What is it made of?</li>
<li>How does it interact with my code? Or maybe more precisely, how is my code controlled by it?</li>
</ul>
<p>When coding assembly language on Linux, I could use the INT instruction to make the system call. So, is the runtime nothing but a bunch of pre-fabricated functions that wrap the low level function into more abstract and high level functions? But doesn't this seem more like the definition for the library, not for the runtime?</p>
<p>Are "runtime" and "<a href="http://en.wikipedia.org/wiki/Runtime_library" rel="noreferrer">runtime library</a>" two different things?</p>
<h2>ADD 1</h2>
<p>These days, I am thinking maybe <em>Runtime</em> has something in common with the so called <em>Virtual Machine</em>, such as JVM. Here's the quotation that leads to such thought:</p>
<blockquote>
<p>This compilation process is sufficiently complex to be broken into
several layers of abstraction, and these usually involve three
translators: a compiler, a virtual machine implementation, and an
assembler. --- <a href="https://rads.stackoverflow.com/amzn/click/com/0262640686" rel="noreferrer" rel="nofollow noreferrer">The Elements of Computing Systems</a> (Introduction,
The Road Down To Hardware Land)</p>
</blockquote>
<h2>ADD 2</h2>
<p>The book <a href="https://rads.stackoverflow.com/amzn/click/com/0131774298" rel="noreferrer" rel="nofollow noreferrer">Expert C Programming: Deep C Secrets</a>. Chapter 6 Runtime Data Structures is an useful reference to this question.</p>
<h2>ADD 3 - 7:31 AM 2/28/2021</h2>
<p>Here's some of my perspective after getting some knowledge about processor design. The whole computer thing is just multiple levels of <strong>abstraction</strong>. It goes from elementary transistors all the way up to the running program. For any <code>level N</code> of abstraction, its <strong>runtime</strong> is the immediate <code>level N-1</code> of abstraction that goes below it. And it is God that give us the level 0 of abstraction.</p> | <p>Runtime describes software/instructions that are executed <em>while</em> your program is running, especially those instructions that you did not write explicitly, but are necessary for the proper execution of your code.</p>
<p>Low-level languages like C have very small (if any) runtime. More complex languages like Objective-C, which allows for dynamic message passing, have a much more extensive runtime.</p>
<p>You are correct that runtime code is library code, but library code is a more general term, describing the code produced by <em>any</em> library. Runtime code is specifically the code required to implement the features of the language itself.</p> | {
"question_id": 3900549,
"question_date": "2010-10-10T13:49:14.733Z",
"question_score": 589,
"tags": "terminology",
"answer_id": 3900574,
"answer_date": "2010-10-10T13:58:24.510Z",
"answer_score": 377
} |
Please answer the following Stack Overflow question:
Title: Separation of business logic and data access in django
<p>I am writing a project in Django and I see that 80% of the code is in the file <code>models.py</code>. This code is confusing and, after a certain time, I cease to understand what is really happening.</p>
<p>Here is what bothers me:</p>
<ol>
<li>I find it ugly that my model level (which was supposed to be
responsible only for the work with data from a database) is also
sending email, walking on API to other services, etc.</li>
<li>Also, I find it unacceptable to place business logic in the view, because
this way it becomes difficult to control. For example, in my
application there are at least three ways to create new
instances of <code>User</code>, but technically it should create them uniformly.</li>
<li>I do not always notice when the methods and
properties of my models become non-deterministic and when they develop
side effects.</li>
</ol>
<p>Here is a simple example. At first, the <code>User</code> model was like this:</p>
<pre><code>class User(db.Models):
def get_present_name(self):
return self.name or 'Anonymous'
def activate(self):
self.status = 'activated'
self.save()
</code></pre>
<p>Over time, it turned into this:</p>
<pre><code>class User(db.Models):
def get_present_name(self):
# property became non-deterministic in terms of database
# data is taken from another service by api
return remote_api.request_user_name(self.uid) or 'Anonymous'
def activate(self):
# method now has a side effect (send message to user)
self.status = 'activated'
self.save()
send_mail('Your account is activated!', '…', [self.email])
</code></pre>
<p>What I want is to separate entities in my code:</p>
<ol>
<li><strong>Database level entities, i.e. database level logic: What kind of data does my application store?</strong></li>
<li><strong>application level entities, i.e. business level logic: What does my application do?</strong></li>
</ol>
<p>What are the good practices to implement such an approach that can be applied in Django?</p> | <p>It seems like you are asking about the difference between the <em>data model</em> and the <em>domain model</em> – the latter is where you can find the business logic and entities as perceived by your end user, the former is where you actually store your data.</p>
<p>Furthermore, I've interpreted the 3rd part of your question as: how to notice failure to keep these models separate.</p>
<p>These are two very different concepts and it's always hard to keep them separate. However, there are some common patterns and tools that can be used for this purpose.</p>
<h2>About the Domain Model</h2>
<p>The first thing you need to recognize is that your domain model is not really about data; it is about <em>actions</em> and <em>questions</em> such as "activate this user", "deactivate this user", "which users are currently activated?", and "what is this user's name?". In classical terms: it's about <em>queries</em> and <em>commands</em>.</p>
<h2>Thinking in Commands</h2>
<p>Let's start by looking at the commands in your example: "activate this user" and "deactivate this user". The nice thing about commands is that they can easily be expressed by small given-when-then scenario's:</p>
<blockquote>
<p><strong>given</strong> an inactive user <br/>
<strong>when</strong> the admin activates this user <br/>
<strong>then</strong> the user becomes active <br/>
<strong>and</strong> a confirmation e-mail is sent to the user <br/>
<strong>and</strong> an entry is added to the system log<br/>
(etc. etc.)</p>
</blockquote>
<p>Such scenario's are useful to see how different parts of your infrastructure can be affected by a single command – in this case your database (some kind of 'active' flag), your mail server, your system log, etc.</p>
<p>Such scenario's also really help you in setting up a Test Driven Development environment.</p>
<p>And finally, thinking in commands really helps you create a task-oriented application. Your users will appreciate this :-)</p>
<h2>Expressing Commands</h2>
<p>Django provides two easy ways of expressing commands; they are both valid options and it is not unusual to mix the two approaches.</p>
<h3>The service layer</h3>
<p>The <em>service module</em> has already been <a href="https://stackoverflow.com/a/12579490/383793">described by @Hedde</a>. Here you define a separate module and each command is represented as a function.</p>
<p><strong>services.py</strong></p>
<pre><code>def activate_user(user_id):
user = User.objects.get(pk=user_id)
# set active flag
user.active = True
user.save()
# mail user
send_mail(...)
# etc etc
</code></pre>
<h3>Using forms</h3>
<p>The other way is to use a Django Form for each command. I prefer this approach, because it combines multiple closely related aspects:</p>
<ul>
<li>execution of the command (what does it do?)</li>
<li>validation of the command parameters (can it do this?)</li>
<li>presentation of the command (how can I do this?)</li>
</ul>
<p><strong>forms.py</strong></p>
<pre><code>class ActivateUserForm(forms.Form):
user_id = IntegerField(widget = UsernameSelectWidget, verbose_name="Select a user to activate")
# the username select widget is not a standard Django widget, I just made it up
def clean_user_id(self):
user_id = self.cleaned_data['user_id']
if User.objects.get(pk=user_id).active:
raise ValidationError("This user cannot be activated")
# you can also check authorizations etc.
return user_id
def execute(self):
"""
This is not a standard method in the forms API; it is intended to replace the
'extract-data-from-form-in-view-and-do-stuff' pattern by a more testable pattern.
"""
user_id = self.cleaned_data['user_id']
user = User.objects.get(pk=user_id)
# set active flag
user.active = True
user.save()
# mail user
send_mail(...)
# etc etc
</code></pre>
<h2>Thinking in Queries</h2>
<p>You example did not contain any queries, so I took the liberty of making up a few useful queries. I prefer to use the term "question", but queries is the classical terminology. Interesting queries are: "What is the name of this user?", "Can this user log in?", "Show me a list of deactivated users", and "What is the geographical distribution of deactivated users?"</p>
<p>Before embarking on answering these queries, you should always ask yourself this question, is this:</p>
<ul>
<li>a <em>presentational</em> query just for my templates, and/or</li>
<li>a <em>business logic</em> query tied to executing my commands, and/or</li>
<li>a <em>reporting</em> query.</li>
</ul>
<p>Presentational queries are merely made to improve the user interface. The answers to business logic queries directly affect the execution of your commands. Reporting queries are merely for analytical purposes and have looser time constraints. These categories are not mutually exclusive.</p>
<p>The other question is: "do I have complete control over the answers?" For example, when querying the user's name (in this context) we do not have any control over the outcome, because we rely on an external API.</p>
<h2>Making Queries</h2>
<p>The most basic query in Django is the use of the Manager object:</p>
<pre><code>User.objects.filter(active=True)
</code></pre>
<p>Of course, this only works if the data is actually represented in your data model. This is not always the case. In those cases, you can consider the options below.</p>
<h3>Custom tags and filters</h3>
<p>The first alternative is useful for queries that are merely presentational: custom tags and template filters.</p>
<p><strong>template.html</strong></p>
<pre><code><h1>Welcome, {{ user|friendly_name }}</h1>
</code></pre>
<p><strong>template_tags.py</strong></p>
<pre><code>@register.filter
def friendly_name(user):
return remote_api.get_cached_name(user.id)
</code></pre>
<h3>Query methods</h3>
<p>If your query is not merely presentational, you could add queries to your <strong>services.py</strong> (if you are using that), or introduce a <strong>queries.py</strong> module:</p>
<p><strong>queries.py</strong></p>
<pre><code>def inactive_users():
return User.objects.filter(active=False)
def users_called_publysher():
for user in User.objects.all():
if remote_api.get_cached_name(user.id) == "publysher":
yield user
</code></pre>
<h3>Proxy models</h3>
<p>Proxy models are very useful in the context of business logic and reporting. You basically define an enhanced subset of your model. You can override a Manager’s base QuerySet by overriding the <a href="https://docs.djangoproject.com/en/2.0/topics/db/managers/#modifying-a-manager-s-initial-queryset" rel="noreferrer"><code>Manager.get_queryset()</code></a> method.</p>
<p><strong>models.py</strong></p>
<pre><code>class InactiveUserManager(models.Manager):
def get_queryset(self):
query_set = super(InactiveUserManager, self).get_queryset()
return query_set.filter(active=False)
class InactiveUser(User):
"""
>>> for user in InactiveUser.objects.all():
… assert user.active is False
"""
objects = InactiveUserManager()
class Meta:
proxy = True
</code></pre>
<h3>Query models</h3>
<p>For queries that are inherently complex, but are executed quite often, there is the possibility of query models. A query model is a form of denormalization where relevant data for a single query is stored in a separate model. The trick of course is to keep the denormalized model in sync with the primary model. Query models can only be used if changes are entirely under your control.</p>
<p><strong>models.py</strong></p>
<pre><code>class InactiveUserDistribution(models.Model):
country = CharField(max_length=200)
inactive_user_count = IntegerField(default=0)
</code></pre>
<p>The first option is to update these models in your commands. This is very useful if these models are only changed by one or two commands.</p>
<p><strong>forms.py</strong></p>
<pre><code>class ActivateUserForm(forms.Form):
# see above
def execute(self):
# see above
query_model = InactiveUserDistribution.objects.get_or_create(country=user.country)
query_model.inactive_user_count -= 1
query_model.save()
</code></pre>
<p>A better option would be to use custom signals. These signals are of course emitted by your commands. Signals have the advantage that you can keep multiple query models in sync with your original model. Furthermore, signal processing can be offloaded to background tasks, using Celery or similar frameworks.</p>
<p><strong>signals.py</strong></p>
<pre><code>user_activated = Signal(providing_args = ['user'])
user_deactivated = Signal(providing_args = ['user'])
</code></pre>
<p><strong>forms.py</strong></p>
<pre><code>class ActivateUserForm(forms.Form):
# see above
def execute(self):
# see above
user_activated.send_robust(sender=self, user=user)
</code></pre>
<p><strong>models.py</strong></p>
<pre><code>class InactiveUserDistribution(models.Model):
# see above
@receiver(user_activated)
def on_user_activated(sender, **kwargs):
user = kwargs['user']
query_model = InactiveUserDistribution.objects.get_or_create(country=user.country)
query_model.inactive_user_count -= 1
query_model.save()
</code></pre>
<h2>Keeping it clean</h2>
<p>When using this approach, it becomes ridiculously easy to determine if your code stays clean. Just follow these guidelines:</p>
<ul>
<li>Does my model contain methods that do more than managing database state? You should extract a command.</li>
<li>Does my model contain properties that do not map to database fields? You should extract a query.</li>
<li>Does my model reference infrastructure that is not my database (such as mail)? You should extract a command.</li>
</ul>
<p>The same goes for views (because views often suffer from the same problem).</p>
<ul>
<li>Does my view actively manage database models? You should extract a command.</li>
</ul>
<h2>Some References</h2>
<p><a href="https://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models" rel="noreferrer">Django documentation: proxy models</a></p>
<p><a href="https://docs.djangoproject.com/en/dev/topics/signals/" rel="noreferrer">Django documentation: signals</a></p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0321125215" rel="noreferrer" rel="nofollow noreferrer">Architecture: Domain Driven Design</a></p> | {
"question_id": 12578908,
"question_date": "2012-09-25T08:23:06.770Z",
"question_score": 589,
"tags": "python|django|model-view-controller|data-access-layer|business-logic-layer",
"answer_id": 12857584,
"answer_date": "2012-10-12T10:59:06.263Z",
"answer_score": 761
} |
Please answer the following Stack Overflow question:
Title: Is it better to call ToList() or ToArray() in LINQ queries?
<p>I often run into the case where I want to eval a query right where I declare it. This is usually because I need to iterate over it multiple times <em>and</em> it is expensive to compute. For example:</p>
<pre><code>string raw = "...";
var lines = (from l in raw.Split('\n')
let ll = l.Trim()
where !string.IsNullOrEmpty(ll)
select ll).ToList();
</code></pre>
<p>This works fine. <strong>But</strong> if I am not going to modify the result, then I might as well call <code>ToArray()</code> instead of <code>ToList()</code>.</p>
<p>I wonder however whether <code>ToArray()</code> is implemented by first calling <code>ToList()</code> and is therefore less memory efficient than just calling <code>ToList()</code>.</p>
<p>Am I crazy? Should I just call <code>ToArray()</code> - safe and secure in the knowledge that the memory won't be allocated twice?</p> | <p>Unless you simply need an array to meet other constraints you should use <code>ToList</code>. In the majority of scenarios <code>ToArray</code> will allocate more memory than <code>ToList</code>. </p>
<p>Both use arrays for storage, but <code>ToList</code> has a more flexible constraint. It needs the array to be at least as large as the number of elements in the collection. If the array is larger, that is not a problem. However <code>ToArray</code> needs the array to be sized exactly to the number of elements.</p>
<p>To meet this constraint <code>ToArray</code> often does one more allocation than <code>ToList</code>. Once it has an array that is big enough it allocates an array which is exactly the correct size and copies the elements back into that array. The only time it can avoid this is when the grow algorithm for the array just happens to coincide with the number of elements needing to be stored (definitely in the minority). </p>
<p><strong>EDIT</strong></p>
<p>A couple of people have asked me about the consequence of having the extra unused memory in the <code>List<T></code> value. </p>
<p>This is a valid concern. If the created collection is long lived, is never modified after being created and has a high chance of landing in the Gen2 heap then you may be better off taking the extra allocation of <code>ToArray</code> up front. </p>
<p>In general though I find this to be the rarer case. It's much more common to see a lot of <code>ToArray</code> calls which are immediately passed to other short lived uses of memory in which case <code>ToList</code> is demonstrably better. </p>
<p>The key here is to profile, profile and then profile some more. </p> | {
"question_id": 1105990,
"question_date": "2009-07-09T19:28:55.387Z",
"question_score": 589,
"tags": ".net|linq|performance",
"answer_id": 16323412,
"answer_date": "2013-05-01T17:42:23.113Z",
"answer_score": 430
} |
Please answer the following Stack Overflow question:
Title: Converting an integer to a string in PHP
<p>Is there a way to convert an integer to a string in PHP?</p> | <p>You can use the <a href="http://php.net/manual/en/function.strval.php" rel="noreferrer"><code>strval()</code></a> function to convert a number to a string.</p>
<p>From a maintenance perspective its obvious what you are trying to do rather than some of the other more esoteric answers. Of course, it depends on your context.</p>
<pre><code>$var = 5;
// Inline variable parsing
echo "I'd like {$var} waffles"; // = I'd like 5 waffles
// String concatenation
echo "I'd like ".$var." waffles"; // I'd like 5 waffles
// The two examples above have the same end value...
// ... And so do the two below
// Explicit cast
$items = (string)$var; // $items === "5";
// Function call
$items = strval($var); // $items === "5";
</code></pre> | {
"question_id": 1035634,
"question_date": "2009-06-23T22:37:45.063Z",
"question_score": 588,
"tags": "php|string|casting|type-conversion|integer",
"answer_id": 1035658,
"answer_date": "2009-06-23T22:43:58.127Z",
"answer_score": 915
} |
Please answer the following Stack Overflow question:
Title: How to check whether an array is empty using PHP?
<p><code>players</code> will either be empty or a comma separated list (or a single value). What is the easiest way to check if it's empty? I'm assuming I can do so as soon as I fetch the <code>$gameresult</code> array into <code>$gamerow</code>? In this case it would probably be more efficient to skip exploding the <code>$playerlist</code> if it's empty, but for the sake of argument, how would I check if an array is empty as well?</p>
<pre><code>$gamerow = mysql_fetch_array($gameresult);
$playerlist = explode(",", $gamerow['players']);
</code></pre> | <p>If you just need to check if there are ANY elements in the array, you can use either the array itself, due to PHP's loose typing, or - if you prefer a stricter approach - use <code>count()</code>:</p>
<pre><code>if (!$playerlist) {
// list is empty.
}
if (count($playerlist) === 0) {
// list is empty.
}
</code></pre>
<p>If you need to clean out empty values before checking (generally done to prevent <code>explode</code>ing weird strings):</p>
<pre><code>foreach ($playerlist as $key => $value) {
if (!strlen($value)) {
unset($playerlist[$key]);
}
}
if (!$playerlist) {
//empty array
}
</code></pre> | {
"question_id": 2216052,
"question_date": "2010-02-07T05:30:02.807Z",
"question_score": 588,
"tags": "php|arrays",
"answer_id": 2216063,
"answer_date": "2010-02-07T05:32:45.677Z",
"answer_score": 948
} |
Please answer the following Stack Overflow question:
Title: How do I iterate over a JSON structure?
<p>I have the following JSON structure:</p>
<pre><code>[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]
</code></pre>
<p>How do I iterate over it using JavaScript?</p> | <p>Taken from <a href="http://docs.jquery.com/Utilities/jQuery.each" rel="noreferrer">jQuery docs</a>:</p>
<pre><code>var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(arr, function() {
$("#" + this).text("My id is " + this + ".");
return (this != "four"); // will stop running to skip "five"
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
</code></pre> | {
"question_id": 1078118,
"question_date": "2009-07-03T07:09:09.857Z",
"question_score": 588,
"tags": "javascript|json|loops",
"answer_id": 1078132,
"answer_date": "2009-07-03T07:12:20.570Z",
"answer_score": 454
} |
Please answer the following Stack Overflow question:
Title: Elasticsearch query to return all records
<p>I have a small database in Elasticsearch and for testing purposes would like to pull all records back. I am attempting to use a URL of the form...</p>
<pre><code>http://localhost:9200/foo/_search?pretty=true&q={'matchAll':{''}}
</code></pre>
<p>Can someone give me the URL you would use to accomplish this, please?</p> | <p>I think lucene syntax is supported so:</p>
<p><code>http://localhost:9200/foo/_search?pretty=true&q=*:*</code></p>
<p>size defaults to 10, so you may also need <code>&size=BIGNUMBER</code> to get more than 10 items. (where BIGNUMBER equals a number you believe is bigger than your dataset)</p>
<p>BUT, elasticsearch documentation <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-search-type.html" rel="noreferrer">suggests</a> for large result sets, using the scan search type.</p>
<p>EG:</p>
<pre><code>curl -XGET 'localhost:9200/foo/_search?search_type=scan&scroll=10m&size=50' -d '
{
"query" : {
"match_all" : {}
}
}'
</code></pre>
<p>and then keep requesting as per the documentation link above suggests.</p>
<p>EDIT: <code>scan</code> Deprecated in 2.1.0.</p>
<p><code>scan</code> does not provide any benefits over a regular <code>scroll</code> request sorted by <code>_doc</code>. <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-search-type.html#scan" rel="noreferrer">link to elastic docs</a> (spotted by @christophe-roussy)</p> | {
"question_id": 8829468,
"question_date": "2012-01-12T02:41:25.847Z",
"question_score": 588,
"tags": "database|elasticsearch|query-string|elasticsearch-dsl",
"answer_id": 8831494,
"answer_date": "2012-01-12T07:28:19.287Z",
"answer_score": 872
} |
Please answer the following Stack Overflow question:
Title: How to read a large file - line by line?
<p>I want to iterate over each line of an entire file. One way to do this is by reading the entire file, saving it to a list, then going over the line of interest. This method uses a lot of memory, so I am looking for an alternative.</p>
<p>My code so far:</p>
<pre><code>for each_line in fileinput.input(input_file):
do_something(each_line)
for each_line_again in fileinput.input(input_file):
do_something(each_line_again)
</code></pre>
<p>Executing this code gives an error message: <code>device active</code>.</p>
<p>Any suggestions?</p>
<p>The purpose is to calculate pair-wise string similarity, meaning for each line in file, I want to calculate the Levenshtein distance with every other line.</p> | <p>The correct, fully Pythonic way to read a file is the following:</p>
<pre><code>with open(...) as f:
for line in f:
# Do something with 'line'
</code></pre>
<p>The <code>with</code> statement handles opening and closing the file, including if an exception is raised in the inner block. The <code>for line in f</code> treats the file object <code>f</code> as an iterable, which automatically uses buffered I/O and memory management so you don't have to worry about large files.</p>
<blockquote>
<p>There should be one -- and preferably only one -- obvious way to do it.</p>
</blockquote> | {
"question_id": 8009882,
"question_date": "2011-11-04T13:26:29.013Z",
"question_score": 588,
"tags": "python|file-read",
"answer_id": 8010133,
"answer_date": "2011-11-04T13:46:44.787Z",
"answer_score": 1358
} |
Please answer the following Stack Overflow question:
Title: How to determine an object's class?
<p>If class <code>B</code> and class <code>C</code> extend class <code>A</code> and I have an object of type <code>B</code> or <code>C</code>, how can I determine of which type it is an instance?</p> | <pre><code>if (obj instanceof C) {
//your code
}
</code></pre> | {
"question_id": 541749,
"question_date": "2009-02-12T15:18:24.763Z",
"question_score": 588,
"tags": "java|inheritance",
"answer_id": 541769,
"answer_date": "2009-02-12T15:21:19.857Z",
"answer_score": 880
} |
Please answer the following Stack Overflow question:
Title: Remove duplicates from a List<T> in C#
<p>Anyone have a quick method for de-duplicating a generic List in C#?</p> | <p>Perhaps you should consider using a <a href="http://msdn.microsoft.com/en-us/library/bb359438.aspx" rel="noreferrer">HashSet</a>.</p>
<p>From the MSDN link:</p>
<pre><code>using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> evenNumbers = new HashSet<int>();
HashSet<int> oddNumbers = new HashSet<int>();
for (int i = 0; i < 5; i++)
{
// Populate numbers with just even numbers.
evenNumbers.Add(i * 2);
// Populate oddNumbers with just odd numbers.
oddNumbers.Add((i * 2) + 1);
}
Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);
DisplaySet(evenNumbers);
Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count);
DisplaySet(oddNumbers);
// Create a new HashSet populated with even numbers.
HashSet<int> numbers = new HashSet<int>(evenNumbers);
Console.WriteLine("numbers UnionWith oddNumbers...");
numbers.UnionWith(oddNumbers);
Console.Write("numbers contains {0} elements: ", numbers.Count);
DisplaySet(numbers);
}
private static void DisplaySet(HashSet<int> set)
{
Console.Write("{");
foreach (int i in set)
{
Console.Write(" {0}", i);
}
Console.WriteLine(" }");
}
}
/* This example produces output similar to the following:
* evenNumbers contains 5 elements: { 0 2 4 6 8 }
* oddNumbers contains 5 elements: { 1 3 5 7 9 }
* numbers UnionWith oddNumbers...
* numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 }
*/
</code></pre> | {
"question_id": 47752,
"question_date": "2008-09-06T19:15:27.690Z",
"question_score": 588,
"tags": "c#|list|generics|duplicates",
"answer_id": 47757,
"answer_date": "2008-09-06T19:21:55.070Z",
"answer_score": 240
} |
Please answer the following Stack Overflow question:
Title: How to iterate over a JavaScript object?
<p>I have an object in JavaScript:</p>
<pre><code>{
abc: '...',
bca: '...',
zzz: '...',
xxx: '...',
ccc: '...',
// ...
}
</code></pre>
<p>I want to use a <code>for</code> loop to get its properties. And I want to iterate it in parts (not all object properties at once).</p>
<p>With a simple array I can do it with a standard <code>for</code> loop:</p>
<pre><code>for (i = 0; i < 100; i++) { ... } // first part
for (i = 100; i < 300; i++) { ... } // second
for (i = 300; i < arr.length; i++) { ... } // last
</code></pre>
<p>But how to do it with objects?</p> | <p>For iterating on keys of <a href="https://stackoverflow.com/a/69604222/343302">Arrays, Strings, or Objects</a>, use <code>for .. in</code> :</p>
<pre><code>for (let key in yourobject) {
console.log(key, yourobject[key]);
}
</code></pre>
<p>With ES6, if you need both keys and values simultaneously, do</p>
<pre><code>for (let [key, value] of Object.entries(yourobject)) {
console.log(key, value);
}
</code></pre>
<p>To avoid logging inherited properties, check with <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty" rel="noreferrer">hasOwnProperty</a> :</p>
<pre><code>for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) {
console.log(key, yourobject[key]);
}
}
</code></pre>
<p><em>You don't need to check <code>hasOwnProperty</code> when iterating on keys if you're using a simple object (for example one you made yourself with <code>{}</code>).</em></p>
<p><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects" rel="noreferrer">This MDN documentation</a> explains more generally how to deal with objects and their properties.</p>
<p>If you want to do it "in chunks", the best is to extract the keys in an array. As the order isn't guaranteed, this is the proper way. In modern browsers, you can use</p>
<pre><code>let keys = Object.keys(yourobject);
</code></pre>
<p>To be more compatible, you'd better do this :</p>
<pre><code> let keys = [];
for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) keys.push(key);
}
</code></pre>
<p>Then you can iterate on your properties by index: <code>yourobject[keys[i]]</code> :</p>
<pre><code>for (let i=300; i < keys.length && i < 600; i++) {
console.log(keys[i], yourobject[keys[i]]);
}
</code></pre> | {
"question_id": 14379274,
"question_date": "2013-01-17T12:36:15.157Z",
"question_score": 588,
"tags": "javascript|loops|object|iteration|javascript-objects",
"answer_id": 14379304,
"answer_date": "2013-01-17T12:37:59.373Z",
"answer_score": 1163
} |
Please answer the following Stack Overflow question:
Title: JSON.NET Error Self referencing loop detected for type
<p>I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used</p>
<pre class="lang-cs prettyprint-override"><code>JsonConvert.SerializeObject
</code></pre>
<p>I got the following error:</p>
<blockquote>
<p>Error Self referencing loop detected for type System.data.entity occurs.</p>
</blockquote>
<p>How do I solve this problem?</p> | <p>That was the best solution
<a href="https://docs.microsoft.com/en-us/archive/blogs/hongyes/loop-reference-handling-in-web-api" rel="noreferrer">https://docs.microsoft.com/en-us/archive/blogs/hongyes/loop-reference-handling-in-web-api</a></p>
<h1>Fix 1: Ignoring circular reference globally</h1>
<p><em>(I have chosen/tried this one, as have many others)</em></p>
<p>The json.net serializer has an option to ignore circular references. Put the following code in <code>WebApiConfig.cs</code> file:</p>
<pre><code> config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling
= Newtonsoft.Json.ReferenceLoopHandling.Ignore;
</code></pre>
<p>The simple fix will make serializer to ignore the reference which will cause a loop. However, it has limitations:</p>
<ul>
<li>The data loses the looping reference information</li>
<li>The fix only applies to JSON.net</li>
<li>The level of references can't be controlled if there is a deep reference chain</li>
</ul>
<p>If you want to use this fix in a non-api ASP.NET project, you can add the above line to <code>Global.asax.cs</code>, but first add:</p>
<pre><code>var config = GlobalConfiguration.Configuration;
</code></pre>
<p>If you want to use this in <strong>.Net Core</strong> project, you can change <code>Startup.cs</code> as:</p>
<pre><code> var mvc = services.AddMvc(options =>
{
...
})
.AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
</code></pre>
<h1>Fix 2: Preserving circular reference globally</h1>
<p>This second fix is similar to the first. Just change the code to:</p>
<pre><code>config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling
= Newtonsoft.Json.ReferenceLoopHandling.Serialize;
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling
= Newtonsoft.Json.PreserveReferencesHandling.Objects;
</code></pre>
<p>The data shape will be changed after applying this setting.</p>
<pre><code>[
{
"$id":"1",
"Category":{
"$id":"2",
"Products":[
{
"$id":"3",
"Category":{
"$ref":"2"
},
"Id":2,
"Name":"Yogurt"
},
{
"$ref":"1"
}
],
"Id":1,
"Name":"Diary"
},
"Id":1,
"Name":"Whole Milk"
},
{
"$ref":"3"
}
]
</code></pre>
<p>The $id and $ref keeps the all the references and makes the object graph level flat, but the client code needs to know the shape change to consume the data and it only applies to JSON.NET serializer as well.</p>
<h1>Fix 3: Ignore and preserve reference attributes</h1>
<p>This fix is decorate attributes on model class to control the serialization behavior on model or property level. To ignore the property:</p>
<pre><code> public class Category
{
public int Id { get; set; }
public string Name { get; set; }
[JsonIgnore]
[IgnoreDataMember]
public virtual ICollection<Product> Products { get; set; }
}
</code></pre>
<p>JsonIgnore is for JSON.NET and IgnoreDataMember is for XmlDCSerializer.
To preserve reference:</p>
<pre><code> // Fix 3
[JsonObject(IsReference = true)]
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
// Fix 3
//[JsonIgnore]
//[IgnoreDataMember]
public virtual ICollection<Product> Products { get; set; }
}
[DataContract(IsReference = true)]
public class Product
{
[Key]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public virtual Category Category { get; set; }
}
</code></pre>
<p><code>JsonObject(IsReference = true)] </code>is for JSON.NET and <code>[DataContract(IsReference = true)]</code> is for XmlDCSerializer. Note that: after applying <code>DataContract</code> on class, you need to add <code>DataMember</code> to properties that you want to serialize.</p>
<p>The attributes can be applied on both json and xml serializer and gives more controls on model class.</p> | {
"question_id": 7397207,
"question_date": "2011-09-13T05:25:25.523Z",
"question_score": 588,
"tags": "c#|json|serialization|json.net",
"answer_id": 18223985,
"answer_date": "2013-08-14T05:41:31.860Z",
"answer_score": 585
} |
Please answer the following Stack Overflow question:
Title: Most efficient way to convert an HTMLCollection to an Array
<p>Is there a more efficient way to convert an HTMLCollection to an Array, other than iterating through the contents of said collection and manually pushing each item into an array?</p> | <pre><code>var arr = Array.prototype.slice.call( htmlCollection )
</code></pre>
<p>will have the same effect using "native" code.</p>
<p><strong>Edit</strong></p>
<p>Since this gets a lot of views, note (per @oriol's comment) that the following more concise expression is <em>effectively</em> equivalent:</p>
<pre><code>var arr = [].slice.call(htmlCollection);
</code></pre>
<p>But note per @JussiR's comment, that unlike the "verbose" form, it does create an empty, unused, and indeed unusable array instance in the process. What compilers do about this is outside the programmer's ken.</p>
<p><strong>Edit</strong></p>
<p>Since ECMAScript 2015 (ES 6) there is also <a href="http://ecma-international.org/ecma-262/8.0/#sec-array.from" rel="noreferrer"><em>Array.from</em></a>:</p>
<pre><code>var arr = Array.from(htmlCollection);
</code></pre>
<p><strong>Edit</strong></p>
<p>ECMAScript 2015 also provides the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax" rel="noreferrer">spread operator</a>, which is functionally equivalent to <code>Array.from</code> (although note that <code>Array.from</code> supports a mapping function as the second argument).</p>
<pre><code>var arr = [...htmlCollection];
</code></pre>
<p>I've confirmed that both of the above work on <code>NodeList</code>.</p>
<p>A performance comparison for the mentioned methods: <a href="http://jsben.ch/h2IFA" rel="noreferrer">http://jsben.ch/h2IFA</a></p> | {
"question_id": 222841,
"question_date": "2008-10-21T18:04:53.997Z",
"question_score": 588,
"tags": "javascript|arrays|object",
"answer_id": 222847,
"answer_date": "2008-10-21T18:06:47.567Z",
"answer_score": 1007
} |
Please answer the following Stack Overflow question:
Title: htmlentities() vs. htmlspecialchars()
<p>What are the differences between <code>htmlspecialchars()</code> and <code>htmlentities()</code>. When should I use one or the other?</p> | <p>From the PHP documentation for <a href="http://us2.php.net/htmlentities" rel="noreferrer">htmlentities</a>:</p>
<blockquote>
<p>This function is identical to <code>htmlspecialchars()</code> in all ways, except with <code>htmlentities()</code>, all characters which have HTML character entity equivalents are translated into these entities. </p>
</blockquote>
<p>From the PHP documentation for <a href="http://us.php.net/htmlspecialchars" rel="noreferrer">htmlspecialchars</a>:</p>
<blockquote>
<p>Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use <code>htmlentities()</code> instead.</p>
</blockquote>
<p>The difference is what gets encoded. The choices are everything (entities) or "special" characters, like ampersand, double and single quotes, less than, and greater than (specialchars).</p>
<p>I prefer to use <code>htmlspecialchars</code> whenever possible.</p>
<p>For example:</p>
<pre class="lang-php prettyprint-override"><code> echo htmlentities('<Il était une fois un être>.');
// Output: &lt;Il &eacute;tait une fois un &ecirc;tre&gt;.
// ^^^^^^^^ ^^^^^^^
echo htmlspecialchars('<Il était une fois un être>.');
// Output: &lt;Il était une fois un être&gt;.
// ^ ^
</code></pre> | {
"question_id": 46483,
"question_date": "2008-09-05T18:29:12.880Z",
"question_score": 588,
"tags": "php",
"answer_id": 46491,
"answer_date": "2008-09-05T18:31:52.920Z",
"answer_score": 382
} |
Please answer the following Stack Overflow question:
Title: What is the best way to initialize a JavaScript Date to midnight?
<p>What is the simplest way to obtain an instance of <code>new Date()</code> but set the time at midnight?</p> | <p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours" rel="noreferrer"><code>setHours</code></a> method can take optional <code>minutes</code>, <code>seconds</code> and <code>ms</code> arguments, for example:</p>
<pre><code>var d = new Date();
d.setHours(0,0,0,0);
</code></pre>
<p>That will set the time to <code>00:00:00.000</code> of <em>your current timezone</em>, if you want to work in UTC time, you can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours" rel="noreferrer"><code>setUTCHours</code></a> method.</p> | {
"question_id": 3894048,
"question_date": "2010-10-08T20:24:51.270Z",
"question_score": 588,
"tags": "javascript",
"answer_id": 3894087,
"answer_date": "2010-10-08T20:31:43.267Z",
"answer_score": 1187
} |
Please answer the following Stack Overflow question:
Title: When would you use the Builder Pattern?
<p>What are some <em>common</em>, <em>real world examples</em> of using the Builder Pattern? What does it buy you? Why not just use a Factory Pattern?</p> | <p>The key difference between a builder and factory IMHO, is that a builder is useful when you need to do lots of things to build an object. For example imagine a DOM. You have to create plenty of nodes and attributes to get your final object. A factory is used when the factory can easily create the entire object within one method call.</p>
<p>One example of using a builder is a building an XML document, I've used this model when building HTML fragments for example I might have a Builder for building a specific type of table and it might have the following methods <strong>(parameters are not shown)</strong>:</p>
<pre><code>BuildOrderHeaderRow()
BuildLineItemSubHeaderRow()
BuildOrderRow()
BuildLineItemSubRow()
</code></pre>
<p>This builder would then spit out the HTML for me. This is much easier to read than walking through a large procedural method.</p>
<p>Check out <a href="http://en.wikipedia.org/wiki/Builder_pattern" rel="noreferrer">Builder Pattern on Wikipedia</a>.</p> | {
"question_id": 328496,
"question_date": "2008-11-30T05:41:23.250Z",
"question_score": 588,
"tags": "java|design-patterns|builder",
"answer_id": 328506,
"answer_date": "2008-11-30T05:51:16.913Z",
"answer_score": 283
} |
Please answer the following Stack Overflow question:
Title: Process all arguments except the first one (in a bash script)
<p>I have a simple script where the first argument is reserved for the filename, and all other optional arguments should be passed to other parts of the script.</p>
<p>Using Google I found <a href="http://wiki.bash-hackers.org/scripting/posparams#mass_usage">this wiki</a>, but it provided a literal example:</p>
<pre><code>echo "${@: -1}"
</code></pre>
<p>I can't get anything else to work, like:</p>
<pre><code>echo "${@:2}"
</code></pre>
<p>or</p>
<pre><code>echo "${@:2,1}"
</code></pre>
<p>I get "Bad substitution" from the terminal.</p>
<p>What is the problem, and how can I process all but the first argument passed to a bash script?</p> | <p>Use this:</p>
<pre><code>echo "${@:2}"
</code></pre>
<hr>
<p>The following syntax:</p>
<pre><code>echo "${*:2}"
</code></pre>
<p>would work as well, but is not recommended, because as <a href="https://stackoverflow.com/questions/9057387/process-all-arguments-except-the-first-one#comment11369452_9057392">@Gordon</a> already explained, that using <code>*</code>, it runs all of the arguments together as a single argument with spaces, while <code>@</code> preserves the breaks between them (even if some of the arguments themselves contain spaces). It doesn't make the difference with <code>echo</code>, but it matters for many other commands.</p> | {
"question_id": 9057387,
"question_date": "2012-01-29T22:31:22.757Z",
"question_score": 588,
"tags": "bash|shell",
"answer_id": 9057392,
"answer_date": "2012-01-29T22:32:55.117Z",
"answer_score": 865
} |
Please answer the following Stack Overflow question:
Title: Multiple line code example in Javadoc comment
<p>I have a small code example I want to include in the Javadoc comment for a method. </p>
<pre><code>/**
* -- ex: looping through List of Map objects --
* <code>
* for (int i = 0; i < list.size(); i++) {
* Map map = (Map)list.get(i);
* System.out.println(map.get("wordID"));
* System.out.println(map.get("word"));
* }
* </code>
*
* @param query - select statement
* @return List of Map objects
*/
</code></pre>
<p>The problem is the code example shows up in the Javadoc with no line breaks making it hard to read. </p>
<pre><code>-- ex: looping through List of Map objects -- for (int i = 0; i list.size(); i++) { Map map = (Map)list.get(i); System.out.println(map.get("wordID")); System.out.println(map.get("word")); }
Parameters
query - - select statement
Returns:
List of Map objects
</code></pre>
<p>I guess I am wrong in assuming the code tag would handle line breaks. What is the best way to format code examples in Javadoc comments ?</p> | <p>In addition to the already mentioned <code><pre></code> tags, you should also use the <code>@code</code> JavaDoc annotation, which will make life much easier when it comes to HTML entities issues (in particular with Generics), e.g.:</p>
<pre><code>* <pre>
* {@code
* Set<String> s;
* System.out.println(s);
* }
* </pre>
</code></pre>
<p>Will give correct HTML output:</p>
<pre><code>Set<String> s;
System.out.println(s);
</code></pre>
<p>While omitting the <code>@code</code> block (or using a <code><code></code> tag) will result in HTML like this:</p>
<pre><code>Set s;
System.out.println(s);
</code></pre>
<p>For reference, a full list of tag descriptions available in Java SE 8 can be found <a href="https://docs.oracle.com/javase/8/docs/technotes/tools/unix/javadoc.html#CHDJGIJB" rel="noreferrer">here</a>.</p> | {
"question_id": 541920,
"question_date": "2009-02-12T15:52:42.620Z",
"question_score": 588,
"tags": "java|html|javadoc",
"answer_id": 542142,
"answer_date": "2009-02-12T16:26:42.633Z",
"answer_score": 821
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.