input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: Global Events in Angular
<p>Is there no equivalent to <code>$scope.emit()</code> or <code>$scope.broadcast()</code> in Angular?</p>
<p>I know the <code>EventEmitter</code> functionality, but as far as I understand that will just emit an event to the parent HTML element.</p>
<p>What if I need to communicate between fx. siblings or between a component in the root of the DOM and an element nested several levels deep?</p> | <p>There is no equivalent to <code>$scope.emit()</code> or <code>$scope.broadcast()</code> from AngularJS.
EventEmitter inside of a component comes close, but as you mentioned, it will only emit an event to the immediate parent component.</p>
<p>In Angular, there are other alternatives which I'll try to explain below. </p>
<p>@Input() bindings allows the application model to be connected in a directed object graph (root to leaves). The default behavior of a component's change detector strategy is to propagate all changes to an application model for all bindings from any connected component. </p>
<p>Aside: There are two types of models: View Models and Application Models. An application model is connected through @Input() bindings. A view model is a just a component property (not decorated with @Input()) which is bound in the component's template.</p>
<p>To answer your questions:</p>
<p>What if I need to communicate between sibling components? </p>
<ol>
<li><p><strong>Shared Application Model</strong>:
Siblings can communicate through a shared application model (just like angular 1). For example, when one sibling makes a change to a model, the other sibling that has bindings to the same model is automatically updated.</p></li>
<li><p><strong>Component Events</strong>: Child components can emit an event to the parent component using @Output() bindings. The parent component can handle the event, and manipulate the application model or it's own view model. Changes to the Application Model are automatically propagated to all components that directly or indirectly bind to the same model.</p></li>
<li><p><strong>Service Events</strong>: Components can subscribe to service events. For example, two sibling components can subscribe to the same service event and respond by modifying their respective models. More on this below.</p></li>
</ol>
<p>How can I communicate between a Root component and a component nested several levels deep?</p>
<ol>
<li><strong>Shared Application Model</strong>: The application model can be passed from the Root component down to deeply nested sub-components through @Input() bindings. Changes to a model from any component will automatically propagate to all components that share the same model.</li>
<li><strong>Service Events</strong>: You can also move the EventEmitter to a shared service, which allows any component to inject the service and subscribe to the event. That way, a Root component can call a service method (typically mutating the model), which in turn emits an event. Several layers down, a grand-child component which has also injected the service and subscribed to the same event, can handle it. Any event handler that changes a shared Application Model, will automatically propagate to all components that depend on it. This is probably the closest equivalent to <code>$scope.broadcast()</code> from Angular 1. The next section describes this idea in more detail.</li>
</ol>
<p><strong>Example of an Observable Service that uses Service Events to Propagate Changes</strong></p>
<p>Here is an example of an observable service that uses service events to propagate changes. When a TodoItem is added, the service emits an event notifying its component subscribers.</p>
<pre><code>export class TodoItem {
constructor(public name: string, public done: boolean) {
}
}
export class TodoService {
public itemAdded$: EventEmitter<TodoItem>;
private todoList: TodoItem[] = [];
constructor() {
this.itemAdded$ = new EventEmitter();
}
public list(): TodoItem[] {
return this.todoList;
}
public add(item: TodoItem): void {
this.todoList.push(item);
this.itemAdded$.emit(item);
}
}
</code></pre>
<p>Here is how a root component would subscribe to the event:</p>
<pre><code>export class RootComponent {
private addedItem: TodoItem;
constructor(todoService: TodoService) {
todoService.itemAdded$.subscribe(item => this.onItemAdded(item));
}
private onItemAdded(item: TodoItem): void {
// do something with added item
this.addedItem = item;
}
}
</code></pre>
<p>A child component nested several levels deep would subscribe to the event in the same way: </p>
<pre><code>export class GrandChildComponent {
private addedItem: TodoItem;
constructor(todoService: TodoService) {
todoService.itemAdded$.subscribe(item => this.onItemAdded(item));
}
private onItemAdded(item: TodoItem): void {
// do something with added item
this.addedItem = item;
}
}
</code></pre>
<p>Here is the component that calls the service to trigger the event (it can reside anywhere in the component tree):</p>
<pre><code>@Component({
selector: 'todo-list',
template: `
<ul>
<li *ngFor="#item of model"> {{ item.name }}
</li>
</ul>
<br />
Add Item <input type="text" #txt /> <button (click)="add(txt.value); txt.value='';">Add</button>
`
})
export class TriggeringComponent{
private model: TodoItem[];
constructor(private todoService: TodoService) {
this.model = todoService.list();
}
add(value: string) {
this.todoService.add(new TodoItem(value, false));
}
}
</code></pre>
<p>Reference: <a href="http://victorsavkin.com/post/110170125256/change-detection-in-angular-2" rel="noreferrer">Change Detection in Angular</a></p> | {
"question_id": 34700438,
"question_date": "2016-01-10T00:03:20.380Z",
"question_score": 235,
"tags": "angular|events",
"answer_id": 34703015,
"answer_date": "2016-01-10T07:13:25.953Z",
"answer_score": 404
} |
Please answer the following Stack Overflow question:
Title: Getting the docstring from a function
<p>I have the following function:</p>
<pre><code>def my_func():
"""My docstring is both funny and informative"""
pass
</code></pre>
<p>How do I get access to the docstring?</p> | <p>Interactively, you can display it with</p>
<pre><code>help(my_func)
</code></pre>
<p>Or from code you can retrieve it with</p>
<pre><code>my_func.__doc__
</code></pre> | {
"question_id": 713138,
"question_date": "2009-04-03T09:04:09.677Z",
"question_score": 235,
"tags": "python",
"answer_id": 713143,
"answer_date": "2009-04-03T09:05:57.440Z",
"answer_score": 327
} |
Please answer the following Stack Overflow question:
Title: How can I use NSError in my iPhone App?
<p>I am working on catching errors in my app, and I am looking into using <code>NSError</code>. I am slightly confused about how to use it, and how to populate it.</p>
<p><strong>Could someone provide an example on how I populate then use <code>NSError</code>?</strong></p> | <p>Well, what I usually do is have my methods that could error-out at runtime take a reference to a <code>NSError</code> pointer. If something does indeed go wrong in that method, I can populate the <code>NSError</code> reference with error data and return nil from the method.</p>
<p>Example:</p>
<pre><code>- (id) endWorldHunger:(id)largeAmountsOfMonies error:(NSError**)error {
// begin feeding the world's children...
// it's all going well until....
if (ohNoImOutOfMonies) {
// sad, we can't solve world hunger, but we can let people know what went wrong!
// init dictionary to be used to populate error object
NSMutableDictionary* details = [NSMutableDictionary dictionary];
[details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey];
// populate the error object with the details
*error = [NSError errorWithDomain:@"world" code:200 userInfo:details];
// we couldn't feed the world's children...return nil..sniffle...sniffle
return nil;
}
// wohoo! We fed the world's children. The world is now in lots of debt. But who cares?
return YES;
}
</code></pre>
<p>We can then use the method like this. Don't even bother to inspect the error object unless the method returns nil:</p>
<pre><code>// initialize NSError object
NSError* error = nil;
// try to feed the world
id yayOrNay = [self endWorldHunger:smallAmountsOfMonies error:&error];
if (!yayOrNay) {
// inspect error
NSLog(@"%@", [error localizedDescription]);
}
// otherwise the world has been fed. Wow, your code must rock.
</code></pre>
<p>We were able to access the error's <code>localizedDescription</code> because we set a value for <code>NSLocalizedDescriptionKey</code>. </p>
<p>The best place for more information is <a href="https://developer.apple.com/documentation/foundation/nserror" rel="noreferrer">Apple's documentation</a>. It really is good.</p>
<p>There is also a nice, simple tutorial on <a href="http://www.cimgf.com/2008/04/04/cocoa-tutorial-using-nserror-to-great-effect/" rel="noreferrer">Cocoa Is My Girlfriend</a>. </p> | {
"question_id": 4654653,
"question_date": "2011-01-11T05:53:59.593Z",
"question_score": 235,
"tags": "iphone|ios|objective-c|ios4|nserror",
"answer_id": 4654759,
"answer_date": "2011-01-11T06:15:51.150Z",
"answer_score": 485
} |
Please answer the following Stack Overflow question:
Title: How do you remove a specific revision in the git history?
<p>Suppose your git history looks like this:</p>
<p>1
2
3
4
5</p>
<p>1–5 are separate revisions. You need to remove 3 while still keeping 1, 2, 4 and 5. How can this be done?</p>
<p>Is there an efficient method when there are hundreds of revisions after the one to be deleted?</p> | <p>To combine revision 3 and 4 into a single revision, you can use git rebase. If you want to remove the changes in revision 3, you need to use the edit command in the interactive rebase mode. If you want to combine the changes into a single revision, use squash.</p>
<p>I have successfully used this squash technique, but have never needed to remove a revision before. The git-rebase documentation under "Splitting commits" should hopefully give you enough of an idea to figure it out. (Or someone else might know).</p>
<p>From the <a href="http://git-scm.com/docs/git-rebase" rel="noreferrer">git documentation</a>:</p>
<blockquote>
<p>Start it with the oldest commit you want to retain as-is:</p>
<blockquote><code>git rebase -i <after-this-commit></code></blockquote>
<p>An editor will be fired up with all the commits in your current branch (ignoring merge commits), which come after the given commit. You can reorder the commits in this list to your heart's content, and you can remove them. The list looks more or less like this:</p>
<blockquote><pre>pick deadbee The oneline of this commit
pick fa1afe1 The oneline of the next commit
...</pre></blockquote>
<p>The oneline descriptions are purely for your pleasure; git-rebase will not look at them but at the commit names ("deadbee" and "fa1afe1" in this example), so do not delete or edit the names.</p>
<p>By replacing the command "pick" with the command "edit", you can tell git-rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.</p>
<p>If you want to fold two or more commits into one, replace the command "pick" with "squash" for the second and subsequent commit. If the commits had different authors, it will attribute the squashed commit to the author of the first commit.</p>
</blockquote> | {
"question_id": 37219,
"question_date": "2008-08-31T22:51:21.327Z",
"question_score": 235,
"tags": "git",
"answer_id": 37267,
"answer_date": "2008-08-31T23:46:33.880Z",
"answer_score": 79
} |
Please answer the following Stack Overflow question:
Title: ViewModelProviders is deprecated in 1.1.0
<p>Looking at the <a href="https://developer.android.com/topic/libraries/architecture/viewmodel" rel="noreferrer">Google docs</a> for <code>ViewModel</code>, they show the below sample code on how to get a <code>ViewModel</code>:</p>
<pre><code>val model = ViewModelProviders.of(this).get(MyViewModel::class.java)
</code></pre>
<p>When using the latest dependency <code>android.arch.lifecycle:extensions:1.1.1</code> there is no such class <code>ViewModelProviders</code>.</p>
<p>Going to the <a href="https://developer.android.com/reference/android/arch/lifecycle/ViewModelProviders" rel="noreferrer">documentation</a> for <code>ViewModelProviders</code>, I saw a comment saying:</p>
<blockquote>
<p>This class was deprecated in API level 1.1.0. Use ViewModelProvider.AndroidViewModelFactory </p>
</blockquote>
<p>The problem is, when trying to use <code>ViewModelProvider.AndroidViewModelFactory</code>, cannot find an equivalent <code>of</code> method to get the instance of the <code>ViewModel</code>.</p>
<p>What i tried doing:</p>
<pre><code>ViewModelProvider.AndroidViewModelFactory.getInstance(application).create(PlayerViewHolder::class.java)
</code></pre>
<p>Hence the name of the method <code>create</code>, I get a new instance of the ViewModel every-time I call it, which is not what I am after.</p>
<p>Any ideas what is the replacement of deprecated code above?</p> | <p><strong>UPDATE 2020-06-16</strong>: <em>Presently</em> <code>ViewModelProviders</code> is deprecated and should no longer be used. This question and answer were from late 2018, when that was not the case. This question and answer are also for the older Architecture Components edition of <code>ViewModelProviders</code>, not the AndroidX edition.</p>
<hr>
<blockquote>
<p>When using the latest dependency <code>android.arch.lifecycle:extensions:1.1.1</code> there is no such class <code>ViewModelProviders</code>.</p>
</blockquote>
<p>Yes, there is. To demonstrate this:</p>
<ul>
<li><p>Create a new project in Android Studio 3.2.1 (with Kotlin, <code>minSdkVersion</code> 21, "empty activity" template)</p></li>
<li><p>Add <code>android.arch.lifecycle:extensions:1.1.1</code> to the dependencies of the <code>app</code> module</p></li>
</ul>
<p>This will give you an <code>app/build.gradle</code> like:</p>
<pre><code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.commonsware.myandroidarch"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'android.arch.lifecycle:extensions:1.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code></pre>
<p>You will then see that library show up in "External Libraries" with that class:</p>
<p><img src="https://i.stack.imgur.com/h7aFI.png" alt="External Libraries"></p>
<p>And you will be able to reference that class:</p>
<pre><code>package com.commonsware.myandroidarch
import android.arch.lifecycle.ViewModelProviders
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val provider = ViewModelProviders.of(this)
}
}
</code></pre>
<blockquote>
<p>Going to the documentation for ViewModelProviders, I saw a comment saying: This class was deprecated in API level 1.1.0. Use ViewModelProvider.AndroidViewModelFactory</p>
</blockquote>
<p>That comment is underneath the <code>ViewModelProviders.DefaultFactory</code> class entry and refers to that class, not <code>ViewModelProviders</code>:</p>
<p><img src="https://i.stack.imgur.com/DDhQE.png" alt="Documentation Screenshot"></p>
<blockquote>
<p>Any ideas what is the replacement of deprecated code above?</p>
</blockquote>
<p>Use <code>ViewModelProviders</code>.</p> | {
"question_id": 53903762,
"question_date": "2018-12-23T12:53:44.143Z",
"question_score": 235,
"tags": "android|android-gradle-plugin|android-architecture-components|android-viewmodel",
"answer_id": 53903865,
"answer_date": "2018-12-23T13:08:01.887Z",
"answer_score": 47
} |
Please answer the following Stack Overflow question:
Title: Interview question: Check if one string is a rotation of other string
<p>A friend of mine was asked the following question today at interview for the position of software developer:</p>
<p>Given two string <code>s1</code> and <code>s2</code> how will you check if <code>s1</code> is a <strong>rotated</strong> version of <code>s2</code> ?</p>
<p><strong><em>Example:</em></strong> </p>
<p>If <code>s1 = "stackoverflow"</code> then the following are some of its rotated versions:</p>
<pre><code>"tackoverflows"
"ackoverflowst"
"overflowstack"
</code></pre>
<p>where as <code>"stackoverflwo"</code> is <strong><em>not</em></strong> a rotated version.</p>
<p>The answer he gave was:<br></p>
<blockquote>
<p>Take <code>s2</code> and find the longest prefix that is a sub string of <code>s1</code>, that will give you the point of rotation. Once you find that point, break <code>s2</code> at that point to get <code>s2a</code> and <code>s2b</code>, then just check if <code>concatenate(s2a,s2b) == s1</code></p>
</blockquote>
<p>It looks like a good solution to me and my friend. But the interviewer thought otherwise. He asked for a simpler solution. Please help me by telling how would you do this in <code>Java/C/C++</code> ?</p>
<p>Thanks in advance.</p> | <p>First make sure <code>s1</code> and <code>s2</code> are of the same length. Then check to see if <code>s2</code> is a substring of <code>s1</code> concatenated with <code>s1</code>:</p>
<pre><code>algorithm checkRotation(string s1, string s2)
if( len(s1) != len(s2))
return false
if( substring(s2,concat(s1,s1))
return true
return false
end
</code></pre>
<p>In Java:</p>
<pre><code>boolean isRotation(String s1,String s2) {
return (s1.length() == s2.length()) && ((s1+s1).indexOf(s2) != -1);
}
</code></pre> | {
"question_id": 2553522,
"question_date": "2010-03-31T13:58:25.650Z",
"question_score": 235,
"tags": "java|c++|c",
"answer_id": 2553533,
"answer_date": "2010-03-31T13:59:58.267Z",
"answer_score": 686
} |
Please answer the following Stack Overflow question:
Title: Transforming a Javascript iterable into an array
<p>I'm trying to use the new <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map">Map</a> object from Javascript EC6, since it's already supported in the latest Firefox and Chrome versions.</p>
<p>But I'm finding it very limited in "functional" programming, because it lacks classic map, filter etc. methods that would work nicely with a <code>[key, value]</code> pair. It has a forEach but that does NOT returns the callback result.</p>
<p>If I could transform its <code>map.entries()</code> from a MapIterator into a simple Array I could then use the standard <code>.map</code>, <code>.filter</code> with no additional hacks.</p>
<p>Is there a "good" way to transform a Javascript Iterator into an Array?
In python it's as easy as doing <code>list(iterator)</code>... but <code>Array(m.entries())</code> return an array with the Iterator as its first element!!!</p>
<p><strong>EDIT</strong></p>
<p>I forgot to specify I'm looking for an answer which works wherever Map works, which means at least Chrome and Firefox (Array.from does not work in Chrome).</p>
<p><strong>PS.</strong></p>
<p>I know there's the fantastic <a href="https://fitzgen.github.io/wu.js/">wu.js</a> but its dependency on traceur puts me off...</p> | <p>You are looking for the new <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from"><code>Array.from</code> function</a> which converts arbitrary iterables to array instances:</p>
<pre><code>var arr = Array.from(map.entries());
</code></pre>
<p>It is now <a href="http://kangax.github.io/compat-table/es6/#test-Array_static_methods_Array.from,_instances_of_generic_iterables">supported in Edge, FF, Chrome and Node 4+</a>.</p>
<p>Of course, it might be worth to define <code>map</code>, <code>filter</code> and similar methods directly on the iterator interface, so that you can avoid allocating the array. You also might want to use a generator function instead of higher-order functions:</p>
<pre><code>function* map(iterable) {
var i = 0;
for (var item of iterable)
yield yourTransformation(item, i++);
}
function* filter(iterable) {
var i = 0;
for (var item of iterable)
if (yourPredicate(item, i++))
yield item;
}
</code></pre> | {
"question_id": 28718641,
"question_date": "2015-02-25T12:06:16.293Z",
"question_score": 235,
"tags": "javascript|ecmascript-6",
"answer_id": 28718967,
"answer_date": "2015-02-25T12:23:18.893Z",
"answer_score": 343
} |
Please answer the following Stack Overflow question:
Title: How can I add an ampersand for a value in a ASP.net/C# app config file value
<p>I've got a C# program with values in a config file. What I want is to store ampersands for an url value like...</p>
<pre><code><appSettings>
<add key="myurl" value="http://www.myurl.com?&cid=&sid="/>
</appSettings>
</code></pre>
<p>But I get errors building my site. The ampersand is not allowed. I've tried various forms of escaping the ampersands to no avail. Anyone know of the correct form to do this? All suggestions are welcome.</p> | <p>Use "<code>&amp;</code>" instead of "&".</p> | {
"question_id": 376135,
"question_date": "2008-12-17T21:45:28.413Z",
"question_score": 235,
"tags": "c#|asp.net|web-config",
"answer_id": 376140,
"answer_date": "2008-12-17T21:46:33.700Z",
"answer_score": 471
} |
Please answer the following Stack Overflow question:
Title: Difference between val() and text()
<p>What the difference between jQuery's functions <code>val()</code> and <code>text()</code>?</p>
<p>Where would you use one over the other?</p> | <p><code>.val()</code> works on input elements (or any element with a value attribute?) and <code>.text()</code> will not work on input elements. <code>.val()</code> gets the value of the input element -- regardless of type. <code>.text()</code> gets the innerText (not HTML) of all the matched elements:</p>
<p><a href="http://docs.jquery.com/Attributes/text" rel="noreferrer"><code>.text()</code></a></p>
<blockquote>
<p>The result is a string that contains
the combined text contents of all
matched elements. This method works on
both HTML and XML documents. Cannot be
used on input elements. For input
field text use the val attribute.</p>
</blockquote>
<p><a href="http://docs.jquery.com/Attributes/val" rel="noreferrer"><code>.val()</code></a></p>
<blockquote>
<p>Get the content of the value attribute
of the first matched element</p>
</blockquote> | {
"question_id": 807867,
"question_date": "2009-04-30T16:36:42.503Z",
"question_score": 235,
"tags": "javascript|jquery|html",
"answer_id": 807908,
"answer_date": "2009-04-30T16:43:06.573Z",
"answer_score": 299
} |
Please answer the following Stack Overflow question:
Title: Can't use forEach with Filelist
<p>I'm trying to loop through a <code>Filelist</code>:</p>
<pre><code>console.log('field:', field.photo.files)
field.photo.files.forEach(file => {
// looping code
})
</code></pre>
<p>As you can see <code>field.photo.files</code> has a <code>Filelist</code>:</p>
<p><a href="https://i.stack.imgur.com/ci9Er.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ci9Er.png" alt="enter image description here"></a></p>
<p>How to properly loop through <code>field.photo.files</code>?</p> | <p>A <code>FileList</code> is not an <code>Array</code>, but it does conform to its contract (has <code>length</code> and numeric indices), so we can "borrow" <code>Array</code> methods:</p>
<pre><code>Array.prototype.forEach.call(field.photo.files, function(file) { ... });
</code></pre>
<p>Since you're obviously using ES6, you could also make it a proper <code>Array</code>, using the new <code>Array.from</code> method:</p>
<pre><code>Array.from(field.photo.files).forEach(file => { ... });
</code></pre> | {
"question_id": 40902437,
"question_date": "2016-12-01T04:02:41.587Z",
"question_score": 235,
"tags": "javascript|file",
"answer_id": 40902462,
"answer_date": "2016-12-01T04:05:25.460Z",
"answer_score": 400
} |
Please answer the following Stack Overflow question:
Title: Why is the use of len(SEQUENCE) in condition values considered incorrect by Pylint?
<p>Considering this code snippet:</p>
<pre><code>from os import walk
files = []
for (dirpath, _, filenames) in walk(mydir):
# More code that modifies files
if len(files) == 0: # <-- C1801
return None
</code></pre>
<p>I was alarmed by Pylint with this message regarding the line with the if statement:</p>
<blockquote>
<p>[pylint] C1801:Do not use <code>len(SEQUENCE)</code> as condition value</p>
</blockquote>
<p>The rule C1801, at first glance, did not sound very reasonable to me, and the <a href="https://pylint.readthedocs.io/en/latest/reference_guide/features.html#id19" rel="noreferrer">definition on the reference guide</a> does not explain why this is a problem. In fact, it downright calls it an <em>incorrect use</em>.</p>
<blockquote>
<p><strong>len-as-condition (C1801)</strong>:
<em>Do not use <code>len(SEQUENCE)</code> as condition value Used when Pylint detects incorrect use of len(sequence) inside conditions.</em></p>
</blockquote>
<p>My search attempts have also failed to provide me a deeper explanation. I do understand that a sequence's length property may be lazily evaluated, and that <code>__len__</code> can be programmed to have side effects, but it is questionable whether that alone is problematic enough for Pylint to call such a use incorrect. Hence, before I simply configure my project to ignore the rule, I would like to know whether I am missing something in my reasoning.</p>
<p>When is the use of <code>len(SEQ)</code> as a condition value problematic? What major situations is Pylint attempting to avoid with C1801?</p> | <blockquote>
<p>When is the use of <code>len(SEQ)</code> as a condition value problematic? What major
situations is Pylint attempting to avoid with C1801?</p>
</blockquote>
<p>It’s not <em>really</em> problematic to use <code>len(SEQUENCE)</code> – though it may not be as efficient (see <a href="https://stackoverflow.com/questions/43121340/why-is-the-use-of-lensequence-in-condition-values-considered-incorrect-by-pyli#comment73322508_43121340">chepner’s comment</a>). Regardless, Pylint checks code for compliance with the <a href="https://www.python.org/dev/peps/pep-0008" rel="noreferrer">PEP 8 style guide</a> which states that</p>
<blockquote>
<p>For sequences, (strings, lists, tuples), use the fact that empty sequences are false.</p>
<pre><code><b>Yes:</b> if not seq:
if seq:
<b>No:</b> if len(seq):
if not len(seq):
</code></pre>
</blockquote>
<p>As an occasional Python programmer, who flits between languages, I’d consider the <code>len(SEQUENCE)</code> construct to be more readable and explicit (“Explicit is better then implicit”). However, using the fact that an empty sequence evaluates to <code>False</code> in a Boolean context is considered more “Pythonic”.</p> | {
"question_id": 43121340,
"question_date": "2017-03-30T14:52:30.960Z",
"question_score": 235,
"tags": "python|conditional-statements|pylint",
"answer_id": 43476778,
"answer_date": "2017-04-18T15:49:48.063Z",
"answer_score": 315
} |
Please answer the following Stack Overflow question:
Title: Use rvmrc or ruby-version file to set a project gemset with RVM?
<p>I use RVM, the <a href="https://rvm.io/">Ruby Version Manager</a> to specify a Ruby version and a set of gems for each of my Rails projects.</p>
<p>I have a <code>.rvmrc</code> file to automatically select a Ruby version and gemset whenever I <code>cd</code> into a project directory.</p>
<p>After installing RVM 1.19.0, I get a message</p>
<blockquote>
<p>You are using <code>.rvmrc</code>, it requires trusting, it is slower and it is
not compatible with other ruby managers, you can switch to
<code>.ruby-version</code> using <code>rvm rvmrc to [.]ruby-version</code> or ignore this
warnings with <code>rvm rvmrc warning ignore
/Users/userName/code/railsapps/rails-prelaunch-signup/.rvmrc</code>,
<code>.rvmrc</code> will continue to be the default project file in RVM 1 and RVM
2, to ignore the warning for all files run <code>rvm rvmrc warning ignore
all.rvmrcs</code>.</p>
</blockquote>
<p>Should I continue using my <code>.rvmrc</code> file or should I switch to a <code>.ruby-version</code> file? Which is optimal? What are the ramifications?</p> | <p>If your <code>.rvmrc</code> file contains custom shell code, continue using <code>.rvmrc</code> as it allows you to include any shell code.</p>
<p>If your only aim is to switch Ruby versions, then use <code>.ruby-version</code> which is supported by other Ruby version switchers such as <a href="https://github.com/sstephenson/rbenv" rel="noreferrer">rbenv</a> or <a href="https://github.com/postmodern/chruby" rel="noreferrer">chruby</a>. This file also does not require trusting as it is just the name of a Ruby version and will not be executed in any way.</p>
<p>If you use <code>.ruby-version</code> you can include <code>@gemset</code> in the file but this will not be compatible with other switchers. To maintain compatibility use the gemset name in a separate file <code>.ruby-gemset</code> which is ignored by other tools <em>(it works only together with <code>.ruby-version</code>)</em>.</p>
<p>For example, if you have a simple <code>.rvmrc</code>:</p>
<pre><code>rvm use 1.9.3@my-app
</code></pre>
<p>It can be transformed to <code>.ruby-version</code>:</p>
<pre><code>1.9.3
</code></pre>
<p>And <code>.ruby-gemset</code>:</p>
<pre><code>my-app
</code></pre>
<p>Be sure to remove the <code>.rvmrc</code> file as it takes precedence over any other project configuration files:</p>
<pre><code>rm .rvmrc
</code></pre> | {
"question_id": 15708916,
"question_date": "2013-03-29T18:09:08.320Z",
"question_score": 235,
"tags": "ruby-on-rails|ruby-on-rails-3|ruby-on-rails-3.2|rvm|rvmrc",
"answer_id": 15709012,
"answer_date": "2013-03-29T18:15:26.593Z",
"answer_score": 381
} |
Please answer the following Stack Overflow question:
Title: What are the main disadvantages of Java Server Faces 2.0?
<p>Yesterday I saw a presentation on Java Server Faces 2.0 which looked truly impressive, even though I am currently a happy ASP.NET MVC / jQuery developer. What I liked most about JSF was the huge amount of AJAX-Enabled UI components which seem to make development much faster than with ASP.NET MVC, especially on AJAX-heavy sites. Integration testing looked very nice too. </p>
<p>Since the presentation only emphasized the advantages of JSF, I'd like to hear about the other side as well. </p>
<p>So my questions are: </p>
<ul>
<li>What are the main disadvantages of Java Server Faces 2.0? </li>
<li>What might make a JSF developer consider using ASP.NET MVC instead of JSF?</li>
</ul> | <p>JSF 2.0 disadvantages? Honestly, apart from the relative steep learning curve when you don't have a solid background knowledge about <a href="https://stackoverflow.com/questions/1958808/java-web-development-what-skills-do-i-need">basic Web Development</a> (HTML/CSS/JS, server side versus client side, etc) and the <a href="https://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-session-variables-and-multithreading">basic Java Servlet API</a> (request/response/session, forwarding/redirecting, etc), no serious disadvantages comes to mind. JSF in its current release still needs to get rid of the negative image it gained during the early ages, during which there were several serious disadvantages.</p>
<h2>JSF 1.0 (March 2004)</h2>
<p>This was the initial release. It was cluttered with bugs in both the core and performance areas you don't want to know about. Your webapplication didn't always work as you'd intuitively expect. You as developer would run hard away crying.</p>
<h2>JSF 1.1 (May 2004)</h2>
<p>This was the bugfix release. The performance was still not much improved. There was also one major disadvantage: you can't inline HTML in the JSF page flawlessly. All plain vanilla HTML get rendered <em>before</em> the JSF component tree. You need to wrap all plain vanilla in <code><f:verbatim></code> tags so that they get included in the JSF component tree. Although this was as per the specification, this has received a lot of criticism. See also a.o. <a href="https://stackoverflow.com/questions/5474178/jsf-facelets-why-is-it-not-a-good-idea-to-mix-jsf-facelets-with-html-tags">JSF/Facelets: why is it not a good idea to mix JSF/Facelets with HTML tags?</a></p>
<h2>JSF 1.2 (May 2006)</h2>
<p>This was the first release of the new JSF development team lead by Ryan Lubke. The new team did a lot of great work. There were also changes in the spec. The major change was the improvement of the view handling. This not only fully detached JSF from JSP, so one could use a different view technology than JSP, but it also allowed developers to inline plain vanilla HTML in the JSF page without hassling with <code><f:verbatim></code> tags. Another major focus of the new team was improving the performance. During the lifetime of the Sun JSF Reference Implementation 1.2 (which was codenamed <em>Mojarra</em> since build 1.2_08, around 2008), practically every build got shipped with (major) performance improvements next to the usual (minor) bugfixes.</p>
<p>The only serious disadvantage of JSF 1.x (including 1.2) is the lack of a scope in between the <em>request</em> and <em>session</em> scope, the so-called <em>conversation</em> scope. This forced developers to hassle with hidden input elements, unnecessary DB queries and/or abusing the session scope whenever one want to retain the initial model data in the subsequent request in order to successfully process validations, conversions, model changes and action invocations in the more complex webapplications. The pain could be softened by adopting a 3rd party library which retains the necessary data in the subsequent request like <a href="http://myfaces.apache.org/tomahawk/" rel="noreferrer">MyFaces Tomahawk</a> <code><t:saveState></code> component, <a href="http://www.jboss.com/products/seam/" rel="noreferrer">JBoss Seam</a> conversation scope and <a href="http://myfaces.apache.org/orchestra/" rel="noreferrer">MyFaces Orchestra</a> conversation framework.</p>
<p>Another disadvantage for HTML/CSS purists is that JSF uses the colon <code>:</code> as ID separator character to ensure uniqueness of the HTML element <code>id</code> in the generated HTML output, especially when a component is reused more than once in the view (templating, iterating components, etc). Because this is an illegal character in CSS identifiers, you would need to use the <code>\</code> to escape the colon in CSS selectors, resulting in ugly and odd-looking selectors like <code>#formId\:fieldId {}</code> or even <code>#formId\3A fieldId {}</code>. See also <a href="https://stackoverflow.com/questions/5878692/how-to-use-jsf-generated-html-element-id-with-colon-in-css-selectors">How to use JSF generated HTML element ID with colon ":" in CSS selectors?</a> However, if you're not a purist, read also <a href="https://stackoverflow.com/questions/10726653/by-default-jsf-generates-unusable-ids-which-are-incompatible-with-css-part-of">By default, JSF generates unusable ids, which are incompatible with css part of web standards</a>.</p>
<p>Also, JSF 1.x didn't ship with Ajax facilities out of the box. Not really a technical disadvantage, but due to the Web 2.0 hype during that period, it became a functional disadvantage. <a href="http://www.exadel.com/" rel="noreferrer">Exadel</a> was early to introduce Ajax4jsf, which was thoroughly developed during the years and became the core part of <a href="http://www.jboss.org/richfaces" rel="noreferrer">JBoss RichFaces</a> component library. Another component libraries were shipped with builtin Ajax powers as well, the well known one being <a href="http://www.icefaces.org" rel="noreferrer">ICEfaces</a>.</p>
<p>About halfway the JSF 1.2 lifetime, a new XML based view technology was introduced: <a href="https://facelets.java.net/nonav/docs/dev/docbook.html#intro" rel="noreferrer">Facelets</a>. This offered enormous advantages above JSP, especially in the area of templating.</p>
<h2>JSF 2.0 (June 2009)</h2>
<p>This was the second major release, with Ajax as buzzword. There were a lot of technical and functional changes. JSP is replaced by Facelets as the default view technology and Facelets was expanded with capabilities to create custom components using pure XML (the so-called <a href="https://stackoverflow.com/tags/composite-component/info">composite components</a>). See also <a href="https://stackoverflow.com/questions/13092161/why-facelets-is-preferred-over-jsp-as-the-view-definition-language-from-jsf2-0-o">Why Facelets is preferred over JSP as the view definition language from JSF2.0 onwards?</a></p>
<p>Ajax powers were introduced in flavor of the <code><f:ajax></code> component which has much similarities with Ajax4jsf. Annotations and convention-over-configuration enhancements were introduced to <a href="http://blogs.oracle.com/rlubke/entry/faces_config_xml_we_don" rel="noreferrer">kill</a> the verbose <code>faces-config.xml</code> file as much as possible. Also, the default naming container ID separator character <code>:</code> became configurable, so HTML/CSS purists could breathe relieved. All you need to do is to define it as <code>init-param</code> in <code>web.xml</code> with the name <code>javax.faces.SEPARATOR_CHAR</code> and ensuring that you aren't using the character yourself anywhere in client ID's, such as <code>-</code>.</p>
<p>Last but not least, a new scope was introduced, the <em>view</em> scope. It eliminated another major JSF 1.x disadvantage as described before. You just declare the bean <code>@ViewScoped</code> to enable the conversation scope without hassling all ways to retain the data in subsequent (conversational) requests. A <code>@ViewScoped</code> bean will live as long as you're subsequently submitting and navigating to the same view (independently of the opened browser tab/window!), either synchronously or asynchronously (Ajax). See also <a href="https://stackoverflow.com/questions/6025998/difference-between-view-and-request-scope-in-managed-beans">Difference between View and Request scope in managed beans</a> and <a href="https://stackoverflow.com/questions/7031885/how-to-choose-the-right-bean-scope">How to choose the right bean scope?</a></p>
<p>Although practically all disadvantages of JSF 1.x were eliminated, there are JSF 2.0 specific bugs which might become a showstopper. The <a href="http://balusc.blogspot.com/2011/09/communication-in-jsf-20.html#ViewScopedFailsInTagHandlers" rel="noreferrer"><code>@ViewScoped</code> fails in tag handlers</a> due to a chicken-egg issue in partial state saving. This is fixed in JSF 2.2 and backported in Mojarra 2.1.18. Also <a href="https://stackoverflow.com/questions/16666472/custom-html-tag-attributes-are-not-rendered-by-jsf/">passing custom attributes like the HTML5 <code>data-xxx</code></a> is not supported. This is fixed in JSF 2.2 by new passthrough elements/attributes feature. Further the JSF implementation Mojarra has <a href="http://java.net/jira/browse/JAVASERVERFACES" rel="noreferrer">its own set of issues</a>. Relatively a lot of them are related to the <a href="https://java.net/jira/issues/?jql=project%20%3D%20JAVASERVERFACES%20AND%20text%20~%20%22%2Bui%3Arepeat%22" rel="noreferrer">sometimes unintuitive behaviour of <code><ui:repeat></code></a>, the <a href="https://java.net/jira/issues/?jql=project%20%3D%20JAVASERVERFACES%20AND%20text%20~%20%22%2Bpartial%20%2Bstate%22" rel="noreferrer">new partial state saving implementation</a> and the <a href="https://java.net/jira/issues/?jql=project%20%3D%20JAVASERVERFACES%20AND%20text%20~%20%22%2Bflash%22" rel="noreferrer">poorly implemented flash scope</a>. Most of them are fixed in a Mojarra 2.2.x version.</p>
<p>Around the JSF 2.0 time, <a href="http://primefaces.org" rel="noreferrer">PrimeFaces</a> was introduced, based on jQuery and jQuery UI. It became the most popular JSF component library.</p>
<h2>JSF 2.2 (May 2013)</h2>
<p>With the introduction of JSF 2.2, HTML5 was used as buzzword even though this was technically just supported in all older JSF versions. See also <a href="https://stackoverflow.com/questions/19189372/javaserver-faces-2-2-and-html5-support-why-is-xhtml-still-being-used">JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used</a>. Most important new JSF 2.2 feature is the support for custom component attributes, hereby opening a world of possibilities, such as <a href="http://balusc.omnifaces.org/2015/10/custom-layout-with-hselectoneradio-in.html" rel="noreferrer">custom tableless radio button groups</a>. </p>
<p>Apart from implementation specific bugs and some "annoying little things" such as inability to inject an EJB in a validator/converter (already fixed in JSF 2.3), there are not really major disadvantages in the JSF 2.2 specification. </p>
<h2>Component based MVC vs Request based MVC</h2>
<p>Some may opt that the major disadvantage of JSF is that it allows very little fine-grained control over the generated HTML/CSS/JS. That's not JSF's own, that's just because it's a <em>component based</em> MVC framework, not a <em>request (action) based</em> MVC framework. If a high degree of controlling the HTML/CSS/JS is your major requirement when considering a MVC framework, then you should already not be looking at a component based MVC framework, but at a request based MVC framework like <a href="http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html" rel="noreferrer">Spring MVC</a>. You only need to take into account that you'll have to write all that HTML/CSS/JS boilerplate yourself. See also <a href="https://stackoverflow.com/questions/4801891/difference-between-request-mvc-and-component-mvc">Difference between Request MVC and Component MVC</a>.</p>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/2095397/what-is-the-difference-between-jsf-servlet-and-jsp">What is the difference between JSF, Servlet and JSP?</a> (just to understand the basics)</li>
<li><a href="https://stackoverflow.com/questions/1867605/is-it-possible-to-use-jsf-without-the-resulting-html-tables">Using JSF to develop tableless CSS layouts</a> (another myth about JSF)</li>
<li><a href="https://stackoverflow.com/questions/4421839/what-is-the-need-of-jsf-when-ui-can-be-achieved-from-css-html-javascript-jquery">JSF vs plain HTML/CSS/JS/jQuery</a> (when JSF is the wrong choice)</li>
<li><a href="https://stackoverflow.com/questions/3541077/design-patterns-web-based-applications/">Design patterns in web applications</a> (illustrates the ideology behind MVC)</li>
</ul> | {
"question_id": 3623911,
"question_date": "2010-09-02T04:54:36.457Z",
"question_score": 235,
"tags": "asp.net-mvc|jsf|jsf-2",
"answer_id": 3646940,
"answer_date": "2010-09-05T17:13:05.283Z",
"answer_score": 467
} |
Please answer the following Stack Overflow question:
Title: Linux equivalent of the Mac OS X "open" command
<p>I've found the "open" command in Mac OS X very handy in the command line. From "man open":</p>
<blockquote>
<p>The <code>open</code> command opens a file (or a directory or URL), just as if you had
double-clicked the file's icon. If no application name is specified, the
default application as determined via LaunchServices is used to open the
specified files.</p>
</blockquote>
<p>That is, if I want to open a PDF file with the default PDF viewer (happens to be Preview), I only need to do:</p>
<pre><code>open my.pdf
</code></pre>
<p>In Linux, however, to open a PDF file from the command line, I had to dig around to find the default PDF viewer is, for instance, "evince" (who'd have guessed??), and then</p>
<pre><code>evince my.pdf
</code></pre>
<p>So, is there a simple equivalent of the 'open' command in the Linux command line?</p>
<p>Thanks!</p> | <p>You could try <code>xdg-open</code>, most Linux distros have it. It will open default associated app for your file.</p>
<p>FYI <a href="https://portland.freedesktop.org/doc/xdg-open.html" rel="noreferrer">https://portland.freedesktop.org/doc/xdg-open.html</a></p> | {
"question_id": 264395,
"question_date": "2008-11-05T05:23:22.783Z",
"question_score": 235,
"tags": "linux|macos|command-line|command-line-interface",
"answer_id": 264401,
"answer_date": "2008-11-05T05:28:35.630Z",
"answer_score": 262
} |
Please answer the following Stack Overflow question:
Title: How can I change the location of docker images when using Docker Desktop on WSL2 with Windows 10 Home?
<p>I've just upgraded to Windows 10 Home May 2020, <a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10" rel="noreferrer">activated WSL2</a>, and installed <a href="https://hub.docker.com/editions/community/docker-ce-desktop-windows" rel="noreferrer">Docker Desktop</a>.</p>
<p>WSL2 must be installed in my system disk, which is a small SSD. I don't want to fill it with docker images. How do I change the docker images path? I'd like to use a path in my big Windows filesystem.</p>
<p>The <a href="https://stackoverflow.com/questions/42250222/what-is-docker-image-location-on-windows-10/">image location</a> is somewhat confusing. I believe it is in <code>/mnt/wsl/docker-desktop-data/</code>.</p>
<p>How do I change the directory of docker images inside WSL2? May I change docker configuration to select a path inside <code>/mnt/d</code>, or mount a path from /mnt/d over docker data dirs?</p> | <p>The WSL 2 docker-desktop-data vm disk image would normally reside in:
<code>%USERPROFILE%\AppData\Local\Docker\wsl\data\ext4.vhdx</code></p>
<p>Follow the following to relocate it to other drive/directory, with all existing docker data preserved (tested against Docker Desktop 2.3.0.4 (46911), and continued to work after updating the 3.1.0 (51484)):</p>
<p>First, shut down your docker desktop by right click on the Docker Desktop icon and select Quit Docker Desktop</p>
<p>Then, open your command prompt:</p>
<pre><code>wsl --list -v
</code></pre>
<p>You should be able to see, make sure the STATE for both is Stopped.(<code>wsl --shutdown</code>)</p>
<pre><code> NAME STATE VERSION
* docker-desktop Stopped 2
docker-desktop-data Stopped 2
</code></pre>
<p>Export docker-desktop-data into a file</p>
<pre><code>wsl --export docker-desktop-data "D:\Docker\wsl\data\docker-desktop-data.tar"
</code></pre>
<p>Unregister docker-desktop-data from wsl, note that after this, your <code>ext4.vhdx</code> file would automatically be removed (so back it up first if you have important existing image/container):</p>
<pre><code>wsl --unregister docker-desktop-data
</code></pre>
<p>Import the docker-desktop-data back to wsl, but now the ext4.vhdx would reside in different drive/directory:</p>
<pre><code>wsl --import docker-desktop-data "D:\Docker\wsl\data" "D:\Docker\wsl\data\docker-desktop-data.tar" --version 2
</code></pre>
<p>Start the Docker Desktop again and it should work</p>
<p>You may delete the <code>D:\Docker\wsl\data\docker-desktop-data.tar</code> file (NOT the <code>ext4.vhdx</code> file) if everything looks good for you after verifying</p> | {
"question_id": 62441307,
"question_date": "2020-06-18T02:21:37.333Z",
"question_score": 235,
"tags": "docker|windows-10|docker-desktop|wsl-2",
"answer_id": 63752264,
"answer_date": "2020-09-05T09:10:13.117Z",
"answer_score": 566
} |
Please answer the following Stack Overflow question:
Title: What is git actually doing when it says it is "resolving deltas"?
<p>During the first clone of a repository, git first receives the objects (which is obvious enough), and then spends about the same amount of time "resolving deltas". What's actually happening during this phase of the clone?</p> | <p>Git uses <a href="http://en.wikipedia.org/wiki/Delta_encoding" rel="noreferrer">delta encoding</a> to store some of the objects in packfiles. However, you don't want to have to play back every single change <em>ever</em> on a given file in order to get the current version, so Git also has occasional snapshots of the file contents stored as well. "Resolving deltas" is the step that deals with making sure all of that stays consistent.</p>
<p><a href="http://www.git-scm.com/book/en/Git-Internals-Packfiles" rel="noreferrer">Here's a chapter</a> from the "Git Internals" section of the Pro Git book, which is available online, that talks about this.</p> | {
"question_id": 4689844,
"question_date": "2011-01-14T09:57:13.923Z",
"question_score": 235,
"tags": "git",
"answer_id": 4689869,
"answer_date": "2011-01-14T10:02:15.437Z",
"answer_score": 59
} |
Please answer the following Stack Overflow question:
Title: How can I animate the drawing of text on a web page?
<p>I want to have a web page which has one centered word. </p>
<p>I want this word to be drawn with an animation, such that the page "writes" the word out the same way that we would, i.e. it starts at one point and draws lines and curves over time such that the end result is a glyph. </p>
<p>I do not care if this is done with <code><canvas></code> or the DOM, and I don't care whether it's done with JavaScript or CSS. The absence of jQuery would be nice, but not required.</p>
<p>How can I do this? I've searched <em>exhaustively</em> with no luck.</p> | <blockquote>
<p>I want this word to be drawn with an animation, such that the page
"writes" the word out the same way that we would</p>
</blockquote>
<h2>Canvas version</h2>
<p>This will draw single chars more like one would write by hand. It uses a long dash-pattern where the on/off order is swapped over time per char. It also has a speed parameter.</p>
<p><img src="https://i.stack.imgur.com/XWQe1.gif" alt="Snapshot"><br>
<sup><em>Example animation (see demo below)</em></sup></p>
<p>To increase realism and the organic feel, I added random letter-spacing, an y delta offset, transparency, a very subtle rotation and finally using an already "handwritten" font. These can be wrapped up as dynamic parameters to provide a broad range of "writing styles".</p>
<p>For a even more realistic look the path data would be required which it isn't by default. But this is a short and efficient piece of code which approximates hand-written behavior, and easy to implement.</p>
<h2>How it works</h2>
<p>By defining a dash pattern we can create marching ants, dotted lines and so forth. Taking advantage of this by defining a very long dot for the "off" dot and gradually increase the "on" dot, it will give the illusion of drawing the line on when stroked while animating the dot length. </p>
<p>Since the off dot is so long the repeating pattern won't be visible (the length will vary with the size and characteristics of the typeface being used). The path of the letter will have a length so we need to make sure we are having each dot at least covering this length.</p>
<p>For letters that consists of more than one path (f.ex. O, R, P etc.) as one is for the outline, one is for the hollow part, the lines will appear to be drawn simultaneously. We can't do much about that with this technique as it would require access to each path segment to be stroked separately.</p>
<h2>Compatibility</h2>
<p>For browsers that don't support the canvas element an alternative way to show the text can be placed between the tags, for example a styled text:</p>
<pre><code><canvas ...>
<div class="txtStyle">STROKE-ON CANVAS</div>
</canvas>
</code></pre>
<h2>Demo</h2>
<p>This produces the live animated stroke-on (<strong>no dependencies</strong>) -</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var ctx = document.querySelector("canvas").getContext("2d"),
dashLen = 220, dashOffset = dashLen, speed = 5,
txt = "STROKE-ON CANVAS", x = 30, i = 0;
ctx.font = "50px Comic Sans MS, cursive, TSCu_Comic, sans-serif";
ctx.lineWidth = 5; ctx.lineJoin = "round"; ctx.globalAlpha = 2/3;
ctx.strokeStyle = ctx.fillStyle = "#1f2f90";
(function loop() {
ctx.clearRect(x, 0, 60, 150);
ctx.setLineDash([dashLen - dashOffset, dashOffset - speed]); // create a long dash mask
dashOffset -= speed; // reduce dash length
ctx.strokeText(txt[i], x, 90); // stroke letter
if (dashOffset > 0) requestAnimationFrame(loop); // animate
else {
ctx.fillText(txt[i], x, 90); // fill final letter
dashOffset = dashLen; // prep next char
x += ctx.measureText(txt[i++]).width + ctx.lineWidth * Math.random();
ctx.setTransform(1, 0, 0, 1, 0, 3 * Math.random()); // random y-delta
ctx.rotate(Math.random() * 0.005); // random rotation
if (i < txt.length) requestAnimationFrame(loop);
}
})();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {background:url(http://i.imgur.com/5RIXWIE.png)}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas width=630></canvas></code></pre>
</div>
</div>
</p> | {
"question_id": 29911143,
"question_date": "2015-04-28T05:38:07.457Z",
"question_score": 235,
"tags": "javascript|css|canvas|html5-canvas|css-shapes",
"answer_id": 29912925,
"answer_date": "2015-04-28T07:25:58.417Z",
"answer_score": 271
} |
Please answer the following Stack Overflow question:
Title: Xcode 8 / Swift 3: "Expression of type UIViewController? is unused" warning
<p>I've got the following function which compiled cleanly previously but generates a warning with Xcode 8.</p>
<pre><code>func exitViewController()
{
navigationController?.popViewController(animated: true)
}
</code></pre>
<blockquote>
<p>"Expression of type "UIViewController?" is unused".</p>
</blockquote>
<p>Why is it saying this and is there a way to remove it?</p>
<p>The code executes as expected.</p> | <h3>TL;DR</h3>
<p><code>popViewController(animated:)</code> returns <code>UIViewController?</code>, and the compiler is giving that warning since you aren't capturing the value. The solution is to assign it to an underscore:</p>
<pre><code>_ = navigationController?.popViewController(animated: true)
</code></pre>
<hr>
<h3>Swift 3 Change</h3>
<p>Before Swift 3, all methods had a "discardable result" by default. No warning would occur when you did not capture what the method returned.</p>
<p>In order to tell the compiler that the result should be captured, you had to add <code>@warn_unused_result</code> before the method declaration. It would be used for methods that have a mutable form (ex. <code>sort</code> and <code>sortInPlace</code>). You would add <code>@warn_unused_result(mutable_variant="mutableMethodHere")</code> to tell the compiler of it.</p>
<p>However, with Swift 3, the behavior is flipped. All methods now warn that the return value is not captured. If you want to tell the compiler that the warning isn't necessary, you add <code>@discardableResult</code> before the method declaration.</p>
<p>If you don't want to use the return value, you have to <em>explicitly</em> tell the compiler by assigning it to an underscore:</p>
<pre><code>_ = someMethodThatReturnsSomething()
</code></pre>
<p>Motivation for adding this to Swift 3:</p>
<ul>
<li>Prevention of possible bugs (ex. using <code>sort</code> thinking it modifies the collection)</li>
<li>Explicit intent of not capturing or needing to capture the result for other collaborators</li>
</ul>
<p>The UIKit API appears to be behind on this, not adding <code>@discardableResult</code> for the perfectly normal (if not more common) use of <code>popViewController(animated:)</code> without capturing the return value. </p>
<h3>Read More</h3>
<ul>
<li><a href="https://github.com/apple/swift-evolution/blob/master/proposals/0047-nonvoid-warn.md" rel="noreferrer">SE-0047 Swift Evolution Proposal</a></li>
<li><a href="https://lists.swift.org/pipermail/swift-evolution-announce/2016-March/000075.html" rel="noreferrer">Accepted proposal with revisions</a></li>
</ul> | {
"question_id": 37843049,
"question_date": "2016-06-15T18:24:57.603Z",
"question_score": 235,
"tags": "ios|swift",
"answer_id": 37843720,
"answer_date": "2016-06-15T19:00:17.550Z",
"answer_score": 504
} |
Please answer the following Stack Overflow question:
Title: Notifications for new Github project releases?
<p>I'm using a library from a Github project. Is there some way to set up a notification for new project releases?</p>
<p>For example, I want to know when a new release appears <a href="https://github.com/dropbox/dropbox-js/releases">here</a></p>
<p>I know I can be notified on every issue update, but that's not what I'm looking for. Though I see <a href="https://github.com/PacificBiosciences/BindingCalculator/issues/1">some projects</a> are using that as a way to keep people notified</p> | <p>Don't know about email, but you can subscribe to <strike>RSS</strike> Atom feed with releases:<br>
<a href="https://github.com/dropbox/dropbox-js/releases.atom" rel="noreferrer">https://github.com/dropbox/dropbox-js/releases.atom</a><br>
or tags:<br>
<a href="https://github.com/dropbox/dropbox-js/tags.atom" rel="noreferrer">https://github.com/dropbox/dropbox-js/tags.atom</a></p>
<hr>
<p><strong>EDIT</strong>:</p>
<p>To get notification via email you can use <a href="https://sibbell.com" rel="noreferrer">Sibbell.com</a> or RSS-to-email service like <a href="http://blogtrottr.com/" rel="noreferrer">Blogtrottr</a>.</p> | {
"question_id": 20839622,
"question_date": "2013-12-30T12:30:24.503Z",
"question_score": 235,
"tags": "github",
"answer_id": 20840694,
"answer_date": "2013-12-30T13:38:20.657Z",
"answer_score": 277
} |
Please answer the following Stack Overflow question:
Title: How can I print variable and string on same line in Python?
<p>I am using python to work out how many children would be born in 5 years if a child was born every 7 seconds. The problem is on my last line. How do I get a variable to work when I'm printing text either side of it? </p>
<p>Here is my code:</p>
<pre><code>currentPop = 312032486
oneYear = 365
hours = 24
minutes = 60
seconds = 60
# seconds in a single day
secondsInDay = hours * minutes * seconds
# seconds in a year
secondsInYear = secondsInDay * oneYear
fiveYears = secondsInYear * 5
#Seconds in 5 years
print fiveYears
# fiveYears in seconds, divided by 7 seconds
births = fiveYears // 7
print "If there was a birth every 7 seconds, there would be: " births "births"
</code></pre> | <p>Use <code>,</code> to separate strings and variables while printing:</p>
<pre><code>print("If there was a birth every 7 seconds, there would be: ", births, "births")
</code></pre>
<p><code>,</code> in print function separates the items by a single space:</p>
<pre><code>>>> print("foo", "bar", "spam")
foo bar spam
</code></pre>
<p>or better use <a href="http://docs.python.org/library/string.html#formatspec" rel="noreferrer">string formatting</a>:</p>
<pre><code>print("If there was a birth every 7 seconds, there would be: {} births".format(births))
</code></pre>
<p>String formatting is much more powerful and allows you to do some other things as well, like padding, fill, alignment, width, set precision, etc.</p>
<pre><code>>>> print("{:d} {:03d} {:>20f}".format(1, 2, 1.1))
1 002 1.100000
^^^
0's padded to 2
</code></pre>
<p>Demo:</p>
<pre><code>>>> births = 4
>>> print("If there was a birth every 7 seconds, there would be: ", births, "births")
If there was a birth every 7 seconds, there would be: 4 births
# formatting
>>> print("If there was a birth every 7 seconds, there would be: {} births".format(births))
If there was a birth every 7 seconds, there would be: 4 births
</code></pre> | {
"question_id": 17153779,
"question_date": "2013-06-17T17:58:08.473Z",
"question_score": 234,
"tags": "python|string|variables|printing",
"answer_id": 17153791,
"answer_date": "2013-06-17T17:58:57.770Z",
"answer_score": 347
} |
Please answer the following Stack Overflow question:
Title: Show/hide 'div' using JavaScript
<p>For a website I'm doing, I want to load one div, and hide another, then have two buttons that will toggle views between the div using JavaScript.</p>
<p><strong>This is my current code</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function replaceContentInContainer(target, source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
function replaceContentInOtherContainer(replace_target, source) {
document.getElementById(replace_target).innerHTML = document.getElementById(source).innerHTML;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<button onClick="replaceContentInContainer('target', 'replace_target')">View Portfolio</button>
<button onClick="replaceContentInOtherContainer('replace_target', 'target')">View Results</button>
<div>
<span id="target">div1</span>
</div>
<div style="display:none">
<span id="replace_target">div2</span>
</div></code></pre>
</div>
</div>
</p>
<p>The second function that replaces div2 is not working, but the first one is.</p> | <h3>How to show or hide an element:</h3>
<p>In order to show or hide an element, manipulate the element's <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style">style property</a>. In most cases, you probably just want to change the element's <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/display"><code>display</code> property</a>:</p>
<pre><code>element.style.display = 'none'; // Hide
element.style.display = 'block'; // Show
element.style.display = 'inline'; // Show
element.style.display = 'inline-block'; // Show
</code></pre>
<p>Alternatively, if you would still like the element to occupy space (like if you were to hide a table cell), you could change the element's <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/visibility"><code>visibility</code> property</a> instead:</p>
<pre><code>element.style.visibility = 'hidden'; // Hide
element.style.visibility = 'visible'; // Show
</code></pre>
<h3>Hiding a collection of elements:</h3>
<p>If you want to hide a collection of elements, just iterate over each element and change the element's <code>display</code> to <code>none</code>:</p>
<pre><code>function hide (elements) {
elements = elements.length ? elements : [elements];
for (var index = 0; index < elements.length; index++) {
elements[index].style.display = 'none';
}
}
</code></pre>
<pre><code>// Usage:
hide(document.querySelectorAll('.target'));
hide(document.querySelector('.target'));
hide(document.getElementById('target'));
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>hide(document.querySelectorAll('.target'));
function hide (elements) {
elements = elements.length ? elements : [elements];
for (var index = 0; index < elements.length; index++) {
elements[index].style.display = 'none';
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="target">This div will be hidden.</div>
<span class="target">This span will be hidden as well.</span></code></pre>
</div>
</div>
</p>
<h3>Showing a collection of elements:</h3>
<p>Most of the time, you will probably just be toggling between <code>display: none</code> and <code>display: block</code>, which means that the following <em>may</em> be sufficient when showing a collection of elements.</p>
<p>You can optionally specify the desired <code>display</code> as the second argument if you don't want it to default to <code>block</code>.</p>
<pre><code>function show (elements, specifiedDisplay) {
elements = elements.length ? elements : [elements];
for (var index = 0; index < elements.length; index++) {
elements[index].style.display = specifiedDisplay || 'block';
}
}
</code></pre>
<pre><code>// Usage:
var elements = document.querySelectorAll('.target');
show(elements);
show(elements, 'inline-block'); // The second param allows you to specify a display value
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var elements = document.querySelectorAll('.target');
show(elements, 'inline-block'); // The second param allows you to specify a display value
show(document.getElementById('hidden-input'));
function show (elements, specifiedDisplay) {
elements = elements.length ? elements : [elements];
for (var index = 0; index < elements.length; index++) {
elements[index].style.display = specifiedDisplay || 'block';
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="target" style="display: none">This hidden div should have a display of 'inline-block' when it is shown.</div>
<span>Inline span..</span>
<input id="hidden-input" /></code></pre>
</div>
</div>
</p>
<p>Alternatively, a better approach for showing the element(s) would be to merely remove the inline <code>display</code> styling in order to revert it back to its initial state. Then check the computed <code>display</code> style of the element in order to determine whether it is being hidden by a cascaded rule. If so, then show the element.</p>
<pre><code>function show (elements, specifiedDisplay) {
var computedDisplay, element, index;
elements = elements.length ? elements : [elements];
for (index = 0; index < elements.length; index++) {
element = elements[index];
// Remove the element's inline display styling
element.style.display = '';
computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');
if (computedDisplay === 'none') {
element.style.display = specifiedDisplay || 'block';
}
}
}
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>show(document.querySelectorAll('.target'));
function show (elements, specifiedDisplay) {
var computedDisplay, element, index;
elements = elements.length ? elements : [elements];
for (index = 0; index < elements.length; index++) {
element = elements[index];
// Remove the element's inline display styling
element.style.display = '';
computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');
if (computedDisplay === 'none') {
element.style.display = specifiedDisplay || 'block';
}
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="target" style="display: none">Should revert back to being inline.</span>
<span class="target" style="display: none">Inline as well.</span>
<div class="target" style="display: none">Should revert back to being block level.</div>
<span class="target" style="display: none">Should revert back to being inline.</span></code></pre>
</div>
</div>
</p>
<p>(If you want to take it a step further, you could even mimic what jQuery does and determine the element's default browser styling by appending the element to a blank <code>iframe</code> (without a conflicting stylesheet) and then retrieve the computed styling. In doing so, you will know the true initial <code>display</code> property value of the element and you won't have to hardcode a value in order to get the desired results.)</p>
<h3>Toggling the display:</h3>
<p>Similarly, if you would like to toggle the <code>display</code> of an element or collection of elements, you could simply iterate over each element and determine whether it is visible by checking the computed value of the <code>display</code> property. If it's visible, set the <code>display</code> to <code>none</code>, otherwise remove the inline <code>display</code> styling, and if it's still hidden, set the <code>display</code> to the specified value or the hardcoded default, <code>block</code>.</p>
<pre><code>function toggle (elements, specifiedDisplay) {
var element, index;
elements = elements.length ? elements : [elements];
for (index = 0; index < elements.length; index++) {
element = elements[index];
if (isElementHidden(element)) {
element.style.display = '';
// If the element is still hidden after removing the inline display
if (isElementHidden(element)) {
element.style.display = specifiedDisplay || 'block';
}
} else {
element.style.display = 'none';
}
}
function isElementHidden (element) {
return window.getComputedStyle(element, null).getPropertyValue('display') === 'none';
}
}
</code></pre>
<pre><code>// Usage:
document.getElementById('toggle-button').addEventListener('click', function () {
toggle(document.querySelectorAll('.target'));
});
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.getElementById('toggle-button').addEventListener('click', function () {
toggle(document.querySelectorAll('.target'));
});
function toggle (elements, specifiedDisplay) {
var element, index;
elements = elements.length ? elements : [elements];
for (index = 0; index < elements.length; index++) {
element = elements[index];
if (isElementHidden(element)) {
element.style.display = '';
// If the element is still hidden after removing the inline display
if (isElementHidden(element)) {
element.style.display = specifiedDisplay || 'block';
}
} else {
element.style.display = 'none';
}
}
function isElementHidden (element) {
return window.getComputedStyle(element, null).getPropertyValue('display') === 'none';
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.target { display: none; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="toggle-button">Toggle display</button>
<span class="target">Toggle the span.</span>
<div class="target">Toggle the div.</div></code></pre>
</div>
</div>
</p> | {
"question_id": 21070101,
"question_date": "2014-01-12T01:12:04.627Z",
"question_score": 234,
"tags": "javascript|html|onclick|innerhtml",
"answer_id": 21070237,
"answer_date": "2014-01-12T01:33:41.930Z",
"answer_score": 511
} |
Please answer the following Stack Overflow question:
Title: SQL: IF clause within WHERE clause
<p>Is it possible to use an <strong>IF</strong> clause within a <strong>WHERE</strong> clause in MS SQL?</p>
<p>Example:</p>
<pre><code>WHERE
IF IsNumeric(@OrderNumber) = 1
OrderNumber = @OrderNumber
ELSE
OrderNumber LIKE '%' + @OrderNumber + '%'
</code></pre> | <p>Use a <a href="http://msdn.microsoft.com/en-us/library/ms181765.aspx" rel="noreferrer">CASE</a> statement<br>
<strong>UPDATE:</strong> The previous syntax (as pointed out by a few people) doesn't work. You can use CASE as follows:</p>
<pre><code>WHERE OrderNumber LIKE
CASE WHEN IsNumeric(@OrderNumber) = 1 THEN
@OrderNumber
ELSE
'%' + @OrderNumber
END
</code></pre>
<p>Or you can use an IF statement like @<a href="https://stackoverflow.com/questions/87821/sql-if-clause-within-where-clause#87992">N. J. Reed</a> points out.</p> | {
"question_id": 87821,
"question_date": "2008-09-17T21:24:49.380Z",
"question_score": 234,
"tags": "sql|sql-server|tsql",
"answer_id": 87839,
"answer_date": "2008-09-17T21:26:39.967Z",
"answer_score": 253
} |
Please answer the following Stack Overflow question:
Title: require(vendor/autoload.php): failed to open stream
<p>I know that this issue has been posted many times, but for me it seems to be a different problem.</p>
<p>Indeed, this error</p>
<blockquote>
<p>Warning: require(vendor/autoload.php): failed to open stream: No such file or directory in C:\xampp\htdocs\site_web\send_mail.php on line 3</p>
<p>Fatal error: require(): Failed opening required 'vendor/autoload.php' (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\site_web\send_mail.php on line 3</p>
</blockquote>
<p>appears at the begining of my code from this line:</p>
<pre><code>require 'vendor/autoload.php';
</code></pre>
<p>So, I guess there must be a /vendor/autoload.php file somewhere in my computer (I have installed composer and ran <code>composer require phpmailer/phpmailer</code>).</p>
<p>So, I looked for this file using: <code>dir /s autoload.php</code> in the Windows command line, and found one here: <code>C:\Windows\SysWOW64\vendor\autoload.php</code>,</p>
<p>but for me, <strong>syswow64</strong> folder has nothing to see with <strong>autoload.php</strong>, I don't see what I am missing here.</p> | <p>What you're missing is running <code>composer install</code>, which will import your packages and create the vendor folder, along with the autoload script.</p>
<p>Make sure your relative path is correct. For example the example scripts in PHPMailer are in <code>examples/</code>, below the project root, so the correct relative path to load the composer autoloader from there would be <code>../vendor/autoload.php</code>.</p>
<p>The autoload.php you found in <code>C:\Windows\SysWOW64\vendor\autoload.php</code> is probably a global composer installation – where you'll usually put things like phpcs, phpunit, phpmd etc.</p>
<p><code>composer update</code> is <strong>not</strong> the same thing, and probably <strong>not</strong> what you want to use. If your code is tested with your current package versions then running <code>update</code> may cause breakages which may require further work and testing, so don't run <code>update</code> unless you have a specific reason to and understand exactly what it means. To clarify further – you should probably only ever run <code>composer update</code> locally, never on your server as it is reasonably likely to break apps in production.</p>
<p>I often see complaints that people can't use composer because they can't run it on their server (e.g. because it's shared and they have no shell access). In that case, you <em>can</em> still use composer: run it locally (an environment that has no such restrictions), and upload the local vendor folder it generates along with all your other PHP scripts.</p>
<p>Running <code>composer update</code> <em>also</em> performs a <code>composer install</code>, and if you do not currently have a <code>vendor</code> folder (normal if you have a fresh checkout of a project), then it will create one, and also overwrite any <code>composer.lock</code> file you already have, updating package versions tagged in it, and this is what is potentially dangerous.</p>
<p>Similarly, if you do not currently have a <code>composer.lock</code> file (e.g. if it was not committed to the project), then <code>composer install</code> also effectively performs a <code>composer update</code>. It's thus vital to understand the difference between the two as they are definitely <em>not</em> interchangeable.</p>
<p>It is also possible to update a single package by naming it, for example:</p>
<pre><code>composer update ramsey/uuid
</code></pre>
<p>This will re-resolve the version specified in your <code>composer.json</code> and install it in your vendor folder, and update your <code>composer.lock</code> file to match. This is far less likely to cause problems than a general <code>composer update</code> if you just need a specific update to one package.</p>
<p>It is normal for libraries to <em>not</em> include a <code>composer.lock</code> file of their own; it's up to apps to fix versions, not the libraries they use. As a result, library developers are expected to maintain compatibility with a wider range of host environments than app developers need to. For example, a library might be compatible with Laravel 5, 6, 7, and 8, but an app using it might require Laravel 8 for other reasons.</p>
<p>Composer 2.0 removed any remaining inconsistencies between install and update results; if you're running composer 1.x you should definitely <a href="https://getcomposer.org/upgrade/UPGRADE-2.0.md" rel="noreferrer">upgrade</a>.</p> | {
"question_id": 41209349,
"question_date": "2016-12-18T14:33:50.857Z",
"question_score": 234,
"tags": "php|email|composer-php|phpmailer",
"answer_id": 41209642,
"answer_date": "2016-12-18T15:01:05.567Z",
"answer_score": 397
} |
Please answer the following Stack Overflow question:
Title: HTML button calling an MVC Controller and Action method
<p>I know this isn't right, but for the sake of illustration I'd like to do something like this:</p>
<pre><code><%= Html.Button("Action", "Controller") %>
</code></pre>
<p>My goal is to make an HTML button that will call my MVC controller's action method.</p> | <p>No need to use a form at all unless you want to post to the action. An input button (not submit) will do the trick.</p>
<pre><code> <input type="button"
value="Go Somewhere Else"
onclick="location.href='<%: Url.Action("Action", "Controller") %>'" />
</code></pre> | {
"question_id": 2503923,
"question_date": "2010-03-23T21:56:58.307Z",
"question_score": 234,
"tags": "html|asp.net-mvc",
"answer_id": 2510668,
"answer_date": "2010-03-24T19:08:36.380Z",
"answer_score": 289
} |
Please answer the following Stack Overflow question:
Title: Create a .csv file with values from a Python list
<p>I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this </p>
<pre><code>[u'value 1', u'value 2', ...]
</code></pre>
<p>If I iterate through the values in the list i.e. <code>for v in mylist: print v</code> they appear to be plain text.</p>
<p>And I can put a <code>,</code> between each with <code>print ','.join(mylist)</code></p>
<p>And I can output to a file, i.e. </p>
<pre><code>myfile = open(...)
print >>myfile, ','.join(mylist)
</code></pre>
<p>But I want to output to a CSV and have delimiters around the values in the list e.g.</p>
<pre><code>"value 1", "value 2", ...
</code></pre>
<p>I can't find an easy way to include the delimiters in the formatting, e.g. I have tried through the <code>join</code> statement. How can I do this?</p> | <pre><code>import csv
with open(..., 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)
</code></pre>
<p>Edit: this only works with python 2.x.</p>
<p>To make it work with python 3.x replace <code>wb</code> with <code>w</code> (<a href="https://stackoverflow.com/questions/34283178/typeerror-a-bytes-like-object-is-required-not-str-in-python-and-csv">see this SO answer</a>)</p>
<pre><code>with open(..., 'w', newline='') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)
</code></pre> | {
"question_id": 2084069,
"question_date": "2010-01-18T05:34:08.903Z",
"question_score": 234,
"tags": "python|csv|xlrd",
"answer_id": 2084135,
"answer_date": "2010-01-18T05:53:25.317Z",
"answer_score": 303
} |
Please answer the following Stack Overflow question:
Title: Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0
<p>I've got a gradle FAILURE:</p>
<pre><code>..."Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0."
</code></pre>
<p>Case description:</p>
<ul>
<li>Attached to the project codebase the next libs:</li>
</ul>
<p><strong>APP/build.gradle</strong></p>
<pre><code> //(Required) Writing and executing Unit Tests on the JUnit Platform
testImplementation "org.junit.jupiter:junit-jupiter-api:5.2.0"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.2.0"
// (Optional) If you need "Parameterized Tests"
testImplementation "org.junit.jupiter:junit-jupiter-params:5.2.0"
// (Optional) If you also have JUnit 4-based tests
testImplementation "junit:junit:4.12"
testRuntimeOnly "org.junit.vintage:junit-vintage-engine:5.2.0"
testImplementation "io.mockk:mockk:1.8.5"
</code></pre>
<ul>
<li><p>Updated the <strong>gradle-wrapper.properties</strong></p>
<p>distributionUrl=https....gradle-<strong>4.4-all</strong>.zip to <strong>4.7-all</strong></p></li>
<li><p>after all of that gradle was built success</p></li>
<li><p>created the test calss</p>
<pre><code>@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class TestClass {
@Test
internal fun testName() {
Assert.assertEquals(2, 1 + 1)
}
}
</code></pre></li>
<li><p>ran the test and got the FAILURE message.
<a href="https://i.stack.imgur.com/7nZ04.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7nZ04.png" alt="enter image description here"></a></p></li>
<li><p>ran the Gradle build with a command line argument <code>./gradlew --warning-mode=all</code> to see what exactly the deprecated features are.
<a href="https://i.stack.imgur.com/TxV5L.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TxV5L.png" alt="enter image description here"></a></p></li>
</ul>
<p>As a result I couldn't build the app and I've got that FAILURE: message.</p> | <p>Run the Gradle build with a command line argument <code>--warning-mode=all</code> to see what exactly the deprecated features are.</p>
<p>It will give you a detailed description of found issues with links to the Gradle docs for instructions how to fix your build.</p>
<p>Adding <code>--stacktrace</code> to that, you will also be able to pinpoint where the warning comes from, if it's triggered by outdated code in one of the plugins and not your build script.</p> | {
"question_id": 51610420,
"question_date": "2018-07-31T09:47:21.653Z",
"question_score": 234,
"tags": "android|unit-testing|gradle|kotlin|junit5",
"answer_id": 51610775,
"answer_date": "2018-07-31T10:03:41.150Z",
"answer_score": 132
} |
Please answer the following Stack Overflow question:
Title: How do I check if my EditText fields are empty?
<p>I have 5 <code>EditTexts</code> in android. I would like to know if I could check if all 5 <code>EditTexts</code> are null. Is there any way to do this??</p> | <p>I did something like this once;</p>
<pre><code>EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
return;
}
</code></pre> | {
"question_id": 6290531,
"question_date": "2011-06-09T09:12:01.553Z",
"question_score": 234,
"tags": "android|android-edittext",
"answer_id": 6290587,
"answer_date": "2011-06-09T09:17:22.753Z",
"answer_score": 402
} |
Please answer the following Stack Overflow question:
Title: how to bypass Access-Control-Allow-Origin?
<p>I'm doing a ajax call to my own server on a platform which they set prevent these ajax calls (but I need it to fetch the data from my server to display retrieved data from my server's database).
My ajax script is working , it can send the data over to my server's php script to allow it to process.
However it cannot get the processed data back as it is blocked by <code>"Access-Control-Allow-Origin"</code></p>
<p>I have no access to that platform's source/core. so I can't remove the script that it disallowing me to do so.
(P/S I used Google Chrome's Console and found out this error)</p>
<p>The Ajax code as shown below:</p>
<pre><code> $.ajax({
type: "GET",
url: "http://example.com/retrieve.php",
data: "id=" + id + "&url=" + url,
dataType: 'json',
cache: false,
success: function(data)
{
var friend = data[1];
var blog = data[2];
$('#user').html("<b>Friends: </b>"+friend+"<b><br> Blogs: </b>"+blog);
}
});
</code></pre>
<p>or is there a <code>JSON</code> equivalent code to the ajax script above ? I think <code>JSON</code> is allowed.</p>
<p>I hope someone could help me out.</p> | <p>Put this on top of retrieve.php:</p>
<pre><code>header('Access-Control-Allow-Origin: *');
</code></pre>
<p>Note that this effectively disables CORS protection, and leaves your users exposed to attack. If you're not completely certain that you need to allow <em>all</em> origins, you should lock this down to a more specific origin:</p>
<pre><code>header('Access-Control-Allow-Origin: https://www.example.com');
</code></pre>
<p>Please refer to following stack answer for better understanding of <code>Access-Control-Allow-Origin</code></p>
<p><a href="https://stackoverflow.com/a/10636765/413670">https://stackoverflow.com/a/10636765/413670</a></p> | {
"question_id": 7564832,
"question_date": "2011-09-27T06:03:12.533Z",
"question_score": 234,
"tags": "javascript|php|jquery|ajax|cors",
"answer_id": 7564919,
"answer_date": "2011-09-27T06:12:52.097Z",
"answer_score": 414
} |
Please answer the following Stack Overflow question:
Title: getResourceAsStream returns null
<p>I'm loading a text file from within a package in a compiled JAR of my Java project. The relevant directory structure is as follows:</p>
<pre><code>/src/initialization/Lifepaths.txt
</code></pre>
<p>My code loads a file by calling <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Class.html#getResourceAsStream(java.lang.String)" rel="noreferrer"><code>Class::getResourceAsStream</code></a> to return a <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/InputStream.html" rel="noreferrer"><code>InputStream</code></a>. </p>
<pre><code>public class Lifepaths {
public static void execute() {
System.out.println(Lifepaths.class.getClass().
getResourceAsStream("/initialization/Lifepaths.txt"));
}
private Lifepaths() {}
//This is temporary; will eventually be called from outside
public static void main(String[] args) {execute();}
}
</code></pre>
<p>The print out will always print <code>null</code>, no matter what I use. I'm not sure why the above wouldn't work, so I've also tried:</p>
<ul>
<li><code>"/src/initialization/Lifepaths.txt"</code></li>
<li><code>"initialization/Lifepaths.txt"</code></li>
<li><code>"Lifepaths.txt"</code></li>
</ul>
<p>Neither of these work. <a href="https://stackoverflow.com/questions/12262062/getresourceasstream-returns-null">I've</a> <a href="https://stackoverflow.com/questions/7017361/getresourceasstream-returning-null">read</a> <a href="https://stackoverflow.com/questions/2797162/getresourceasstream-is-always-returning-null">numerous</a> <a href="https://stackoverflow.com/questions/2195445/eclipse-getresourceasstream-returning-null">questions</a> so far on the topic, but none of them have been helpful - usually, they just say to load files using the root path, which I'm already doing. That, or just load the file from the current directory (just load <code>filename</code>), which I've also tried. The file is being compiled into the JAR in the appropriate location with the appropriate name. </p>
<p>How do I solve this?</p> | <p><code>Lifepaths.class.getClass().getResourceAsStream(...)</code> loads resources using system class loader, it obviously fails because it does not see your JARs</p>
<p><code>Lifepaths.class.getResourceAsStream(...)</code> loads resources using the same class loader that loaded Lifepaths class and it should have access to resources in your JARs</p> | {
"question_id": 16570523,
"question_date": "2013-05-15T16:37:01.830Z",
"question_score": 234,
"tags": "java|file-io|resources",
"answer_id": 16571046,
"answer_date": "2013-05-15T17:06:24.487Z",
"answer_score": 214
} |
Please answer the following Stack Overflow question:
Title: Map a network drive to be used by a service
<p>Suppose some Windows service uses code that wants mapped network drives and no UNC paths. How can I make the drive mapping available to the service's session when the service is started? Logging in as the service user and creating a persistent mapping will not establish the mapping in the context of the actual service.</p> | <p>You'll either need to modify the service, or wrap it inside a helper process: apart from session/drive access issues, persistent drive mappings are only restored on an interactive logon, which services typically don't perform.</p>
<p>The helper process approach can be pretty simple: just create a new service that maps the drive and starts the 'real' service. The only things that are not entirely trivial about this are:</p>
<ul>
<li><p>The helper service will need to pass on all appropriate SCM commands (start/stop, etc.) to the real service. If the real service accepts custom SCM commands, remember to pass those on as well (I don't expect a service that considers UNC paths exotic to use such commands, though...)</p></li>
<li><p>Things may get a bit tricky credential-wise. If the real service runs under a normal user account, you can run the helper service under that account as well, and all should be OK as long as the account has appropriate access to the network share. If the real service will only work when run as LOCALSYSTEM or somesuch, things get more interesting, as it either won't be able to 'see' the network drive at all, or require some credential juggling to get things to work.</p></li>
</ul> | {
"question_id": 182750,
"question_date": "2008-10-08T13:29:49.080Z",
"question_score": 234,
"tags": "windows|windows-services|unc|system-administration|mapped-drive",
"answer_id": 182846,
"answer_date": "2008-10-08T13:48:29.540Z",
"answer_score": 50
} |
Please answer the following Stack Overflow question:
Title: Creating Threads in python
<p>I have a script and I want one function to run at the same time as the other.</p>
<p>The example code I have looked at:</p>
<pre class="lang-py prettyprint-override"><code>import threading
def MyThread (threading.thread):
# doing something........
def MyThread2 (threading.thread):
# doing something........
MyThread().start()
MyThread2().start()
</code></pre>
<p>I am having trouble getting this working. I would prefer to get this going using a threaded function rather than a class.</p>
<p>This is the working script:</p>
<pre class="lang-py prettyprint-override"><code>from threading import Thread
class myClass():
def help(self):
os.system('./ssh.py')
def nope(self):
a = [1,2,3,4,5,6,67,78]
for i in a:
print i
sleep(1)
if __name__ == "__main__":
Yep = myClass()
thread = Thread(target = Yep.help)
thread2 = Thread(target = Yep.nope)
thread.start()
thread2.start()
thread.join()
print 'Finished'
</code></pre> | <p>You don't need to use a subclass of <code>Thread</code> to make this work - take a look at the simple example I'm posting below to see how:</p>
<pre><code>from threading import Thread
from time import sleep
def threaded_function(arg):
for i in range(arg):
print("running")
sleep(1)
if __name__ == "__main__":
thread = Thread(target = threaded_function, args = (10, ))
thread.start()
thread.join()
print("thread finished...exiting")
</code></pre>
<p>Here I show how to use the threading module to create a thread which invokes a normal function as its target. You can see how I can pass whatever arguments I need to it in the thread constructor.</p> | {
"question_id": 2905965,
"question_date": "2010-05-25T15:15:01.463Z",
"question_score": 234,
"tags": "python|multithreading",
"answer_id": 2906014,
"answer_date": "2010-05-25T15:20:56.860Z",
"answer_score": 392
} |
Please answer the following Stack Overflow question:
Title: "X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"
<pre><code><meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
</code></pre>
<ol>
<li><p>Actually what is the meaning of this statement ?</p></li>
<li><p>Some of the examples use <code>,</code> to separate versions of IE, while some use <code>;</code>; which is correct?</p></li>
<li><p>The order <code>IE=9; IE=8; IE=7; IE=EDGE</code> has some importance, I wish to know that.</p></li>
</ol>
<p><strong>Edit</strong>: I am using <code><!DOCTYPE html></code></p> | <p>If you support IE, for versions of Internet Explorer 8 and above, this:</p>
<pre><code><meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />
</code></pre>
<p>Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.</p>
<p>If you separate with semi-colon, it sets compatibility levels for different versions. For example:</p>
<pre><code><meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />
</code></pre>
<p>Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:</p>
<pre><code><meta http-equiv="X-UA-Compatible" content="IE=8" />
</code></pre>
<p>This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:</p>
<pre><code><meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
</code></pre>
<p>For this:</p>
<pre><code><meta http-equiv="X-UA-Compatible" content="IE=Edge" />
</code></pre>
<p>It forces the browser the render at whatever the most recent version's standards are. </p>
<p>For more information, <a href="http://msdn.microsoft.com/en-us/library/ie/ms533876(v=vs.85).aspx" rel="noreferrer">there is plenty to read about on MSDN</a>,</p> | {
"question_id": 14611264,
"question_date": "2013-01-30T18:36:00.423Z",
"question_score": 234,
"tags": "html|internet-explorer|x-ua-compatible",
"answer_id": 14611323,
"answer_date": "2013-01-30T18:39:23.370Z",
"answer_score": 330
} |
Please answer the following Stack Overflow question:
Title: MySQL: Set user variable from result of query
<p>Is it possible to set an user variable based on the result of a query in MySQL? </p>
<p>What I want to achieve is something like this (we can assume that both <code>USER</code> and <code>GROUP</code> are unique): </p>
<pre><code>set @user = 123456;
set @group = select GROUP from USER where User = @user;
select * from USER where GROUP = @group;
</code></pre>
<p>Please note that I know it's possible but I do not wish to do this with nested queries.</p> | <p>Yes, but you need to move the variable assignment into the query:</p>
<pre><code>SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;
</code></pre>
<p>Test case:</p>
<pre><code>CREATE TABLE user (`user` int, `group` int);
INSERT INTO user VALUES (123456, 5);
INSERT INTO user VALUES (111111, 5);
</code></pre>
<p>Result:</p>
<pre><code>SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;
+--------+-------+
| user | group |
+--------+-------+
| 123456 | 5 |
| 111111 | 5 |
+--------+-------+
2 rows in set (0.00 sec)
</code></pre>
<p>Note that for <code>SET</code>, either <code>=</code> or <code>:=</code> can be used as the assignment operator. However inside other statements, the assignment operator must be <code>:=</code> and not <code>=</code> because <code>=</code> is treated as a comparison operator in non-SET statements.</p>
<hr>
<p><strong>UPDATE:</strong></p>
<p>Further to comments below, you may also do the following:</p>
<pre><code>SET @user := 123456;
SELECT `group` FROM user LIMIT 1 INTO @group;
SELECT * FROM user WHERE `group` = @group;
</code></pre> | {
"question_id": 3888735,
"question_date": "2010-10-08T08:04:05.093Z",
"question_score": 234,
"tags": "mysql",
"answer_id": 3888755,
"answer_date": "2010-10-08T08:08:08.160Z",
"answer_score": 384
} |
Please answer the following Stack Overflow question:
Title: Checking if jquery is loaded using Javascript
<p>I am attempting to check if my Jquery Library is loaded onto my HTML page. I am checking to see if it works, but something is not right. Here is what I have:</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="/query-1.6.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
if (jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
});
</script>
</code></pre> | <blockquote>
<p>something is not right</p>
</blockquote>
<p>Well, you are using jQuery to check for the presence of jQuery. If jQuery isn't loaded then <code>$()</code> won't even run at all and your callback won't execute, unless you're using another library and that library happens to share the same <code>$()</code> syntax.</p>
<p>Remove your <code>$(document).ready()</code> (use something like <code>window.onload</code> instead):</p>
<pre><code>window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
}
</code></pre> | {
"question_id": 7341865,
"question_date": "2011-09-08T00:15:58.907Z",
"question_score": 234,
"tags": "javascript|jquery",
"answer_id": 7341884,
"answer_date": "2011-09-08T00:19:08.373Z",
"answer_score": 435
} |
Please answer the following Stack Overflow question:
Title: Flutter- wrapping text
<p>I want wrap text as text grows. I searched through and tried wrap with almost everything but still text stays one line and overflows from the screen.
Does anyone know how to achieve this?
Any help is highly appreciated!</p>
<pre><code>Positioned(
left: position.dx,
top: position.dy,
child: new Draggable(
data: widget.index,
onDragStarted: widget.setDragging,
onDraggableCanceled: (velocity, offset) {
setState(() {
position = offset;
widget.secondCallback(offset, widget.index);
widget.endDragging();
});
},
child: new GestureDetector(
onTap: () {
widget.callback(widget.caption, widget.index);
},
child: new Text(
widget.caption.caption,
style: new TextStyle(
color: widget.caption.color,
fontSize: widget.caption.fontSize,
),
),
),
feedback: new Material(
type: MaterialType.transparency,
child: new Text(
widget.caption.caption,
style: new TextStyle(
color: widget.caption.color,
fontSize: widget.caption.fontSize),
softWrap: true,
),
),
));
</code></pre> | <p>In a project of mine I wrap <code>Text</code> instances around <code>Container</code>s. This particular code sample features two stacked Text objects. </p>
<p>Here's a code sample. </p>
<pre><code> //80% of screen width
double c_width = MediaQuery.of(context).size.width*0.8;
return new Container (
padding: const EdgeInsets.all(16.0),
width: c_width,
child: new Column (
children: <Widget>[
new Text ("Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 ", textAlign: TextAlign.left),
new Text ("Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2", textAlign: TextAlign.left),
],
),
);
</code></pre>
<p>[edit] Added a width constraint to the container</p> | {
"question_id": 51930754,
"question_date": "2018-08-20T12:26:36.310Z",
"question_score": 234,
"tags": "dart|flutter",
"answer_id": 51931091,
"answer_date": "2018-08-20T12:46:54.270Z",
"answer_score": 136
} |
Please answer the following Stack Overflow question:
Title: Adding headers when using httpClient.GetAsync
<p>I'm implementing an API made by other colleagues with Apiary.io, in a Windows Store app project.</p>
<p>They show this example of a method I have to implement:</p>
<pre><code>var baseAddress = new Uri("https://private-a8014-xxxxxx.apiary-mock.com/");
using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{
using (var response = await httpClient.GetAsync("user/list{?organizationId}"))
{
string responseData = await response.Content.ReadAsStringAsync();
}
}
</code></pre>
<p>In this and some other methods, I need to have a header with a token that I get before.</p>
<p>Here's an image of Postman (chrome extension) with the header I'm talking about:
<img src="https://i.stack.imgur.com/UE43N.png" alt="enter image description here"></p>
<p>How do I add that Authorization header to the request?</p> | <p>When using GetAsync with the HttpClient you can add the authorization headers like so:</p>
<pre><code>httpClient.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("Bearer", "Your Oauth token");
</code></pre>
<p>This does add the authorization header for the lifetime of the HttpClient so is useful if you are hitting one site where the authorization header doesn't change.</p>
<p>Here is an detailed SO <a href="https://stackoverflow.com/questions/14627399/setting-authorization-header-of-httpclient">answer</a></p> | {
"question_id": 29801195,
"question_date": "2015-04-22T14:46:07.747Z",
"question_score": 234,
"tags": "c#|windows-runtime|windows-store-apps|dotnet-httpclient|apiary.io",
"answer_id": 29801299,
"answer_date": "2015-04-22T14:50:17.590Z",
"answer_score": 241
} |
Please answer the following Stack Overflow question:
Title: How to modify list entries during for loop?
<p>Now I know that it is not safe to modify the list during an iterative looping. However, suppose I have a list of strings, and I want to strip the strings themselves. Does replacement of mutable values count as modification? </p> | <p>It's considered poor form. Use a list comprehension instead, with slice assignment if you need to retain existing references to the list.</p>
<pre><code>a = [1, 3, 5]
b = a
a[:] = [x + 2 for x in a]
print(b)
</code></pre> | {
"question_id": 4081217,
"question_date": "2010-11-02T19:04:29.467Z",
"question_score": 234,
"tags": "python",
"answer_id": 4081234,
"answer_date": "2010-11-02T19:07:16.207Z",
"answer_score": 169
} |
Please answer the following Stack Overflow question:
Title: Disabling of EditText in Android
<p>In my application, I have an EditText that the user only has Read access not Write access.</p>
<p>In code I set <code>android:enabled="false"</code>. </p>
<p>Although the background of EditText changed to dark, when I click on it the keyboard pops up and I can change the text.</p>
<p>What should I set to disable EditText?</p> | <p>I believe the correct would be to set <a href="http://developer.android.com/reference/android/widget/TextView.html#attr_android:editable" rel="noreferrer"><code>android:editable="false"</code></a>.</p>
<p>And if you wonder why my link point to the attributes of <code>TextView</code>, you the answer is because <a href="http://developer.android.com/reference/android/widget/EditText.html" rel="noreferrer"><code>EditText</code></a> inherits from <code>TextView</code>:</p>
<blockquote>
<p>EditText is a thin veneer over
TextView that configures itself to be
editable.</p>
</blockquote>
<p><strong>Update:</strong><br>
As mentioned in the comments below, <code>editable</code> is deprecated (<a href="http://developer.android.com/reference/android/R.attr.html#editable" rel="noreferrer">since API level 3</a>). You should instead be using <a href="http://developer.android.com/reference/android/R.attr.html#inputType" rel="noreferrer"><code>inputType</code></a> (with the value <code>none</code>).</p> | {
"question_id": 4297763,
"question_date": "2010-11-28T16:29:36.277Z",
"question_score": 234,
"tags": "android|android-edittext",
"answer_id": 4297791,
"answer_date": "2010-11-28T16:34:49.383Z",
"answer_score": 278
} |
Please answer the following Stack Overflow question:
Title: How to style a div to be a responsive square?
<p>I want my div to adapt its height to always equal its width. The width is percental. When the parent's width decreases, the box should decrease by keeping its aspect ratio.</p>
<p>How to do this is CSS?</p> | <p>Works on almost all browsers.</p>
<p>You can try giving <code>padding-bottom</code> as a percentage.</p>
<pre><code><div style="height:0;width:20%;padding-bottom:20%;background-color:red">
<div>
Content goes here
</div>
</div>
</code></pre>
<p>The outer div is making a square and inner div contains the content. This solution worked for me many times.</p>
<p>Here's a <a href="https://jsfiddle.net/x6jj3dar/">jsfiddle</a></p> | {
"question_id": 19068070,
"question_date": "2013-09-28T14:37:03.077Z",
"question_score": 234,
"tags": "css|layout|responsive-design|aspect-ratio",
"answer_id": 19068538,
"answer_date": "2013-09-28T15:28:49.307Z",
"answer_score": 238
} |
Please answer the following Stack Overflow question:
Title: Get a list of all git commits, including the 'lost' ones
<p>Let's say that I have a graph like this:</p>
<pre><code>A---B---C---D (master)
\
\-E---F (HEAD)
</code></pre>
<p>If I do <code>git log --all --oneline</code>, I will get all six of my commits.</p>
<p>But if the graph is</p>
<pre><code>A---B---C---D (master, HEAD)
\
\-E---F
</code></pre>
<p>I will not see E and F. Can I get git to tell me all the commits, including those on branches which are not named?</p>
<p>Thanks</p> | <p>Not particularly easily- if you've lost the pointer to the tip of a branch, it's rather like finding a needle in a haystack. You can find all the commits that don't appear to be referenced any more- <code>git fsck --unreachable</code> will do this for you- but that will include commits that you threw away after a <code>git commit --amend</code>, old commits on branches that you rebased etc etc. So seeing all these commits at once is quite likely far too much information to wade through.</p>
<p>So the flippant answer is, don't lose track of things you're interested in. More seriously, the reflogs will hold references to all the commits you've used for the last 60 days or so by default. More importantly, they will give some context about what those commits <em>are</em>.</p> | {
"question_id": 4786972,
"question_date": "2011-01-24T20:43:41.020Z",
"question_score": 234,
"tags": "git|git-log",
"answer_id": 4787030,
"answer_date": "2011-01-24T20:49:46.343Z",
"answer_score": 72
} |
Please answer the following Stack Overflow question:
Title: Remove first Item of the array (like popping from stack)
<p>I have list of items created via <code>ng-repeat</code>. I also have Delete button.
Clicking delete button removes last item of the array one by one. <strong><a href="http://plnkr.co/edit/QDuklfthp2g7MMAoWxIx?p=preview" rel="noreferrer">Plunker</a></strong></p>
<p>But I want to remove items one by one starting from the first item. How can I do that? I used this for removing list Items:</p>
<pre><code> $scope.index = 1;
$scope.remove = function(item) {
var index = $scope.cards.indexOf(item);
$scope.cards.splice(index, 1);
}
</code></pre>
<p>Is there any way I can remove from the top? </p> | <p>The easiest way is using <code>shift()</code>. If you have an array, the <code>shift</code> function shifts everything to the left.</p>
<pre><code>var arr = [1, 2, 3, 4];
var theRemovedElement = arr.shift(); // theRemovedElement == 1
console.log(arr); // [2, 3, 4]
</code></pre> | {
"question_id": 29605929,
"question_date": "2015-04-13T12:57:25.760Z",
"question_score": 234,
"tags": "javascript|angularjs",
"answer_id": 29606016,
"answer_date": "2015-04-13T13:01:54.557Z",
"answer_score": 426
} |
Please answer the following Stack Overflow question:
Title: Cannot resolve symbol 'AppCompatActivity'
<p>I've just tried to use Android Studio. I've created blank project and tried to create <code>Activity</code> which extends <code>AppCompatActivity</code>. Unfortunalty Android Studio "says" that it</p>
<blockquote>
<p>Cannot resolve symbol 'AppCompatActivity'</p>
</blockquote>
<p>I have <code>compile "com.android.support:appcompat-v7:22.0.+"</code> in dependency list of my "app" module and rebuilt project several times. However I can only use <code>ActionBarActivity</code>. What am I doing wrong?</p> | <p>A little addition to other answers here, for anyone having the same error while using the right lib version and the right class.</p>
<p>When I upgraded to </p>
<pre><code>appcompat-v7:22.1.0
</code></pre>
<p>In which <code>ActionBarActivity</code> is deprecated and empty and <code>AppCompatActivty</code> is the way to go, due to some glitch in Android Studio, It didn't quite pick up on version change.</p>
<p>i.e. Even though Gradle ran without errors, the IDE itself kept saying
<code>Cannot resolve symbol 'AppCompatActivity'</code> (and it also wasn't available through the <code>Ctrl+N</code> search)</p>
<p>I looked into the <code>.idea/libraries</code> folder and noticed there's no appropriate metafile for the new version of the lib.</p>
<p>So, using the old-reliable <strong>File->Invalidate Caches/Restart</strong> did the trick. Always try this when you feel something is magically wrong with Android Studio.
And then Disable offline mode and sync.</p> | {
"question_id": 29199891,
"question_date": "2015-03-22T21:09:37.933Z",
"question_score": 234,
"tags": "android|android-studio|gradle|android-support-library|android-appcompat",
"answer_id": 30698604,
"answer_date": "2015-06-07T21:26:46.303Z",
"answer_score": 376
} |
Please answer the following Stack Overflow question:
Title: MySQL Update Inner Join tables query
<p>I have no idea what the problem is. Using MySQL 5.0 I get a compile error when attempting to run the following MySQL update query:</p>
<pre><code>UPDATE b
SET b.mapx = g.latitude,
b.mapy = g.longitude
FROM business AS b
INNER JOIN business_geocode g ON b.business_id = g.business_id
WHERE (b.mapx = '' OR b.mapx = 0) AND
g.latitude > 0
</code></pre>
<p>All the field names are correct. Any thoughts?</p> | <p>Try this:</p>
<pre><code>UPDATE business AS b
INNER JOIN business_geocode AS g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
b.mapy = g.longitude
WHERE (b.mapx = '' or b.mapx = 0) and
g.latitude > 0
</code></pre>
<h2>Update:</h2>
<p>Since you said the query yielded a syntax error, I created some tables that I could test it against and confirmed that there is no syntax error in my query:</p>
<pre><code>mysql> create table business (business_id int unsigned primary key auto_increment, mapx varchar(255), mapy varchar(255)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)
mysql> create table business_geocode (business_geocode_id int unsigned primary key auto_increment, business_id int unsigned not null, latitude varchar(255) not null, longitude varchar(255) not null, foreign key (business_id) references business(business_id)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)
mysql> UPDATE business AS b
-> INNER JOIN business_geocode AS g ON b.business_id = g.business_id
-> SET b.mapx = g.latitude,
-> b.mapy = g.longitude
-> WHERE (b.mapx = '' or b.mapx = 0) and
-> g.latitude > 0;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
</code></pre>
<p>See? No syntax error. I tested against MySQL 5.5.8.</p> | {
"question_id": 8057565,
"question_date": "2011-11-08T21:53:07.280Z",
"question_score": 234,
"tags": "mysql|compiler-errors",
"answer_id": 8057585,
"answer_date": "2011-11-08T21:54:51.070Z",
"answer_score": 487
} |
Please answer the following Stack Overflow question:
Title: Find the most common element in a list
<p>What is an efficient way to find the most common element in a Python list?</p>
<p>My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:</p>
<pre><code>>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
</code></pre> | <p>With so many solutions proposed, I'm amazed nobody's proposed what I'd consider an obvious one (for non-hashable but comparable elements) -- [<code>itertools.groupby</code>][1]. <code>itertools</code> offers fast, reusable functionality, and lets you delegate some tricky logic to well-tested standard library components. Consider for example:</p>
<pre><code>import itertools
import operator
def most_common(L):
# get an iterable of (item, iterable) pairs
SL = sorted((x, i) for i, x in enumerate(L))
# print 'SL:', SL
groups = itertools.groupby(SL, key=operator.itemgetter(0))
# auxiliary function to get "quality" for an item
def _auxfun(g):
item, iterable = g
count = 0
min_index = len(L)
for _, where in iterable:
count += 1
min_index = min(min_index, where)
# print 'item %r, count %r, minind %r' % (item, count, min_index)
return count, -min_index
# pick the highest-count/earliest item
return max(groups, key=_auxfun)[0]
</code></pre>
<p>This could be written more concisely, of course, but I'm aiming for maximal clarity. The two <code>print</code> statements can be uncommented to better see the machinery in action; for example, <em>with</em> prints uncommented:</p>
<pre><code>print most_common(['goose', 'duck', 'duck', 'goose'])
</code></pre>
<p>emits:</p>
<pre><code>SL: [('duck', 1), ('duck', 2), ('goose', 0), ('goose', 3)]
item 'duck', count 2, minind 1
item 'goose', count 2, minind 0
goose
</code></pre>
<p>As you see, <code>SL</code> is a list of pairs, each pair an item followed by the item's index in the original list (to implement the key condition that, if the "most common" items with the same highest count are > 1, the result must be the earliest-occurring one).</p>
<p><code>groupby</code> groups by the item only (via <code>operator.itemgetter</code>). The auxiliary function, called once per grouping during the <code>max</code> computation, receives and internally unpacks a group - a tuple with two items <code>(item, iterable)</code> where the iterable's items are also two-item tuples, <code>(item, original index)</code> [[the items of <code>SL</code>]].</p>
<p>Then the auxiliary function uses a loop to determine both the count of entries in the group's iterable, <em>and</em> the minimum original index; it returns those as combined "quality key", with the min index sign-changed so the <code>max</code> operation will consider "better" those items that occurred earlier in the original list.</p>
<p>This code could be much simpler if it worried a <em>little</em> less about big-O issues in time and space, e.g....:</p>
<pre><code>def most_common(L):
groups = itertools.groupby(sorted(L))
def _auxfun((item, iterable)):
return len(list(iterable)), -L.index(item)
return max(groups, key=_auxfun)[0]
</code></pre>
<p>same basic idea, just expressed more simply and compactly... but, alas, an extra O(N) auxiliary space (to embody the groups' iterables to lists) and O(N squared) time (to get the <code>L.index</code> of every item). While premature optimization is the root of all evil in programming, deliberately picking an O(N squared) approach when an O(N log N) one is available just goes too much against the grain of scalability!-)</p>
<p>Finally, for those who prefer "oneliners" to clarity and performance, a bonus 1-liner version with suitably mangled names:-).</p>
<pre><code>from itertools import groupby as g
def most_common_oneliner(L):
return max(g(sorted(L)), key=lambda(x, v):(len(list(v)),-L.index(x)))[0]
</code></pre> | {
"question_id": 1518522,
"question_date": "2009-10-05T06:35:44.640Z",
"question_score": 234,
"tags": "python|list",
"answer_id": 1520716,
"answer_date": "2009-10-05T15:16:29.613Z",
"answer_score": 115
} |
Please answer the following Stack Overflow question:
Title: CSS: Control space between bullet and <li>
<p>I'd like to control how much horizontal space a bullet pushes its <code><li></code> to the right in an <code><ol></code> or <code><ul></code>.</p>
<p>That is, instead of always having</p>
<pre><code>* Some list text goes
here.
</code></pre>
<p>I'd like to be able to change that to be</p>
<pre><code>* Some list text goes
here.
</code></pre>
<p>or</p>
<pre><code>*Some list text goes
here.
</code></pre>
<p>I looked around but could only find instructions for shifting the entire block left or right, for example, <a href="http://www.alistapart.com/articles/taminglists/" rel="noreferrer">http://www.alistapart.com/articles/taminglists/</a></p> | <p>Put its content in a <code>span</code> which is relatively positioned, then you can control the space by the <code>left</code> property of the <code>span</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>li span {
position: relative;
left: -10px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li><span>item 1</span></li>
<li><span>item 2</span></li>
<li><span>item 3</span></li>
</ul></code></pre>
</div>
</div>
</p> | {
"question_id": 4373046,
"question_date": "2010-12-07T03:10:34.303Z",
"question_score": 234,
"tags": "html|css|html-lists",
"answer_id": 4373216,
"answer_date": "2010-12-07T03:47:02.663Z",
"answer_score": 200
} |
Please answer the following Stack Overflow question:
Title: Pandas dataframe fillna() only some columns in place
<p>I am trying to fill none values in a Pandas dataframe with 0's for only some subset of columns.</p>
<p>When I do:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(data={'a':[1,2,3,None],'b':[4,5,None,6],'c':[None,None,7,8]})
print df
df.fillna(value=0, inplace=True)
print df
</code></pre>
<p>The output:</p>
<pre><code> a b c
0 1.0 4.0 NaN
1 2.0 5.0 NaN
2 3.0 NaN 7.0
3 NaN 6.0 8.0
a b c
0 1.0 4.0 0.0
1 2.0 5.0 0.0
2 3.0 0.0 7.0
3 0.0 6.0 8.0
</code></pre>
<p>It replaces every <code>None</code> with <code>0</code>'s. What I want to do is, only replace <code>None</code>s in columns <code>a</code> and <code>b</code>, but not <code>c</code>.</p>
<p>What is the best way of doing this?</p> | <p>You can select your desired columns and do it by assignment:</p>
<pre><code>df[['a', 'b']] = df[['a','b']].fillna(value=0)
</code></pre>
<p>The resulting output is as expected:</p>
<pre><code> a b c
0 1.0 4.0 NaN
1 2.0 5.0 NaN
2 3.0 0.0 7.0
3 0.0 6.0 8.0
</code></pre> | {
"question_id": 38134012,
"question_date": "2016-06-30T22:06:16.820Z",
"question_score": 234,
"tags": "python|pandas|dataframe",
"answer_id": 38134049,
"answer_date": "2016-06-30T22:09:23.560Z",
"answer_score": 362
} |
Please answer the following Stack Overflow question:
Title: Undo a merge by pull request?
<p>Someone accepted a pull request which they shouldn't have. Now we have a bunch of broken code merged in. How do you undo a pull request? I was just going to revert the changes to the commit just before the merge, but I noticed that it merged in a bunch of commits. So now there are all these commits from this person from days before the merge. How do you undo this?</p> | <p>There is a <a href="https://stackoverflow.com/a/6217372/717998">better answer</a> to this problem, though I could just break this down step-by-step. </p>
<p>You will need to fetch and checkout the latest upstream changes like so, e.g.:</p>
<pre><code>git fetch upstream
git checkout upstream/master -b revert/john/foo_and_bar
</code></pre>
<p>Taking a look at the commit log, you should find something similar to this:</p>
<blockquote>
<pre><code>commit b76a5f1f5d3b323679e466a1a1d5f93c8828b269
Merge: 9271e6e a507888
Author: Tim Tom <[email protected]>
Date: Mon Apr 29 06:12:38 2013 -0700
Merge pull request #123 from john/foo_and_bar
Add foo and bar
commit a507888e9fcc9e08b658c0b25414d1aeb1eef45e
Author: John Doe <[email protected]>
Date: Mon Apr 29 12:13:29 2013 +0000
Add bar
commit 470ee0f407198057d5cb1d6427bb8371eab6157e
Author: John Doe <[email protected]>
Date: Mon Apr 29 10:29:10 2013 +0000
Add foo
</code></pre>
</blockquote>
<p>Now you want to revert the entire pull request with the ability to unrevert later.
To do so, you will need to take the ID of the <em>merge commit</em>.</p>
<p>In the above example the <em>merge commit</em> is the top one where it says <em>"Merged pull request #123..."</em>.</p>
<p>Do this to revert the both changes (<em>"Add bar"</em> and <em>"Add foo"</em>) and you will end up with in one commit reverting the entire pull request which you can unrevert later on and keep the history of changes clean:</p>
<pre><code>git revert -m 1 b76a5f1f5d3b323679e466a1a1d5f93c8828b269
</code></pre> | {
"question_id": 6481575,
"question_date": "2011-06-26T01:26:37.890Z",
"question_score": 234,
"tags": "git|github|merge|pull-request",
"answer_id": 16298304,
"answer_date": "2013-04-30T11:03:38.677Z",
"answer_score": 248
} |
Please answer the following Stack Overflow question:
Title: Tool to generate JSON schema from JSON data
<p>We have this json schema <a href="https://datatracker.ietf.org/doc/html/draft-zyp-json-schema-03" rel="noreferrer">draft</a>. I would like to get a sample of my JSON data and generate a skeleton for the JSON schema, that I can rework manually, adding things like description, required, etc, which can not be infered from the specific examples.</p>
<p>For example, from my input <code>example.json</code>:</p>
<pre><code>{
"foo": "lorem",
"bar": "ipsum"
}
</code></pre>
<p>I would run my json_schema_generator tool and would get:</p>
<pre><code>{ "foo": {
"type" : "string",
"required" : true,
"description" : "unknown"
},
"bar": {
"type" : "string",
"required" : true,
"description" : "unknown"
}
}
</code></pre>
<p>This example has been coded manually, so it has maybe errors.
Is there any tool out there which could help me with the conversion JSON -> JSON schema?</p> | <p>Seeing that this question is getting quite some upvotes, I add new information (I am not sure if this is new, but I couldn't find it at the time)</p>
<ul>
<li><a href="http://json-schema.org/" rel="noreferrer">The home of JSON Schema</a></li>
<li><a href="https://pypi.python.org/pypi/jsonschema" rel="noreferrer">An implementation of JSON Schema validation for Python</a></li>
<li>Related hacker news <a href="http://caines.ca/blog/2013/04/29/so-i-wrote-a-json-api-framework-and-the-framework-was-the-least-interesting-part/" rel="noreferrer">discussion</a></li>
<li><a href="https://github.com/perenecabuto/json_schema_generator" rel="noreferrer">A json schema generator in python</a>, which is what I was looking for.</li>
</ul> | {
"question_id": 7341537,
"question_date": "2011-09-07T23:14:15.997Z",
"question_score": 234,
"tags": "json|validation|reflection|jsonschema",
"answer_id": 16403603,
"answer_date": "2013-05-06T17:06:01.227Z",
"answer_score": 22
} |
Please answer the following Stack Overflow question:
Title: docker entrypoint running bash script gets "permission denied"
<p>I'm trying to dockerize my node.js app. When the container is built I want it to run a <code>git clone</code> and then start the node server. Therefore I put these operations in a .sh script. And run the script as a single command in the ENTRYPOINT:</p>
<pre><code>FROM ubuntu:14.04
RUN apt-get update && apt-get install -y build-essential libssl-dev gcc curl npm git
#install gcc 4.9
RUN apt-get install -y software-properties-common python-software-properties
RUN add-apt-repository -y ppa:ubuntu-toolchain-r/test
RUN apt-get update
RUN apt-get install -y libstdc++-4.9-dev
#install newst nodejs
RUN curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
RUN apt-get install -y nodejs
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
ADD package.json /usr/src/app/
RUN npm install
ADD docker-entrypoint.sh /usr/src/app/
EXPOSE 8080
ENTRYPOINT ["/usr/src/app/docker-entrypoint.sh"]
</code></pre>
<p>My docker-entrypoint.sh looks like this:</p>
<pre><code>git clone git@<repo>.git
git add remote upstream git@<upstream_repo>.git
/usr/bin/node server.js
</code></pre>
<p>After building this image and run:</p>
<pre><code>docker run --env NODE_ENV=development -p 8080:8080 -t -i <image>
</code></pre>
<p>I'm getting: </p>
<pre><code>docker: Error response from daemon: oci runtime error: exec: "/usr/src/app/docker-entrypoint.sh": permission denied.
</code></pre>
<p>I shell into the container and the permission of docker-entrypoint.sh is:</p>
<pre><code>-rw-r--r-- 1 root root 292 Aug 10 18:41 docker-entrypoint.sh
</code></pre>
<p>three questions:</p>
<ol>
<li><p>Does my bash script have wrong syntax?</p></li>
<li><p>How do I change the permission of a bash file before adding it into an image?</p></li>
<li><p>What's the best way to run multiple git commands in entrypoint without using a bash script?</p></li>
</ol>
<p>Thanks.</p> | <ol>
<li><p>"Permission denied" prevents your script from being invoked <em>at all</em>. Thus, the only syntax that could be possibly pertinent is that of the first line (the "shebang"), which should look like <code>#!/usr/bin/env bash</code>, or <code>#!/bin/bash</code>, or similar depending on your target's filesystem layout.</p></li>
<li><p>Most likely the filesystem permissions not being set to allow execute. It's also possible that the shebang references something that isn't executable, but this is <em>far</em> less likely.</p></li>
<li><p>Mooted by the ease of repairing the prior issues.</p></li>
</ol>
<hr>
<p>The simple reading of</p>
<pre><code>docker: Error response from daemon: oci runtime error: exec: "/usr/src/app/docker-entrypoint.sh": permission denied.
</code></pre>
<p>...is that the script isn't marked executable.</p>
<pre><code>RUN ["chmod", "+x", "/usr/src/app/docker-entrypoint.sh"]
</code></pre>
<p>will address this within the container. Alternately, you can <em>ensure that the local copy referenced by the Dockerfile is executable</em>, and then use <code>COPY</code> (which is explicitly documented to retain metadata).</p> | {
"question_id": 38882654,
"question_date": "2016-08-10T20:11:04.320Z",
"question_score": 234,
"tags": "bash|shell|docker",
"answer_id": 38882798,
"answer_date": "2016-08-10T20:19:26.513Z",
"answer_score": 315
} |
Please answer the following Stack Overflow question:
Title: "Parser Error Message: Could not load type" in Global.asax
<p>I'm working on an MVC3 project and receive the following error:</p>
<blockquote>
<p>Parser Error Message: Could not load type 'GodsCreationTaxidermy.MvcApplication'.</p>
</blockquote>
<p>Source Error: </p>
<blockquote>
<p>Line 1: <code><%@ Application Codebehind="Global.asax.cs" Inherits="GodsCreationTaxidermy.Core.MvcApplication" Language="C#" %></code></p>
</blockquote>
<p>The error I get is cannot load GodsCreationTaxidermy.Core.MvcApplication but in this screen shot the Core part isn't displaying in the error:</p>
<p><img src="https://i.stack.imgur.com/LL3Vb.png" alt="Error Page Screenshot"></p>
<p>Does anyone have any ideas or a solution to this error?</p> | <p>Your local web server is running different code than what you're actually working on. Ensure you have stopped debugging, stop your local web server, clean and rebuild as Peter suggested, double-check your global.asax and global.asax.cs, and try again.</p>
<p>If this doesn't work and you are using local IIS, try removing the site in IIS Manager and recreating it manually.</p> | {
"question_id": 11682216,
"question_date": "2012-07-27T05:56:12.893Z",
"question_score": 234,
"tags": "asp.net|asp.net-mvc-3",
"answer_id": 11873809,
"answer_date": "2012-08-08T21:56:48.860Z",
"answer_score": 187
} |
Please answer the following Stack Overflow question:
Title: C++ equivalent of StringBuffer/StringBuilder?
<p>Is there a C++ Standard Template Library class that provides efficient string concatenation functionality, similar to C#'s <a href="http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx" rel="noreferrer">StringBuilder</a> or Java's <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html" rel="noreferrer">StringBuffer</a>?</p> | <p>The C++ way would be to use <a href="http://en.cppreference.com/w/cpp/io/basic_stringstream" rel="noreferrer">std::stringstream</a> or just plain string concatenations. C++ strings are mutable so the performance considerations of concatenation are less of a concern.</p>
<p>with regards to formatting, you can do all the same formatting on a stream, but <a href="http://en.cppreference.com/w/cpp/io/manip" rel="noreferrer">in a different way, similar to <code>cout</code></a>. or you can use a strongly typed functor which encapsulates this and provides a String.Format like interface e.g. <a href="http://www.boost.org/doc/libs/1_42_0/libs/format/doc/format.html" rel="noreferrer">boost::format</a> </p> | {
"question_id": 2462951,
"question_date": "2010-03-17T14:20:22.813Z",
"question_score": 234,
"tags": "c++|stl|string-concatenation",
"answer_id": 2462985,
"answer_date": "2010-03-17T14:23:43.930Z",
"answer_score": 200
} |
Please answer the following Stack Overflow question:
Title: How do you update objects in a document's array (nested updating)
<p>Assume we have the following collection, which I have few questions about:</p>
<pre><code>{
"_id" : ObjectId("4faaba123412d654fe83hg876"),
"user_id" : 123456,
"total" : 100,
"items" : [
{
"item_name" : "my_item_one",
"price" : 20
},
{
"item_name" : "my_item_two",
"price" : 50
},
{
"item_name" : "my_item_three",
"price" : 30
}
]
}
</code></pre>
<ol>
<li><p>I want to increase the price for "item_name":"my_item_two" <strong>and if it doesn't exists</strong>, it should be appended to the "items" array.</p>
</li>
<li><p>How can I update two fields at the same time? For example, increase the price for "my_item_three" and at the same time increase the "total" (with the same value).</p>
</li>
</ol>
<p>I prefer to do this on the MongoDB side, otherwise I have to load the document in client-side (Python) and construct the updated document and replace it with the existing one in MongoDB.</p>
<p>This is what I have tried and works fine <strong>if</strong> the object exists:</p>
<pre><code>db.test_invoice.update({user_id : 123456 , "items.item_name":"my_item_one"} , {$inc: {"items.$.price": 10}})
</code></pre>
<p>However, if the key doesn't exist, it does nothing.
Also, it only updates the nested object. There is no way with this command to update the "total" field as well.</p> | <p>For question #1, let's break it into two parts. First, increment any document that has "items.item_name" equal to "my_item_two". For this you'll have to use the positional "$" operator. Something like:</p>
<pre><code> db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } ,
{$inc : {"items.$.price" : 1} } ,
false ,
true);
</code></pre>
<p>Note that this will only increment the first matched subdocument in any array (so if you have another document in the array with "item_name" equal to "my_item_two", it won't get incremented). But this might be what you want. </p>
<p>The second part is trickier. We can push a new item to an array without a "my_item_two" as follows:</p>
<pre><code> db.bar.update( {user_id : 123456, "items.item_name" : {$ne : "my_item_two" }} ,
{$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
false ,
true);
</code></pre>
<p>For your question #2, the answer is easier. To increment the total and the price of item_three in any document that contains "my_item_three," you can use the $inc operator on multiple fields at the same time. Something like:</p>
<pre><code>db.bar.update( {"items.item_name" : {$ne : "my_item_three" }} ,
{$inc : {total : 1 , "items.$.price" : 1}} ,
false ,
true);
</code></pre> | {
"question_id": 10522347,
"question_date": "2012-05-09T18:53:26.547Z",
"question_score": 234,
"tags": "mongodb",
"answer_id": 10523963,
"answer_date": "2012-05-09T20:57:28.373Z",
"answer_score": 270
} |
Please answer the following Stack Overflow question:
Title: When to use a linked list over an array/array list?
<p>I use a lot of lists and arrays but I have yet to come across a scenario in which the array list couldn't be used just as easily as, if not easier than, the linked list. I was hoping someone could give me some examples of when the linked list is notably better.</p> | <p><strong>Linked lists are preferable over arrays when:</strong></p>
<ol>
<li><p>you need constant-time insertions/deletions from the list (such as in real-time computing where time predictability is absolutely critical)</p></li>
<li><p>you don't know how many items will be in the list. With arrays, you may need to re-declare and copy memory if the array grows too big</p></li>
<li><p>you don't need random access to any elements</p></li>
<li><p>you want to be able to insert items in the middle of the list (such as a priority queue)</p></li>
</ol>
<p><strong>Arrays are preferable when:</strong></p>
<ol>
<li><p>you need indexed/random access to elements</p></li>
<li><p>you know the number of elements in the array ahead of time so that you can allocate the correct amount of memory for the array</p></li>
<li><p>you need speed when iterating through all the elements in sequence. You can use pointer math on the array to access each element, whereas you need to lookup the node based on the pointer for each element in linked list, which may result in page faults which may result in performance hits.</p></li>
<li><p>memory is a concern. Filled arrays take up less memory than linked lists. Each element in the array is just the data. Each linked list node requires the data as well as one (or more) pointers to the other elements in the linked list.</p></li>
</ol>
<p>Array Lists (like those in .Net) give you the benefits of arrays, but dynamically allocate resources for you so that you don't need to worry too much about list size and you can delete items at any index without any effort or re-shuffling elements around. Performance-wise, arraylists are slower than raw arrays.</p> | {
"question_id": 393556,
"question_date": "2008-12-26T06:52:53.057Z",
"question_score": 234,
"tags": "arrays|list|arraylist|linked-list",
"answer_id": 393578,
"answer_date": "2008-12-26T07:12:04.860Z",
"answer_score": 321
} |
Please answer the following Stack Overflow question:
Title: How do I format a date in Jinja2?
<p>Using Jinja2, how do I format a date field? I know in Python I can simply do this:</p>
<pre><code>print(car.date_of_manufacture.strftime('%Y-%m-%d'))
</code></pre>
<p>But how do I format the date in Jinja2?</p> | <p>There are two ways to do it. The direct approach would be to simply call (and print) the strftime() method in your template, for example</p>
<pre><code>{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}
</code></pre>
<p>Another, sightly better approach would be to define your own filter, e.g.:</p>
<pre><code>from flask import Flask
import babel
app = Flask(__name__)
@app.template_filter()
def format_datetime(value, format='medium'):
if format == 'full':
format="EEEE, d. MMMM y 'at' HH:mm"
elif format == 'medium':
format="EE dd.MM.y HH:mm"
return babel.dates.format_datetime(value, format)
</code></pre>
<p>(This filter is based on babel for reasons regarding i18n, but you can use strftime too). The advantage of the filter is, that you can write</p>
<pre><code>{{ car.date_of_manufacture|format_datetime }}
{{ car.date_of_manufacture|format_datetime('full') }}
</code></pre>
<p>which looks nicer and is more maintainable. Another common filter is also the "timedelta" filter, which evaluates to something like "written 8 minutes ago". You can use <code>babel.dates.format_timedelta</code> for that, and register it as filter similar to the datetime example given here.</p> | {
"question_id": 4830535,
"question_date": "2011-01-28T16:19:35.693Z",
"question_score": 234,
"tags": "python|jinja2",
"answer_id": 4830620,
"answer_date": "2011-01-28T16:29:46.260Z",
"answer_score": 411
} |
Please answer the following Stack Overflow question:
Title: Pandas column of lists, create a row for each list element
<p>I have a dataframe where some cells contain lists of multiple values. Rather than storing multiple
values in a cell, I'd like to expand the dataframe so that each item in the list gets its own row (with the same values in all other columns). So if I have:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(
{'trial_num': [1, 2, 3, 1, 2, 3],
'subject': [1, 1, 1, 2, 2, 2],
'samples': [list(np.random.randn(3).round(2)) for i in range(6)]
}
)
df
Out[10]:
samples subject trial_num
0 [0.57, -0.83, 1.44] 1 1
1 [-0.01, 1.13, 0.36] 1 2
2 [1.18, -1.46, -0.94] 1 3
3 [-0.08, -4.22, -2.05] 2 1
4 [0.72, 0.79, 0.53] 2 2
5 [0.4, -0.32, -0.13] 2 3
</code></pre>
<p>How do I convert to long form, e.g.:</p>
<pre><code> subject trial_num sample sample_num
0 1 1 0.57 0
1 1 1 -0.83 1
2 1 1 1.44 2
3 1 2 -0.01 0
4 1 2 1.13 1
5 1 2 0.36 2
6 1 3 1.18 0
# etc.
</code></pre>
<p>The index is not important, it's OK to set existing
columns as the index and the final ordering isn't
important.</p> | <p><strong>UPDATE:</strong> the solution below was helpful for older Pandas versions, because the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.explode.html" rel="noreferrer">DataFrame.explode()</a> wasn’t available. Starting from Pandas 0.25.0 you can simply use <code>DataFrame.explode()</code>.</p>
<hr />
<pre><code>lst_col = 'samples'
r = pd.DataFrame({
col:np.repeat(df[col].values, df[lst_col].str.len())
for col in df.columns.drop(lst_col)}
).assign(**{lst_col:np.concatenate(df[lst_col].values)})[df.columns]
</code></pre>
<p>Result:</p>
<pre><code>In [103]: r
Out[103]:
samples subject trial_num
0 0.10 1 1
1 -0.20 1 1
2 0.05 1 1
3 0.25 1 2
4 1.32 1 2
5 -0.17 1 2
6 0.64 1 3
7 -0.22 1 3
8 -0.71 1 3
9 -0.03 2 1
10 -0.65 2 1
11 0.76 2 1
12 1.77 2 2
13 0.89 2 2
14 0.65 2 2
15 -0.98 2 3
16 0.65 2 3
17 -0.30 2 3
</code></pre>
<p>PS <a href="https://stackoverflow.com/a/40449726/5741205">here you may find a bit more generic solution</a></p>
<hr />
<p><strong>UPDATE:</strong> some explanations: IMO the easiest way to understand this code is to try to execute it step-by-step:</p>
<p>in the following line we are repeating values in one column <code>N</code> times where <code>N</code> - is the length of the corresponding list:</p>
<pre><code>In [10]: np.repeat(df['trial_num'].values, df[lst_col].str.len())
Out[10]: array([1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3], dtype=int64)
</code></pre>
<p>this can be generalized for all columns, containing scalar values:</p>
<pre><code>In [11]: pd.DataFrame({
...: col:np.repeat(df[col].values, df[lst_col].str.len())
...: for col in df.columns.drop(lst_col)}
...: )
Out[11]:
trial_num subject
0 1 1
1 1 1
2 1 1
3 2 1
4 2 1
5 2 1
6 3 1
.. ... ...
11 1 2
12 2 2
13 2 2
14 2 2
15 3 2
16 3 2
17 3 2
[18 rows x 2 columns]
</code></pre>
<p>using <code>np.concatenate()</code> we can flatten all values in the <code>list</code> column (<code>samples</code>) and get a 1D vector:</p>
<pre><code>In [12]: np.concatenate(df[lst_col].values)
Out[12]: array([-1.04, -0.58, -1.32, 0.82, -0.59, -0.34, 0.25, 2.09, 0.12, 0.83, -0.88, 0.68, 0.55, -0.56, 0.65, -0.04, 0.36, -0.31])
</code></pre>
<p>putting all this together:</p>
<pre><code>In [13]: pd.DataFrame({
...: col:np.repeat(df[col].values, df[lst_col].str.len())
...: for col in df.columns.drop(lst_col)}
...: ).assign(**{lst_col:np.concatenate(df[lst_col].values)})
Out[13]:
trial_num subject samples
0 1 1 -1.04
1 1 1 -0.58
2 1 1 -1.32
3 2 1 0.82
4 2 1 -0.59
5 2 1 -0.34
6 3 1 0.25
.. ... ... ...
11 1 2 0.68
12 2 2 0.55
13 2 2 -0.56
14 2 2 0.65
15 3 2 -0.04
16 3 2 0.36
17 3 2 -0.31
[18 rows x 3 columns]
</code></pre>
<p>using <code>pd.DataFrame()[df.columns]</code> will guarantee that we are selecting columns in the original order...</p> | {
"question_id": 27263805,
"question_date": "2014-12-03T04:44:44.443Z",
"question_score": 234,
"tags": "python|pandas|list",
"answer_id": 48532692,
"answer_date": "2018-01-31T00:34:48.197Z",
"answer_score": 77
} |
Please answer the following Stack Overflow question:
Title: Check if an element's content is overflowing?
<p>What's the easiest way to detect if an element has been overflowed?</p>
<p>My use case is, I want to limit a certain content box to have a height of 300px. If the inner content is taller than that, I cut it off with an overflow. But if it is overflowed I want to show a 'more' button, but if not I don't want to show that button.</p>
<p>Is there an easy way to detect overflow, or is there a better method?</p> | <p>If you want to show only an identifier for more content, then you can do this with pure CSS. I use pure scrolling shadows for this. The trick is the use of <code>background-attachment: local;</code>. Your css looks like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.scrollbox {
overflow: auto;
width: 200px;
max-height: 200px;
margin: 50px auto;
background:
/* Shadow covers */
linear-gradient(white 30%, rgba(255,255,255,0)),
linear-gradient(rgba(255,255,255,0), white 70%) 0 100%,
/* Shadows */
radial-gradient(50% 0, farthest-side, rgba(0,0,0,.2), rgba(0,0,0,0)),
radial-gradient(50% 100%,farthest-side, rgba(0,0,0,.2), rgba(0,0,0,0)) 0 100%;
background:
/* Shadow covers */
linear-gradient(white 30%, rgba(255,255,255,0)),
linear-gradient(rgba(255,255,255,0), white 70%) 0 100%,
/* Shadows */
radial-gradient(farthest-side at 50% 0, rgba(0,0,0,.2), rgba(0,0,0,0)),
radial-gradient(farthest-side at 50% 100%, rgba(0,0,0,.2), rgba(0,0,0,0)) 0 100%;
background-repeat: no-repeat;
background-color: white;
background-size: 100% 40px, 100% 40px, 100% 14px, 100% 14px;
/* Opera doesn't support this in the shorthand */
background-attachment: local, local, scroll, scroll;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="scrollbox">
<ul>
<li>Not enough content to scroll</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
<div class="scrollbox">
<ul>
<li>Ah! Scroll below!</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>10</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>The end!</li>
<li>No shadow there.</li>
</ul>
</div></code></pre>
</div>
</div>
</p>
<p>The code and the example you can find on <a href="http://dabblet.com/gist/2462915" rel="noreferrer">http://dabblet.com/gist/2462915</a></p>
<p>And an explanation you can find here: <a href="http://lea.verou.me/2012/04/background-attachment-local/" rel="noreferrer">http://lea.verou.me/2012/04/background-attachment-local/</a>.</p> | {
"question_id": 9333379,
"question_date": "2012-02-17T18:22:03.537Z",
"question_score": 234,
"tags": "javascript|css|overflow",
"answer_id": 34299947,
"answer_date": "2015-12-15T21:42:12.123Z",
"answer_score": 122
} |
Please answer the following Stack Overflow question:
Title: How to use "/" (directory separator) in both Linux and Windows in Python?
<p>I have written a code in python which uses / to make a particular file in a folder, if I want to use the code in windows it will not work, is there a way by which I can use the code in Windows and Linux.</p>
<p>In python I am using this code:</p>
<pre><code>pathfile=os.path.dirname(templateFile)
rootTree.write(''+pathfile+'/output/log.txt')
</code></pre>
<p>When I will use my code in suppose windows machine my code will not work.</p>
<p>How do I use "/" (directory separator) in both Linux and Windows?</p> | <p>Use <code>os.path.join()</code>.
Example: <code>os.path.join(pathfile,"output","log.txt")</code>.</p>
<p>In your code that would be: <code>rootTree.write(os.path.join(pathfile,"output","log.txt"))</code></p> | {
"question_id": 16010992,
"question_date": "2013-04-15T08:42:12.850Z",
"question_score": 234,
"tags": "python|linux|windows|unix",
"answer_id": 16011098,
"answer_date": "2013-04-15T08:48:03.970Z",
"answer_score": 314
} |
Please answer the following Stack Overflow question:
Title: How to run only one task in ansible playbook?
<p>Is there a way to only run one task in ansible playbook?</p>
<p>For example, in <code>roles/hadoop_primary/tasks/hadoop_master.yml</code>. I have <code>"start hadoop job tracker services"</code> task. Can I just run that one task?</p>
<p>hadoop_master.yml file:</p>
<pre class="lang-yaml prettyprint-override"><code># Playbook for Hadoop master servers
- name: Install the namenode and jobtracker packages
apt: name={{item}} force=yes state=latest
with_items:
- hadoop-0.20-mapreduce-jobtracker
- hadoop-hdfs-namenode
- hadoop-doc
- hue-plugins
- name: start hadoop jobtracker services
service: name=hadoop-0.20-mapreduce-jobtracker state=started
tags:
debug
</code></pre> | <p>You should use <code>tags:</code> as documented in <a href="https://docs.ansible.com/ansible/latest/user_guide/playbooks_tags.html" rel="noreferrer">https://docs.ansible.com/ansible/latest/user_guide/playbooks_tags.html</a></p>
<hr />
<p>If you have a large playbook it may become useful to be able to run a specific part of the configuration without running the whole playbook.</p>
<p>Both plays and tasks support a “tags:” attribute for this reason.</p>
<p>Example:</p>
<pre><code>tasks:
- yum: name={{ item }} state=installed
with_items:
- httpd
- memcached
tags:
- packages
- template: src=templates/src.j2 dest=/etc/foo.conf
tags:
- configuration
</code></pre>
<p>If you wanted to just run the “configuration” and “packages” part of a very long playbook, you could do this:</p>
<pre><code>ansible-playbook example.yml --tags "configuration,packages"
</code></pre>
<p>On the other hand, if you want to run a playbook without certain tasks, you could do this:</p>
<pre><code>ansible-playbook example.yml --skip-tags "notification"
</code></pre>
<p>You may also apply tags to roles:</p>
<pre><code>roles:
- { role: webserver, port: 5000, tags: [ 'web', 'foo' ] }
</code></pre>
<p>And you may also tag basic include statements:</p>
<pre><code>- include: foo.yml tags=web,foo
</code></pre>
<p>Both of these have the function of tagging every single task inside the include statement.</p> | {
"question_id": 23945201,
"question_date": "2014-05-30T00:27:15.453Z",
"question_score": 234,
"tags": "ansible",
"answer_id": 23947050,
"answer_date": "2014-05-30T04:29:46.183Z",
"answer_score": 339
} |
Please answer the following Stack Overflow question:
Title: How do I compare two files using Eclipse? Is there any option provided by Eclipse?
<p>How do I compare two files using Eclipse?</p>
<p>(Currently I am using <a href="http://en.wikipedia.org/wiki/WinMerge" rel="noreferrer">WinMerge</a>.)</p> | <p>To compare two files in Eclipse, first select them in the <em>Project Explorer / Package Explorer / Navigator</em> with control-click. Now right-click on one of the files, and the following context menu will appear. Select <strong>Compare With / Each Other</strong>. </p>
<p><img src="https://i.stack.imgur.com/Y2xwz.png" alt="enter image description here"></p> | {
"question_id": 4623564,
"question_date": "2011-01-07T07:54:29.040Z",
"question_score": 234,
"tags": "eclipse",
"answer_id": 4623645,
"answer_date": "2011-01-07T08:08:30.963Z",
"answer_score": 375
} |
Please answer the following Stack Overflow question:
Title: Moving Git repository content to another repository preserving history
<p>I am trying to move only the contents of one repository (<code>repo1</code>) to another existing repository (<code>repo2</code>) using the following commands:</p>
<pre><code>git clone repo1
git clone repo2
cd repo1
git remote rm origin
git remote add repo1
git push
</code></pre>
<p>But it's not working. I reviewed a similar post, but I only found one moving the folder, not the contents.</p> | <p>I think the commands you are looking for are:</p>
<pre><code>cd repo2
git checkout master
git remote add r1remote **url-of-repo1**
git fetch r1remote
git merge r1remote/master --allow-unrelated-histories
git remote rm r1remote
</code></pre>
<p>After that <code>repo2/master</code> will contain everything from <code>repo2/master</code> and <code>repo1/master</code>, and will also have the history of both of them.</p> | {
"question_id": 17371150,
"question_date": "2013-06-28T18:15:01.673Z",
"question_score": 234,
"tags": "git|merge|repository|migrate",
"answer_id": 17373088,
"answer_date": "2013-06-28T20:25:22.093Z",
"answer_score": 384
} |
Please answer the following Stack Overflow question:
Title: Set color of TextView span in Android
<p>Is it possible to set the color of just span of text in a TextView?</p>
<p>I would like to do something similar to the Twitter app, in which a part of the text is blue. See image below:</p>
<p><a href="https://i.stack.imgur.com/rq1ZY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rq1ZY.png" alt="alt text"></a><br>
<sub>(source: <a href="https://g.twimg.com/blog/s1600/ss-localsearch.png" rel="noreferrer">twimg.com</a>)</sub> </p> | <p>Another answer would be very similar, but wouldn't need to set the text of the <code>TextView</code> twice</p>
<pre><code>TextView TV = (TextView)findViewById(R.id.mytextview01);
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TV.setText(wordtoSpan);
</code></pre> | {
"question_id": 3282940,
"question_date": "2010-07-19T16:27:00.940Z",
"question_score": 234,
"tags": "android|text|formatting|textview",
"answer_id": 3514435,
"answer_date": "2010-08-18T16:40:34.870Z",
"answer_score": 483
} |
Please answer the following Stack Overflow question:
Title: Rails - How to use a Helper Inside a Controller
<p>While I realize you are supposed to use a helper inside a view, I need a helper in my controller as I'm building a JSON object to return.</p>
<p>It goes a little like this:</p>
<pre><code>def xxxxx
@comments = Array.new
@c_comments.each do |comment|
@comments << {
:id => comment.id,
:content => html_format(comment.content)
}
end
render :json => @comments
end
</code></pre>
<p>How can I access my <code>html_format</code> helper?</p> | <p><strong>Note:</strong> This was written and accepted back in the Rails 2 days; nowadays <a href="https://stackoverflow.com/questions/5130150/rails-how-to-use-a-helper-inside-a-controller/22583393#answer-11161692">grosser's answer</a> is the way to go.</p>
<p><strong>Option 1:</strong> Probably the simplest way is to include your helper module in your controller:</p>
<pre><code>class MyController < ApplicationController
include MyHelper
def xxxx
@comments = []
Comment.find_each do |comment|
@comments << {:id => comment.id, :html => html_format(comment.content)}
end
end
end
</code></pre>
<p><strong>Option 2:</strong> Or you can declare the helper method as a class function, and use it like so:</p>
<pre><code>MyHelper.html_format(comment.content)
</code></pre>
<p>If you want to be able to use it as both an instance function and a class function, you can declare both versions in your helper:</p>
<pre><code>module MyHelper
def self.html_format(str)
process(str)
end
def html_format(str)
MyHelper.html_format(str)
end
end
</code></pre>
<p>Hope this helps!</p> | {
"question_id": 5130150,
"question_date": "2011-02-26T22:31:58.750Z",
"question_score": 234,
"tags": "ruby-on-rails|ruby-on-rails-3|ruby-on-rails-5",
"answer_id": 5130344,
"answer_date": "2011-02-26T23:09:13.770Z",
"answer_score": 223
} |
Please answer the following Stack Overflow question:
Title: Auto-fit TextView for Android
<h2>Background</h2>
<p>Many times we need to auto-fit the font of the TextView to the boundaries given to it.</p>
<h2>The problem</h2>
<p>Sadly, even though there are many threads and posts (and suggested solutions) talking about this problem (example <a href="https://stackoverflow.com/questions/2617266/how-to-adjust-text-font-size-to-fit-textview">here</a>, <a href="https://stackoverflow.com/questions/5033012/auto-scale-textview-text-to-fit-within-bounds">here</a> and <a href="https://bitbucket.org/ankri/autoscaletextview/src" rel="noreferrer">here</a>), none of them actually work well.</p>
<p>That's why, I've decided to test each of them till I find the real deal.</p>
<p>I think that the requirements from such a textView should be:</p>
<ol>
<li><p>Should allow using any font, typeface, style, and set of characters.</p></li>
<li><p>Should handle both width and height</p></li>
<li><p>No truncation unless text cannot fit because of the limitation, we've
given to it (example: too long text, too small available size). However, we could request for horizontal/vertical scrollbar if we wish, just for those cases.</p></li>
<li><p>Should allow multi-line or single-line. In case of multi-line, allow max & min lines.</p></li>
<li><p>Should not be slow in computation. Using a loop for finding the best size? At least optimize it and don't increment your sampling by 1 each time.</p></li>
<li><p>In case of multi-line, should allow to prefer resizing or using more lines, and/or allow to choose the lines ourselves by using the "\n" character.</p></li>
</ol>
<h2>What I've tried</h2>
<p>I've tried so many samples (including those of the links, I've written about), and I've also tried to modify them to handle the cases, I've talked about, but none really work.</p>
<p>I've made a sample project that allows me to visually see if the TextView auto-fits correctly.</p>
<p>Currently, my sample project only randomize the text (the English alphabet plus digits) and the size of the textView, and let it stay with single line, but even this doesn't work well on any of the samples I've tried.</p>
<p>Here's the code (also available <a href="https://mega.co.nz/#!w9QRyBaB!J3KdnyTuNXRsYH9Hk5f4nBBXkRM1IAQnV8-53ckRooY" rel="noreferrer">here</a>):</p>
<h3>File <code>res/layout/activity_main.xml</code></h3>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">
<Button android:id="@+id/button1" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" android:text="Button" />
<FrameLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_above="@+id/button1"
android:layout_alignParentLeft="true" android:background="#ffff0000"
android:layout_alignParentRight="true" android:id="@+id/container"
android:layout_alignParentTop="true" />
</RelativeLayout>
</code></pre>
<h3>File <code>src/.../MainActivity.java</code></h3>
<pre><code>public class MainActivity extends Activity
{
private final Random _random =new Random();
private static final String ALLOWED_CHARACTERS ="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
@Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewGroup container=(ViewGroup)findViewById(R.id.container);
findViewById(R.id.button1).setOnClickListener(new OnClickListener()
{
@Override
public void onClick(final View v)
{
container.removeAllViews();
final int maxWidth=container.getWidth();
final int maxHeight=container.getHeight();
final FontFitTextView fontFitTextView=new FontFitTextView(MainActivity.this);
final int width=_random.nextInt(maxWidth)+1;
final int height=_random.nextInt(maxHeight)+1;
fontFitTextView.setLayoutParams(new LayoutParams(width,height));
fontFitTextView.setSingleLine();
fontFitTextView.setBackgroundColor(0xff00ff00);
final String text=getRandomText();
fontFitTextView.setText(text);
container.addView(fontFitTextView);
Log.d("DEBUG","width:"+width+" height:"+height+" text:"+text);
}
});
}
private String getRandomText()
{
final int textLength=_random.nextInt(20)+1;
final StringBuilder builder=new StringBuilder();
for(int i=0;i<textLength;++i)
builder.append(ALLOWED_CHARACTERS.charAt(_random.nextInt(ALLOWED_CHARACTERS.length())));
return builder.toString();
}
}
</code></pre>
<h2>The question</h2>
<p>Does anybody know of a solution for this common problem that actually work?</p>
<p>Even a solution that has much less features that what I've written about, for example one that has just a constant number of lines of text, and adjusts its font according to its size, yet never have weird glitches and having the text get too large/small compared to its available space.</p>
<hr>
<h2>GitHub project</h2>
<p>Since this is such an important TextView, I've decided to publish a library, so that everyone could easily use it, and contribute to it, <a href="https://github.com/AndroidDeveloperLB/AutoFitTextView" rel="noreferrer"><strong>here</strong></a>.</p> | <p>Thanks to MartinH's simple fix <a href="https://stackoverflow.com/a/19578517/1112882">here</a>, this code also takes care of <code>android:drawableLeft</code>, <code>android:drawableRight</code>, <code>android:drawableTop</code> and <code>android:drawableBottom</code> tags.</p>
<hr>
<p>My answer here should make you happy <a href="https://stackoverflow.com/questions/5033012/auto-scale-textview-text-to-fit-within-bounds/17782522#17782522">Auto Scale TextView Text to Fit within Bounds</a></p>
<p>I have modified your test case:</p>
<pre><code>@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewGroup container = (ViewGroup) findViewById(R.id.container);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
container.removeAllViews();
final int maxWidth = container.getWidth();
final int maxHeight = container.getHeight();
final AutoResizeTextView fontFitTextView = new AutoResizeTextView(MainActivity.this);
final int width = _random.nextInt(maxWidth) + 1;
final int height = _random.nextInt(maxHeight) + 1;
fontFitTextView.setLayoutParams(new FrameLayout.LayoutParams(
width, height));
int maxLines = _random.nextInt(4) + 1;
fontFitTextView.setMaxLines(maxLines);
fontFitTextView.setTextSize(500);// max size
fontFitTextView.enableSizeCache(false);
fontFitTextView.setBackgroundColor(0xff00ff00);
final String text = getRandomText();
fontFitTextView.setText(text);
container.addView(fontFitTextView);
Log.d("DEBUG", "width:" + width + " height:" + height
+ " text:" + text + " maxLines:" + maxLines);
}
});
}
</code></pre>
<p>I am posting code here at per <em>android developer's</em> request:</p>
<p><strong>Final effect:</strong></p>
<p><img src="https://i.stack.imgur.com/x9z0I.png" alt="Enter image description here"></p>
<p><strong>Sample Layout file:</strong></p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp" >
<com.vj.widgets.AutoResizeTextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:ellipsize="none"
android:maxLines="2"
android:text="Auto Resized Text, max 2 lines"
android:textSize="100sp" /> <!-- maximum size -->
<com.vj.widgets.AutoResizeTextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:ellipsize="none"
android:gravity="center"
android:maxLines="1"
android:text="Auto Resized Text, max 1 line"
android:textSize="100sp" /> <!-- maximum size -->
<com.vj.widgets.AutoResizeTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Auto Resized Text"
android:textSize="500sp" /> <!-- maximum size -->
</LinearLayout>
</code></pre>
<p><strong>And the Java code:</strong></p>
<pre><code>import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.RectF;
import android.os.Build;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.SparseIntArray;
import android.util.TypedValue;
import android.widget.TextView;
public class AutoResizeTextView extends TextView {
private interface SizeTester {
/**
*
* @param suggestedSize
* Size of text to be tested
* @param availableSpace
* available space in which text must fit
* @return an integer < 0 if after applying {@code suggestedSize} to
* text, it takes less space than {@code availableSpace}, > 0
* otherwise
*/
public int onTestSize(int suggestedSize, RectF availableSpace);
}
private RectF mTextRect = new RectF();
private RectF mAvailableSpaceRect;
private SparseIntArray mTextCachedSizes;
private TextPaint mPaint;
private float mMaxTextSize;
private float mSpacingMult = 1.0f;
private float mSpacingAdd = 0.0f;
private float mMinTextSize = 20;
private int mWidthLimit;
private static final int NO_LINE_LIMIT = -1;
private int mMaxLines;
private boolean mEnableSizeCache = true;
private boolean mInitializedDimens;
public AutoResizeTextView(Context context) {
super(context);
initialize();
}
public AutoResizeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public AutoResizeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize();
}
private void initialize() {
mPaint = new TextPaint(getPaint());
mMaxTextSize = getTextSize();
mAvailableSpaceRect = new RectF();
mTextCachedSizes = new SparseIntArray();
if (mMaxLines == 0) {
// no value was assigned during construction
mMaxLines = NO_LINE_LIMIT;
}
}
@Override
public void setTextSize(float size) {
mMaxTextSize = size;
mTextCachedSizes.clear();
adjustTextSize();
}
@Override
public void setMaxLines(int maxlines) {
super.setMaxLines(maxlines);
mMaxLines = maxlines;
adjustTextSize();
}
public int getMaxLines() {
return mMaxLines;
}
@Override
public void setSingleLine() {
super.setSingleLine();
mMaxLines = 1;
adjustTextSize();
}
@Override
public void setSingleLine(boolean singleLine) {
super.setSingleLine(singleLine);
if (singleLine) {
mMaxLines = 1;
} else {
mMaxLines = NO_LINE_LIMIT;
}
adjustTextSize();
}
@Override
public void setLines(int lines) {
super.setLines(lines);
mMaxLines = lines;
adjustTextSize();
}
@Override
public void setTextSize(int unit, float size) {
Context c = getContext();
Resources r;
if (c == null)
r = Resources.getSystem();
else
r = c.getResources();
mMaxTextSize = TypedValue.applyDimension(unit, size,
r.getDisplayMetrics());
mTextCachedSizes.clear();
adjustTextSize();
}
@Override
public void setLineSpacing(float add, float mult) {
super.setLineSpacing(add, mult);
mSpacingMult = mult;
mSpacingAdd = add;
}
/**
* Set the lower text size limit and invalidate the view
*
* @param minTextSize
*/
public void setMinTextSize(float minTextSize) {
mMinTextSize = minTextSize;
adjustTextSize();
}
private void adjustTextSize() {
if (!mInitializedDimens) {
return;
}
int startSize = (int) mMinTextSize;
int heightLimit = getMeasuredHeight() - getCompoundPaddingBottom()
- getCompoundPaddingTop();
mWidthLimit = getMeasuredWidth() - getCompoundPaddingLeft()
- getCompoundPaddingRight();
mAvailableSpaceRect.right = mWidthLimit;
mAvailableSpaceRect.bottom = heightLimit;
super.setTextSize(
TypedValue.COMPLEX_UNIT_PX,
efficientTextSizeSearch(startSize, (int) mMaxTextSize,
mSizeTester, mAvailableSpaceRect));
}
private final SizeTester mSizeTester = new SizeTester() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public int onTestSize(int suggestedSize, RectF availableSPace) {
mPaint.setTextSize(suggestedSize);
String text = getText().toString();
boolean singleline = getMaxLines() == 1;
if (singleline) {
mTextRect.bottom = mPaint.getFontSpacing();
mTextRect.right = mPaint.measureText(text);
} else {
StaticLayout layout = new StaticLayout(text, mPaint,
mWidthLimit, Alignment.ALIGN_NORMAL, mSpacingMult,
mSpacingAdd, true);
// Return early if we have more lines
if (getMaxLines() != NO_LINE_LIMIT
&& layout.getLineCount() > getMaxLines()) {
return 1;
}
mTextRect.bottom = layout.getHeight();
int maxWidth = -1;
for (int i = 0; i < layout.getLineCount(); i++) {
if (maxWidth < layout.getLineWidth(i)) {
maxWidth = (int) layout.getLineWidth(i);
}
}
mTextRect.right = maxWidth;
}
mTextRect.offsetTo(0, 0);
if (availableSPace.contains(mTextRect)) {
// May be too small, don't worry we will find the best match
return -1;
} else {
// too big
return 1;
}
}
};
/**
* Enables or disables size caching, enabling it will improve performance
* where you are animating a value inside TextView. This stores the font
* size against getText().length() Be careful though while enabling it as 0
* takes more space than 1 on some fonts and so on.
*
* @param enable
* Enable font size caching
*/
public void enableSizeCache(boolean enable) {
mEnableSizeCache = enable;
mTextCachedSizes.clear();
adjustTextSize(getText().toString());
}
private int efficientTextSizeSearch(int start, int end,
SizeTester sizeTester, RectF availableSpace) {
if (!mEnableSizeCache) {
return binarySearch(start, end, sizeTester, availableSpace);
}
int key = getText().toString().length();
int size = mTextCachedSizes.get(key);
if (size != 0) {
return size;
}
size = binarySearch(start, end, sizeTester, availableSpace);
mTextCachedSizes.put(key, size);
return size;
}
private static int binarySearch(int start, int end, SizeTester sizeTester,
RectF availableSpace) {
int lastBest = start;
int lo = start;
int hi = end - 1;
int mid = 0;
while (lo <= hi) {
mid = (lo + hi) >>> 1;
int midValCmp = sizeTester.onTestSize(mid, availableSpace);
if (midValCmp < 0) {
lastBest = lo;
lo = mid + 1;
} else if (midValCmp > 0) {
hi = mid - 1;
lastBest = hi;
} else {
return mid;
}
}
// Make sure to return the last best.
// This is what should always be returned.
return lastBest;
}
@Override
protected void onTextChanged(final CharSequence text, final int start,
final int before, final int after) {
super.onTextChanged(text, start, before, after);
adjustTextSize();
}
@Override
protected void onSizeChanged(int width, int height, int oldwidth,
int oldheight) {
mInitializedDimens = true;
mTextCachedSizes.clear();
super.onSizeChanged(width, height, oldwidth, oldheight);
if (width != oldwidth || height != oldheight) {
adjustTextSize();
}
}
}
</code></pre>
<p><strong>Warning:</strong></p>
<p>Beware of this <a href="http://code.google.com/p/android/issues/detail?id=17343#c9" rel="noreferrer">resolved</a> <a href="http://code.google.com/p/android/issues/detail?id=17343" rel="noreferrer">bug</a> in Android 3.1 (Honeycomb) though.</p> | {
"question_id": 16017165,
"question_date": "2013-04-15T14:00:46.583Z",
"question_score": 234,
"tags": "android|textview|font-size|layoutparams",
"answer_id": 17786051,
"answer_date": "2013-07-22T11:09:10.550Z",
"answer_score": 148
} |
Please answer the following Stack Overflow question:
Title: jquery stop child triggering parent event
<p>I have a div which I have attached an <code>onclick</code> event to. in this div there is a tag with a link. When I click the link the <code>onclick</code> event from the div is also triggered. How can i disable this so that if the link is clicked on the div <code>onclick</code> is not fired?</p>
<p>script:</p>
<pre><code>$(document).ready(function(){
$(".header").bind("click", function(){
$(this).children(".children").toggle();
});
})
</code></pre>
<p>html code:</p>
<pre><code><div class="header">
<a href="link.html">some link</a>
<ul class="children">
<li>some list</li>
</ul>
</div>
</code></pre> | <p>Do this:</p>
<pre><code>$(document).ready(function(){
$(".header").click(function(){
$(this).children(".children").toggle();
});
$(".header a").click(function(e) {
e.stopPropagation();
});
});
</code></pre>
<p>If you want to <a href="http://api.jquery.com/event.stopPropagation/" rel="noreferrer">read more on .stopPropagation(), look here</a>.</p> | {
"question_id": 2364629,
"question_date": "2010-03-02T16:12:12.553Z",
"question_score": 234,
"tags": "jquery",
"answer_id": 2364639,
"answer_date": "2010-03-02T16:13:10.583Z",
"answer_score": 444
} |
Please answer the following Stack Overflow question:
Title: How to determine the longest increasing subsequence using dynamic programming?
<p>I have a set of integers. I want to find the <a href="https://en.wikipedia.org/wiki/Longest_increasing_subsequence" rel="noreferrer">longest increasing subsequence</a> of that set using dynamic programming.</p> | <p>OK, I will describe first the simplest solution which is O(N^2), where N is the size of the collection. There also exists a O(N log N) solution, which I will describe also. Look <a href="http://en.wikipedia.org/wiki/Longest_increasing_subsequence" rel="noreferrer">here</a> for it at the section Efficient algorithms.</p>
<p>I will assume the indices of the array are from 0 to N - 1. So let's define <code>DP[i]</code> to be the length of the LIS (Longest increasing subsequence) which is ending at element with index <code>i</code>. To compute <code>DP[i]</code> we look at all indices <code>j < i</code> and check both if <code>DP[j] + 1 > DP[i]</code> and <code>array[j] < array[i]</code> (we want it to be increasing). If this is true we can update the current optimum for <code>DP[i]</code>. To find the global optimum for the array you can take the maximum value from <code>DP[0...N - 1]</code>.</p>
<pre><code>int maxLength = 1, bestEnd = 0;
DP[0] = 1;
prev[0] = -1;
for (int i = 1; i < N; i++)
{
DP[i] = 1;
prev[i] = -1;
for (int j = i - 1; j >= 0; j--)
if (DP[j] + 1 > DP[i] && array[j] < array[i])
{
DP[i] = DP[j] + 1;
prev[i] = j;
}
if (DP[i] > maxLength)
{
bestEnd = i;
maxLength = DP[i];
}
}
</code></pre>
<p>I use the array <code>prev</code> to be able later to find the actual sequence not only its length. Just go back recursively from <code>bestEnd</code> in a loop using <code>prev[bestEnd]</code>. The <code>-1</code> value is a sign to stop.</p>
<hr />
<h2>OK, now to the more efficient <code>O(N log N)</code> solution:</h2>
<p>Let <code>S[pos]</code> be defined as the smallest integer that ends an increasing sequence of length <code>pos</code>. Now iterate through every integer <code>X</code> of the input set and do the following:</p>
<ol>
<li><p>If <code>X</code> > last element in <code>S</code>, then append <code>X</code> to the end of <code>S</code>. This essentially means we have found a new largest <code>LIS</code>.</p>
</li>
<li><p>Otherwise find the smallest element in <code>S</code>, which is <code>>=</code> than <code>X</code>, and change it to <code>X</code>.
Because <code>S</code> is sorted at any time, the element can be found using binary search in <code>log(N)</code>.</p>
</li>
</ol>
<p>Total runtime - <code>N</code> integers and a binary search for each of them - N * log(N) = O(N log N)</p>
<p>Now let's do a real example:</p>
<p>Collection of integers:
<code>2 6 3 4 1 2 9 5 8</code></p>
<p>Steps:</p>
<pre><code>0. S = {} - Initialize S to the empty set
1. S = {2} - New largest LIS
2. S = {2, 6} - New largest LIS
3. S = {2, 3} - Changed 6 to 3
4. S = {2, 3, 4} - New largest LIS
5. S = {1, 3, 4} - Changed 2 to 1
6. S = {1, 2, 4} - Changed 3 to 2
7. S = {1, 2, 4, 9} - New largest LIS
8. S = {1, 2, 4, 5} - Changed 9 to 5
9. S = {1, 2, 4, 5, 8} - New largest LIS
</code></pre>
<p>So the length of the LIS is <code>5</code> (the size of S).</p>
<p>To reconstruct the actual <code>LIS</code> we will again use a parent array.
Let <code>parent[i]</code> be the predecessor of an element with index <code>i</code> in the <code>LIS</code> ending at the element with index <code>i</code>.</p>
<p>To make things simpler, we can keep in the array <code>S</code>, not the actual integers, but their indices(positions) in the set. We do not keep <code>{1, 2, 4, 5, 8}</code>, but keep <code>{4, 5, 3, 7, 8}</code>.</p>
<p>That is input[4] = <strong>1</strong>, input[5] = <strong>2</strong>, input[3] = <strong>4</strong>, input[7] = <strong>5</strong>, input[8] = <strong>8</strong>.</p>
<p>If we update properly the parent array, the actual LIS is:</p>
<pre><code>input[S[lastElementOfS]],
input[parent[S[lastElementOfS]]],
input[parent[parent[S[lastElementOfS]]]],
........................................
</code></pre>
<p>Now to the important thing - how do we update the parent array? There are two options:</p>
<ol>
<li><p>If <code>X</code> > last element in <code>S</code>, then <code>parent[indexX] = indexLastElement</code>. This means the parent of the newest element is the last element. We just prepend <code>X</code> to the end of <code>S</code>.</p>
</li>
<li><p>Otherwise find the index of the smallest element in <code>S</code>, which is <code>>=</code> than <code>X</code>, and change it to <code>X</code>. Here <code>parent[indexX] = S[index - 1]</code>.</p>
</li>
</ol> | {
"question_id": 2631726,
"question_date": "2010-04-13T17:26:50.700Z",
"question_score": 234,
"tags": "algorithm|computer-science|dynamic-programming|memoization|lis",
"answer_id": 2631810,
"answer_date": "2010-04-13T17:39:57.907Z",
"answer_score": 438
} |
Please answer the following Stack Overflow question:
Title: What's the Kotlin equivalent of Java's String[]?
<p>I see that Kotlin has <code>ByteArray, ShortArray, IntArray, CharArray, DoubleArray, FloatArray</code>, which are equivalent to <code>byte[], short[], int[],char[], double[], float[]</code> in Java.</p>
<p>Now I'm wondering, is there any <code>StringArray</code> equivalent to Java's <code>String[]</code>?</p> | <p>There's no special case for <code>String</code>, because <code>String</code> is an ordinary referential type on JVM, in contrast with <a href="https://stackoverflow.com/questions/8790809/whats-the-difference-between-primitive-and-reference-types">Java primitives (<code>int</code>, <code>double</code>, ...)</a> -- storing them in a reference <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/" rel="noreferrer"><code>Array<T></code></a> requires <a href="https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html" rel="noreferrer">boxing them into objects like <code>Integer</code> and <code>Double</code></a>. The purpose of specialized arrays like <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int-array/" rel="noreferrer"><code>IntArray</code></a> in Kotlin is to store non-boxed primitives, getting rid of boxing and unboxing overhead (the same as Java <code>int[]</code> instead of <code>Integer[]</code>).</p>
<p>You can use <code>Array<String></code> (and <code>Array<String?></code> for nullables), which is equivalent to <code>String[]</code> in Java:</p>
<pre><code>val stringsOrNulls = arrayOfNulls<String>(10) // returns Array<String?>
val someStrings = Array<String>(5) { "it = $it" }
val otherStrings = arrayOf("a", "b", "c")
</code></pre>
<p>See also: <a href="https://kotlinlang.org/docs/reference/basic-types.html#arrays" rel="noreferrer"><em>Arrays</em> in the language reference</a></p> | {
"question_id": 44239869,
"question_date": "2017-05-29T10:10:12.017Z",
"question_score": 234,
"tags": "java|kotlin",
"answer_id": 44239940,
"answer_date": "2017-05-29T10:13:02.730Z",
"answer_score": 311
} |
Please answer the following Stack Overflow question:
Title: List of unique dictionaries
<p>Let's say I have a list of dictionaries:</p>
<pre><code>[
{'id': 1, 'name': 'john', 'age': 34},
{'id': 1, 'name': 'john', 'age': 34},
{'id': 2, 'name': 'hanna', 'age': 30},
]
</code></pre>
<p>How can I obtain a list of unique dictionaries (removing the duplicates)?</p>
<pre><code>[
{'id': 1, 'name': 'john', 'age': 34},
{'id': 2, 'name': 'hanna', 'age': 30},
]
</code></pre> | <p>So make a temporary dict with the key being the <code>id</code>. This filters out the duplicates.
The <code>values()</code> of the dict will be the list</p>
<p>In Python2.7</p>
<pre><code>>>> L=[
... {'id':1,'name':'john', 'age':34},
... {'id':1,'name':'john', 'age':34},
... {'id':2,'name':'hanna', 'age':30},
... ]
>>> {v['id']:v for v in L}.values()
[{'age': 34, 'id': 1, 'name': 'john'}, {'age': 30, 'id': 2, 'name': 'hanna'}]
</code></pre>
<p>In Python3</p>
<pre><code>>>> L=[
... {'id':1,'name':'john', 'age':34},
... {'id':1,'name':'john', 'age':34},
... {'id':2,'name':'hanna', 'age':30},
... ]
>>> list({v['id']:v for v in L}.values())
[{'age': 34, 'id': 1, 'name': 'john'}, {'age': 30, 'id': 2, 'name': 'hanna'}]
</code></pre>
<p>In Python2.5/2.6</p>
<pre><code>>>> L=[
... {'id':1,'name':'john', 'age':34},
... {'id':1,'name':'john', 'age':34},
... {'id':2,'name':'hanna', 'age':30},
... ]
>>> dict((v['id'],v) for v in L).values()
[{'age': 34, 'id': 1, 'name': 'john'}, {'age': 30, 'id': 2, 'name': 'hanna'}]
</code></pre> | {
"question_id": 11092511,
"question_date": "2012-06-18T23:30:38.333Z",
"question_score": 234,
"tags": "python|dictionary",
"answer_id": 11092590,
"answer_date": "2012-06-18T23:42:23.153Z",
"answer_score": 330
} |
Please answer the following Stack Overflow question:
Title: What is The difference between ListBox and ListView
<p>What is the difference between WPF's ListBox and ListView? I can not find any significant difference in their properties. Is there different typical use?</p> | <p>A <code>ListView</code> is basically like a <code>ListBox</code> (and inherits from it), but it also has a <code>View</code> property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (<a href="https://en.wikipedia.org/wiki/Standard_Libraries_(CLI)#Base_Class_Library" rel="noreferrer">Base Class Library</a>) is <code>GridView</code>, but you can easily <a href="http://msdn.microsoft.com/en-us/library/ms748859.aspx" rel="noreferrer">create your own</a>.</p>
<p>Another difference is the default selection mode: it's <code>Single</code> for a <code>ListBox</code>, but <code>Extended</code> for a <code>ListView</code></p> | {
"question_id": 4703641,
"question_date": "2011-01-16T03:30:07.927Z",
"question_score": 234,
"tags": ".net|wpf|wpf-controls|wpf-listview",
"answer_id": 4703658,
"answer_date": "2011-01-16T03:37:33.390Z",
"answer_score": 249
} |
Please answer the following Stack Overflow question:
Title: How to calculate the SVG Path for an arc (of a circle)
<p>Given a circle centered at (200,200), radius 25, how do I draw an arc from 270 degree to 135 degree and one that goes from 270 to 45 degree?</p>
<p>0 degree means it is right on the x-axis (the right side) (meaning it is 3 o' clock position)
270 degree means it is 12 o'clock position, and 90 means it is 6 o'clock position</p>
<p>More generally, what is a path for an arc for part of a circle with</p>
<pre><code>x, y, r, d1, d2, direction
</code></pre>
<p>meaning</p>
<pre><code>center (x,y), radius r, degree_start, degree_end, direction
</code></pre> | <p>Expanding on @wdebeaum's great answer, here's a method for generating an arced path: </p>
<pre><code>function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;
return {
x: centerX + (radius * Math.cos(angleInRadians)),
y: centerY + (radius * Math.sin(angleInRadians))
};
}
function describeArc(x, y, radius, startAngle, endAngle){
var start = polarToCartesian(x, y, radius, endAngle);
var end = polarToCartesian(x, y, radius, startAngle);
var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";
var d = [
"M", start.x, start.y,
"A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
].join(" ");
return d;
}
</code></pre>
<p>to use</p>
<pre><code>document.getElementById("arc1").setAttribute("d", describeArc(200, 400, 100, 0, 180));
</code></pre>
<p>and in your html</p>
<pre><code><path id="arc1" fill="none" stroke="#446688" stroke-width="20" />
</code></pre>
<p><a href="http://jsbin.com/quhujowota/1/edit?html,js,output">Live demo</a></p> | {
"question_id": 5736398,
"question_date": "2011-04-20T20:44:31.260Z",
"question_score": 234,
"tags": "svg",
"answer_id": 18473154,
"answer_date": "2013-08-27T18:44:09.047Z",
"answer_score": 469
} |
Please answer the following Stack Overflow question:
Title: What is the "Upgrade-Insecure-Requests" HTTP header?
<p>I made a POST request to a HTTP (non-HTTPS) site, inspected the request in Chrome's Developer Tools, and found that it added its own header before sending it to the server:</p>
<pre><code>Upgrade-Insecure-Requests: 1
</code></pre>
<p>After doing a search on <code>Upgrade-Insecure-Requests</code>, I can only find <a href="http://www.w3.org/TR/upgrade-insecure-requests/" rel="noreferrer">information</a> about the server sending <a href="https://googlechrome.github.io/samples/csp-upgrade-insecure-requests/" rel="noreferrer">this</a> header:</p>
<pre><code>Content-Security-Policy: upgrade-insecure-requests
</code></pre>
<p>This seems related, but still very different since in my case, the CLIENT is sending the header in the <em>Request</em>, whereas all the information I've found is concerning the SERVER sending the related header in a <em>Response</em>.</p>
<hr>
<p>So why is Chrome (44.0.2403.130 m) adding <code>Upgrade-Insecure-Requests</code> to my request and what does it do?</p>
<hr>
<h1>Update 2016-08-24:</h1>
<p>This header has since been added as a <a href="https://www.w3.org/TR/2015/CR-upgrade-insecure-requests-20151008/#preference" rel="noreferrer">W3C Candidate Recommendation</a> and is now officially recognized.</p>
<p>For those who just came across this question and are confused, the <a href="https://stackoverflow.com/a/32003517/2891365">excellent answer</a> by Simon East explains it well.</p>
<p>The <code>Upgrade-Insecure-Requests: 1</code> header used to be <code>HTTPS: 1</code> <a href="https://www.w3.org/TR/2015/WD-upgrade-insecure-requests-20150424/#preference" rel="noreferrer">in the previous W3C Working Draft</a> and was renamed <strong><em>quietly</em></strong> by Chrome before the change became officially accepted.</p>
<p>(This question was asked during this transition when there were no official documentation on this header and Chrome was the only browser that sent this header.)</p> | <p><strong>Short answer: it's closely related to the <code>Content-Security-Policy: upgrade-insecure-requests</code> response header, indicating that the browser supports it (and in fact prefers it).</strong></p>
<p>It took me 30mins of Googling, but I finally found it buried in the W3 spec.</p>
<p>The confusion comes because the header in the spec was <code>HTTPS: 1</code>, and this is how Chromium implemented it, but after this <a href="https://superuser.com/questions/943842/chrome-adds-weird-https1-header-to-all-requests">broke lots of websites that were poorly coded</a> (particularly WordPress and WooCommerce) the Chromium team apologized:</p>
<blockquote>
<p>"I apologize for the breakage; I apparently underestimated the impact based on the feedback during dev and beta."<br />
— Mike West, in <a href="https://code.google.com/p/chromium/issues/detail?id=501842#c43" rel="noreferrer">Chrome Issue 501842</a></p>
</blockquote>
<p>Their fix was to rename it to <code>Upgrade-Insecure-Requests: 1</code>, and the spec has since been updated to match.</p>
<p>Anyway, here is the explanation from <a href="http://www.w3.org/TR/upgrade-insecure-requests/#preference" rel="noreferrer"><strong>the W3 spec</strong> (as it appeared at the time)</a>...</p>
<blockquote>
<p>The <code>HTTPS</code> HTTP request header field sends a signal to the server <strong>expressing the client’s preference</strong> for an encrypted and authenticated response, and that <strong>it can successfully handle the upgrade-insecure-requests directive</strong> in order to make that preference as seamless as possible to provide.</p>
<p>...</p>
<p>When a server encounters this preference in an HTTP request’s headers, it SHOULD redirect the user to a potentially secure representation of the resource being requested.</p>
<p>When a server encounters this preference in an HTTPS request’s headers, it SHOULD include a <code>Strict-Transport-Security</code> header in the response if the request’s host is HSTS-safe or conditionally HSTS-safe [RFC6797].</p>
</blockquote> | {
"question_id": 31950470,
"question_date": "2015-08-11T19:36:40.570Z",
"question_score": 234,
"tags": "google-chrome|http|http-headers|upgrade-insecure-requests",
"answer_id": 32003517,
"answer_date": "2015-08-14T06:22:18.830Z",
"answer_score": 279
} |
Please answer the following Stack Overflow question:
Title: LINQ - Full Outer Join
<p>I have a list of people's ID and their first name, and a list of people's ID and their surname. Some people don't have a first name and some don't have a surname; I'd like to do a full outer join on the two lists.</p>
<p>So the following lists:</p>
<pre><code>ID FirstName
-- ---------
1 John
2 Sue
ID LastName
-- --------
1 Doe
3 Smith
</code></pre>
<p>Should produce:</p>
<pre><code>ID FirstName LastName
-- --------- --------
1 John Doe
2 Sue
3 Smith
</code></pre>
<p>I'm new to LINQ (so forgive me if I'm being lame) and have found quite a few solutions for 'LINQ Outer Joins' which all look quite similar, but really seem to be left outer joins.</p>
<p>My attempts so far go something like this:</p>
<pre><code>private void OuterJoinTest()
{
List<FirstName> firstNames = new List<FirstName>();
firstNames.Add(new FirstName { ID = 1, Name = "John" });
firstNames.Add(new FirstName { ID = 2, Name = "Sue" });
List<LastName> lastNames = new List<LastName>();
lastNames.Add(new LastName { ID = 1, Name = "Doe" });
lastNames.Add(new LastName { ID = 3, Name = "Smith" });
var outerJoin = from first in firstNames
join last in lastNames
on first.ID equals last.ID
into temp
from last in temp.DefaultIfEmpty()
select new
{
id = first != null ? first.ID : last.ID,
firstname = first != null ? first.Name : string.Empty,
surname = last != null ? last.Name : string.Empty
};
}
}
public class FirstName
{
public int ID;
public string Name;
}
public class LastName
{
public int ID;
public string Name;
}
</code></pre>
<p>But this returns:</p>
<pre><code>ID FirstName LastName
-- --------- --------
1 John Doe
2 Sue
</code></pre>
<p>What am I doing wrong?</p> | <p>I don't know if this covers all cases, logically it seems correct. The idea is to take a left outer join and right outer join then take the union of the results.</p>
<pre><code>var firstNames = new[]
{
new { ID = 1, Name = "John" },
new { ID = 2, Name = "Sue" },
};
var lastNames = new[]
{
new { ID = 1, Name = "Doe" },
new { ID = 3, Name = "Smith" },
};
var leftOuterJoin =
from first in firstNames
join last in lastNames on first.ID equals last.ID into temp
from last in temp.DefaultIfEmpty()
select new
{
first.ID,
FirstName = first.Name,
LastName = last?.Name,
};
var rightOuterJoin =
from last in lastNames
join first in firstNames on last.ID equals first.ID into temp
from first in temp.DefaultIfEmpty()
select new
{
last.ID,
FirstName = first?.Name,
LastName = last.Name,
};
var fullOuterJoin = leftOuterJoin.Union(rightOuterJoin);
</code></pre>
<p>This works as written since it is in LINQ to Objects. If LINQ to SQL or other, the query processor might not support safe navigation or other operations. You'd have to use the conditional operator to conditionally get the values.</p>
<p>i.e.,</p>
<pre><code>var leftOuterJoin =
from first in firstNames
join last in lastNames on first.ID equals last.ID into temp
from last in temp.DefaultIfEmpty()
select new
{
first.ID,
FirstName = first.Name,
LastName = last != null ? last.Name : default,
};
</code></pre> | {
"question_id": 5489987,
"question_date": "2011-03-30T17:41:57.120Z",
"question_score": 234,
"tags": "c#|.net|linq|outer-join|full-outer-join",
"answer_id": 5491381,
"answer_date": "2011-03-30T19:38:01.617Z",
"answer_score": 137
} |
Please answer the following Stack Overflow question:
Title: Ruby on Rails: Where to define global constants?
<p>I'm just getting started with my first Ruby on Rails webapp. I've got a bunch of different models, views, controllers, and so on. </p>
<p>I'm wanting to find a good place to stick definitions of truly global constants, that apply across my whole app. In particular, they apply both in the logic of my models, and in the decisions taken in my views. I cannot find any DRY place to put these definitions where they're available both to <em>all</em> my models and also in all my views.</p>
<p>To take a specific example, I want a constant <code>COLOURS = ['white', 'blue', 'black', 'red', 'green']</code>. This is used all over the place, in both models and views. Where can I define it in just one place so that it's accessible?</p>
<p>What I've tried:</p>
<ul>
<li>Constant class variables in the model.rb file that they're most associated with, such as <code>@@COLOURS = [...]</code>. But I couldn't find a sane way to define it so that I can write in my views <code>Card.COLOURS</code> rather than something kludgy like <code>Card.first.COLOURS</code>.</li>
<li>A method on the model, something like <code>def colours ['white',...] end</code> - same problem.</li>
<li>A method in application_helper.rb - this is what I'm doing so far, but the helpers are only accessible in views, not in models</li>
<li>I think I might have tried something in application.rb or environment.rb, but those don't really seem right (and they don't seem to work either)</li>
</ul>
<p>Is there just no way to define anything to be accessible both from models and from views? I mean, I know models and views should be separate, but surely in some domains there'll be times they need to refer to the same domain-specific knowledge?</p> | <p>If your model is really "responsible" for the constants you should stick them there. You can create class methods to access them without creating a new object instance:</p>
<pre><code>class Card < ActiveRecord::Base
def self.colours
['white', 'blue']
end
end
# accessible like this
Card.colours
</code></pre>
<p>Alternatively, you can create class variables and an accessor. This is however discouraged as class variables might act kind of surprising with inheritance and in multi-thread environments.</p>
<pre><code>class Card < ActiveRecord::Base
@@colours = ['white', 'blue'].freeze
cattr_reader :colours
end
# accessible the same as above
Card.colours
</code></pre>
<p>The two options above allow you to change the returned array on each invocation of the accessor method if required. If you have true a truly unchangeable constant, you can also define it on the model class:</p>
<pre><code>class Card < ActiveRecord::Base
COLOURS = ['white', 'blue'].freeze
end
# accessible as
Card::COLOURS
</code></pre>
<p>You could also create global constants which are accessible from everywhere in an initializer like in the following example. This is probably the best place, if your colours are really global and used in more than one model context.</p>
<pre><code># put this into config/initializers/my_constants.rb
COLOURS = ['white', 'blue'].freeze
# accessible as a top-level constant this time
COLOURS
</code></pre>
<p><em>Note: when we define constants above, often we want to <code>freeze</code> the array. That prevents other code from later (inadvertently) modifying the array by e.g. adding a new element. Once an object is frozen, it can't be changed anymore.</em></p> | {
"question_id": 4110866,
"question_date": "2010-11-05T23:06:37.190Z",
"question_score": 234,
"tags": "ruby-on-rails|constants|global",
"answer_id": 4110947,
"answer_date": "2010-11-05T23:27:07.880Z",
"answer_score": 257
} |
Please answer the following Stack Overflow question:
Title: Can the Unix list command 'ls' output numerical chmod permissions?
<p>Is it possible when listing a directory to view numerical unix permissions such as 644 rather than the symbolic output -rw-rw-r--</p>
<p>Thanks.</p> | <p>it almost can ..</p>
<pre><code> ls -l | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/) \
*2^(8-i));if(k)printf("%0o ",k);print}'
</code></pre> | {
"question_id": 1795976,
"question_date": "2009-11-25T10:21:35.197Z",
"question_score": 234,
"tags": "unix|command-line|permissions",
"answer_id": 1796009,
"answer_date": "2009-11-25T10:26:15.593Z",
"answer_score": 397
} |
Please answer the following Stack Overflow question:
Title: How can I check if a jQuery plugin is loaded?
<p>Is there any way to check if a particular plugin is available?</p>
<p>Imagine that you are developing a plugin that depends on another plugin being loaded.</p>
<p>For example I want the jQuery Validation plugin to use the dateJS library to check if a given date is valid. What would be the best way to detect, in the jQuery Valdation plugin if the dateJS was available?</p> | <p>Generally speaking, jQuery plugins are namespaces on the jQuery scope. You could run a simple check to see if the namespace exists:</p>
<pre><code> if(jQuery().pluginName) {
//run plugin dependent code
}
</code></pre>
<p>dateJs however is not a jQuery plugin. It modifies/extends the javascript date object, and is not added as a jQuery namespace. You could check if the method you need exists, for example:</p>
<pre><code> if(Date.today) {
//Use the dateJS today() method
}
</code></pre>
<p>But you might run into problems where the API overlaps the native Date API.</p> | {
"question_id": 400916,
"question_date": "2008-12-30T17:26:13.073Z",
"question_score": 234,
"tags": "jquery|jquery-plugins",
"answer_id": 400943,
"answer_date": "2008-12-30T17:36:10.603Z",
"answer_score": 380
} |
Please answer the following Stack Overflow question:
Title: In Python, how do I indicate I'm overriding a method?
<p>In Java, for example, the <code>@Override</code> annotation not only provides compile-time checking of an override but makes for excellent self-documenting code. </p>
<p>I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the idiomatic way to indicate an override in Python?</p> | <p><strong>Based on this and fwc:s answer I created a pip installable package <a href="https://github.com/mkorpela/overrides" rel="noreferrer">https://github.com/mkorpela/overrides</a></strong></p>
<p>From time to time I end up here looking at this question.
Mainly this happens after (again) seeing the same bug in our code base: Someone has forgotten some "interface" implementing class while renaming a method in the "interface"..</p>
<p>Well Python ain't Java but Python has power -- and explicit is better than implicit -- and there are real concrete cases in the real world where this thing would have helped me.</p>
<p>So here is a sketch of overrides decorator. This will check that the class given as a parameter has the same method (or something) name as the method being decorated.</p>
<p>If you can think of a better solution please post it here!</p>
<pre><code>def overrides(interface_class):
def overrider(method):
assert(method.__name__ in dir(interface_class))
return method
return overrider
</code></pre>
<p>It works as follows:</p>
<pre><code>class MySuperInterface(object):
def my_method(self):
print 'hello world!'
class ConcreteImplementer(MySuperInterface):
@overrides(MySuperInterface)
def my_method(self):
print 'hello kitty!'
</code></pre>
<p>and if you do a faulty version it will raise an assertion error during class loading:</p>
<pre><code>class ConcreteFaultyImplementer(MySuperInterface):
@overrides(MySuperInterface)
def your_method(self):
print 'bye bye!'
>> AssertionError!!!!!!!
</code></pre> | {
"question_id": 1167617,
"question_date": "2009-07-22T19:26:48.607Z",
"question_score": 234,
"tags": "python|inheritance|overriding|self-documenting-code",
"answer_id": 8313042,
"answer_date": "2011-11-29T15:07:19.627Z",
"answer_score": 253
} |
Please answer the following Stack Overflow question:
Title: "ERROR:root:code for hash md5 was not found" when using any hg mercurial commands
<p>When trying to use any <code>hg</code> Mercurial commands on the console, I keep getting this error.
I installed Python using Homebrew and I am running Mac OS Catalina v. 10.15.1.</p>
<p>Any reference would be appreciated. Here is the error I'm getting:</p>
<pre><code>hg commit --amend
ERROR:root:code for hash md5 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type md5
ERROR:root:code for hash sha1 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha1
ERROR:root:code for hash sha224 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha224
ERROR:root:code for hash sha256 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha256
ERROR:root:code for hash sha384 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha384
ERROR:root:code for hash sha512 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha512
Traceback (most recent call last):
File "/usr/local/bin/hg", line 43, in <module>
dispatch.run()
File "/usr/local/Cellar/mercurial/4.9/lib/python2.7/site-packages/hgdemandimport/demandimportpy2.py", line 150, in __getattr__
self._load()
File "/usr/local/Cellar/mercurial/4.9/lib/python2.7/site-packages/hgdemandimport/demandimportpy2.py", line 94, in _load
_origimport, head, globals, locals, None, level)
File "/usr/local/Cellar/mercurial/4.9/lib/python2.7/site-packages/hgdemandimport/demandimportpy2.py", line 43, in _hgextimport
return importfunc(name, globals, *args, **kwargs)
File "/usr/local/Cellar/mercurial/4.9/lib/python2.7/site-packages/mercurial/dispatch.py", line 625, in <module>
class lazyaliasentry(object):
File "/usr/local/Cellar/mercurial/4.9/lib/python2.7/site-packages/mercurial/dispatch.py", line 636, in lazyaliasentry
@util.propertycache
File "/usr/local/Cellar/mercurial/4.9/lib/python2.7/site-packages/hgdemandimport/demandimportpy2.py", line 150, in __getattr__
self._load()
File "/usr/local/Cellar/mercurial/4.9/lib/python2.7/site-packages/hgdemandimport/demandimportpy2.py", line 94, in _load
_origimport, head, globals, locals, None, level)
File "/usr/local/Cellar/mercurial/4.9/lib/python2.7/site-packages/hgdemandimport/demandimportpy2.py", line 43, in _hgextimport
return importfunc(name, globals, *args, **kwargs)
File "/usr/local/Cellar/mercurial/4.9/lib/python2.7/site-packages/mercurial/util.py", line 180, in <module>
'md5': hashlib.md5,
File "/usr/local/Cellar/mercurial/4.9/lib/python2.7/site-packages/hgdemandimport/demandimportpy2.py", line 151, in __getattr__
return getattr(self._module, attr)
AttributeError: 'module' object has no attribute 'md5'
</code></pre>
<p>I also tried following the instruction on this issue but none of the solutions seem to work </p>
<pre><code>brew link openssl --force
Warning: Refusing to link macOS-provided software: [email protected]
If you need to have [email protected] first in your PATH run:
echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' >> ~/.zshrc
For compilers to find [email protected] you may need to set:
export LDFLAGS="-L/usr/local/opt/[email protected]/lib"
export CPPFLAGS="-I/usr/local/opt/[email protected]/include"
For pkg-config to find [email protected] you may need to set:
export PKG_CONFIG_PATH="/usr/local/opt/[email protected]/lib/pkgconfig"
</code></pre> | <p>Running <code>brew reinstall python@2</code> didn't work for my existing Python 2.7 virtual environments. Inside them there were still <code>ERROR:root:code for hash sha1 was not found</code> errors.</p>
<p>I encountered this problem after I ran <code>brew upgrade openssl</code>. And here's the fix:</p>
<pre><code>$ ls /usr/local/Cellar/openssl
</code></pre>
<p>...which shows</p>
<pre><code>1.0.2t
</code></pre>
<p>According to the existing version, run:</p>
<pre><code>$ brew switch openssl 1.0.2t
</code></pre>
<p>...which shows</p>
<pre><code>Cleaning /usr/local/Cellar/openssl/1.0.2t
Opt link created for /usr/local/Cellar/openssl/1.0.2t
</code></pre>
<p>After that, run the following command in a Python 2.7 virtualenv:</p>
<pre><code>(my-venv) $ python -c "import hashlib;m=hashlib.md5();print(m.hexdigest())"
</code></pre>
<p>...which shows</p>
<pre><code>d41d8cd98f00b204e9800998ecf8427e
</code></pre>
<p>No more errors.</p> | {
"question_id": 59269208,
"question_date": "2019-12-10T14:13:50.077Z",
"question_score": 234,
"tags": "python|macos|openssl|mercurial|homebrew",
"answer_id": 59816812,
"answer_date": "2020-01-20T03:55:39.060Z",
"answer_score": 712
} |
Please answer the following Stack Overflow question:
Title: What is the use for Task.FromResult<TResult> in C#
<p>In C# and TPL (<a href="http://msdn.microsoft.com/en-us/library/dd460717.aspx">Task Parallel Library</a>), the <code>Task</code> class represents an ongoing work that produces a value of type T.</p>
<p>I'd like to know what is the need for the <a href="http://msdn.microsoft.com/en-us/library/hh194922.aspx">Task.FromResult</a> method ?</p>
<p>That is: In a scenario where you already have the produced value at hand, what is the need to wrap it back into a Task?</p>
<p>The only thing that comes to mind is that it's used as some adapter for other methods accepting a Task instance.</p> | <p>There are two common use cases I've found:</p>
<ol>
<li>When you're implementing an interface that allows asynchronous callers, but your implementation is synchronous.</li>
<li>When you're stubbing/mocking asynchronous code for testing.</li>
</ol> | {
"question_id": 19568280,
"question_date": "2013-10-24T14:06:35.620Z",
"question_score": 234,
"tags": "c#|.net|task-parallel-library|task|async-await",
"answer_id": 19696462,
"answer_date": "2013-10-31T00:40:47.987Z",
"answer_score": 337
} |
Please answer the following Stack Overflow question:
Title: Android Studio Stuck at Gradle Download on create new project
<p>I have installed the new <code>Android Studio</code>. Everything was working fine but when I try to create a new project it gets stuck at downloading <strong>Gradle</strong>.</p>
<p>Is there any way to install the <strong>Gradle</strong> required by <code>Android Studio</code> manually? Or any other method to solve this problem ?</p>
<p><img src="https://i.stack.imgur.com/9hlLI.jpg" alt="screenshot"></p> | <p>It is not stuck, it will take some time normally 5-7 mins , it also depends upon internet connection, so wait for some time. It will take time only for first launch. </p>
<p>Update: Check the latest log file in your <strong><code>C:\Users\<User>\.gradle\daemon\x.y</code></strong> folder to see what it's downloading.</p> | {
"question_id": 16580873,
"question_date": "2013-05-16T06:56:48.883Z",
"question_score": 234,
"tags": "android|gradle|android-studio",
"answer_id": 16580916,
"answer_date": "2013-05-16T06:59:23.917Z",
"answer_score": 199
} |
Please answer the following Stack Overflow question:
Title: Suppress echo of command invocation in makefile?
<p>I wrote a program for an assignment which is supposed to print its output to stdout. The assignment spec requires the creation of a Makefile which when invoked as <code>make run > outputFile</code> should run the program and write the output to a file, which has a SHA1 fingerprint identical to the one given in the spec. </p>
<p>My problem is that my makefile:</p>
<pre><code>...
run:
java myprogram
</code></pre>
<p>also prints the command which runs my program (e.g. java myprogram) to the output file, so that my file includes this extra line causing the fingerprint to be wrong.</p>
<p>Is there any way to execute a command without the command invocation echoing to the command line?</p> | <p>Add <code>@</code> to the beginning of command to tell gmake not to print the command being executed. Like this:</p>
<pre><code>run:
@java myprogram
</code></pre>
<p>As Oli suggested, this is a feature of Make and not of Bash.</p>
<p>On the other hand, Bash will never echo commands being executed unless you tell it to do so explicitly (i.e. with <code>-x</code> option).</p> | {
"question_id": 9967105,
"question_date": "2012-04-01T18:36:50.827Z",
"question_score": 234,
"tags": "linux|unix|makefile|posix",
"answer_id": 9967125,
"answer_date": "2012-04-01T18:38:47.503Z",
"answer_score": 388
} |
Please answer the following Stack Overflow question:
Title: Security of REST authentication schemes
<p>Background:</p>
<p>I'm designing the authentication scheme for a REST web service. This doesn't "really" need to be secure (it's more of a personal project) but I want to make it as secure as possible as an exercise/learning experience. I don't want to use SSL since I don't want the hassle and, mostly, the expense of setting it up.</p>
<p>These SO questions were especially useful to get me started:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/319530/restful-authentication">RESTful Authentication</a></li>
<li><a href="https://stackoverflow.com/questions/7551/best-practices-for-securing-a-rest-api-web-service">Best Practices for securing a REST API / web service</a></li>
<li><a href="https://stackoverflow.com/questions/409338/examples-of-the-best-soap-rest-rpc-web-apis-and-why-do-you-like-them-and-whats">Examples of the best SOAP/REST/RPC web APIs? And why do you like them? And what’s wrong with them?</a></li>
</ul>
<p>I'm thinking of using a simplified version of <a href="http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?RESTAuthentication.html" rel="noreferrer">Amazon S3's authentication</a> (I like <a href="http://oauth.net/" rel="noreferrer">OAuth</a> but it seems too complicated for my needs). I'm adding a randomly generated <a href="http://en.wikipedia.org/wiki/Cryptographic_nonce" rel="noreferrer">nonce</a>, supplied by the server, to the request, to prevent replay attacks.</p>
<p>To get to the question: </p>
<p>Both S3 and OAuth rely on signing the request URL along with a few selected headers. <strong>Neither of them sign the request body</strong> for POST or PUT requests. Isn't this vulnerable to a man-in-the-middle attack, which keeps the url and headers and replaces the request body with any data the attacker wants?</p>
<p>It seems like I can guard against this by including a hash of the request body in the string that gets signed. Is this secure?</p> | <p>A previous answer only mentioned SSL in the context of data transfer and didn't actually cover authentication.</p>
<p>You're really asking about securely authenticating REST API clients. Unless you're using TLS client authentication, SSL <em>alone</em> is NOT a viable authentication mechanism for a REST API. SSL without client authc only authenticates the <em>server</em>, which is irrelevant for most REST APIs because you really want to authenticate the <em>client</em>. </p>
<p>If you don't use TLS client authentication, you'll need to use something like a digest-based authentication scheme (like Amazon Web Service's custom scheme) or OAuth 1.0a or even HTTP Basic authentication (but over SSL only).</p>
<p>These schemes authenticate that the request was sent by someone expected. TLS (SSL) (without client authentication) ensures that the data sent over the wire remains untampered. They are separate - but complementary - concerns.</p>
<p>For those interested, I've expanded on an SO question about <a href="https://stackoverflow.com/questions/14043397/http-basic-authentication-instead-of-tls-client-certificaiton">HTTP Authentication Schemes and how they work</a>.</p> | {
"question_id": 454355,
"question_date": "2009-01-18T00:12:10.863Z",
"question_score": 234,
"tags": "rest|authentication|oauth|amazon-s3|rest-security",
"answer_id": 10557662,
"answer_date": "2012-05-11T19:47:08.407Z",
"answer_score": 172
} |
Please answer the following Stack Overflow question:
Title: C# short/long/int literal format?
<p>In C/C#/etc. you can tell the compiler that a literal number is not what it appears to be (ie., <code>float</code> instead of <code>double</code>, <code>unsigned long</code> instead of <code>int</code>):</p>
<pre><code>var d = 1.0; // double
var f = 1.0f; // float
var u = 1UL; // unsigned long
</code></pre>
<p>etc.</p>
<p>Could someone point me to a list of these? I'm specifically looking for a suffix for <code>short</code> or <code>Int16</code>.</p> | <pre><code>var d = 1.0d; // double
var d0 = 1.0; // double
var d1 = 1e+3; // double
var d2 = 1e-3; // double
var f = 1.0f; // float
var m = 1.0m; // decimal
var i = 1; // int
var ui = 1U; // uint
var ul = 1UL; // ulong
var l = 1L; // long
</code></pre>
<p>I think that's all... there are no literal specifiers for short/ushort/byte/sbyte</p> | {
"question_id": 5820721,
"question_date": "2011-04-28T15:03:32.133Z",
"question_score": 234,
"tags": "c#|literals|language-specifications",
"answer_id": 5820772,
"answer_date": "2011-04-28T15:07:18.130Z",
"answer_score": 392
} |
Please answer the following Stack Overflow question:
Title: Cancel/kill window.setTimeout() before it happens
<p>I have a few places where I use the line below to clear out a status, for example. I have a few of these that hang out for 10 seconds or more and if the user gets clicking around the action can occur at incorrect time intervals.</p>
<pre><code>window.setTimeout(function() { removeStatusIndicator(); }, statusTimeout);
</code></pre>
<p>Is it possible to cancel or kill this with some jQuery or JavaScript code, so I don't have this process hanging around?</p> | <pre><code>var timer1 = setTimeout(function() { removeStatusIndicator(); }, statusTimeout);
clearTimeout(timer1)
</code></pre> | {
"question_id": 452003,
"question_date": "2009-01-16T21:05:27.857Z",
"question_score": 234,
"tags": "javascript|jquery",
"answer_id": 452007,
"answer_date": "2009-01-16T21:06:16.123Z",
"answer_score": 445
} |
Please answer the following Stack Overflow question:
Title: What's the difference between using INDEX vs KEY in MySQL?
<p>I know how to use INDEX as in the following code. And I know how to use <em>foreign key</em> and <em>primary key</em>.</p>
<pre><code>CREATE TABLE tasks (
task_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
parent_id INT UNSIGNED NOT NULL DEFAULT 0,
task VARCHAR(100) NOT NULL,
date_added TIMESTAMP NOT NULL,
date_completed TIMESTAMP,
PRIMARY KEY (task_id),
INDEX parent (parent_id),
....
</code></pre>
<p><br>
However I found a code using KEY instead of INDEX as following.</p>
<pre><code>...
KEY order_date (order_date)
...
</code></pre>
<p><br>
I could not find any explanation on the official MySQL page. Could anyone tell me what is the differences between KEY and INDEX?</p>
<p>The only difference I see is that when I use <code>KEY ...</code>, I need to repeat the word, e.g.<br>
<code>KEY order_date (order_date)</code>.</p> | <p>There's no difference. They are synonyms.</p>
<p>From <a href="https://dev.mysql.com/doc/refman/8.0/en/create-table.html#:%7E:text=KEY%20%7C%20INDEX" rel="noreferrer">the <code>CREATE TABLE</code> manual entry</a>:</p>
<blockquote>
<p><code>KEY</code> is normally a synonym for <code>INDEX</code>. The key attribute <code>PRIMARY KEY</code> can
also be specified as just <code>KEY</code> when given in a column definition. This was
implemented for compatibility with other database systems.</p>
</blockquote> | {
"question_id": 1401572,
"question_date": "2009-09-09T19:26:23.813Z",
"question_score": 234,
"tags": "mysql|indexing|key",
"answer_id": 1401615,
"answer_date": "2009-09-09T19:33:08.183Z",
"answer_score": 322
} |
Please answer the following Stack Overflow question:
Title: django test app error - Got an error creating the test database: permission denied to create database
<p>When I try to test any app with command (I noticed it when I tried to deploy myproject using fabric, which uses this command):</p>
<pre><code>python manage.py test appname
</code></pre>
<p>I get this error:</p>
<pre><code>Creating test database for alias 'default'...
Got an error creating the test database: permission denied to create database
Type 'yes' if you would like to try deleting the test database 'test_finance', or 'no' to cancel
</code></pre>
<p><code>syncdb</code> command seems to work. My database settings in settings.py:</p>
<pre><code>DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'finance', # Or path to database file if using sqlite3.
'USER': 'django', # Not used with sqlite3.
'PASSWORD': 'mydb123', # Not used with sqlite3.
'HOST': '127.0.0.1', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
</code></pre> | <p>When Django runs the test suite, it creates a new database, in your case <code>test_finance</code>. The postgres user with username <code>django</code> does not have permission to create a database, hence the error message.</p>
<p>When you run <code>migrate</code> or <code>syncdb</code>, Django does not try to create the <code>finance</code> database, so you don't get any errors.</p>
<p>You can add the createdb permission to the django user by running the following command in the postgres shell as a superuser (hat tip to <a href="https://stackoverflow.com/questions/8988495/postgres-user-create-database/8989722#8989722">this stack overflow answer</a>).</p>
<pre><code>=> ALTER USER django CREATEDB;
</code></pre>
<p><strong>Note:</strong> The username used in the <code>ALTER USER <username> CREATEDB;</code> command needs to match the database user in your Django settings files. In this case, the original poster, had the user as <code>django</code> the above answer.</p> | {
"question_id": 14186055,
"question_date": "2013-01-06T19:51:21.253Z",
"question_score": 234,
"tags": "python|sql|django|postgresql|django-testing",
"answer_id": 14186439,
"answer_date": "2013-01-06T20:31:49.907Z",
"answer_score": 468
} |
Please answer the following Stack Overflow question:
Title: What are differences between SystemJS and Webpack?
<p>I'm creating my first Angular application and I would figure out what is the role of the module loaders.
Why we need them?
I tried to search and search on Google and I can't understand why we need to install one of them to run our application?</p>
<p>Couldn't it be enough to just use <code>import</code> to load stuff from node modules?</p>
<p>I have followed <a href="https://angular.io/docs/ts/latest/quickstart.html#!#systemjs" rel="noreferrer">this tutorial</a> (that uses SystemJS) and it makes me to use <code>systemjs.config.js</code> file:</p>
<pre><code>/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function(global) {
// map tells the System loader where to look for things
var map = {
'app': 'transpiled', // 'dist',
'@angular': 'node_modules/@angular',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'rxjs': 'node_modules/rxjs'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
};
var ngPackageNames = [
'common',
'compiler',
'core',
'forms',
'http',
'platform-browser',
'platform-browser-dynamic',
'router',
'router-deprecated',
'upgrade',
];
// Individual files (~300 requests):
function packIndex(pkgName) {
packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
}
// Bundled (~40 requests):
function packUmd(pkgName) {
packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
}
// Most environments should use UMD; some (Karma) need the individual index files
var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
// Add package entries for angular packages
ngPackageNames.forEach(setPackageConfig);
var config = {
map: map,
packages: packages
};
System.config(config);
})(this);
</code></pre>
<p>Why we need this configuration file?<br>
Why we need SystemJS (or WebPack or others)?<br>
Finally, in your opinion what is the better?</p> | <p>If you go to the SystemJS Github page, you will see the description of the tool:</p>
<blockquote>
<p>Universal dynamic module loader - loads ES6 modules, AMD, CommonJS and global scripts in the browser and NodeJS.</p>
</blockquote>
<p>Because you use modules in TypeScript or ES6, you need a module loader. In the case of SystemJS, the <code>systemjs.config.js</code> allows us to configure the way in which module names are matched with their corresponding files.</p>
<p>This configuration file (and SystemJS) is necessary if you explicitly use it to import the main module of your application:</p>
<pre><code><script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</code></pre>
<p>When using TypeScript, and configuring the compiler to the <code>commonjs</code> module, the compiler creates code that is no longer based on SystemJS. In this example, the typescript compiler config file would appear like this:</p>
<pre><code>{
"compilerOptions": {
"target": "es5",
"module": "commonjs", // <------
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
}
}
</code></pre>
<p>Webpack is a flexible module bundler. This means that it goes further and doesn't only handle modules but also provides a way to package your application (concat files, uglify files, ...). It also provides a dev server with load reload for development.</p>
<p>SystemJS and Webpack are different but with SystemJS, you still have work to do (with <a href="http://gulpjs.com/" rel="noreferrer">Gulp</a> or <a href="https://github.com/systemjs/builder" rel="noreferrer">SystemJS builder</a> for example) to package your Angular2 application for production.</p> | {
"question_id": 38263406,
"question_date": "2016-07-08T09:36:18.147Z",
"question_score": 234,
"tags": "javascript|angular|webpack|node-modules|systemjs",
"answer_id": 38263593,
"answer_date": "2016-07-08T09:46:33.290Z",
"answer_score": 144
} |
Please answer the following Stack Overflow question:
Title: What's the difference between Ruby's dup and clone methods?
<p>The <a href="http://www.ruby-doc.org/core-2.0/Object.html#method-i-dup" rel="noreferrer">Ruby docs for <code>dup</code></a> say:</p>
<blockquote>
<p>In general, <code>clone</code> and <code>dup</code> may have different semantics in descendent classes. While <code>clone</code> is used to duplicate an object, including its internal state, <code>dup</code> typically uses the class of the descendent object to create the new instance.</p>
</blockquote>
<p>But when I do some test I found they are actually the same:</p>
<pre><code>class Test
attr_accessor :x
end
x = Test.new
x.x = 7
y = x.dup
z = x.clone
y.x => 7
z.x => 7
</code></pre>
<p>So what are the differences between the two methods?</p> | <p>Subclasses may override these methods to provide different semantics. In <code>Object</code> itself, there are two key differences.</p>
<p>First, <code>clone</code> copies the singleton class, while <code>dup</code> does not.</p>
<pre><code>o = Object.new
def o.foo
42
end
o.dup.foo # raises NoMethodError
o.clone.foo # returns 42
</code></pre>
<p>Second, <code>clone</code> preserves the frozen state, while <code>dup</code> does not.</p>
<pre><code>class Foo
attr_accessor :bar
end
o = Foo.new
o.freeze
o.dup.bar = 10 # succeeds
o.clone.bar = 10 # raises RuntimeError
</code></pre>
<p>The <a href="https://github.com/rubinius/rubinius/blob/master/kernel/alpha.rb#L189" rel="noreferrer">Rubinius implementation for these methods</a>
is often my source for answers to these questions, since it is quite clear, and a fairly compliant Ruby implementation.</p> | {
"question_id": 10183370,
"question_date": "2012-04-17T00:08:28.927Z",
"question_score": 234,
"tags": "ruby|clone|dup",
"answer_id": 10183477,
"answer_date": "2012-04-17T00:24:38.137Z",
"answer_score": 317
} |
Please answer the following Stack Overflow question:
Title: Javadoc: package.html or package-info.java
<p>When trying to create package level Javadoc comments, whats the preferred method? What do you do?</p>
<p><strong>package-info.java</strong></p>
<ul>
<li>Pros
<ul>
<li>Newer</li>
</ul></li>
<li>Cons
<ul>
<li>Abuse of a class - Classes are for code, not for only comments</li>
</ul></li>
</ul>
<p><strong>package.html</strong></p>
<ul>
<li>Pros
<ul>
<li>HTML extension means its not code</li>
<li>Syntax highlighting in IDE's/text editors</li>
</ul></li>
<li>Cons
<ul>
<li>None?</li>
</ul></li>
</ul>
<hr>
<p>For me, I've always used Package.html. But I'm wondering if its the correct choice. </p> | <p><code>package-info.java</code>: "This file is new in JDK 5.0, and is preferred over package.html."—<a href="https://docs.oracle.com/javase/8/docs/technotes/tools/unix/javadoc.html#packagecomment" rel="nofollow noreferrer"><em>javadoc - The Java API Documentation Generator</em></a></p>
<p>Addendum: The big difference seems to be <em>package annotations</em>. There's a little more in the way of rationale in <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.4" rel="nofollow noreferrer"><em>7.4 Package Declarations</em></a>.</p>
<p>Addendum: The annotation feature is also mentioned <a href="http://tech.puredanger.com/2007/02/28/package-annotations/" rel="nofollow noreferrer">here</a> and in <a href="https://web.archive.org/web/20080204050234/http://blogs.sun.com/darcy/entry/javadoc_tip_prefer_package_info" rel="nofollow noreferrer"><em>Javadoc tip: Prefer package-info to package.html</em></a>, cited <a href="https://github.com/jddarcy/BlogsSunComArchive#2006" rel="nofollow noreferrer">here</a>.</p>
<p>Addendum: See also <a href="https://www.intertech.com/Blog/whats-package-info-java-for/" rel="nofollow noreferrer"><em>What’s <code>package-info.java</code> for?</em></a>.</p> | {
"question_id": 3644726,
"question_date": "2010-09-05T02:02:03.397Z",
"question_score": 234,
"tags": "java|javadoc",
"answer_id": 3644733,
"answer_date": "2010-09-05T02:09:16.057Z",
"answer_score": 274
} |
Please answer the following Stack Overflow question:
Title: How can I turn on (literally) ALL of GCC's warnings?
<p>I would like to enable—literally—<em><strong>all</strong></em> of the warnings that GCC has. (You'd think it would be easy...)</p>
<ul>
<li><p>You'd think <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wall" rel="nofollow noreferrer">-Wall</a> might do the trick, but nope! You still need <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wextra" rel="nofollow noreferrer">-Wextra</a>.</p>
</li>
<li><p>You'd think <code>-Wextra</code> might do the trick, but nope! Not all of the warnings listed <a href="http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Warning-Options.html" rel="nofollow noreferrer">here</a> (for example, <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wshadow" rel="nofollow noreferrer">-Wshadow</a>) are enabled by this. And I still don't have any idea if this list is comprehensive.</p>
</li>
</ul>
<p>How do I tell GCC to enable (no if's, and's, or but's!) <strong>all</strong> the warnings it has?</p> | <p>You can't.</p>
<p>The manual for GCC 4.4.0 is only comprehensive for that version, but it does list all the possible warnings for 4.4.0. They're not all on the page you link to though. For instance, some language-specific options are on the pages for C++ options or Objective-C options. To find them all, you're better off looking at the <a href="http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Option-Summary.html" rel="nofollow noreferrer">Options Summary</a></p>
<p>Turning on <strong>everything</strong> would include <code>-Wdouble-promotion</code> which is only relevant on CPUs with a 32-bit single-precision floating-point unit which implements <code>float</code> in hardware, but emulates <code>double</code> in software. Doing calculations as <code>double</code> would use the software emulation and be slower. That's relevant for some embedded CPUs, but completely irrelevant for modern desktop CPUs with hardware support for 64-bit floating-point.</p>
<p>Another warning that's not usually useful is <code>-Wtraditional</code>, which warns about perfectly well formed code that has a different meaning (or doesn't work) in traditional C, e.g., <code>"string " "concatenation"</code>, or ISO C function definitions! Do you really care about compatibility with 30 year old compilers? Do you really want a warning for writing <code>int inc(int i) { return i+1; }</code>?</p>
<p>I think <code>-Weffc++</code> is too noisy to be useful. It's based on the outdated first edition of <em><a href="https://en.wikipedia.org/wiki/Scott_Meyers#Publications" rel="nofollow noreferrer">Effective C++</a></em> and warns about constructs which are perfectly valid C++ (and for which the guidelines changed in later editions of the book). I don't want to be warned that I haven't initialized a <code>std::string</code> member in my constructor; it has a default constructor that does exactly what I want. Why should I write <code>m_str()</code> to call it? The <code>-Weffc++</code> warnings that would be helpful are too difficult for the compiler to detect accurately (giving false negatives), and the ones that aren't useful, such as initializing all members explicitly, just produce too much noise, giving false positives.</p>
<p>Luc Danton provided a <a href="http://coliru.stacked-crooked.com/a/1afffbfed83fec2a" rel="nofollow noreferrer">great example</a> of useless warnings from <code>-Waggregate-return</code> that almost certainly never makes sense for C++ code.</p>
<p>I.e., you don't really want <em>all</em> warnings; you just think you do.</p>
<p>Go through the manual, read about them, decide which you might want to enable, and try them. Reading your compiler's manual is a Good Thing<sup>TM</sup> anyway, taking a shortcut and enabling warnings you don't understand is not a very good idea, especially if it's to avoid having to <a href="https://en.wiktionary.org/wiki/RTFM#Phrase" rel="nofollow noreferrer">RTFM</a>.</p>
<p><a href="http://gcc.gnu.org/ml/gcc-help/2012-04/msg00248.html" rel="nofollow noreferrer">Anyone who just turns on <em>everything</em> is probably either doing so because they're clueless because or a pointy-haired boss said "no warnings."</a></p>
<p><a href="http://gcc.gnu.org/ml/gcc-help/2012-04/msg00253.html" rel="nofollow noreferrer">Some warnings are important, and some aren't. You have to be discriminating or you mess up your program. Consider, for instance, <code>-Wdouble-promotion</code>. If you're working on an embedded system you might want this; if you're working on a desktop system you probably don't. And do you want <code>-Wtraditional</code>? I doubt it</a>.</p>
<p>See also <a href="http://gcc.gnu.org/bugzilla/show_bug.cgi?id=31573" rel="nofollow noreferrer">-Wall-all to enable all warnings</a> which is closed as <em>WONTFIX</em>.</p>
<p>In response to DevSolar's complaint about makefiles needing to use different warnings depending on compiler version, if <code>-Wall -Wextra</code> isn't suitable then it's not difficult to use compiler-specific and version-specific CFLAGS:</p>
<pre class="lang-none prettyprint-override"><code>compiler_name := $(notdir $(CC))
ifeq ($(compiler_name),gcc)
compiler_version := $(basename $(shell $(CC) -dumpversion))
endif
ifeq ($(compile_name),clang)
compiler_version := $(shell $(CC) --version | awk 'NR==1{print $$3}')
endif
# ...
wflags.gcc.base := -Wall -Wextra
wflags.gcc.4.7 := -Wzero-as-null-pointer-constant
wflags.gcc.4.8 := $(wflags.gcc.4.7)
wflags.clang.base := -Wall -Wextra
wflags.clang.3.2 := -Weverything
CFLAGS += $(wflags.$(compiler_name).base) $(wflags.$(compiler_name).$(compiler_version))
</code></pre> | {
"question_id": 11714827,
"question_date": "2012-07-30T02:39:08.720Z",
"question_score": 234,
"tags": "c++|gcc|warnings|compiler-warnings|gcc-warning",
"answer_id": 11720263,
"answer_date": "2012-07-30T11:09:09.887Z",
"answer_score": 148
} |
Please answer the following Stack Overflow question:
Title: asp.net mvc: why is Html.CheckBox generating an additional hidden input
<p>I just noticed that <code>Html.CheckBox("foo")</code> generates 2 inputs instead of one, anybody knows why is this so ?</p>
<pre><code><input id="foo" name="foo" type="checkbox" value="true" />
<input name="foo" type="hidden" value="false" />
</code></pre> | <p>If checkbox is not selected, form field is not submitted. That is why there is always false value in hidden field. If you leave checkbox unchecked, form will still have value from hidden field. That is how ASP.NET MVC handles checkbox values. </p>
<p>If you want to confirm that, place a checkbox on form not with Html.Hidden, but with <code><input type="checkbox" name="MyTestCheckboxValue"></input></code>. Leave checkbox unchecked, submit form and look at posted request values on server side. You'll see that there is no checkbox value. If you had hidden field, it would contain <code>MyTestCheckboxValue</code> entry with <code>false</code> value.</p> | {
"question_id": 2697299,
"question_date": "2010-04-23T08:53:03.270Z",
"question_score": 234,
"tags": "asp.net-mvc",
"answer_id": 2697311,
"answer_date": "2010-04-23T08:56:11.763Z",
"answer_score": 213
} |
Please answer the following Stack Overflow question:
Title: Android what does the clipToPadding Attribute do?
<p>I would like to know what the <code>clipToPadding</code> attribute does for <code>ViewGroup</code> in Android ?</p>
<p>I've been through the docs and some websites but none I have come across actually explain what it does and what it means, well none that I could actually understand so I thought it might be a good idea to ask it here.</p> | <p>You can use clipToPadding for views that scroll. Say you have a listview for example and you having padding set on the top and bottom. Normally the padding is visible no matter which items are visible on the screen. The diagram below represents a list with 10 items but only 4 are visible on screen, with default clipToPadding settings:</p>
<ul>
<li>(padding)</li>
<li>item 4</li>
<li>item 5</li>
<li>item 6</li>
<li>item 7</li>
<li>(padding)</li>
</ul>
<p>Now if you were to set <code>clipToPadding="false"</code> instead of just being applied normally to the entire view it only applies the padding to the end items, this is what you'd see in the same scenario:</p>
<ul>
<li>item 4</li>
<li>item 5</li>
<li>item 6</li>
<li>item 7</li>
</ul>
<p>Now if you were to scroll to the top or bottom of the list, this is what you would see:</p>
<ul>
<li>(padding)</li>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ul>
<p>OR</p>
<ul>
<li>item 7</li>
<li>item 8</li>
<li>item 9</li>
<li>item 10</li>
<li>(padding)</li>
</ul>
<p>A practical usage for this is if you have a Floating Action Button for example, you should use clipToPadding combined with bottom padding to ensure the entirety of the bottom item can be seen without being obstructed by the FAB.</p>
<p>Does that make sense?</p> | {
"question_id": 40953049,
"question_date": "2016-12-03T22:12:04.937Z",
"question_score": 234,
"tags": "android|android-layout",
"answer_id": 40955714,
"answer_date": "2016-12-04T05:28:25.277Z",
"answer_score": 565
} |
Please answer the following Stack Overflow question:
Title: git - skipping specific commits when merging
<p>I've been using Git for about a year now and think it's fantastic, but I've just started on a second version of the project and started a new branch for it. I'm struggling a little with the best way to handle things going forward.</p>
<p>I have two branches called say master10 (for v1) and master20 (for v2). I've been making bug fixes in v1 on branch master10, and developing new stuff of master20. Whenever I make a bug fix I merge it into v2 by checking out master20 and doing <code>git merge master10</code>. So far so good.</p>
<p>Now however, I've made a change in v1 that I don't want in v2, but I want to continue merging other bug fixes. How do I tell Git to skip that particular commit (or a range of commits), but that going forward I still want to merge other bug fixes.</p>
<p>I thought <code>git rebase</code> might be what I need but read the doc and my head nearly exploded.</p>
<p>I think what I want is something like a "git sync" command that tells git that two branches are now in-sync and in future only merge the commits from this sync-point on.</p>
<p>Any help appreciated.</p> | <p>If you want to merge most but not all of the commits on branch "maint" to "master", for instance, you can do this. It requires some work---- as mentioned above, the usual use case is to merge everything from a branch--- but sometimes it happens that you made a change to a release version that shouldn't be integrated back (maybe that code's been superceded in master already), so how do you represent that? Here goes...</p>
<p>So let's suppose maint has had 5 changes applied, and one of those (maint~3) is not to be merged back into master, although all the others should be. You do this in three stages: actually merge everything before that one, tell git to mark maint~3 as merged even when it isn't, and then merge the rest. The magic is:</p>
<pre><code>bash <master>$ git merge maint~4
bash <master>$ git merge -s ours maint~3
bash <master>$ git merge maint
</code></pre>
<p>The first command merges everything <em>before</em> your troublesome maint commit onto master. The default merge log message will explain you're merging "branch 'maint' (early part)".</p>
<p>The second command merges the troublesome maint~3 commit, but the "-s ours" option tells git to use a special "merge strategy" which, in fact, works by simply keeping the tree you are merging into and ignoring the commit(s) you are merging completely. But it does still make a new merge commit with HEAD and maint~3 as the parents, so the revision graph now says that maint~3 is merged. So in fact you probably want to use the -m option to <code>git merge</code> as well, to explain that that maint~3 commit is actually being ignored!</p>
<p>The final command simply merges the rest of maint (maint~2..maint) into master so that you're all synced up again.</p> | {
"question_id": 727994,
"question_date": "2009-04-07T23:32:54.437Z",
"question_score": 234,
"tags": "git|version-control",
"answer_id": 729723,
"answer_date": "2009-04-08T12:26:14.170Z",
"answer_score": 330
} |
Please answer the following Stack Overflow question:
Title: Queries vs. Filters
<p>I can't see any description of when I should use a query or a filter or some combination of the two. What is the difference between them? Can anyone please explain?</p> | <p>The difference is simple: filters are cached and don't influence the score, therefore faster than queries. Have a look <a href="http://www.elasticsearch.org/guide/reference/query-dsl/">here</a> too. Let's say a query is usually something that the users type and pretty much unpredictable, while filters help users narrowing down the search results , for example using facets.</p> | {
"question_id": 14595988,
"question_date": "2013-01-30T03:03:48.710Z",
"question_score": 234,
"tags": "elasticsearch",
"answer_id": 14600680,
"answer_date": "2013-01-30T09:37:07.903Z",
"answer_score": 228
} |
Please answer the following Stack Overflow question:
Title: What do you call the -> operator in Ruby?
<ol>
<li><p>What do you call the <code>-></code> operator as in the following?</p>
<pre><code>->(...) do
...
end
</code></pre></li>
<li><p>Aren't the following snippets equivalent?</p>
<pre><code>succ = ->(x) {x + 1}
succ = lambda {|x| x + 1}
</code></pre></li>
</ol> | <p>In <em>Ruby Programming Language</em> ("Methods, Procs, Lambdas, and Closures"), a lambda defined using <code>-></code> is called <em>lambda literal</em>. </p>
<pre><code>succ = ->(x){ x+1 }
succ.call(2)
</code></pre>
<p>The code is equivalent to the following one. </p>
<pre><code>succ = lambda { |x| x + 1 }
succ.call(2)
</code></pre>
<p>Informally, I have heard it being called <em>stabby lambda</em> or <em>stabby literal</em>.</p> | {
"question_id": 8476627,
"question_date": "2011-12-12T15:26:09.363Z",
"question_score": 234,
"tags": "ruby|syntax",
"answer_id": 8538513,
"answer_date": "2011-12-16T18:27:36Z",
"answer_score": 266
} |
Please answer the following Stack Overflow question:
Title: How do I contribute to other's code in GitHub?
<p>I would like to contribute to a certain project in <a href="http://en.wikipedia.org/wiki/GitHub" rel="noreferrer">GitHub</a>. Should I <strong>fork</strong> it? <strong>Branch</strong> it? What is recommended and how to do it?</p> | <p>Ideally you:</p>
<ol>
<li><a href="https://help.github.com/en/articles/fork-a-repo" rel="noreferrer">Fork</a> the project</li>
<li>Make one or more well commented and clean commits to the repository. You can make a new branch here if you are modifying more than one part or feature.</li>
<li>Perform a <a href="https://help.github.com/en/articles/about-pull-requests" rel="noreferrer">pull request</a> in github's web interface.</li>
</ol>
<p>if it is a new Feature request, don't start the coding first. Remember to post an issue to discuss the new feature.</p>
<p>If the feature is well discuss and there are some +1 or the project owner approved it, assign the issue to yourself, then do the steps above.</p>
<p>Some projects won't use the pull request system. Check with the author or mailing list on the best way to get your code back into the project.</p> | {
"question_id": 4384776,
"question_date": "2010-12-08T06:31:11.100Z",
"question_score": 234,
"tags": "git|open-source|github",
"answer_id": 4384824,
"answer_date": "2010-12-08T06:40:21.647Z",
"answer_score": 187
} |
Please answer the following Stack Overflow question:
Title: Illegal string offset Warning PHP
<p>I get a strange PHP error after updating my php version to 5.4.0-3.</p>
<p>I have this array:</p>
<pre><code>Array
(
[host] => 127.0.0.1
[port] => 11211
)
</code></pre>
<p>When I try to access it like this I get strange warnings</p>
<pre><code> print $memcachedConfig['host'];
print $memcachedConfig['port'];
Warning: Illegal string offset 'host' in ....
Warning: Illegal string offset 'port' in ...
</code></pre>
<p>I really don't want to just edit my php.ini and re-set the error level.</p> | <p>Please try this way.... I have tested this code.... It works....</p>
<pre><code>$memcachedConfig = array("host" => "127.0.0.1","port" => "11211");
print_r($memcachedConfig['host']);
</code></pre> | {
"question_id": 9869150,
"question_date": "2012-03-26T08:55:03.403Z",
"question_score": 233,
"tags": "php|warnings",
"answer_id": 9869249,
"answer_date": "2012-03-26T09:00:46.973Z",
"answer_score": 37
} |
Please answer the following Stack Overflow question:
Title: How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0
<p>What causes this error, how can I fix it?</p>
<blockquote>
<p>Detailed Error Information<br>
Module IIS Web Core<br>
Notification BeginRequest<br>
Handler Not yet determined<br>
Error Code 0x8007052e<br>
Config Error Can not log on locally to C:\inetpub\wwwroot as user administrator with virtual directory password<br>
Config File Unavailable (Config Isolation)<br>
Requested URL <a href="http://192.168.0.3:80/" rel="noreferrer">http://192.168.0.3:80/</a><br>
Physical Path C:\inetpub\wwwroot<br>
Logon Method Not yet determined<br>
Logon User Not yet determined </p>
</blockquote>
<p>Config Source</p>
<pre><code><application path="/" applicationPool="PS-Extranet">
<virtualDirectory path="/" physicalPath="%SystemDrive%\inetpub\wwwroot" userName="administrator" password="[enc:AesProvider:PrISRz2ggJH4bV46ktObfCSh91Y/yF9pAoLmH7eCnj0=:enc]" />
</application>
</code></pre> | <p>Looks like the user account you're using for your app pool doesn't have rights to the web site directory, so it can't read config from there. Check the app pool and see what user it is configured to run as. Check the directory and see if that user has appropriate rights to it. While you're at it, check the event log and see if IIS logged any more detailed diagnostic information there.</p> | {
"question_id": 929131,
"question_date": "2009-05-30T06:06:08.610Z",
"question_score": 233,
"tags": "asp.net|iis|web-applications|iis-7",
"answer_id": 929225,
"answer_date": "2009-05-30T07:09:30.120Z",
"answer_score": 165
} |
Please answer the following Stack Overflow question:
Title: Finding the max/min value in an array of primitives using Java
<p>It's trivial to write a function to determine the min/max value in an array, such as:</p>
<pre><code>/**
*
* @param chars
* @return the max value in the array of chars
*/
private static int maxValue(char[] chars) {
int max = chars[0];
for (int ktr = 0; ktr < chars.length; ktr++) {
if (chars[ktr] > max) {
max = chars[ktr];
}
}
return max;
}
</code></pre>
<p>but isn't this already done somewhere?</p> | <p>Using Commons Lang (to convert) + Collections (to min/max)</p>
<pre><code>import java.util.Arrays;
import java.util.Collections;
import org.apache.commons.lang.ArrayUtils;
public class MinMaxValue {
public static void main(String[] args) {
char[] a = {'3', '5', '1', '4', '2'};
List b = Arrays.asList(ArrayUtils.toObject(a));
System.out.println(Collections.min(b));
System.out.println(Collections.max(b));
}
}
</code></pre>
<p>Note that <code>Arrays.asList()</code> wraps the underlying array, so it should not be too memory intensive and it should not perform a copy on the elements of the array.</p> | {
"question_id": 1484347,
"question_date": "2009-09-27T20:07:56.857Z",
"question_score": 233,
"tags": "java|arrays|algorithm|frameworks",
"answer_id": 1486010,
"answer_date": "2009-09-28T08:43:12.203Z",
"answer_score": 195
} |
Please answer the following Stack Overflow question:
Title: Pinging servers in Python
<p>In Python, is there a way to ping a server through ICMP and return TRUE if the server responds, or FALSE if there is no response?</p> | <p><strong>This function works in any OS (Unix, Linux, macOS, and Windows)</strong><br>
<strong>Python 2 and Python 3</strong></p>
<p>EDITS:<br>
By <a href="https://stackoverflow.com/users/797396/radato">@radato</a> <code>os.system</code> was replaced by <code>subprocess.call</code>. This avoids <a href="https://en.wikipedia.org/wiki/Shell_injection#Shell_injection" rel="noreferrer">shell injection</a> vulnerability in cases where your hostname string might not be validated.</p>
<pre><code>import platform # For getting the operating system name
import subprocess # For executing a shell command
def ping(host):
"""
Returns True if host (str) responds to a ping request.
Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
"""
# Option for the number of packets as a function of
param = '-n' if platform.system().lower()=='windows' else '-c'
# Building the command. Ex: "ping -c 1 google.com"
command = ['ping', param, '1', host]
return subprocess.call(command) == 0
</code></pre>
<p>Note that, according to @ikrase on Windows this function will still return <code>True</code> if you get a <code>Destination Host Unreachable</code> error.</p>
<p><strong>Explanation</strong></p>
<p>The command is <code>ping</code> in both Windows and Unix-like systems.<br>
The option <code>-n</code> (Windows) or <code>-c</code> (Unix) controls the number of packets which in this example was set to 1.</p>
<p><a href="https://docs.python.org/library/platform.html#platform.system" rel="noreferrer"><code>platform.system()</code></a> returns the platform name. Ex. <code>'Darwin'</code> on macOS.<br>
<a href="https://docs.python.org/library/subprocess.html#subprocess.call" rel="noreferrer"><code>subprocess.call()</code></a> performs a system call. Ex. <code>subprocess.call(['ls','-l'])</code>. </p> | {
"question_id": 2953462,
"question_date": "2010-06-01T21:27:21.747Z",
"question_score": 233,
"tags": "python|python-3.x|ping|icmp",
"answer_id": 32684938,
"answer_date": "2015-09-20T22:24:11.323Z",
"answer_score": 188
} |
Please answer the following Stack Overflow question:
Title: Bootstrap Center Vertical and Horizontal Alignment
<p>I have a page where only form exists and I want form to be placed in the center of the screen.</p>
<pre><code><div class="container">
<div class="row justify-content-center align-items-center">
<form>
<div class="form-group">
<label for="formGroupExampleInput">Example label</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Another label</label>
<input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
</div>
</form>
</div>
</div>
</code></pre>
<p>The <code>justify-content-center</code> aligns the form horizontally, but I can't figure out how to align it vertically. I have tried to use <code>align-items-center</code> and <code>align-self-center</code>, but it doesn't work. </p>
<p>What am I missing?</p>
<p><a href="http://jsbin.com/xotonekita/edit?html,css,output" rel="noreferrer">DEMO</a></p> | <p><strong>Bootstrap 5 (Updated 2021)</strong></p>
<p>Bootstrap 5 is still <em>flexbox</em> based so vertical centering works the same way as it did in Bootstrap 4. For example, <code>align-items-center</code> (flex-direction: row) and <code>justify-content-center</code> (flex-direction: column) can used on the flexbox parent (row or d-flex).</p>
<p><a href="https://codeply.com/p/0VM5MJ7Had" rel="noreferrer">Centering examples in Bootstrap 5</a></p>
<p><strong>Vertical center (don't forget the parent must have a defined height!):</strong></p>
<ul>
<li><code>my-auto</code> for centering <em>inside</em> flex (<code>.d-flex</code>) elements</li>
<li><code>my-auto</code> can be used to <strong>center columns</strong> (<code>.col-</code>) <em>inside</em> <code>row</code></li>
<li><code>align-items-center</code> to <strong>center columns</strong> (<code>col-*</code>) <em>inside</em> <code>row</code></li>
</ul>
<p><strong>Horizontal center:</strong></p>
<ul>
<li><code>text-center</code> to center <code>display:inline</code> elements & column content</li>
<li><code>mx-auto</code> for centering inside flex elements</li>
<li><code>mx-auto</code> can be used to <strong>center columns</strong> (<code>.col-</code>) inside <code>row</code></li>
<li><code>justify-content-center</code> to <strong>center columns</strong> (<code>col-*</code>) inside <code>row</code></li>
</ul>
<hr />
<p><strong>Bootstrap 4.3+ (Update 2019)</strong></p>
<p>There's <strong>no need</strong> for <strong>extra CSS</strong>. What's already included in Bootstrap will work. Make sure the container(s) of the form are <strong>full height</strong>. Bootstrap 4 now has a <code>h-100</code> class for 100% height...</p>
<p><strong>Vertical center:</strong></p>
<pre><code><div class="container h-100">
<div class="row h-100 justify-content-center align-items-center">
<form class="col-12">
<div class="form-group">
<label for="formGroupExampleInput">Example label</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Another label</label>
<input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
</div>
</form>
</div>
</div>
</code></pre>
<p><a href="https://codeply.com/go/raCutAGHre" rel="noreferrer">https://codeply.com/go/raCutAGHre</a></p>
<p><strong>the height of the container with the item(s) to center should be 100%</strong>
(or whatever the desired height is relative to the centered item)</p>
<p>Note: When using <code>height:100%</code> (<strong>percentage height</strong>) on any element, the element <a href="https://stackoverflow.com/a/7049918/171456"><strong>takes in the height of it's container</strong></a>. In modern browsers vh units <code>height:100vh;</code> can be used instead of <code>%</code> to get the desired height.</p>
<p>Therefore, you can set html, body {height: 100%}, or use the new <code>min-vh-100</code> class on container instead of <code>h-100</code>.</p>
<hr>
<p><strong>Horizontal center:</strong></p>
<ul>
<li><code>text-center</code> to center <code>display:inline</code> elements & column content</li>
<li><code>mx-auto</code> for centering inside flex elements</li>
<li><code>offset-*</code> or <code>mx-auto</code> can be used to <strong>center columns</strong> (<code>.col-</code>)</li>
<li><code>justify-content-center</code> to <strong>center columns</strong> (<code>col-*</code>) inside <code>row</code></li>
</ul>
<hr>
<p><a href="https://stackoverflow.com/questions/42252443/vertical-align-center-in-bootstrap-4/42252877#42252877">Vertical Align Center in Bootstrap</a><br>
<a href="https://www.codeply.com/go/GeBvYXxFKY" rel="noreferrer">Bootstrap 4 full-screen centered form</a><br>
<a href="https://www.codeply.com/go/yk1uKMtvdd" rel="noreferrer">Bootstrap 4 center input group</a><br>
<a href="https://www.codeply.com/go/9HWnyQm2Sf" rel="noreferrer">Bootstrap 4 horizontal + vertical center full screen</a></p> | {
"question_id": 42388989,
"question_date": "2017-02-22T10:45:07.257Z",
"question_score": 233,
"tags": "css|twitter-bootstrap|bootstrap-4|centering|bootstrap-5",
"answer_id": 44801382,
"answer_date": "2017-06-28T11:40:03.727Z",
"answer_score": 466
} |
Please answer the following Stack Overflow question:
Title: forEach is not a function error with JavaScript array
<p>I'm trying to make a simple loop:</p>
<pre><code>const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
console.log(child)
})
</code></pre>
<p>But I get the following error:</p>
<blockquote>
<p>VM384:53 Uncaught TypeError: parent.children.forEach is not a function</p>
</blockquote>
<p>Even though <code>parent.children</code> logs:</p>
<p><a href="https://i.stack.imgur.com/cjUUW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cjUUW.png" alt="enter image description here"></a></p>
<p>What could be the problem?</p>
<p>Note: Here's a <a href="https://jsfiddle.net/swb12kqn/1/" rel="noreferrer">JSFiddle</a>.</p> | <h1>First option: invoke forEach indirectly</h1>
<p>The <code>parent.children</code> is an Array like object. Use the following solution:</p>
<pre class="lang-js prettyprint-override"><code>const parent = this.el.parentElement;
Array.prototype.forEach.call(parent.children, child => {
console.log(child)
});
</code></pre>
<p>The <code>parent.children</code> is <code>NodeList</code> type, which is an Array like object because:</p>
<ul>
<li>It contains the <code>length</code> property, which indicates the number of nodes</li>
<li>Each node is a property value with numeric name, starting from 0: <code>{0: NodeObject, 1: NodeObject, length: 2, ...}</code></li>
</ul>
<p>See more details in <a href="https://dmitripavlutin.com/foreach-iterate-array-javascript/#6-iterate-array-like-objects-using-foreach" rel="noreferrer">this article</a>.</p>
<hr>
<h1>Second option: use the iterable protocol</h1>
<p><code>parent.children</code> is an <code>HTMLCollection</code>: which implements the <a href="https://dmitripavlutin.com/how-three-dots-changed-javascript/#5-spread-operator-and-iteration-protocols" rel="noreferrer">iterable protocol</a>. In an ES2015 environment, you can use the <code>HTMLCollection</code> with any construction that accepts iterables.</p>
<p>Use <code>HTMLCollection</code> with the spread operatator:</p>
<pre class="lang-js prettyprint-override"><code>const parent = this.el.parentElement;
[...parent.children].forEach(child => {
console.log(child);
});
</code></pre>
<p>Or with the <code>for..of</code> cycle (which is my preferred option):</p>
<pre class="lang-js prettyprint-override"><code>const parent = this.el.parentElement;
for (const child of parent.children) {
console.log(child);
}
</code></pre> | {
"question_id": 35969974,
"question_date": "2016-03-13T12:03:30.667Z",
"question_score": 233,
"tags": "javascript|ecmascript-6|vue.js",
"answer_id": 35970020,
"answer_date": "2016-03-13T12:08:35.613Z",
"answer_score": 205
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.