input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: cannot convert data (type interface {}) to type string: need type assertion
<p>I am pretty new to go and I was playing with this <a href="https://github.com/bitly/go-notify/blob/master/notify.go" rel="noreferrer">notify</a> package.</p>
<p>At first I had code that looked like this:</p>
<pre><code>func doit(w http.ResponseWriter, r *http.Request) {
notify.Post("my_event", "Hello World!")
fmt.Fprint(w, "+OK")
}
</code></pre>
<p>I wanted to append newline to <code>Hello World!</code> but not in the function <code>doit</code> above, because that would be pretty trivial, but in the <code>handler</code> afterwards like this below:</p>
<pre><code>func handler(w http.ResponseWriter, r *http.Request) {
myEventChan := make(chan interface{})
notify.Start("my_event", myEventChan)
data := <-myEventChan
fmt.Fprint(w, data + "\n")
}
</code></pre>
<p>After <code>go run</code>:</p>
<pre><code>$ go run lp.go
# command-line-arguments
./lp.go:15: invalid operation: data + "\n" (mismatched types interface {} and string)
</code></pre>
<p>After a little bit of Googling I found <a href="https://stackoverflow.com/a/4801045/11926">this question on SO</a>.</p>
<p>Then I updated my code to:</p>
<pre><code>func handler(w http.ResponseWriter, r *http.Request) {
myEventChan := make(chan interface{})
notify.Start("my_event", myEventChan)
data := <-myEventChan
s:= data.(string) + "\n"
fmt.Fprint(w, s)
}
</code></pre>
<p>Is this what I was supposed to do? My compiler errors are gone so I guess that's pretty good? Is this efficient? Should you do it differently?</p> | <p>According to the <a href="http://golang.org/ref/spec#Type_assertions" rel="noreferrer">Go specification</a>:</p>
<blockquote>
<p>For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T.</p>
</blockquote>
<p>A "type assertion" allows you to declare an interface value contains a certain concrete type or that its concrete type satisfies another interface.</p>
<p>In your example, you were asserting data (type interface{}) has the concrete type string. If you are wrong, the program will panic at runtime. You do not need to worry about efficiency, checking just requires comparing two pointer values.</p>
<p>If you were unsure if it was a string or not, you could test using the two return syntax.</p>
<pre><code>str, ok := data.(string)
</code></pre>
<p>If data is not a string, ok will be false. It is then common to wrap such a statement into an if statement like so:</p>
<pre><code>if str, ok := data.(string); ok {
/* act on str */
} else {
/* not string */
}
</code></pre> | {
"question_id": 14289256,
"question_date": "2013-01-12T01:27:57.603Z",
"question_score": 229,
"tags": "go|type-mismatch",
"answer_id": 14289568,
"answer_date": "2013-01-12T02:25:44.003Z",
"answer_score": 350
} |
Please answer the following Stack Overflow question:
Title: Sorting a Python list by two fields
<p>I have the following list created from a sorted csv</p>
<pre><code>list1 = sorted(csv1, key=operator.itemgetter(1))
</code></pre>
<p>I would actually like to sort the list by two criteria: first by the value in field 1 and then by the value in field 2. How do I do this?</p> | <p>like this:</p>
<pre><code>import operator
list1 = sorted(csv1, key=operator.itemgetter(1, 2))
</code></pre> | {
"question_id": 5212870,
"question_date": "2011-03-06T19:36:08.090Z",
"question_score": 229,
"tags": "python|sorting",
"answer_id": 5212885,
"answer_date": "2011-03-06T19:38:25.667Z",
"answer_score": 180
} |
Please answer the following Stack Overflow question:
Title: How to insert in XSLT
<p>How can I insert</p>
<blockquote>
<p><code>&nbsp;</code></p>
</blockquote>
<p>Into an XSLT stylesheet, I keep getting this error:</p>
<blockquote>
<p>XML Parsing Error: undefined entity</p>
</blockquote>
<p>Essentially I want a non breaking space character in the XSLT Template.</p> | <p>Use the entity code <code>&#160;</code> instead.</p>
<p><code>&nbsp;</code> is a HTML "character entity reference". There is no named entity for non-breaking space in XML, so you use the code <code>&#160;</code>.</p>
<p><a href="https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references" rel="noreferrer">Wikipedia includes a list of XML and HTML entities</a>, and you can see that there are only 5 "predefined entities" in XML, but HTML has over 200. I'll also point over to <a href="https://stackoverflow.com/questions/15798957/creating-a-space-nbsp-in-xsl">Creating a space (&nbsp;) in XSL</a> which has excellent answers.</p> | {
"question_id": 1461649,
"question_date": "2009-09-22T18:05:26.657Z",
"question_score": 229,
"tags": "xslt",
"answer_id": 1461681,
"answer_date": "2009-09-22T18:09:13.203Z",
"answer_score": 362
} |
Please answer the following Stack Overflow question:
Title: URLEncoder not able to translate space character
<p>I am expecting</p>
<pre><code>System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8"));
</code></pre>
<p>to output:</p>
<p><code>Hello%20World</code></p>
<p>(20 is ASCII Hex code for space)</p>
<p>However, what I get is:</p>
<p><code>Hello+World</code></p>
<p>Am I using the wrong method? What is the correct method I should be using?</p> | <p>This behaves as expected. The <code>URLEncoder</code> implements the HTML Specifications for how to encode URLs in HTML forms.</p>
<p>From the <a href="http://download.oracle.com/javase/6/docs/api/java/net/URLEncoder.html" rel="noreferrer"><strong>javadocs</strong></a>:</p>
<blockquote>
<p>This class contains static methods for
converting a String to the
application/x-www-form-urlencoded MIME
format.</p>
</blockquote>
<p>and from the <a href="http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4" rel="noreferrer"><strong>HTML Specification</strong></a>:</p>
<blockquote>
<p><strong>application/x-www-form-urlencoded</strong> </p>
<p>Forms submitted with this content type
must be encoded as follows:</p>
<ol>
<li>Control names and values are escaped. Space characters are replaced
by `+'</li>
</ol>
</blockquote>
<p>You will have to replace it, e.g.:</p>
<pre><code>System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8").replace("+", "%20"));
</code></pre> | {
"question_id": 4737841,
"question_date": "2011-01-19T16:26:05.697Z",
"question_score": 229,
"tags": "java|url|urlencode",
"answer_id": 4737967,
"answer_date": "2011-01-19T16:37:12.243Z",
"answer_score": 249
} |
Please answer the following Stack Overflow question:
Title: How to add ID property to Html.BeginForm() in asp.net mvc?
<p>I want to validate my form using jquery but it doesn't have an <code>ID</code> property as of now how to add it to the form in asp.net mvc? I am using this...</p>
<pre><code><% using (Html.BeginForm()) {%>
</code></pre>
<p>and my jquery validator plugin takes this,</p>
<pre><code>var validator = $("#signupform").validate({
</code></pre>
<p>Now i want to give id as <code>signupform</code>... Any suggestion...</p> | <p>This should get the id added.</p>
<p>ASP.NET MVC 5 and lower:</p>
<pre><code><% using (Html.BeginForm(null, null, FormMethod.Post, new { id = "signupform" }))
{ } %>
</code></pre>
<p>ASP.NET Core: You can <a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms" rel="noreferrer">use tag helpers in forms</a> to avoid the odd syntax for setting the id.</p>
<pre><code><form asp-controller="Account" asp-action="Register" method="post" id="signupform" role="form"></form>
</code></pre> | {
"question_id": 2854616,
"question_date": "2010-05-18T04:44:49.920Z",
"question_score": 229,
"tags": "jquery|asp.net-mvc|forms",
"answer_id": 2854649,
"answer_date": "2010-05-18T04:55:30.383Z",
"answer_score": 377
} |
Please answer the following Stack Overflow question:
Title: Add up a column of numbers at the Unix shell
<p>Given a list of files in <code>files.txt</code>, I can get a list of their sizes like this:</p>
<pre><code>cat files.txt | xargs ls -l | cut -c 23-30
</code></pre>
<p>which produces something like this:</p>
<pre><code> 151552
319488
1536000
225280
</code></pre>
<p>How can I get the <strong>total</strong> of all those numbers?</p> | <pre><code>... | paste -sd+ - | bc
</code></pre>
<p>is the shortest one I've found (from the <a href="http://www.unixcl.com/2009/11/sum-of-numbers-in-file-unix.html">UNIX Command Line</a> blog).</p>
<p><strong>Edit:</strong> added the <code>-</code> argument for portability, thanks @Dogbert and @Owen.</p> | {
"question_id": 926069,
"question_date": "2009-05-29T13:50:41.453Z",
"question_score": 229,
"tags": "linux|unix|shell",
"answer_id": 18141152,
"answer_date": "2013-08-09T06:27:15.880Z",
"answer_score": 436
} |
Please answer the following Stack Overflow question:
Title: How do you delete a column by name in data.table?
<p>To get rid of a column named "foo" in a <code>data.frame</code>, I can do:</p>
<p><code>df <- df[-grep('foo', colnames(df))]</code></p>
<p>However, once <code>df</code> is converted to a <code>data.table</code> object, there is no way to just remove a column.</p>
<p>Example:</p>
<pre><code>df <- data.frame(id = 1:100, foo = rnorm(100))
df2 <- df[-grep('foo', colnames(df))] # works
df3 <- data.table(df)
df3[-grep('foo', colnames(df3))]
</code></pre>
<p>But once it is converted to a <code>data.table</code> object, this no longer works. </p> | <p>Any of the following will remove column <code>foo</code> from the data.table <code>df3</code>:</p>
<pre><code># Method 1 (and preferred as it takes 0.00s even on a 20GB data.table)
df3[,foo:=NULL]
df3[, c("foo","bar"):=NULL] # remove two columns
myVar = "foo"
df3[, (myVar):=NULL] # lookup myVar contents
# Method 2a -- A safe idiom for excluding (possibly multiple)
# columns matching a regex
df3[, grep("^foo$", colnames(df3)):=NULL]
# Method 2b -- An alternative to 2a, also "safe" in the sense described below
df3[, which(grepl("^foo$", colnames(df3))):=NULL]
</code></pre>
<p><strong>data.table</strong> also supports the following syntax:</p>
<pre><code>## Method 3 (could then assign to df3,
df3[, !"foo"]
</code></pre>
<p>though if you were actually wanting to remove column <code>"foo"</code> from <code>df3</code> (as opposed to just printing a view of <code>df3</code> minus column <code>"foo"</code>) you'd really want to use Method 1 instead.</p>
<p>(Do note that if you use a method relying on <code>grep()</code> or <code>grepl()</code>, you need to set <code>pattern="^foo$"</code> rather than <code>"foo"</code>, if you don't want columns with names like <code>"fool"</code> and <code>"buffoon"</code> (i.e. those containing <code>foo</code> as a substring) to also be matched and removed.)</p>
<h3>Less safe options, fine for interactive use:</h3>
<p>The next two idioms will also work -- <strong>if <code>df3</code> contains a column matching <code>"foo"</code></strong> -- but will fail in a probably-unexpected way if it does not. If, for instance, you use any of them to search for the non-existent column <code>"bar"</code>, you'll end up with a zero-row data.table.</p>
<p>As a consequence, they are really best suited for interactive use where one might, e.g., want to display a data.table minus any columns with names containing the substring <code>"foo"</code>. For programming purposes (or if you are wanting to actually remove the column(s) from <code>df3</code> rather than from a copy of it), Methods 1, 2a, and 2b are really the best options.</p>
<pre><code># Method 4:
df3[, .SD, .SDcols = !patterns("^foo$")]
</code></pre>
<hr>
<p>Lastly there are approaches using <code>with=FALSE</code>, though <code>data.table</code> is gradually moving away from using this argument so it's now discouraged where you can avoid it; showing here so you know the option exists in case you really do need it:</p>
<pre><code># Method 5a (like Method 3)
df3[, !"foo", with=FALSE]
# Method 5b (like Method 4)
df3[, !grep("^foo$", names(df3)), with=FALSE]
# Method 5b (another like Method 4)
df3[, !grepl("^foo$", names(df3)), with=FALSE]
</code></pre> | {
"question_id": 9202413,
"question_date": "2012-02-08T22:20:31.203Z",
"question_score": 229,
"tags": "r|data.table",
"answer_id": 9202485,
"answer_date": "2012-02-08T22:27:00.460Z",
"answer_score": 334
} |
Please answer the following Stack Overflow question:
Title: Getting assembly name
<p>C#'s exception class has a source property which is set to the name of the assembly by default.<br>
Is there another way to get this exact string (without parsing a different string)? </p>
<p>I have tried the following:</p>
<pre><code>catch(Exception e)
{
string str = e.Source;
//"EPA" - what I want
str = System.Reflection.Assembly.GetExecutingAssembly().FullName;
//"EPA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
str = typeof(Program).FullName;
//"EPA.Program"
str = typeof(Program).Assembly.FullName;
//"EPA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
str = typeof(Program).Assembly.ToString();
//"EPA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
str = typeof(Program).AssemblyQualifiedName;
//"EPA.Program, EPA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
}
</code></pre> | <pre><code>System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
</code></pre>
<p>or</p>
<pre><code>typeof(Program).Assembly.GetName().Name;
</code></pre> | {
"question_id": 4266202,
"question_date": "2010-11-24T11:24:03.060Z",
"question_score": 229,
"tags": "c#|.net|reflection|assemblyinfo",
"answer_id": 4266261,
"answer_date": "2010-11-24T11:30:10.493Z",
"answer_score": 424
} |
Please answer the following Stack Overflow question:
Title: Edit and replay XHR chrome/firefox etc?
<p>I have been looking for a way to alter a <code>XHR request</code> made in my browser and then replay it again.</p>
<p>Say I have a complete <code>POST</code> request done in my browser, and the only thing I want to change is a small value and then play it again.
This would be a lot easier and faster to do directly in the browser.</p>
<p>I have googled a bit around, and haven't found a way to do this in Chrome or Firefox.</p>
<p>Is there some way to do it in either one of those browsers, or maybe another one?</p> | <p><strong>Chrome :</strong></p>
<ul>
<li>In the Network panel of devtools, right-click and select <em>Copy as cURL</em></li>
<li>Paste / Edit the request, and then send it from a terminal, assuming you have the <code>curl</code> command</li>
</ul>
<p>See capture :</p>
<p><img src="https://i.stack.imgur.com/zcWIu.png" alt="enter image description here"></p>
<p>Alternatively, and <strong>in case you need to send the request in the context of a webpage</strong>, select <em>"Copy as fetch"</em> and edit-send the content from the javascript console panel.</p>
<p><br></p>
<p><strong>Firefox :</strong> </p>
<p>Firefox allows to edit and resend XHR right from the Network panel. Capture below is from Firefox 36:</p>
<p><img src="https://i.stack.imgur.com/8hBvg.png" alt="enter image description here"></p> | {
"question_id": 28775123,
"question_date": "2015-02-27T22:03:35.837Z",
"question_score": 229,
"tags": "google-chrome|firefox|browser|xmlhttprequest",
"answer_id": 28775346,
"answer_date": "2015-02-27T22:21:08.747Z",
"answer_score": 285
} |
Please answer the following Stack Overflow question:
Title: How are echo and print different in PHP?
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/7094118/reference-comparing-phps-print-and-echo">Reference: Comparing PHP's print and echo</a> </p>
</blockquote>
<p>Is there any major and fundamental difference between these two functions in PHP?</p> | <p>From:
<a href="http://web.archive.org/web/20090221144611/http://faqts.com/knowledge_base/view.phtml/aid/1/fid/40" rel="noreferrer">http://web.archive.org/web/20090221144611/http://faqts.com/knowledge_base/view.phtml/aid/1/fid/40</a></p>
<ol>
<li><p>Speed. There is a difference between the two, but speed-wise it
should be irrelevant which one you use. echo is marginally faster
since it doesn't set a return value if you really want to get down to the
nitty gritty. </p></li>
<li><p>Expression. <code>print()</code> behaves like a function in that you can do:
<code>$ret = print "Hello World"</code>; And <code>$ret</code> will be <code>1</code>. That means that print
can be used as part of a more complex expression where echo cannot. An
example from the PHP Manual:</p></li>
</ol>
<pre class="lang-php prettyprint-override"><code>$b ? print "true" : print "false";
</code></pre>
<p>print is also part of the precedence table which it needs to be if it
is to be used within a complex expression. It is just about at the bottom
of the precedence list though. Only <code>,</code> <code>AND</code> <code>OR</code> <code>XOR</code> are lower.</p>
<ol start="3">
<li>Parameter(s). The grammar is: <code>echo expression [, expression[,
expression] ... ]</code> But <code>echo ( expression, expression )</code> is not valid.
This would be valid: <code>echo ("howdy"),("partner")</code>; the same as: <code>echo
"howdy","partner"</code>; (Putting the brackets in that simple example
serves
no purpose since there is no operator precedence issue with a single
term like that.)</li>
</ol>
<p>So, echo without parentheses can take multiple parameters, which get
concatenated:</p>
<pre><code> echo "and a ", 1, 2, 3; // comma-separated without parentheses
echo ("and a 123"); // just one parameter with parentheses
</code></pre>
<p><code>print()</code> can only take one parameter:</p>
<pre><code> print ("and a 123");
print "and a 123";
</code></pre> | {
"question_id": 234241,
"question_date": "2008-10-24T16:25:12.767Z",
"question_score": 229,
"tags": "php|echo",
"answer_id": 234255,
"answer_date": "2008-10-24T16:27:56.393Z",
"answer_score": 296
} |
Please answer the following Stack Overflow question:
Title: INSERT ... ON DUPLICATE KEY (do nothing)
<p>I have a table with a unique key for two columns:</p>
<pre><code>CREATE TABLE `xpo`.`user_permanent_gift` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`fb_user_id` INT UNSIGNED NOT NULL ,
`gift_id` INT UNSIGNED NOT NULL ,
`purchase_timestamp` TIMESTAMP NULL DEFAULT now() ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `user_gift_UNIQUE` (`fb_user_id` ASC, `gift_id` ASC) );
</code></pre>
<p>I want to insert a row into that table, but if the key exists, to do nothing! I don't want an error to be generated because the keys exist.</p>
<p>I know that there is the following syntax:</p>
<pre><code>INSERT ... ON DUPLICATE KEY UPDATE ...
</code></pre>
<p>but is there something like:</p>
<pre><code>INSERT ... ON DUPLICATE KEY DO NOTHING
</code></pre>
<p>?</p> | <p>Yes, use <code>INSERT ... ON DUPLICATE KEY UPDATE id=id</code> (it won't trigger row update even though <code>id</code> is assigned to itself).</p>
<p>If you don't care about errors (conversion errors, foreign key errors) and autoincrement field exhaustion (it's incremented even if the row is not inserted due to duplicate key), then use <code>INSERT IGNORE</code> like this:</p>
<pre><code>INSERT IGNORE INTO <table_name> (...) VALUES (...)
</code></pre> | {
"question_id": 4596390,
"question_date": "2011-01-04T17:13:28.567Z",
"question_score": 229,
"tags": "mysql|sql|unique-key",
"answer_id": 4596409,
"answer_date": "2011-01-04T17:15:05.620Z",
"answer_score": 404
} |
Please answer the following Stack Overflow question:
Title: Rendering a template variable as HTML
<p>I use the 'messages' interface to pass messages to user like this:</p>
<pre><code>request.user.message_set.create(message=message)
</code></pre>
<p>I would like to include html in my <code>{{ message }}</code> variable and render it without escaping the markup in the template.</p> | <p>If you don't want the HTML to be escaped, look at the <code>safe</code> filter and the <code>autoescape</code> tag:</p>
<p><a href="http://docs.djangoproject.com/en/stable/ref/templates/builtins/#safe" rel="noreferrer"><code>safe</code></a>:</p>
<pre><code>{{ myhtml |safe }}
</code></pre>
<p><a href="http://docs.djangoproject.com/en/stable/ref/templates/builtins/#autoescape" rel="noreferrer"><code>autoescape</code></a>:</p>
<pre><code>{% autoescape off %}
{{ myhtml }}
{% endautoescape %}
</code></pre> | {
"question_id": 4848611,
"question_date": "2011-01-31T07:40:00Z",
"question_score": 229,
"tags": "django|django-templates",
"answer_id": 4848661,
"answer_date": "2011-01-31T07:49:14.047Z",
"answer_score": 429
} |
Please answer the following Stack Overflow question:
Title: How do I write good/correct package __init__.py files
<p>My package has the following structure:</p>
<pre><code>mobilescouter/
__init__.py #1
mapper/
__init__.py #2
lxml/
__init__.py #3
vehiclemapper.py
vehiclefeaturemapper.py
vehiclefeaturesetmapper.py
...
basemapper.py
vehicle/
__init__.py #4
vehicle.py
vehiclefeature.py
vehiclefeaturemapper.py
...
</code></pre>
<p>I'm not sure how the <code>__init__.py</code> files should be correctly written.<br/> The <code>__init__.py #1</code> looks like:</p>
<pre><code>__all__ = ['mapper', 'vehicle']
import mapper
import vehicle
</code></pre>
<p>But how should for example <code>__init__.py #2</code> look like? Mine is:</p>
<pre><code>__all__ = ['basemapper', 'lxml']
from basemaper import *
import lxml
</code></pre>
<p>When should be <code>__all__</code> used? </p> | <p><code>__all__</code> is very good - it helps guide import statements without automatically importing modules
<a href="http://docs.python.org/tutorial/modules.html#importing-from-a-package" rel="noreferrer">http://docs.python.org/tutorial/modules.html#importing-from-a-package</a></p>
<p>using <code>__all__</code> and <code>import *</code> is redundant, only <code>__all__</code> is needed</p>
<p>I think one of the most powerful reasons to use <code>import *</code> in an <code>__init__.py</code> to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave <code>__init__.py</code> files empty.</p>
<p>for example:</p>
<pre><code>foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo
</code></pre>
<p>then the app grows and now it's a whole folder</p>
<pre><code>foo/
__init__.py
foofactories.py
tallFoos.py
shortfoos.py
mediumfoos.py
santaslittlehelperfoo.py
superawsomefoo.py
anotherfoo.py
</code></pre>
<p>then the init script can say</p>
<pre><code>__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo
</code></pre>
<p>so that a script written to do the following does not break during the change:</p>
<pre><code>from foo import fooFactory, tallFoo, shortFoo
</code></pre> | {
"question_id": 1944569,
"question_date": "2009-12-22T06:48:52.580Z",
"question_score": 229,
"tags": "python|package",
"answer_id": 1947834,
"answer_date": "2009-12-22T17:16:14.327Z",
"answer_score": 173
} |
Please answer the following Stack Overflow question:
Title: nginx missing sites-available directory
<p>I installed Nginx on Centos 6 and I am trying to set up virtual hosts. The problem I am having is that I can't seem to find the <code>/etc/nginx/sites-available</code> directory.</p>
<p>Is there something I need to do in order to create it? I know Nginx is up and running because I can browse to it.</p> | <p>Well, I think nginx by itself doesn't have that in its setup, because the Ubuntu-maintained package does it as a convention to imitate Debian's apache setup. You could create it yourself if you wanted to emulate the same setup.</p>
<p>Create <code>/etc/nginx/sites-available</code> and <code>/etc/nginx/sites-enabled</code> and then edit the <code>http</code> block inside <code>/etc/nginx/nginx.conf</code> and add this line</p>
<pre><code>include /etc/nginx/sites-enabled/*;
</code></pre>
<p>Of course, all the files will be inside <code>sites-available</code>, and you'd create a symlink for them inside <code>sites-enabled</code> for those you want enabled.</p> | {
"question_id": 17413526,
"question_date": "2013-07-01T20:54:25.137Z",
"question_score": 229,
"tags": "nginx|centos|virtualhost",
"answer_id": 17415606,
"answer_date": "2013-07-02T00:23:23.757Z",
"answer_score": 437
} |
Please answer the following Stack Overflow question:
Title: Understanding colors on Android (six characters)
<p>I am trying to understand how colors work in Android. I have this color set as the background of my <code>LinearLayout</code>, and I get a background gray with some transparency:</p>
<pre><code><gradient android:startColor="#b4555555" android:endColor="#b4555555"
android:angle="270.0" />
</code></pre>
<p>If I remove the last two characters (55) I get a solid color, losing the transparency. I was trying to find a page where I can see some explanation about this, but I couldn't find it. </p> | <p>If you provide 6 hex digits, that means RGB (2 hex digits for each value of red, green and blue).</p>
<p>If you provide 8 hex digits, it's an ARGB (2 hex digits for each value of alpha, red, green and blue respectively).</p>
<p>So by removing the final 55 you're changing from A=B4, R=55, G=55, B=55 (a mostly transparent grey), to R=B4, G=55, B=55 (a fully-non-transparent dusky pinky).</p>
<p>See the <a href="http://developer.android.com/guide/topics/resources/more-resources.html#Color" rel="noreferrer">"Color" documentation</a> for the supported formats.</p> | {
"question_id": 5445085,
"question_date": "2011-03-26T20:28:32.050Z",
"question_score": 229,
"tags": "android|colors|hex|transparency",
"answer_id": 5445108,
"answer_date": "2011-03-26T20:32:20.917Z",
"answer_score": 175
} |
Please answer the following Stack Overflow question:
Title: Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"
<p>I would like install R on my laptop Mac OS X version 10.7.3</p>
<p>I downloaded the last version and I double click on it and it was installed, when i start up I get the following error, I searched in internet but I could not solve the problem, any help would be appreciated </p>
<p>the errors are </p>
<blockquote>
<p>During startup - Warning messages:<br>
1: Setting LC_CTYPE failed, using "C"<br>
2: Setting LC_COLLATE failed, using "C"<br>
3: Setting LC_TIME failed, using "C"<br>
4: Setting LC_MESSAGES failed, using "C"<br>
5: Setting LC_PAPER failed, using "C"<br>
[R.app GUI 1.50 (6126) x86_64-apple-darwin9.8.0] </p>
<p>WARNING: You're using a non-UTF8 locale, therefore only ASCII characters will work.
Please read R for Mac OS X FAQ (see Help) section 9 and adjust your system preferences accordingly.
[History restored from /Users/nemo/.Rapp.history]</p>
</blockquote> | <ol>
<li>Open Terminal</li>
<li>Write or paste in: <code>defaults write org.R-project.R force.LANG en_US.UTF-8</code></li>
<li>Close Terminal (including any RStudio window)</li>
<li>Start R</li>
</ol>
<hr />
<p>For someone runs R in a docker environment (under root), try to run R with below command,</p>
<pre class="lang-sh prettyprint-override"><code>LC_ALL=C.UTF-8 R
# instead of just `R`
</code></pre> | {
"question_id": 9689104,
"question_date": "2012-03-13T17:35:38.297Z",
"question_score": 229,
"tags": "macos|r|installation",
"answer_id": 17510093,
"answer_date": "2013-07-07T07:24:34.583Z",
"answer_score": 489
} |
Please answer the following Stack Overflow question:
Title: Deleting all pending tasks in celery / rabbitmq
<p>How can I delete all pending tasks without knowing the <code>task_id</code> for each task?</p> | <p>From the <a href="http://docs.celeryproject.org/en/latest/faq.html?highlight=purge#how-do-i-purge-all-waiting-tasks" rel="noreferrer">docs</a>:</p>
<pre><code>$ celery -A proj purge
</code></pre>
<p>or</p>
<pre><code>from proj.celery import app
app.control.purge()
</code></pre>
<p>(EDIT: Updated with current method.)</p> | {
"question_id": 7149074,
"question_date": "2011-08-22T14:35:22.407Z",
"question_score": 229,
"tags": "task|rabbitmq|celery|celery-task",
"answer_id": 7155348,
"answer_date": "2011-08-23T01:20:23.907Z",
"answer_score": 373
} |
Please answer the following Stack Overflow question:
Title: Angular 2 Unit Tests: Cannot find name 'describe'
<p>I'm following <a href="https://angular.io/docs/ts/latest/guide/testing.html#!#jasmine-101" rel="noreferrer">this tutorial from angular.io</a></p>
<p>As they said, I've created hero.spec.ts file to create unit tests:</p>
<pre><code>import { Hero } from './hero';
describe('Hero', () => {
it('has name', () => {
let hero: Hero = {id: 1, name: 'Super Cat'};
expect(hero.name).toEqual('Super Cat');
});
it('has id', () => {
let hero: Hero = {id: 1, name: 'Super Cat'};
expect(hero.id).toEqual(1);
});
});
</code></pre>
<p>Unit Tests work like a charm. The problem is: I see some errors, which are mentioned in tutorial:</p>
<blockquote>
<p>Our editor and the compiler may complain that they don’t know what <code>it</code>
and <code>expect</code> are because they lack the typing files that describe
Jasmine. We can ignore those annoying complaints for now as they are
harmless.</p>
</blockquote>
<p>And they indeed ignored it. Even though those errors are harmless, it doesn't look good in my output console when I receive bunch of them.</p>
<p>Example of what I get:</p>
<blockquote>
<p>Cannot find name 'describe'.</p>
<p>Cannot find name 'it'.</p>
<p>Cannot find name 'expect'.</p>
</blockquote>
<p>What can I do to fix it?</p> | <p>I hope you've installed -</p>
<pre><code>npm install --save-dev @types/jasmine
</code></pre>
<p>Then put following import at the top of the <code>hero.spec.ts</code> file -</p>
<pre><code>import 'jasmine';
</code></pre>
<p>It should solve the problem.</p> | {
"question_id": 39020022,
"question_date": "2016-08-18T13:51:46.870Z",
"question_score": 229,
"tags": "unit-testing|angular|typescript|jasmine",
"answer_id": 39945169,
"answer_date": "2016-10-09T15:18:48.220Z",
"answer_score": 421
} |
Please answer the following Stack Overflow question:
Title: How to express a NOT IN query with ActiveRecord/Rails?
<p>I'm hoping there is a easy solution that doesn't involve <code>find_by_sql</code>, if not then I guess that will have to work.</p>
<p>I found <a href="http://trevorturk.com/2007/03/19/active-record-and-the-in-clause/" rel="noreferrer">this article</a> which references this:</p>
<pre><code>Topic.find(:all, :conditions => { :forum_id => @forums.map(&:id) })
</code></pre>
<p>which is the same as</p>
<pre><code>SELECT * FROM topics WHERE forum_id IN (<@forum ids>)
</code></pre>
<p>I am wondering if there is a way to do <code>NOT IN</code> with that, like:</p>
<pre><code>SELECT * FROM topics WHERE forum_id NOT IN (<@forum ids>)
</code></pre> | <p>Rails 4+:</p>
<pre><code>Article.where.not(title: ['Rails 3', 'Rails 5'])
</code></pre>
<p>Rails 3:</p>
<pre><code>Topic.where('id NOT IN (?)', Array.wrap(actions))
</code></pre>
<p>Where <code>actions</code> is an array with: <code>[1,2,3,4,5]</code></p> | {
"question_id": 4307411,
"question_date": "2010-11-29T19:46:30.153Z",
"question_score": 229,
"tags": "ruby-on-rails|rails-activerecord",
"answer_id": 6817170,
"answer_date": "2011-07-25T13:51:36.197Z",
"answer_score": 349
} |
Please answer the following Stack Overflow question:
Title: Remove an onclick listener
<p>I have an object where the text cycles and displays status messages. When the messages change, I want the click event of the object to change to take you to the activity that the message is relating to.</p>
<p>So, I have a <code>TextView mTitleView</code> and I'm assigning the event like this.</p>
<pre><code>public void setOnTitleClickListener(OnClickListener listener) {
mTitleView.setOnClickListener(listener);
}
</code></pre>
<p>How do I remove that click event? There are some status messages that do not have an actionable area so I'd like to turn off the click event. I'd also like to be able to cycle through these click events and dispose of them properly, but I'm unsure of the best practice.</p> | <p><code>mTitleView.setOnClickListener(null)</code> should do the trick.</p>
<p>A better design might be to do a check of the status in the OnClickListener and then determine whether or not the click should do something vs adding and clearing click listeners.</p> | {
"question_id": 5195321,
"question_date": "2011-03-04T14:57:05.917Z",
"question_score": 229,
"tags": "android|onclick|textview|listener",
"answer_id": 5195379,
"answer_date": "2011-03-04T15:01:27.623Z",
"answer_score": 486
} |
Please answer the following Stack Overflow question:
Title: JS generate random boolean
<p>Simple question, but I'm interested in the nuances here.</p>
<p>I'm generating random booleans using the following method I came up with myself:</p>
<pre><code>const rand = Boolean(Math.round(Math.random()));
</code></pre>
<p>Whenever <code>random()</code> shows up, it seems there's always a pitfall - it's not truly random, it's compromised by something or other, etc. So, I'd like to know:</p>
<p>a) Is the above the best-practice way to do it? </p>
<p>b) Am I overthinking things? </p>
<p>c) Am I underthinking things? </p>
<p>d) Is there a better/faster/elegant-er way I don't know of?</p>
<p>(Also somewhat interested if B and C are mutually exclusive.)</p>
<p><em>Update</em></p>
<p>If it makes a difference, I'm using this for movement of an AI character.</p> | <p>You can compare <code>Math.random()</code> to <code>0.5</code> directly, as the range of <code>Math.random()</code> is <code>[0, 1)</code> (this means 'in the range 0 to 1 including 0, but not 1'). You can divide the range into <code>[0, 0.5)</code> and <code>[0.5, 1)</code>.</p>
<pre><code>var random_boolean = Math.random() < 0.5;
</code></pre>
<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>// Example
console.log(Math.random() < 0.1); //10% probability of getting true
console.log(Math.random() < 0.4); //40% probability of getting true
console.log(Math.random() < 0.5); //50% probability of getting true
console.log(Math.random() < 0.8); //80% probability of getting true
console.log(Math.random() < 0.9); //90% probability of getting true</code></pre>
</div>
</div>
</p> | {
"question_id": 36756331,
"question_date": "2016-04-20T22:27:53.943Z",
"question_score": 229,
"tags": "javascript|random|boolean",
"answer_id": 36756480,
"answer_date": "2016-04-20T22:39:54.440Z",
"answer_score": 584
} |
Please answer the following Stack Overflow question:
Title: How can I get the iOS 7 default blue color programmatically?
<p>I'm creating custom elements in my app and want to match the look and feel of the new iOS. iOS 7 introduced to us a very common lighter blue color, the default color or tint for several elements, including the system button, segmented control, etc. They've made it easy to select the color using IB, as seen here:</p>
<p><img src="https://i.stack.imgur.com/deFsk.png" alt="enter image description here"></p>
<p>However, I haven't found how to easily access the color programmatically. I checked out the <a href="https://developer.apple.com/library/ios/DOCUMENTATION/UIKit/Reference/UIColor_Class/Reference/Reference.html">UIColor documentation</a>, and there doesn't seem to be any accessor for the blue system color in the class itself.</p>
<p>Here's my question: does a simple accessor exist for this color? <code>[UIColor ?]</code> or something like it? If not, does someone know the exact <strong>RGB values</strong> for that color?</p> | <p>Use <code>self.view.tintColor</code> from a view controller, or <code>self.tintColor</code> from a <code>UIView</code> subclass.</p> | {
"question_id": 19032940,
"question_date": "2013-09-26T15:51:20.560Z",
"question_score": 229,
"tags": "ios|colors|ios7|uicolor",
"answer_id": 19033326,
"answer_date": "2013-09-26T16:10:49.860Z",
"answer_score": 257
} |
Please answer the following Stack Overflow question:
Title: How do I print the elements of a C++ vector in GDB?
<p>I want to examine the contents of a <code>std::vector</code> in GDB, how do I do it? Let's say it's a <code>std::vector<int></code> for the sake of simplicity.</p> | <p>To view vector std::vector myVector contents, just type in GDB:</p>
<pre><code>(gdb) print myVector
</code></pre>
<p>This will produce an output similar to:</p>
<pre><code>$1 = std::vector of length 3, capacity 4 = {10, 20, 30}
</code></pre>
<p>To achieve above, you need to have gdb 7 (I tested it on gdb 7.01) and some python pretty-printer. Installation process of these is described on <a href="https://sourceware.org/gdb/wiki/STLSupport" rel="nofollow noreferrer">gdb wiki</a>.</p>
<p>What is more, after installing above, this works well with <strong>Eclipse</strong> C++ debugger GUI (and any other IDE using GDB, as I think).</p> | {
"question_id": 253099,
"question_date": "2008-10-31T10:33:14.180Z",
"question_score": 229,
"tags": "c++|debugging|stl|vector|gdb",
"answer_id": 2123260,
"answer_date": "2010-01-23T13:23:51.787Z",
"answer_score": 83
} |
Please answer the following Stack Overflow question:
Title: Word wrapping in PhpStorm
<p>How can I enable <em>word</em> wrapping in PhpStorm?</p>
<p>I need to enable it only for some of my files (with extension .txt). Is it possible?</p> | <p><strong>For all files</strong> (default setting for opened files): <em>Settings/Preferences</em> → <em>Editor</em> → <em>General</em> → <em>Use soft wraps in editor</em>. You can now specify file names/extensions where this option will be enabled by default:</p>
<p><a href="https://i.stack.imgur.com/kk723.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kk723.png" alt="Enter image description here" /></a></p>
<hr />
<p><strong>For the currently opened file</strong> in the editor: menu → <em>View</em> → <em>Active Editor</em> → <em>Use Soft Wraps</em> <em>(Note: I've assigned custom <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>R</kbd> + shortcut for that)</em></p>
<p><a href="https://i.stack.imgur.com/OfbHP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OfbHP.png" alt="Enter image description here" /></a></p>
<p>For quite a while (since v2016 or so) you can also access this option via the context menu for the editor gutter area (the area with line numbers on the left side of the editor):</p>
<p><a href="https://i.stack.imgur.com/UViKn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UViKn.png" alt="Enter image description here" /></a></p>
<p><em>(Note: I have customised this menu quite a bit; by default it has much less items here)</em></p>
<hr />
<p><em>Search Everywhere</em> (<kbd>Shift 2x times</kbd>) or menu <em>Help</em> → <em>Find Action...</em> (<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>A</kbd> on Windows using the Default keymap) can also be used to quickly change this option (instead of going into <em>Settings/Preferences</em>).</p>
<p><a href="https://i.stack.imgur.com/oDkSW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/oDkSW.png" alt="Enter image description here" /></a></p> | {
"question_id": 10351608,
"question_date": "2012-04-27T13:33:53.853Z",
"question_score": 229,
"tags": "intellij-idea|pycharm|phpstorm|webstorm|jetbrains-ide",
"answer_id": 10352166,
"answer_date": "2012-04-27T14:05:47.190Z",
"answer_score": 458
} |
Please answer the following Stack Overflow question:
Title: if A vs if A is not None:
<p>Can I use:</p>
<pre><code>if A:
</code></pre>
<p>instead of </p>
<pre><code>if A is not None:
</code></pre>
<p>The latter seems so verbose. Is there a difference?</p> | <p>The statement</p>
<pre><code>if A:
</code></pre>
<p>will call <code>A.__bool__()</code> (see <a href="http://docs.python.org/reference/datamodel.html#object.__bool__" rel="noreferrer">Special method names</a> documentation), which was called <code>__nonzero__</code> in Python 2, and use the return value of that function. Here's the summary:</p>
<blockquote>
<h3><code>object.__bool__(self)</code></h3>
<p>Called to implement truth value testing and the built-in operation <code>bool()</code>; should return <code>False</code> or <code>True</code>. When this method is not defined, <code>__len__()</code> is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither <code>__len__()</code> nor <code>__bool__()</code>, all its instances are considered true.</p>
</blockquote>
<p>On the other hand,</p>
<pre><code>if A is not None:
</code></pre>
<p>compares <em>only</em> the reference <code>A</code> with <code>None</code> to see whether it is the same or not.</p> | {
"question_id": 7816363,
"question_date": "2011-10-19T03:55:06.170Z",
"question_score": 229,
"tags": "python",
"answer_id": 7816439,
"answer_date": "2011-10-19T04:09:41.177Z",
"answer_score": 206
} |
Please answer the following Stack Overflow question:
Title: How can I get a side-by-side diff when I do "git diff"?
<p>When I type <code>git diff</code>, I'd like to see a side-by-side diff, like with <code>diff -y</code>, or like to display the diff in an interactive diff tool like <code>kdiff3</code>. How can this be done?</p> | <p>Although Git has an internal implementation of diff, you can set up an external tool instead.</p>
<p>There are two different ways to specify an external diff tool:</p>
<ol>
<li>setting the <code>GIT_EXTERNAL_DIFF</code> and the <code>GIT_DIFF_OPTS</code> environment variables.</li>
<li>configuring the external diff tool via <code>git config</code></li>
</ol>
<p><code>ymattw</code>'s answer is also pretty neat, using <code>ydiff</code></p>
<p>See also:</p>
<ul>
<li><a href="https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration" rel="noreferrer">https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration</a></li>
<li><code>git diff --help</code></li>
<li><a href="http://www.pixelbeat.org/programming/diffs/" rel="noreferrer">http://www.pixelbeat.org/programming/diffs/</a></li>
</ul>
<p>When doing a <code>git diff</code>, Git checks both the settings of above environment variables and its <code>.gitconfig</code> file.</p>
<p>By default, Git passes the following seven arguments to the diff program:</p>
<pre><code>path old-file old-hex old-mode new-file new-hex new-mode
</code></pre>
<p>You typically only need the old-file and new-file parameters. Of course most diff tools only take two file names as an argument. This means that you need to write a small wrapper-script, which takes the arguments which Git provides to the script, and hands them on to the external git program of your choice.</p>
<p>Let's say you put your wrapper-script under <code>~/scripts/my_diff.sh</code>:</p>
<pre><code>#!/bin/bash
# un-comment one diff tool you'd like to use
# side-by-side diff with custom options:
# /usr/bin/sdiff -w200 -l "$2" "$5"
# using kdiff3 as the side-by-side diff:
# /usr/bin/kdiff3 "$2" "$5"
# using Meld
/usr/bin/meld "$2" "$5"
# using VIM
# /usr/bin/vim -d "$2" "$5"
</code></pre>
<p>you then need to make that script executable:</p>
<pre><code>chmod a+x ~/scripts/my_diff.sh
</code></pre>
<p>you then need to tell Git how and where to find your custom diff wrapper script.
You have three choices how to do that: (I prefer editing the .gitconfig file)</p>
<ol>
<li><p>Using <code>GIT_EXTERNAL_DIFF</code>, <code>GIT_DIFF_OPTS</code></p>
<p>e.g. in your .bashrc or .bash_profile file you can set:</p>
<pre><code> GIT_EXTERNAL_DIFF=$HOME/scripts/my_diff.sh
export GIT_EXTERNAL_DIFF
</code></pre>
</li>
<li><p>Using <code>git config</code></p>
<p>use "git config" to define where your wrapper script can be found:</p>
<pre><code> git config --global diff.external ~/scripts/my_diff.sh
</code></pre>
</li>
<li><p>Editing your <code>~/.gitconfig</code> file</p>
<p>you can edit your <code>~/.gitconfig</code> file to add these lines:</p>
<pre><code> [diff]
external = ~/scripts/my_diff.sh
</code></pre>
</li>
</ol>
<p>Note:</p>
<p>Similarly to installing your custom diff tool, you can also install a custom merge-tool, which could be a visual merging tool to better help visualizing the merge. (see the progit.org page)</p>
<p>See: <a href="http://fredpalma.com/518/visual-diff-and-merge-tool/" rel="noreferrer">http://fredpalma.com/518/visual-diff-and-merge-tool/</a> and <a href="https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration" rel="noreferrer">https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration</a></p> | {
"question_id": 7669963,
"question_date": "2011-10-06T03:10:00.640Z",
"question_score": 229,
"tags": "git|git-diff|code-visualization",
"answer_id": 7669988,
"answer_date": "2011-10-06T03:14:03.527Z",
"answer_score": 98
} |
Please answer the following Stack Overflow question:
Title: Stop UIWebView from "bouncing" vertically?
<p>Does anyone know how to stop a UIWebView from bouncing vertically? I mean when a user touches their iphone screen, drags their finger downwards, and the webview shows a blank spot above the web page I had loaded?</p>
<p>I've looked at the following possible solutions, but none of them worked for me:</p>
<p><a href="http://www.iphonedevsdk.com/forum/iphone-sdk-development/996-turn-off-scrolling-bounces-uiwebview.html" rel="noreferrer">http://www.iphonedevsdk.com/forum/iphone-sdk-development/996-turn-off-scrolling-bounces-uiwebview.html</a></p>
<p><a href="http://forums.macrumors.com/showthread.php?t=619534" rel="noreferrer">http://forums.macrumors.com/showthread.php?t=619534</a></p>
<p><a href="https://stackoverflow.com/questions/173786/how-do-i-stop-a-uiscrollview-from-bouncing-horizontally">How do I stop a UIScrollView from bouncing horizontally?</a></p> | <pre><code>for (id subview in webView.subviews)
if ([[subview class] isSubclassOfClass: [UIScrollView class]])
((UIScrollView *)subview).bounces = NO;
</code></pre>
<p>...seems to work fine.</p>
<p>It'll be accepted to App Store as well.</p>
<p><strong>Update</strong>: in iOS 5.x+ there's an easier way - <code>UIWebView</code> has <code>scrollView</code> property, so your code can look like this:</p>
<pre><code>webView.scrollView.bounces = NO;
</code></pre>
<p>Same goes for <code>WKWebView</code>.</p> | {
"question_id": 500761,
"question_date": "2009-02-01T13:08:30.940Z",
"question_score": 229,
"tags": "ios|objective-c|iphone|uiscrollview|uiwebview",
"answer_id": 3324886,
"answer_date": "2010-07-24T11:22:43.423Z",
"answer_score": 429
} |
Please answer the following Stack Overflow question:
Title: What is the easiest way to push an element to the beginning of the array?
<p>I can't think of a one line way to do this. Is there a way?</p> | <p>What about using the <a href="http://www.ruby-doc.org/core/Array.html#method-i-unshift" rel="noreferrer"><code>unshift</code></a> method?</p>
<blockquote>
<p><code>ary.unshift(obj, ...) → ary</code><br>
Prepends objects to the front of self, moving other elements upwards.</p>
</blockquote>
<p>And in use:</p>
<pre><code>irb>> a = [ 0, 1, 2]
=> [0, 1, 2]
irb>> a.unshift('x')
=> ["x", 0, 1, 2]
irb>> a.inspect
=> "["x", 0, 1, 2]"
</code></pre> | {
"question_id": 6085518,
"question_date": "2011-05-22T01:42:27.830Z",
"question_score": 229,
"tags": "arrays|ruby",
"answer_id": 6085543,
"answer_date": "2011-05-22T01:48:35.680Z",
"answer_score": 426
} |
Please answer the following Stack Overflow question:
Title: How to convert a color integer to a hex String in Android?
<p>I have an integer that was generated from an <code>android.graphics.Color</code></p>
<p>The Integer has a value of -16776961</p>
<p>How do I convert this value into a hex string with the format #RRGGBB</p>
<p>Simply put: I would like to output #0000FF from -16776961</p>
<p><strong>Note:</strong> I do not want the output to contain an alpha and i have also tried <a href="https://stackoverflow.com/questions/4506708/android-convert-color-int-to-hexa-string">this example</a> without any success</p> | <p>The mask makes sure you only get RRGGBB, and the %06X gives you zero-padded hex (always 6 chars long):</p>
<pre><code>String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
</code></pre> | {
"question_id": 6539879,
"question_date": "2011-06-30T19:12:24.010Z",
"question_score": 229,
"tags": "java|android|string|colors|hex",
"answer_id": 6540378,
"answer_date": "2011-06-30T19:56:32.627Z",
"answer_score": 540
} |
Please answer the following Stack Overflow question:
Title: Is there a way to get a collection of all the Models in your Rails app?
<p>Is there a way that you can get a collection of all of the Models in your Rails app?</p>
<p>Basically, can I do the likes of: -</p>
<pre><code>Models.each do |model|
puts model.class.name
end
</code></pre> | <p><strong>EDIT: Look at the comments and other answers. There are smarter answers than this one! Or try to improve this one as community wiki.</strong></p>
<p>Models do not register themselves to a master object, so no, Rails does not have the list of models.</p>
<p>But you could still look in the content of the models directory of your application...</p>
<pre><code>Dir.foreach("#{RAILS_ROOT}/app/models") do |model_path|
# ...
end
</code></pre>
<p>EDIT: Another (wild) idea would be to use Ruby reflection to search for every classes that extends ActiveRecord::Base. Don't know how you can list all the classes though...</p>
<p>EDIT: Just for fun, I found a way to list all classes</p>
<pre><code>Module.constants.select { |c| (eval c).is_a? Class }
</code></pre>
<p>EDIT: Finally succeeded in listing all models without looking at directories</p>
<pre><code>Module.constants.select do |constant_name|
constant = eval constant_name
if not constant.nil? and constant.is_a? Class and constant.superclass == ActiveRecord::Base
constant
end
end
</code></pre>
<p>If you want to handle derived class too, then you will need to test the whole superclass chain. I did it by adding a method to the Class class:</p>
<pre><code>class Class
def extend?(klass)
not superclass.nil? and ( superclass == klass or superclass.extend? klass )
end
end
def models
Module.constants.select do |constant_name|
constant = eval constant_name
if not constant.nil? and constant.is_a? Class and constant.extend? ActiveRecord::Base
constant
end
end
end
</code></pre> | {
"question_id": 516579,
"question_date": "2009-02-05T16:10:15.437Z",
"question_score": 229,
"tags": "ruby-on-rails|activerecord|collections|model",
"answer_id": 516605,
"answer_date": "2009-02-05T16:17:39.543Z",
"answer_score": 104
} |
Please answer the following Stack Overflow question:
Title: Object of custom type as dictionary key
<p>What must I do to use my objects of a custom type as keys in a Python dictionary (where I don't want the "object id" to act as the key) , e.g. </p>
<pre><code>class MyThing:
def __init__(self,name,location,length):
self.name = name
self.location = location
self.length = length
</code></pre>
<p>I'd want to use MyThing's as keys that are considered the same if name and location are the same.
From C#/Java I'm used to having to override and provide an equals and hashcode method, and promise not to mutate anything the hashcode depends on.</p>
<p>What must I do in Python to accomplish this ? Should I even ? </p>
<p>(In a simple case, like here, perhaps it'd be better to just place a (name,location) tuple as key - but consider I'd want the key to be an object)</p> | <p>You need to add <a href="https://docs.python.org/3/glossary.html#term-hashable" rel="noreferrer">2 methods</a>, note <code>__hash__</code> and <code>__eq__</code>:</p>
<pre><code>class MyThing:
def __init__(self,name,location,length):
self.name = name
self.location = location
self.length = length
def __hash__(self):
return hash((self.name, self.location))
def __eq__(self, other):
return (self.name, self.location) == (other.name, other.location)
def __ne__(self, other):
# Not strictly necessary, but to avoid having both x==y and x!=y
# True at the same time
return not(self == other)
</code></pre>
<p>The Python <a href="https://docs.python.org/3/library/stdtypes.html#mapping-types-dict" rel="noreferrer">dict documentation</a> defines these requirements on key objects, i.e. they must be <a href="https://docs.python.org/3/glossary.html#term-hashable" rel="noreferrer">hashable</a>.</p> | {
"question_id": 4901815,
"question_date": "2011-02-04T18:51:40.240Z",
"question_score": 229,
"tags": "python|dictionary",
"answer_id": 4901847,
"answer_date": "2011-02-04T18:55:44.377Z",
"answer_score": 270
} |
Please answer the following Stack Overflow question:
Title: Reload the path in PowerShell
<p>If I have an instance of PowerShell ISE running and I install something that modifies the PATH or I modify it in any way outside of PowerShell then I need to restart PowerShell for it to see the updated PATH variable. </p>
<p>Is there a way to reload the path from within PowerShell without restarting it?</p> | <p>Just to bring <a href="https://stackoverflow.com/questions/17794507/reload-the-path-in-powershell#comment25967553_17794885">Rob's comment</a> to light:</p>
<pre><code>$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
</code></pre> | {
"question_id": 17794507,
"question_date": "2013-07-22T18:14:20.140Z",
"question_score": 229,
"tags": "powershell|console|powershell-ise",
"answer_id": 31845512,
"answer_date": "2015-08-06T01:44:59.080Z",
"answer_score": 336
} |
Please answer the following Stack Overflow question:
Title: Why prefer two's complement over sign-and-magnitude for signed numbers?
<p>I'm just curious if there's a reason why in order to represent -1 in binary, two's complement is used: flipping the bits and adding 1?</p>
<p>-1 is represented by 11111111 (two's complement) rather than (to me more intuitive) 10000001 which is binary 1 with first bit as negative flag.</p>
<p>Disclaimer: I don't rely on binary arithmetic for my job!</p> | <p>It's done so that addition doesn't need to have any special logic for dealing with negative numbers. Check out <a href="http://en.wikipedia.org/wiki/Two's_complement" rel="noreferrer">the article on Wikipedia</a>.</p>
<p>Say you have two numbers, 2 and -1. In your "intuitive" way of representing numbers, they would be <code>0010</code> and <code>1001</code>, respectively (I'm sticking to 4 bits for size). In the <a href="https://stackoverflow.com/q/1049722/">two's complement</a> way, they are <code>0010</code> and <code>1111</code>. Now, let's say I want to add them.</p>
<p>Two's complement addition is very simple. You add numbers normally and any carry bit at the end is discarded. So they're added as follows:</p>
<pre><code> 0010
+ 1111
=10001
= 0001 (discard the carry)
</code></pre>
<p><code>0001</code> is 1, which is the expected result of "2+(-1)".</p>
<p>But in your "intuitive" method, adding is more complicated:</p>
<pre><code> 0010
+ 1001
= 1011
</code></pre>
<p>Which is -3, right? Simple addition doesn't work in this case. You need to note that one of the numbers is negative and use a different algorithm if that's the case.</p>
<p>For this "intuitive" storage method, subtraction is a different operation than addition, requiring additional checks on the numbers before they can be added. Since you want the most basic operations (addition, subtraction, etc) to be as fast as possible, you need to store numbers in a way that lets you use the simplest algorithms possible.</p>
<p>Additionally, in the "intuitive" storage method, there are two zeroes:</p>
<pre><code>0000 "zero"
1000 "negative zero"
</code></pre>
<p>Which are intuitively the same number but have two different values when stored. Every application will need to take extra steps to make sure that non-zero values are also not negative zero.</p>
<p>There's another bonus with storing ints this way, and that's when you need to extend the width of the register the value is being stored in. With two's complement, storing a 4-bit number in an 8-bit register is a matter of repeating its most significant bit:</p>
<pre><code> 0001 (one, in four bits)
00000001 (one, in eight bits)
1110 (negative two, in four bits)
11111110 (negative two, in eight bits)
</code></pre>
<p>It's just a matter of looking at the sign bit of the smaller word and repeating it until it pads the width of the bigger word.</p>
<p>With your method you would need to clear the existing bit, which is an extra operation in addition to padding:</p>
<pre><code> 0001 (one, in four bits)
00000001 (one, in eight bits)
1010 (negative two, in four bits)
10000010 (negative two, in eight bits)
</code></pre>
<p>You still need to set those extra 4 bits in both cases, but in the "intuitive" case you need to clear the 5th bit as well. It's one tiny extra step in one of the most fundamental and common operations present in every application.</p> | {
"question_id": 1125304,
"question_date": "2009-07-14T13:15:08.303Z",
"question_score": 229,
"tags": "binary|math|twos-complement|negative-number|internal-representation",
"answer_id": 1125317,
"answer_date": "2009-07-14T13:17:17.427Z",
"answer_score": 367
} |
Please answer the following Stack Overflow question:
Title: There are multiple heroes that share the same tag within a subtree
<p>I am trying to navigate from one screen to another with route. When I hit the button for the page to move to the route provided I get the error</p>
<pre><code>I/flutter ( 8790): Another exception was thrown: There are multiple heroes that share the same tag within a subtree.
</code></pre>
<p>Here's the code:</p>
<p>Routes:</p>
<pre><code> <String, WidgetBuilder>{
'/first':(BuildContext context) =>NavigatorOne() ,
'/second':(BuildContext context) =>NavigatorTwo(),
'/third':(BuildContext context) =>NavigatorThree(),
},
Navigator.of(context).pushNamed('/first');
Navigator.of(context).pushNamed('/second');
Navigator.of(context).pushNamed('/third');
class NavigatorOne extends StatefulWidget {
@override
_NavigatorOneState createState() => _NavigatorOneState();
}
class _NavigatorOneState extends State<NavigatorOne> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Container(
color: Colors.green,
child: RaisedButton(child: Text(' one 1'),onPressed: (){
Navigator.of(context).pushNamed('/second');
},),
),
);
}
}
</code></pre>
<p>And The Error:</p>
<p><code>══╡ EXCEPTION CAUGHT BY SCHEDULER LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter (21786): The following assertion was thrown during a scheduler callback:
I/flutter (21786): There are multiple heroes that share the same tag within a subtree.
I/flutter (21786): Within each subtree for which heroes are to be animated (typically a PageRoute subtree), each Hero
I/flutter (21786): must have a unique non-null tag.
I/flutter (21786): In this case, multiple heroes had the following tag: <default FloatingActionButton tag>
</code></p>
<p>How do I solve this?</p> | <p>I have encountered this before, and it was because I had two <code>FloatingAction</code> buttons on one screen, I had to add a heroTag property + value per <code>FloatingActionButton</code> in order for the error to go away.</p>
<p>Example:</p>
<pre class="lang-dart prettyprint-override"><code>FloatingActionButton(
heroTag: "btn1",
...
)
FloatingActionButton(
heroTag: "btn2",
...
)
</code></pre>
<p>From the example code you provided it doesn't appear that you have a <code>FloatingActionButton</code>, but from the error it does seem to reference it:</p>
<pre class="lang-none prettyprint-override"><code>I/flutter (21786): In this case, multiple heroes had the following tag: default FloatingActionButton tag
</code></pre>
<p>Perhaps you used it on the page you were navigating to which then triggered the error. Note that if you're using a programmatic way of creating tagged heroes, you will need to find a way of giving them different tags. For example, if you have a <code>ListView.builder()</code> creating <code>FloatingActionButtons</code>, try passing tags with string formatting so each button has a different tag, e.g.: <code>heroTag: "btn$index"</code>.</p>
<p>In any event, hope that helps someone.</p> | {
"question_id": 51125024,
"question_date": "2018-07-01T16:21:47.393Z",
"question_score": 229,
"tags": "flutter",
"answer_id": 51359266,
"answer_date": "2018-07-16T10:03:31.317Z",
"answer_score": 580
} |
Please answer the following Stack Overflow question:
Title: What's a correct and good way to implement __hash__()?
<p>What's a correct and good way to implement <code>__hash__()</code>?</p>
<p>I am talking about the function that returns a hashcode that is then used to insert objects into hashtables aka dictionaries.</p>
<p>As <code>__hash__()</code> returns an integer and is used for "binning" objects into hashtables I assume that the values of the returned integer should be uniformly distributed for common data (to minimize collisions).
What's a good practice to get such values? Are collisions a problem?
In my case I have a small class which acts as a container class holding some ints, some floats and a string.</p> | <p>An easy, correct way to implement <code>__hash__()</code> is to use a key tuple. It won't be as fast as a specialized hash, but if you need that then you should probably implement the type in C.</p>
<p>Here's an example of using a key for hash and equality:</p>
<pre><code>class A:
def __key(self):
return (self.attr_a, self.attr_b, self.attr_c)
def __hash__(self):
return hash(self.__key())
def __eq__(self, other):
if isinstance(other, A):
return self.__key() == other.__key()
return NotImplemented
</code></pre>
<p>Also, the <a href="https://docs.python.org/3.5/reference/datamodel.html#object.__hash__" rel="noreferrer">documentation of <code>__hash__</code></a> has more information, that may be valuable in some particular circumstances.</p> | {
"question_id": 2909106,
"question_date": "2010-05-25T22:56:46.743Z",
"question_score": 229,
"tags": "python|hashtable|hashcode|dictionary",
"answer_id": 2909119,
"answer_date": "2010-05-25T22:59:52.080Z",
"answer_score": 258
} |
Please answer the following Stack Overflow question:
Title: When and why should I use a namedtuple instead of a dictionary?
<p>The standard library <code>namedtuple</code> class looks to me like a way to make tuples more like dictionaries. How do <code>namedtuple</code>s compare to <code>dict</code>s? When should we use them? Do they work with non-hashable types?</p> | <p>In <code>dict</code>s, only the keys have to be hashable, not the values. <code>namedtuple</code>s don't have keys, so hashability isn't an issue.</p>
<p>However, they have a more stringent restriction -- their key-equivalents, "field names", have to be strings.</p>
<p>Basically, if you were going to create a bunch of instances of a class like:</p>
<pre><code>class Container:
def __init__(self, name, date, foo, bar):
self.name = name
self.date = date
self.foo = foo
self.bar = bar
mycontainer = Container(name, date, foo, bar)
</code></pre>
<p>and <strong>not change the attributes after you set them in <code>__init__</code>,</strong> you could instead use</p>
<pre><code>Container = namedtuple('Container', ['name', 'date', 'foo', 'bar'])
mycontainer = Container(name, date, foo, bar)
</code></pre>
<p>as a replacement.</p>
<p>Of course, you could create a bunch of <code>dict</code>s where you used the same keys in each one, but assuming you will have only valid Python identifiers as keys and don't need mutability,</p>
<pre><code>mynamedtuple.fieldname
</code></pre>
<p>is prettier than</p>
<pre><code>mydict['fieldname']
</code></pre>
<p>and </p>
<pre><code>mynamedtuple = MyNamedTuple(firstvalue, secondvalue)
</code></pre>
<p>is prettier than</p>
<pre><code>mydict = {'fieldname': firstvalue, 'secondfield': secondvalue}
</code></pre>
<p>Finally, <code>namedtuple</code>s are ordered, unlike regular <code>dict</code>s, so you get the items in the order you defined the fields, unlike a <code>dict</code>.</p> | {
"question_id": 9872255,
"question_date": "2012-03-26T12:37:16.150Z",
"question_score": 229,
"tags": "python",
"answer_id": 9872434,
"answer_date": "2012-03-26T12:49:37.383Z",
"answer_score": 265
} |
Please answer the following Stack Overflow question:
Title: Determine if a function exists in bash
<p>Currently I'm doing some unit tests which are executed from bash. Unit tests are initialized, executed and cleaned up in a bash script. This script usualy contains an init(), execute() and cleanup() functions. But they are not mandatory. I'd like to test if they are or are not defined.</p>
<p>I did this previously by greping and seding the source, but it seemed wrong. Is there a more elegant way to do this?</p>
<p>Edit: The following sniplet works like a charm:</p>
<pre><code>fn_exists()
{
LC_ALL=C type $1 | grep -q 'shell function'
}
</code></pre> | <p>Like this: <code>[[ $(type -t foo) == function ]] && echo "Foo exists"</code></p>
<p>The built-in <code>type</code> command will tell you whether something is a function, built-in function, external command, or just not defined.</p>
<p>Additional examples:</p>
<pre class="lang-none prettyprint-override"><code>$ LC_ALL=C type foo
bash: type: foo: not found
$ LC_ALL=C type ls
ls is aliased to `ls --color=auto'
$ which type
$ LC_ALL=C type type
type is a shell builtin
$ LC_ALL=C type -t rvm
function
$ if [ -n "$(LC_ALL=C type -t rvm)" ] && [ "$(LC_ALL=C type -t rvm)" = function ]; then echo rvm is a function; else echo rvm is NOT a function; fi
rvm is a function
</code></pre> | {
"question_id": 85880,
"question_date": "2008-09-17T17:57:38.300Z",
"question_score": 229,
"tags": "bash|function|testing|scripting",
"answer_id": 85903,
"answer_date": "2008-09-17T18:00:15.283Z",
"answer_score": 238
} |
Please answer the following Stack Overflow question:
Title: How to tell git to ignore individual lines, i.e. gitignore for specific lines of code
<p><code>.gitignore</code> can ignore whole files, but is there a way to ignore specific lines of code while coding?</p>
<p>I frequently and repeatedly add the same debug lines in a project, only to have to remember to remove them before committing. I'd like to just keep the lines in the code and have git disregard them.</p> | <p>This is how you can kind of do it with <a href="https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html#_tt_filter_tt" rel="noreferrer">git filters</a>:</p>
<ol>
<li>Create/Open gitattributes file:
<ul>
<li><code><project root>/.gitattributes</code> (will be committed into repo)<br>
OR</li>
<li><code><project root>/.git/info/attributes</code> (won't be committed into repo)</li>
</ul></li>
<li>Add a line defining the files to be filtered:
<ul>
<li><code>*.rb filter=gitignore</code>, i.e. run filter named <code>gitignore</code> on all <code>*.rb</code> files</li>
</ul></li>
<li>Define the <code>gitignore</code> filter in your <code>gitconfig</code>:
<ul>
<li><code>$ git config --global filter.gitignore.clean "sed '/#gitignore$/d'"</code>, i.e. delete these lines</li>
<li><code>$ git config --global filter.gitignore.smudge cat</code>, i.e. do nothing when pulling file from repo</li>
</ul></li>
</ol>
<p>Notes:<br>
Of course, this is for ruby files, applied when a line ends with <code>#gitignore</code>, applied globally in <code>~/.gitconfig</code>. Modify this however you need for your purposes.</p>
<p>Warning!!<br>
This leaves your working file different from the repo (of course). Any checking out or rebasing will mean these lines will be lost! This trick may seem useless since these lines are repeatedly lost on check out, rebase, or pull, but I've a specific use case in order to make use of it.</p>
<p>Just <code>git stash save "proj1-debug"</code> <em>while the filter is inactive</em> (just temporarily disable it in <code>gitconfig</code> or something). This way, my debug code can always be <code>git stash apply</code>'d to my code at any time without fear of these lines ever being accidentally committed.</p>
<p>I have a possible idea for dealing with these problems, but I'll try implementing it some other time.</p>
<p>Thanks to Rudi and jw013 for mentioning git filters and gitattributes.</p> | {
"question_id": 16244969,
"question_date": "2013-04-26T20:47:17.183Z",
"question_score": 229,
"tags": "git|gitignore|ignore",
"answer_id": 16244970,
"answer_date": "2013-04-26T20:47:17.183Z",
"answer_score": 181
} |
Please answer the following Stack Overflow question:
Title: Overloading Macro on Number of Arguments
<p>I have two macros <code>FOO2</code> and <code>FOO3</code>:</p>
<pre><code>#define FOO2(x,y) ...
#define FOO3(x,y,z) ...
</code></pre>
<p>I want to define a new macro <code>FOO</code> as follows:</p>
<pre><code>#define FOO(x,y) FOO2(x,y)
#define FOO(x,y,z) FOO3(x,y,z)
</code></pre>
<p>But this doesn't work because macros do not overload on number of arguments.</p>
<p>Without modifying <code>FOO2</code> and <code>FOO3</code>, is there some way to define a macro <code>FOO</code> (using <code>__VA_ARGS__</code> or otherwise) to get the same effect of dispatching <code>FOO(x,y)</code> to <code>FOO2</code>, and <code>FOO(x,y,z)</code> to <code>FOO3</code>?</p> | <p>Simple as:</p>
<pre><code>#define GET_MACRO(_1,_2,_3,NAME,...) NAME
#define FOO(...) GET_MACRO(__VA_ARGS__, FOO3, FOO2)(__VA_ARGS__)
</code></pre>
<p>So if you have these macros, they expand as described:</p>
<pre><code>FOO(World, !) // expands to FOO2(World, !)
FOO(foo,bar,baz) // expands to FOO3(foo,bar,baz)
</code></pre>
<p>If you want a fourth one:</p>
<pre><code>#define GET_MACRO(_1,_2,_3,_4,NAME,...) NAME
#define FOO(...) GET_MACRO(__VA_ARGS__, FOO4, FOO3, FOO2)(__VA_ARGS__)
FOO(a,b,c,d) // expands to FOO4(a,b,c,d)
</code></pre>
<p>Naturally, if you define <code>FOO2</code>, <code>FOO3</code> and <code>FOO4</code>, the output will be replaced by those of the defined macros.</p> | {
"question_id": 11761703,
"question_date": "2012-08-01T14:42:42.357Z",
"question_score": 229,
"tags": "c|macros|c-preprocessor",
"answer_id": 11763277,
"answer_date": "2012-08-01T16:08:22.890Z",
"answer_score": 332
} |
Please answer the following Stack Overflow question:
Title: Why put in front of the file name "_" or "_" in scss/css?
<p>Why put <code>_</code> in front of the filename in scss?</p>
<p><code>_filename.scss</code> - Why does it need <code>_</code> ?</p> | <p>The _ (underscore) is a partial for scss. That means the stylesheet its going to be imported (@import) to a main stylesheet i.e. styles.scss. The advantage on using partials is that you can use many files to organize your code and everything will be compiled on a single file.</p> | {
"question_id": 34889962,
"question_date": "2016-01-20T01:25:56.177Z",
"question_score": 229,
"tags": "css|import|sass",
"answer_id": 34890015,
"answer_date": "2016-01-20T01:32:41.503Z",
"answer_score": 222
} |
Please answer the following Stack Overflow question:
Title: Empty arrays seem to equal true and false at the same time
<p>Empty arrays are true but they're also equal to false.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [];
console.log('Array:', arr);
if (arr) console.log("It's true!");
if (arr == false) console.log("It's false!");
if (arr && arr == false) console.log("...what??");</code></pre>
</div>
</div>
</p>
<p>I guess this is due to the implicit conversion operated by the equality operator.</p>
<p>Can anyone explain what's going on behind the scenes?</p> | <p>You're testing different things here. </p>
<p><code>if (arr)</code> called on object (Array is instance of Object in JS) will check if the object is present, and returns true/false. </p>
<p>When you call <code>if (arr == false)</code> you compare <em>values</em> of this object and the primitive <code>false</code> value. Internally, <code>arr.toString()</code> is called, which returns an empty string <code>""</code>. </p>
<p>This is because <code>toString</code> called on Array returns <code>Array.join()</code>, and empty string is one of falsy values in JavaScript.</p> | {
"question_id": 5491605,
"question_date": "2011-03-30T19:59:30.833Z",
"question_score": 229,
"tags": "javascript",
"answer_id": 5491730,
"answer_date": "2011-03-30T20:10:16.120Z",
"answer_score": 298
} |
Please answer the following Stack Overflow question:
Title: Is it possible to configure control + scroll-wheel to increase/decrease zoom in VS Code?
<p>Similar to the default in the Visual Studio editors or Sublime, I would like to use control + scroll-wheel to change the font size / zoom level, rather than control-plus/minus. I did not see any option in the User or Workspace preferences.</p>
<p>Edit from Derek Morin:
If you want this to be the default behaviour, please upvote:
<a href="https://github.com/microsoft/vscode/issues/97137" rel="noreferrer">https://github.com/microsoft/vscode/issues/97137</a></p> | <p>You can edit settings.json and add this line:</p>
<pre><code> "editor.mouseWheelZoom": true
</code></pre>
<p>Or go to settings <code>CTRL + ,</code> or <code>File > Preferences > Settings</code> and search for:</p>
<pre><code>mouseWheelZoom
</code></pre>
<p><a href="https://i.stack.imgur.com/8fGhE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8fGhE.png" alt="enter image description here" /></a></p> | {
"question_id": 30192884,
"question_date": "2015-05-12T13:49:23.240Z",
"question_score": 229,
"tags": "visual-studio-code",
"answer_id": 38360205,
"answer_date": "2016-07-13T19:31:04.710Z",
"answer_score": 439
} |
Please answer the following Stack Overflow question:
Title: prototype based vs. class based inheritance
<p>In JavaScript, every object is at the same time an instance and a class. To do inheritance, you can use any object instance as a prototype.</p>
<p>In Python, C++, etc.. there are classes, and instances, as separate concepts. In order to do inheritance, you have to use the base class to create a new class, which can then be used to produce derived instances.</p>
<p>Why did JavaScript go in this direction (prototype-based object orientation)? what are the advantages (and disadvantages) of prototype-based OO with respect to traditional, class-based OO?</p> | <p>There are about a hundred terminology issues here, mostly built around someone (not you) trying to make their idea sound like The Best.</p>
<p>All object oriented languages need to be able to deal with several concepts:</p>
<ol>
<li>encapsulation of data along with associated operations on the data, variously known as data members and member functions, or as data and methods, among other things.</li>
<li>inheritance, the ability to say that these objects are just like that other set of objects EXCEPT for these changes</li>
<li>polymorphism ("many shapes") in which an object decides for itself what methods are to be run, so that you can depend on the language to route your requests correctly.</li>
</ol>
<p>Now, as far as comparison:</p>
<p>First thing is the whole "class" vs "prototype" question. The idea originally began in Simula, where with a class-based method each class represented a set of objects that shared the same state space (read "possible values") and the same operations, thereby forming an equivalence class. If you look back at Smalltalk, since you can open a class and add methods, this is effectively the same as what you can do in Javascript.</p>
<p>Later OO languages wanted to be able to use static type checking, so we got the notion of a fixed class set at compile time. In the open-class version, you had more flexibility; in the newer version, you had the ability to check some kinds of correctness at the compiler that would otherwise have required testing.</p>
<p>In a "class-based" language, that copying happens at compile time. In a prototype language, the operations are stored in the prototype data structure, which is copied and modified at run time. Abstractly, though, a class is still the equivalence class of all objects that share the same state space and methods. When you add a method to the prototype, you're effectively making an element of a new equivalence class.</p>
<p>Now, why do that? primarily because it makes for a simple, logical, elegant mechanism at run time. now, to create a new object, <em>or</em> to create a new class, you simply have to perform a deep copy, copying all the data and the prototype data structure. You get inheritance and polymorphism more or less for free then: method lookup <em>always</em> consists of asking a dictionary for a method implementation by name.</p>
<p>The reason that ended up in Javascript/ECMA script is basically that when we were getting started with this 10 years ago, we were dealing with much less powerful computers and much less sophisticated browsers. Choosing the prototype-based method meant the interpreter could be very simple while preserving the desirable properties of object orientation.</p> | {
"question_id": 816071,
"question_date": "2009-05-03T01:39:10.043Z",
"question_score": 229,
"tags": "javascript|oop|inheritance|prototype-programming",
"answer_id": 816075,
"answer_date": "2009-05-03T01:43:28.567Z",
"answer_score": 225
} |
Please answer the following Stack Overflow question:
Title: What APIs are used to draw over other apps (like Facebook's Chat Heads)?
<p>How does Facebook create the Chat Heads on Android? What is the API to create the floating views on top of all other views?</p> | <p><a href="http://developer.android.com/reference/android/Manifest.permission.html#SYSTEM_ALERT_WINDOW" rel="noreferrer">This</a> one:</p>
<blockquote>
<p>Allows an application to open windows using the type
TYPE_SYSTEM_ALERT, shown on top of all other applications.
Very few applications should use this permission; these windows are intended
for system-level interaction with the user.</p>
<p>Constant Value: "android.permission.SYSTEM_ALERT_WINDOW"</p>
</blockquote>
<p>//EDIT:
The full code <a href="http://www.piwai.info/chatheads-basics" rel="noreferrer">here</a>: </p>
<pre><code>public class ChatHeadService extends Service {
private WindowManager windowManager;
private ImageView chatHead;
@Override public IBinder onBind(Intent intent) {
// Not used
return null;
}
@Override public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
chatHead = new ImageView(this);
chatHead.setImageResource(R.drawable.android_head);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
windowManager.addView(chatHead, params);
}
@Override
public void onDestroy() {
super.onDestroy();
if (chatHead != null) windowManager.removeView(chatHead);
}
}
</code></pre>
<p>Don't forget to start the service somehow:</p>
<pre><code>startService(new Intent(context, ChatHeadService.class));
</code></pre>
<p>.. And add this service to your Manifest.</p> | {
"question_id": 15975988,
"question_date": "2013-04-12T16:03:28.757Z",
"question_score": 229,
"tags": "android|facebook|android-windowmanager",
"answer_id": 15980900,
"answer_date": "2013-04-12T21:11:53.720Z",
"answer_score": 219
} |
Please answer the following Stack Overflow question:
Title: Linking to other Wiki pages on GitHub?
<p>GitHub wikis allow you to link to other pages in the wiki like so:</p>
<pre><code>[[Wiki Page Name]]
</code></pre>
<p>However, I want to display different text than the wiki page name when making the link. Is there a way to do this? Am I linking to wiki pages all wrong?</p> | <p>GitHub by default uses <a href="http://en.wikipedia.org/wiki/Markdown" rel="noreferrer">Markdown</a> syntax for the wikis so you can just do:</p>
<pre><code>[Arbitrary Link Text](Wiki Page Name)
</code></pre>
<p>Check out <a href="http://daringfireball.net/projects/markdown/syntax" rel="noreferrer">Markdown</a> and <a href="https://github.com/blog/699-making-github-more-open-git-backed-wikis" rel="noreferrer">this blog post</a> for more information about their wikis and the other markup syntaxes they support.</p>
<p>This solution has issues when you're on the home page because it creates relative URLs. Check out <a href="https://stackoverflow.com/a/8972756/145530">Sven's answer</a>, below.</p> | {
"question_id": 6474045,
"question_date": "2011-06-24T21:40:07.597Z",
"question_score": 229,
"tags": "github",
"answer_id": 6474147,
"answer_date": "2011-06-24T21:52:09.690Z",
"answer_score": 94
} |
Please answer the following Stack Overflow question:
Title: Find merge commit which include a specific commit
<p>Imagine the following history:</p>
<pre><code> c---e---g--- feature
/ \
-a---b---d---f---h--- master
</code></pre>
<p>How can I find when commit "c" has been merged into master (ie, find merge commit "h") ?</p> | <p>Your example shows that the branch <code>feature</code> is still available.</p>
<p>In that case <code>h</code> is the last result of:</p>
<pre><code>git log master ^feature --ancestry-path
</code></pre>
<hr>
<p>If the branch <code>feature</code> is not available anymore, you can show the merge commits in the history line between <code>c</code> and <code>master</code>:</p>
<pre><code>git log <SHA-1_for_c>..master --ancestry-path --merges
</code></pre>
<p>This will however also show all the merges that happened after <code>h</code>, and between <code>e</code> and <code>g</code> on <code>feature</code>.</p>
<hr>
<p>Comparing the result of the following commands:</p>
<pre><code>git rev-list <SHA-1_for_c>..master --ancestry-path
git rev-list <SHA-1_for_c>..master --first-parent
</code></pre>
<p>will give you the SHA-1 of <code>h</code> as the last row in common. </p>
<p>If you have it available, you can use <code>comm -1 -2</code> on these results. If you are on msysgit, you can use the following perl code to compare:</p>
<pre><code>perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/' file1 file2
</code></pre>
<p>(perl code from <a href="http://www.cyberciti.biz/faq/command-to-display-lines-common-in-files/" rel="noreferrer">http://www.cyberciti.biz/faq/command-to-display-lines-common-in-files/</a> , which took it from "someone at comp.unix.shell news group").</p>
<p>See <a href="http://tldp.org/LDP/abs/html/process-sub.html" rel="noreferrer">process substitution</a> if you want to make it a one-liner.</p> | {
"question_id": 8475448,
"question_date": "2011-12-12T14:00:44.533Z",
"question_score": 229,
"tags": "git",
"answer_id": 8492711,
"answer_date": "2011-12-13T16:36:02.330Z",
"answer_score": 179
} |
Please answer the following Stack Overflow question:
Title: Paperclip::Errors::MissingRequiredValidatorError with Rails 4
<p>I'm getting this error when I try to upload using paperclip with my rails blogging app.
Not sure what it is referring to when it says "MissingRequiredValidatorError"
I thought that by updating post_params and giving it :image it would be fine, as both create and update use post_params</p>
<pre><code>Paperclip::Errors::MissingRequiredValidatorError in PostsController#create
Paperclip::Errors::MissingRequiredValidatorError
Extracted source (around line #30):
def create
@post = Post.new(post_params)
</code></pre>
<p>This is my posts_controller.rb </p>
<pre><code>def update
@post = Post.find(params[:id])
if @post.update(post_params)
redirect_to action: :show, id: @post.id
else
render 'edit'
end
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to action: :show, id: @post.id
else
render 'new'
end
end
#...
private
def post_params
params.require(:post).permit(:title, :text, :image)
end
</code></pre>
<p>and this is my posts helper </p>
<pre><code>module PostsHelper
def post_params
params.require(:post).permit(:title, :body, :tag_list, :image)
end
end
</code></pre>
<p>Please let me know if I can supplement extra material to help you help me.</p> | <p>Starting with <code>Paperclip version 4.0</code>, all attachments are required to include a <em>content_type validation</em>, <em>a file_name validation</em>, or to <em>explicitly</em> state that they're not going to have either. </p>
<p>Paperclip raises <code>Paperclip::Errors::MissingRequiredValidatorError</code> error if you do not do any of this.</p>
<p>In your case, you can add any of the following line to your <code>Post</code> model, <strong>after</strong> specifying <code>has_attached_file :image</code></p>
<h2>Option 1: Validate content type</h2>
<pre><code>validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
</code></pre>
<p><strong>-OR- another way</strong></p>
<pre><code>validates_attachment :image, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
</code></pre>
<p><strong>-OR- yet another way</strong></p>
<p>is to use <em>regex</em> for validating content type. </p>
<p>For example: To validate all image formats, regex expression can be specified as shown in</p>
<p><em><a href="https://stackoverflow.com/questions/21897725/papercliperrorsmissingrequiredvalidatorerror-with-rails-4/21898204#answer-22525202">@LucasCaton's answer</a></em></p>
<h2>Option 2: Validate filename</h2>
<pre><code>validates_attachment_file_name :image, :matches => [/png\Z/, /jpe?g\Z/, /gif\Z/]
</code></pre>
<h2>Option 3: Do not validate</h2>
<p>If for some <em>crazy</em> reason (can be <em>valid</em> but I cannot think of one right now), you do not wish to add any <code>content_type</code> validation and allow people to spoof Content-Types and receive data you weren't expecting onto your server then add the following:</p>
<pre><code>do_not_validate_attachment_file_type :image
</code></pre>
<hr>
<p><strong>Note:</strong> </p>
<p><strong>Specify the MIME types as per your requirement within <code>content_type</code>/ <code>matches</code> options above.</strong> I have just given a few image MIME types for you to start with.</p>
<p><strong>Reference:</strong></p>
<p>Refer to <strong><a href="https://github.com/thoughtbot/paperclip#security-validations" rel="noreferrer">Paperclip: Security Validations</a></strong>, if you still need to verify. :)</p>
<p>You might also have to deal with the spoofing validation explained here <a href="https://stackoverflow.com/a/23846121">https://stackoverflow.com/a/23846121</a></p> | {
"question_id": 21897725,
"question_date": "2014-02-20T03:51:32.577Z",
"question_score": 229,
"tags": "ruby-on-rails|ruby|ruby-on-rails-4|paperclip",
"answer_id": 21898204,
"answer_date": "2014-02-20T04:34:49.903Z",
"answer_score": 511
} |
Please answer the following Stack Overflow question:
Title: When to use RxJava in Android and when to use LiveData from Android Architectural Components?
<p>I am not getting the reason to use RxJava in Android and LiveData from Android Architectural Components.It would be really helpful if the usecases and differences between the both are explained along with sample example in the form of code which explains the differences between the both.</p> | <p>Android LiveData is a variant of the original observer pattern, with the addition of active/inactive transitions. As such, it is very restrictive in its scope.</p>
<p>Using the example described in <a href="https://developer.android.com/topic/libraries/architecture/livedata.html" rel="noreferrer">Android LiveData</a>, a class is created to monitor location data, and register and unregister based on application state.</p>
<p>RxJava provides operators that are much more generalized. Let's assume that this observable will provide location data:</p>
<pre><code>Observable<LocationData> locationObservable;
</code></pre>
<p>The implementation of the observable can be built up using <code>Observable.create()</code> to map the call back operations. When the observable is subscribed, the call back is registered, and when it is unsubscribed, the call back is unregistered. The implementation looks very similar to the code provided in the example.</p>
<p>Let's also assume that you have an observable that emits true when the application is active:</p>
<pre><code>Observable<Boolean> isActive;
</code></pre>
<p>Then you can provide all the functionality of LiveData by the following</p>
<pre><code>Observable<LocationData> liveLocation =
isActive
.switchMap( active -> active ? locationObservable : Observable.never() );
</code></pre>
<p>The <code>switchMap()</code> operator will either provide the current location as a stream, or nothing if the application is not active. Once you have the <code>liveLocation</code> observable, there a lot of things you can do with it using RxJava operators. My favorite example is:</p>
<pre><code>liveLocation.distinctUntilChanged()
.filter( location -> isLocationInAreaOfInterest( location ) )
.subscribe( location -> doSomethingWithNewLocation( location ) );
</code></pre>
<p>That will only perform the action when the location changed, and the location is interesting. You can create similar operations that
combine time operators to determine speed. More importantly, you can provide detailed control of whether operations happen in the main thread, or a background thread, or a multiple threads, using RxJava operators.</p>
<p>The point of RxJava is that it combines control and timing into a single universe, using operations provided from the library, or even custom operations that you provide.</p>
<p>LiveData addresses only one small part of that universe, the equivalent of building the <code>liveLocation</code>.</p> | {
"question_id": 46312937,
"question_date": "2017-09-20T03:44:10.340Z",
"question_score": 229,
"tags": "android|rx-java2|rx-android|reactive|android-architecture-components",
"answer_id": 46327105,
"answer_date": "2017-09-20T16:18:55.320Z",
"answer_score": 134
} |
Please answer the following Stack Overflow question:
Title: How can I check if a Flutter application is running in debug?
<p>I'm looking for a way to execute code in Flutter when the app is in Debug mode. Is that possible in Flutter? I can't seem to find it anywhere in the documentation.</p>
<p>Something like this</p>
<pre><code>If(app.inDebugMode) {
print("Print only in debug mode");
}
</code></pre>
<p>How can I check if the Flutter application is running in debug or release mode?</p> | <p>While this works, using constants <code>kReleaseMode</code> or <code>kDebugMode</code> is preferable. See <a href="https://stackoverflow.com/questions/49707028/check-if-running-app-is-in-debug-mode/49707787#answer-55612795">Rémi's answer</a> below for a full explanation, which should probably be the accepted question.</p>
<hr />
<p>The easiest way is to use <em>assert</em> as it only runs in debug mode.</p>
<p>Here's an example from Flutter's Navigator source code:</p>
<pre><code>assert(() {
if (navigator == null && !nullOk) {
throw new FlutterError(
'Navigator operation requested with a context that does not include a Navigator.\n'
'The context used to push or pop routes from the Navigator must be that of a '
'widget that is a descendant of a Navigator widget.'
);
}
return true;
}());
</code></pre>
<p>Note in particular the <code>()</code> at the end of the call - <em>assert</em> can only operate on a Boolean, so just passing in a function doesn't work.</p> | {
"question_id": 49707028,
"question_date": "2018-04-07T11:45:18.833Z",
"question_score": 229,
"tags": "flutter|debugging|dart|flutter-run|flutter-debug",
"answer_id": 49707787,
"answer_date": "2018-04-07T13:19:36.533Z",
"answer_score": 57
} |
Please answer the following Stack Overflow question:
Title: What do @, - and + do as prefixes to recipe lines in Make?
<p>In the GNU Makefile manual, it <a href="http://www.gnu.org/software/make/manual/make.html#One-Shell" rel="noreferrer">mentions</a> these prefixes.</p>
<blockquote>
<p>If .ONESHELL is provided, then only the first line of the recipe will be checked for the special prefix characters (‘@’, ‘-’, and ‘+’).</p>
</blockquote>
<p>What do these prefixes do, and where are they mentioned?</p> | <p>They control the behaviour of make for the tagged command lines:</p>
<ul>
<li><p><code>@</code> suppresses the normal 'echo' of the command that is executed.</p></li>
<li><p><code>-</code> means ignore the exit status of the command that is executed (normally, a non-zero exit status would stop that part of the build).</p></li>
<li><p><code>+</code> means 'execute this command under <code>make -n</code>' (or 'make -t' or 'make -q') when commands are not normally executed. See also the POSIX specification for <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/make.html" rel="noreferrer"><code>make</code></a> and also <a href="https://www.gnu.org/software/make/manual/html_node/Instead-of-Execution.html#Instead-of-Execution" rel="noreferrer">§9.3</a> of the GNU Make manual.</p></li>
</ul>
<p>The <code>+</code> notation is a (POSIX-standardized) generalization of the <em>de facto</em> (non-standardized) mechanism whereby a command line containing <code>${MAKE}</code> or <code>$(MAKE)</code> is executed under <code>make -n</code>.</p>
<p>(<code>@</code> is discussed in <a href="https://www.gnu.org/software/make/manual/make.html#Recipe-Echoing" rel="noreferrer">§5.2</a> of the GNU Make manual; <code>-</code> is described in <a href="https://www.gnu.org/software/make/manual/make.html#Errors-in-Recipes" rel="noreferrer">§5.5</a>; and <a href="https://www.gnu.org/software/make/manual/make.html#How-the-MAKE-Variable-Works" rel="noreferrer">§5.7.1</a> mentions the use of <code>+</code>.)</p> | {
"question_id": 3477292,
"question_date": "2010-08-13T13:35:22.310Z",
"question_score": 229,
"tags": "makefile|gnu-make",
"answer_id": 3477400,
"answer_date": "2010-08-13T13:44:05.930Z",
"answer_score": 323
} |
Please answer the following Stack Overflow question:
Title: Cancellation token in Task constructor: why?
<p>Certain <code>System.Threading.Tasks.Task</code> constructors take a <code>CancellationToken</code> as a parameter:</p>
<pre><code>CancellationTokenSource source = new CancellationTokenSource();
Task t = new Task (/* method */, source.Token);
</code></pre>
<p>What baffles me about this is that there is no way from <em>inside</em> the method body to actually get at the token passed in (e.g., nothing like <code>Task.CurrentTask.CancellationToken</code>). The token has to be provided through some other mechanism, such as the state object or captured in a lambda.</p>
<p>So what purpose does providing the cancellation token in the constructor serve?</p> | <p>Passing a <code>CancellationToken</code> into the <code>Task</code> constructor associates it with the task.</p>
<p>Quoting <a href="http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/c2f614f6-c96c-4821-84cc-050b21aaee45" rel="noreferrer">Stephen Toub's answer from MSDN</a>:</p>
<blockquote>
<p>This has two primary benefits:</p>
<ol>
<li>If the token has cancellation requested prior to the <code>Task</code> starting to execute, the <code>Task</code> won't execute. Rather than transitioning to
<code>Running</code>, it'll immediately transition to <code>Canceled</code>. This avoids the
costs of running the task if it would just be canceled while running
anyway.</li>
<li>If the body of the task is also monitoring the cancellation token and throws an <code>OperationCanceledException</code> containing that token
(which is what <code>ThrowIfCancellationRequested</code> does), then when the task
sees that <code>OperationCanceledException</code>, it checks whether the <code>OperationCanceledException</code>'s token matches the Task's
token. If it does, that exception is viewed as an acknowledgement of
cooperative cancellation and the <code>Task</code> transitions to the <code>Canceled</code>
state (rather than the <code>Faulted</code> state).</li>
</ol>
</blockquote> | {
"question_id": 3712939,
"question_date": "2010-09-14T21:10:32.467Z",
"question_score": 229,
"tags": "c#|.net-4.0|task-parallel-library|cancellation-token",
"answer_id": 3713113,
"answer_date": "2010-09-14T21:38:23.220Z",
"answer_score": 261
} |
Please answer the following Stack Overflow question:
Title: How does git merge after cherry-pick work?
<p>Let's imagine that we have a <code>master</code> branch.</p>
<p>Then we create a <code>newbranch</code></p>
<pre><code>git checkout -b newbranch
</code></pre>
<p>and make two new commits to <code>newbranch</code>: <em>commit1</em> and <em>commit2</em></p>
<p>Then we switch to master and make <code>cherry-pick</code></p>
<pre><code>git checkout master
git cherry-pick hash_of_commit1
</code></pre>
<p>Looking into <code>gitk</code> we see that <em>commit1</em> and its cherry-picked version have different hashes, so technically they are two different commits.</p>
<p>Finally we merge <code>newbranch</code> into <code>master</code>:</p>
<pre><code>git merge newbranch
</code></pre>
<p>and see that these two commits with different hashes were merged without problems although they imply that the same changes should be applied twice, so one of them should fail.</p>
<p>Does git really do a smart analysis of commit's content while merging and decide that changes shouldn't be applied twice or these commits are marked internally as linked together?</p> | <h2>Short answer</h2>
<p>Don't worry, Git will handle it.</p>
<h2>Long answer</h2>
<p>Unlike e.g. SVN<sup>1</sup>, Git does not store commits in delta format, but is <strong>snapshot-based</strong><sup>2,3</sup>. While SVN would naively try to apply each merged commit as a patch (and fail, for the exact reason you described), Git is generally able to handle this scenario.</p>
<p>When merging, Git will try to combine the snapshots of both HEAD commits into a new snapshot. If a portion of code or a file is identical in both snapshots (i.e. because a commit was already cherry-picked), Git won't touch it.</p>
<p><strong>Sources</strong></p>
<p><sup>1</sup> <a href="http://svn.apache.org/repos/asf/subversion/trunk/notes/skip-deltas" rel="noreferrer">Skip-Deltas in Subversion</a><br>
<sup>2</sup> <a href="https://git-scm.com/book/en/v2/Getting-Started-Git-Basics" rel="noreferrer">Git Basics</a><br>
<sup>3</sup> <a href="http://shafiulazam.com/gitbook/1_the_git_object_model.html" rel="noreferrer">The Git object model</a></p> | {
"question_id": 14486122,
"question_date": "2013-01-23T17:50:15.817Z",
"question_score": 229,
"tags": "git|git-merge|cherry-pick",
"answer_id": 14486425,
"answer_date": "2013-01-23T18:08:56.713Z",
"answer_score": 155
} |
Please answer the following Stack Overflow question:
Title: How can I make the memberwise initialiser public, by default, for structs in Swift?
<p>I have a Swift framework that defines a struct:</p>
<pre><code>public struct CollectionTO {
var index: Order
var title: String
var description: String
}
</code></pre>
<p>However, I can't seem to use the implicit memberwise initialiser from another project that imports the library. The error is:</p>
<blockquote>
<p>'CollectionTO' cannot be initialised because it has no accessible initialisers</p>
</blockquote>
<p>i.e. the default synthesized memberwise initialiser is not <code>public</code>.</p>
<pre><code>var collection1 = CollectionTO(index: 1, title: "New Releases", description: "All the new releases")
</code></pre>
<p>I'm having to add my own init method like so:</p>
<pre><code>public struct CollectionTO {
var index: Order
var title: String
var description: String
public init(index: Order, title: String, description: String) {
self.index = index;
self.title = title;
self.description = description;
}
}
</code></pre>
<p>... but is there a way to do this without explicitly defining a <code>public init</code>?</p> | <p>Quoting the manual:</p>
<blockquote>
<p>"Default Memberwise Initializers for Structure Types
The default memberwise initializer for a structure type is considered private if any of the structure’s stored properties are private. Otherwise, the initializer has an access level of internal.</p>
<p>As with the default initializer above, if you want a public structure type to be initializable with a memberwise initializer when used in another module, you must provide a public memberwise initializer yourself as part of the type’s definition."</p>
</blockquote>
<p>Excerpt from <a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/" rel="noreferrer">"The Swift Programming Language"</a>, section <a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AccessControl.html#//apple_ref/doc/uid/TP40014097-CH41-ID3" rel="noreferrer">"Access Control"</a>.</p> | {
"question_id": 26224693,
"question_date": "2014-10-06T20:53:11.490Z",
"question_score": 229,
"tags": "swift|initialization",
"answer_id": 26224873,
"answer_date": "2014-10-06T21:06:14.203Z",
"answer_score": 366
} |
Please answer the following Stack Overflow question:
Title: How can I schedule code to run every few hours in Elixir or Phoenix framework?
<p>So let's say I want to send a bunch of emails or recreate sitemap or whatever every 4 hours, how would I do that in Phoenix or just with Elixir? </p> | <p>There is a simple alternative that does not require any external dependencies:</p>
<pre class="lang-ex prettyprint-override"><code>defmodule MyApp.Periodically do
use GenServer
def start_link(_opts) do
GenServer.start_link(__MODULE__, %{})
end
def init(state) do
schedule_work() # Schedule work to be performed at some point
{:ok, state}
end
def handle_info(:work, state) do
# Do the work you desire here
schedule_work() # Reschedule once more
{:noreply, state}
end
defp schedule_work() do
Process.send_after(self(), :work, 2 * 60 * 60 * 1000) # In 2 hours
end
end
</code></pre>
<p>Now in your supervision tree:</p>
<pre class="lang-ex prettyprint-override"><code>children = [
MyApp.Periodically
]
Supervisor.start_link(children, strategy: :one_for_one)
</code></pre> | {
"question_id": 32085258,
"question_date": "2015-08-19T01:47:45.813Z",
"question_score": 229,
"tags": "elixir|phoenix-framework",
"answer_id": 32097971,
"answer_date": "2015-08-19T14:12:48.753Z",
"answer_score": 471
} |
Please answer the following Stack Overflow question:
Title: Java method with return type compiles without return statement
<p><strong>Question 1:</strong></p>
<p>Why does the following code compile without having a return statement?</p>
<pre><code>public int a() {
while(true);
}
</code></pre>
<p>Notice: If I add return after the while then I get an <code>Unreachable Code Error</code>.</p>
<p><strong>Question 2:</strong> </p>
<p>On the other hand, why does the following code compile,</p>
<pre><code>public int a() {
while(0 == 0);
}
</code></pre>
<p>even though the following does not.</p>
<pre><code>public int a(int b) {
while(b == b);
}
</code></pre> | <blockquote>
<p><strong>Question 1:</strong></p>
<p>Why does the following code compile without having a return statement?</p>
<pre><code>public int a()
{
while(true);
}
</code></pre>
</blockquote>
<p>This is covered by <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.7" rel="nofollow noreferrer">JLS§8.4.7</a>:</p>
<blockquote>
<p>If a method is declared to have a return type (§8.4.5), then a compile-time error occurs if the body of the method can complete normally (§14.1).</p>
<p>In other words, a method with a return type must return only by using a return statement that provides a value return; the method is not allowed to "drop off the end of its body". See §14.17 for the precise rules about return statements in a method body.</p>
<p>It is possible for a method to have a return type and yet contain no return statements. Here is one example:</p>
<pre><code>class DizzyDean {
int pitch() { throw new RuntimeException("90 mph?!"); }
}
</code></pre>
</blockquote>
<p>Since the compiler knows that the loop will never terminate (<code>true</code> is always true, of course), it knows the function cannot "return normally" (drop off the end of its body), and thus it's okay that there's no <code>return</code>.</p>
<blockquote>
<p><strong>Question 2:</strong></p>
<p>On the other hand, why does the following code compile,</p>
<pre><code>public int a()
{
while(0 == 0);
}
</code></pre>
<p>even though the following does not.</p>
<pre><code>public int a(int b)
{
while(b == b);
}
</code></pre>
</blockquote>
<p>In the <code>0 == 0</code> case, the compiler knows that the loop will never terminate (that <code>0 == 0</code> will always be true). But it <strong>doesn't</strong> know that for <code>b == b</code>.</p>
<p>Why not?</p>
<p>The compiler understands <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28" rel="nofollow noreferrer">constant expressions (§15.28)</a>. Quoting <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.2" rel="nofollow noreferrer">§15.2 - Forms of Expressions</a> <em>(because oddly this sentence isn't in §15.28)</em>:</p>
<blockquote>
<p>Some expressions have a value that can be determined at compile time. These are <em>constant expressions</em> (§15.28).</p>
</blockquote>
<p>In your <code>b == b</code> example, because there is a variable involved, it isn't a constant expression and isn't specified to be determined at compilation time. <strong>We</strong> can see that it's always going to be true in this case (although if <code>b</code> were a <code>double</code>, as QBrute <a href="https://stackoverflow.com/questions/31050114/java-method-with-return-type-compiles-without-actually-returning-anything/31050290#comment50126058_31050290">pointed out</a>, we could easily be fooled by <code>Double.NaN</code>, which is <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2.3" rel="nofollow noreferrer">not <code>==</code> itself</a>), but the JLS only specifies that constant expressions are determined at compile time, it doesn't allow the compiler to try to evaluate non-constant expressions. bayou.io <a href="https://stackoverflow.com/questions/31050114/java-method-with-return-type-compiles-without-actually-returning-anything#comment50122240_31050290">raised a good point</a> for why not: If you start going down the road of trying to determine expressions involving variables at compilation time, where do you stop? <code>b == b</code> is obvious (er, for non-<code>NaN</code> values), but what about <code>a + b == b + a</code>? Or <code>(a + b) * 2 == a * 2 + b * 2</code>? Drawing the line at constants makes sense.</p>
<p>So since it doesn't "determine" the expression, the compiler doesn't know that the loop will never terminate, so it thinks the method can return normally — which it's not allowed to do, because it's required to use <code>return</code>. So it complains about the lack of a <code>return</code>.</p> | {
"question_id": 31050114,
"question_date": "2015-06-25T12:14:57.283Z",
"question_score": 229,
"tags": "java|syntax|while-loop|compilation|return",
"answer_id": 31050290,
"answer_date": "2015-06-25T12:23:43.633Z",
"answer_score": 274
} |
Please answer the following Stack Overflow question:
Title: How to create Temp table with SELECT * INTO tempTable FROM CTE Query
<p>I have a MS SQL CTE query from which I want to create a temporary table. I am not sure how to do it as it gives an <code>Invalid Object name</code> error.</p>
<p>Below is the whole query for reference</p>
<pre><code>SELECT * INTO TEMPBLOCKEDDATES FROM
;with Calendar as (
select EventID, EventTitle, EventStartDate, EventEndDate, EventEnumDays,EventStartTime,EventEndTime, EventRecurring, EventStartDate as PlannedDate
,EventType from EventCalender
where EventActive = 1 AND LanguageID =1 AND EventBlockDate = 1
union all
select EventID, EventTitle, EventStartDate, EventEndDate, EventEnumDays,EventStartTime,EventEndTime, EventRecurring, dateadd(dd, 1, PlannedDate)
,EventType from Calendar
where EventRecurring = 1
and dateadd(dd, 1, PlannedDate) <= EventEndDate
)
select EventID, EventStartDate, EventEndDate, PlannedDate as [EventDates], Cast(PlannedDate As datetime) AS DT, Cast(EventStartTime As time) AS ST,Cast(EventEndTime As time) AS ET, EventTitle
,EventType from Calendar
where (PlannedDate >= GETDATE()) AND ',' + EventEnumDays + ',' like '%,' + cast(datepart(dw, PlannedDate) as char(1)) + ',%'
or EventEnumDays is null
order by EventID, PlannedDate
option (maxrecursion 0)
</code></pre>
<p>I would appreciate a point in the right direction or if I can create a temporary table from this CTE query </p> | <h2>Sample DDL</h2>
<pre><code>create table #Temp
(
EventID int,
EventTitle Varchar(50),
EventStartDate DateTime,
EventEndDate DatetIme,
EventEnumDays int,
EventStartTime Datetime,
EventEndTime DateTime,
EventRecurring Bit,
EventType int
)
</code></pre>
<hr>
<pre><code>;WITH Calendar
AS (SELECT /*...*/)
Insert Into #Temp
Select EventID, EventStartDate, EventEndDate, PlannedDate as [EventDates], Cast(PlannedDate As datetime) AS DT, Cast(EventStartTime As time) AS ST,Cast(EventEndTime As time) AS ET, EventTitle
,EventType from Calendar
where (PlannedDate >= GETDATE()) AND ',' + EventEnumDays + ',' like '%,' + cast(datepart(dw, PlannedDate) as char(1)) + ',%'
or EventEnumDays is null
</code></pre>
<hr>
<p>Make sure that the table is deleted after use</p>
<pre><code>If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
Drop Table #Temp
End
</code></pre> | {
"question_id": 11491240,
"question_date": "2012-07-15T10:45:41.060Z",
"question_score": 228,
"tags": "sql|sql-server|common-table-expression",
"answer_id": 11491353,
"answer_date": "2012-07-15T11:07:36.403Z",
"answer_score": 305
} |
Please answer the following Stack Overflow question:
Title: java.net.ConnectException: Connection refused
<p>I'm trying to implement a TCP connection, everything works fine from the server's side but when I run the client program (from client computer) I get the following error:</p>
<pre><code>java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at TCPClient.main(TCPClient.java:13)
</code></pre>
<p>I tried changing the socket number in case it was in use but to no avail, does anyone know what is causing this error & how to fix it.</p>
<p>The Server Code:</p>
<pre><code>//TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception {
String fromclient;
String toclient;
ServerSocket Server = new ServerSocket(5000);
System.out.println("TCPServer Waiting for client on port 5000");
while (true) {
Socket connected = Server.accept();
System.out.println(" THE CLIENT" + " " + connected.getInetAddress()
+ ":" + connected.getPort() + " IS CONNECTED ");
BufferedReader inFromUser = new BufferedReader(
new InputStreamReader(System.in));
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connected.getInputStream()));
PrintWriter outToClient = new PrintWriter(
connected.getOutputStream(), true);
while (true) {
System.out.println("SEND(Type Q or q to Quit):");
toclient = inFromUser.readLine();
if (toclient.equals("q") || toclient.equals("Q")) {
outToClient.println(toclient);
connected.close();
break;
} else {
outToClient.println(toclient);
}
fromclient = inFromClient.readLine();
if (fromclient.equals("q") || fromclient.equals("Q")) {
connected.close();
break;
} else {
System.out.println("RECIEVED:" + fromclient);
}
}
}
}
}
</code></pre>
<p>The Client Code:</p>
<pre><code>//TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception {
String FromServer;
String ToServer;
Socket clientSocket = new Socket("localhost", 5000);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
System.in));
PrintWriter outToServer = new PrintWriter(
clientSocket.getOutputStream(), true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while (true) {
FromServer = inFromServer.readLine();
if (FromServer.equals("q") || FromServer.equals("Q")) {
clientSocket.close();
break;
} else {
System.out.println("RECIEVED:" + FromServer);
System.out.println("SEND(Type Q or q to Quit):");
ToServer = inFromUser.readLine();
if (ToServer.equals("Q") || ToServer.equals("q")) {
outToServer.println(ToServer);
clientSocket.close();
break;
} else {
outToServer.println(ToServer);
}
}
}
}
}
</code></pre> | <p>This exception means that there is no service listening on the IP/port you are trying to connect to:</p>
<ul>
<li>You are trying to connect to the wrong IP/Host or port.</li>
<li>You have not started your server.</li>
<li>Your server is not listening for connections.</li>
<li>On Windows servers, the listen backlog queue is full.</li>
</ul> | {
"question_id": 6876266,
"question_date": "2011-07-29T16:37:51.447Z",
"question_score": 228,
"tags": "java|networking|tcp",
"answer_id": 6876306,
"answer_date": "2011-07-29T16:41:37.647Z",
"answer_score": 386
} |
Please answer the following Stack Overflow question:
Title: CSS 3 slide-in from left transition
<p>Is there a cross browser solution to produce a slide-in transition with CSS only, no javascript? Below is an example of the html content:</p>
<pre><code><div>
<img id="slide" src="http://.../img.jpg />
</div>
</code></pre> | <p>You can use CSS3 transitions or maybe CSS3 animations to slide in an element.</p>
<p>For browser support: <a href="http://caniuse.com/" rel="nofollow noreferrer">http://caniuse.com/</a></p>
<p>I made two quick examples just to show you what I mean.</p>
<p><strong>CSS transition (on hover)</strong></p>
<p><a href="http://jsfiddle.net/2vLjU/1/" rel="nofollow noreferrer">Demo One</a></p>
<p>Relevant Code</p>
<pre><code>.wrapper:hover #slide {
transition: 1s;
left: 0;
}
</code></pre>
<p>In this case, I'm just transitioning the position from <code>left: -100px;</code> to <code>0;</code> with a 1s. duration. It's also possible to move the element using <code>transform: translate();</code></p>
<p><strong>CSS animation</strong></p>
<p><a href="http://jsfiddle.net/mhRec/2/" rel="nofollow noreferrer">Demo Two</a></p>
<pre><code>#slide {
position: absolute;
left: -100px;
width: 100px;
height: 100px;
background: blue;
-webkit-animation: slide 0.5s forwards;
-webkit-animation-delay: 2s;
animation: slide 0.5s forwards;
animation-delay: 2s;
}
@-webkit-keyframes slide {
100% { left: 0; }
}
@keyframes slide {
100% { left: 0; }
}
</code></pre>
<p>Same principle as above (Demo One), but the animation starts automatically after 2s, and in this case, I've set <code>animation-fill-mode</code> to <code>forwards</code>, which will persist the end state, keeping the div visible when the animation ends.</p>
<p>Like I said, two quick examples to show you how it could be done.</p>
<p><em><strong>EDIT:</strong></em>
<em><strong>For details regarding CSS Animations and Transitions see:</strong></em></p>
<p><strong>Animations</strong></p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations</a></p>
<p><strong>Transitions</strong></p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions</a></p> | {
"question_id": 16989585,
"question_date": "2013-06-07T17:14:56.823Z",
"question_score": 228,
"tags": "css|css-transitions",
"answer_id": 16997598,
"answer_date": "2013-06-08T08:28:52.917Z",
"answer_score": 343
} |
Please answer the following Stack Overflow question:
Title: How do I link a JavaScript file to a HTML file?
<p>How do you properly link a JavaScript file to a HTML document?</p>
<p>Secondly, how do you use jQuery within a JavaScript file?</p> | <p>First you need to download JQuery library from <a href="http://jquery.com/" rel="noreferrer">http://jquery.com/</a> then
load the jquery library the following way within your html head tags</p>
<p>then you can test whether the jquery is working by coding your jquery code after the jquery loading script</p>
<pre><code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--LINK JQUERY-->
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<!--PERSONAL SCRIPT JavaScript-->
<script type="text/javascript">
$(function(){
alert("My First Jquery Test");
});
</script>
</head>
<body><!-- Your web--></body>
</html>
</code></pre>
<p>If you want to use your jquery scripts file seperately you must define the external .js file this way after the jquery library loading.</p>
<pre><code><script type="text/javascript" src="jquery-3.3.1.js"></script>
<script src="js/YourExternalJQueryScripts.js"></script>
</code></pre>
<h1>Test in real time</h1>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--LINK JQUERY-->
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<!--PERSONAL SCRIPT JavaScript-->
<script type="text/javascript">
$(function(){
alert("My First Jquery Test");
});
</script>
</head>
<body><!-- Your web--></body>
</html></code></pre>
</div>
</div>
</p> | {
"question_id": 13739568,
"question_date": "2012-12-06T08:23:52.003Z",
"question_score": 228,
"tags": "javascript|jquery|html",
"answer_id": 13739791,
"answer_date": "2012-12-06T08:40:25.040Z",
"answer_score": 222
} |
Please answer the following Stack Overflow question:
Title: Replacing NULL with 0 in a SQL server query
<p>I have developed a query, and in the results for the first three columns I get <code>NULL</code>. How can I replace it with <code>0</code>? </p>
<pre><code> Select c.rundate,
sum(case when c.runstatus = 'Succeeded' then 1 end) as Succeeded,
sum(case when c.runstatus = 'Failed' then 1 end) as Failed,
sum(case when c.runstatus = 'Cancelled' then 1 end) as Cancelled,
count(*) as Totalrun from
( Select a.name,case when b.run_status=0 Then 'Failed' when b.run_status=1 Then 'Succeeded'
when b.run_status=2 Then 'Retry' Else 'Cancelled' End as Runstatus,
---cast(run_date as datetime)
cast(substring(convert(varchar(8),run_date),1,4)+'/'+substring(convert(varchar(8),run_date),5,2)+'/' +substring(convert(varchar(8),run_date),7,2) as Datetime) as RunDate
from msdb.dbo.sysjobs as a(nolock) inner join msdb.dbo.sysjobhistory as b(nolock)
on a.job_id=b.job_id
where a.name='AI'
and b.step_id=0) as c
group by
c.rundate
</code></pre> | <p>When you want to replace a possibly <code>null</code> column with something else, use <a href="http://msdn.microsoft.com/en-us/library/ms184325.aspx" rel="noreferrer">IsNull</a>.</p>
<pre><code>SELECT ISNULL(myColumn, 0 ) FROM myTable
</code></pre>
<p>This will put a 0 in myColumn if it is null in the first place.</p> | {
"question_id": 16840522,
"question_date": "2013-05-30T15:47:01.007Z",
"question_score": 228,
"tags": "sql|sql-server",
"answer_id": 16840585,
"answer_date": "2013-05-30T15:49:21.860Z",
"answer_score": 475
} |
Please answer the following Stack Overflow question:
Title: Converting double to string
<p>I am not sure it is me or what but I am having a problem converting a double to string.</p>
<p>here is my code:</p>
<pre><code>double total = 44;
String total2 = Double.toString(total);
</code></pre>
<p>Am i doing something wrong or am i missing a step here.</p>
<p>I get error <code>NumberFormatException</code> when trying to convert this.</p>
<pre><code>totalCost.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
try {
double priceG = Double.parseDouble(priceGal.getText().toString());
double valG = Double.parseDouble(volGal.toString());
double total = priceG * valG;
String tot = new Double(total).toString();
totalCost.setText(tot);
} catch(Exception e) {
Log.e("text", e.toString());
}
return false;
}
});
</code></pre>
<p>I am trying to do this in an onTouchListener. Ill post more code, basically when the user touches the edittext box i want the information to calculate a fill the edittext box.</p> | <pre><code>double total = 44;
String total2 = String.valueOf(total);
</code></pre>
<p>This will convert double to String</p> | {
"question_id": 5766318,
"question_date": "2011-04-23T19:13:37.303Z",
"question_score": 228,
"tags": "java|android",
"answer_id": 9963574,
"answer_date": "2012-04-01T10:10:56.187Z",
"answer_score": 487
} |
Please answer the following Stack Overflow question:
Title: How do I get the last character of a string?
<p>How do I get the last character of a string?</p>
<pre><code>public class Main {
public static void main(String[] args) {
String s = "test string";
//char lastChar = ???
}
}
</code></pre> | <p>The code:</p>
<pre><code>public class Test {
public static void main(String args[]) {
String string = args[0];
System.out.println("last character: " +
string.substring(string.length() - 1));
}
}
</code></pre>
<p>The output of <code>java Test abcdef</code>:</p>
<pre><code>last character: f
</code></pre> | {
"question_id": 5163785,
"question_date": "2011-03-02T05:34:16.490Z",
"question_score": 228,
"tags": "java|string|substring",
"answer_id": 5163852,
"answer_date": "2011-03-02T05:44:13.597Z",
"answer_score": 296
} |
Please answer the following Stack Overflow question:
Title: What is the best way to implement a "timer"?
<p>What is the best way to implement a timer? A code sample would be great! For this question, "best" is defined as most reliable (least number of misfires) and precise. If I specify an interval of 15 seconds, I want the target method invoked every 15 seconds, not every 10 - 20 seconds. On the other hand, I don't need nanosecond accuracy. In this example, it would be acceptable for the method to fire every 14.51 - 15.49 seconds.</p> | <p>Use the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?redirectedfrom=MSDN&view=netframework-4.8" rel="noreferrer"><code>Timer</code></a> class.</p>
<pre><code>public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 5000;
aTimer.Enabled = true;
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read() != 'q');
}
// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
}
</code></pre>
<p>The <code>Elapsed</code> event will be raised every X amount of milliseconds, specified by the <code>Interval</code> property on the Timer object. It will call the <code>Event Handler</code> method you specify. In the example above, it is <code>OnTimedEvent</code>.</p> | {
"question_id": 12535722,
"question_date": "2012-09-21T17:58:25.623Z",
"question_score": 228,
"tags": "c#|.net-4.0",
"answer_id": 12535731,
"answer_date": "2012-09-21T17:59:22.890Z",
"answer_score": 388
} |
Please answer the following Stack Overflow question:
Title: Regex not operator
<p>Is there an NOT operator in Regexes?
Like in that string : <code>"(2001) (asdf) (dasd1123_asd 21.01.2011 zqge)(dzqge) name (20019)"</code></p>
<p>I want to delete all <code>\([0-9a-zA-z _\.\-:]*\)</code> but not the one where it is a year: <code>(2001)</code>.</p>
<p>So what the regex should return must be: <code>(2001) name</code>.</p>
<p>NOTE: something like <code>\((?![\d]){4}[0-9a-zA-z _\.\-:]*\)</code> does not work for me (the <code>(20019)</code> somehow also matches...)</p> | <p>No, there's no direct not operator. At least not the way you hope for.</p>
<p>You can use a zero-width negative lookahead, however:</p>
<pre><code>\((?!2001)[0-9a-zA-z _\.\-:]*\)
</code></pre>
<p>The <code>(?!...)</code> part means "only match if the text <em>following</em> (hence: lookahead) this <em>doesn't</em> (hence: negative) match this. But it doesn't actually <em>consume</em> the characters it matches (hence: zero-width).</p>
<p>There are actually 4 combinations of <a href="http://www.regular-expressions.info/lookaround.html" rel="noreferrer">lookarounds</a> with 2 axes:</p>
<ul>
<li>lookbehind / lookahead : specifies if the characters <em>before</em> or <em>after</em> the point are considered</li>
<li>positive / negative : specifies if the characters <em>must</em> match or <em>must not</em> match.</li>
</ul> | {
"question_id": 7317043,
"question_date": "2011-09-06T08:33:51.797Z",
"question_score": 228,
"tags": "regex|string|operators",
"answer_id": 7317116,
"answer_date": "2011-09-06T08:39:43.647Z",
"answer_score": 181
} |
Please answer the following Stack Overflow question:
Title: How do I iterate through table rows and cells in JavaScript?
<p>If I have an HTML table...say</p>
<pre><code><div id="myTabDiv">
<table name="mytab" id="mytab1">
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
</div>
</code></pre>
<p>How would I iterate through all table rows (assuming the number of rows could change each time I check) and retrieve values from each cell in each row from within JavaScript?</p> | <p>If you want to go through each row(<code><tr></code>), knowing/identifying the row(<code><tr></code>), and iterate through each column(<code><td></code>) of each row(<code><tr></code>), then this is the way to go.</p>
<pre><code>var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i++) {
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//iterate through columns
//columns would be accessed using the "col" variable assigned in the for loop
}
}
</code></pre>
<p>If you just want to go through the cells(<code><td></code>), ignoring which row you're on, then this is the way to go.</p>
<pre><code>var table = document.getElementById("mytab1");
for (var i = 0, cell; cell = table.cells[i]; i++) {
//iterate through cells
//cells would be accessed using the "cell" variable assigned in the for loop
}
</code></pre> | {
"question_id": 3065342,
"question_date": "2010-06-17T20:22:27.273Z",
"question_score": 228,
"tags": "javascript",
"answer_id": 3065389,
"answer_date": "2010-06-17T20:28:10.733Z",
"answer_score": 366
} |
Please answer the following Stack Overflow question:
Title: How can I find the last element in a List<>?
<p>The following is an extract from my code:</p>
<pre><code>public class AllIntegerIDs
{
public AllIntegerIDs()
{
m_MessageID = 0;
m_MessageType = 0;
m_ClassID = 0;
m_CategoryID = 0;
m_MessageText = null;
}
~AllIntegerIDs()
{
}
public void SetIntegerValues (int messageID, int messagetype,
int classID, int categoryID)
{
this.m_MessageID = messageID;
this.m_MessageType = messagetype;
this.m_ClassID = classID;
this.m_CategoryID = categoryID;
}
public string m_MessageText;
public int m_MessageID;
public int m_MessageType;
public int m_ClassID;
public int m_CategoryID;
}
</code></pre>
<p>I am trying to use the following in my <code>main()</code> function code:</p>
<pre><code>List<AllIntegerIDs> integerList = new List<AllIntegerIDs>();
/* some code here that is ised for following assignments*/
{
integerList.Add(new AllIntegerIDs());
index++;
integerList[index].m_MessageID = (int)IntegerIDsSubstring[IntOffset];
integerList[index].m_MessageType = (int)IntegerIDsSubstring[IntOffset + 1];
integerList[index].m_ClassID = (int)IntegerIDsSubstring[IntOffset + 2];
integerList[index].m_CategoryID = (int)IntegerIDsSubstring[IntOffset + 3];
integerList[index].m_MessageText = MessageTextSubstring;
}
</code></pre>
<p>Problem is here: I am trying to print all elements in my List using a for loop:</p>
<pre><code>for (int cnt3 = 0 ; cnt3 <= integerList.FindLastIndex ; cnt3++) //<----PROBLEM HERE
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\n", integerList[cnt3].m_MessageID,integerList[cnt3].m_MessageType,integerList[cnt3].m_ClassID,integerList[cnt3].m_CategoryID, integerList[cnt3].m_MessageText);
}
</code></pre>
<p>I want to find the last element so that I equate cnt3 in my for loop and print out all entries in the <code>List</code>. Each element in the list is an object of the class <code>AllIntegerIDs</code> as mentioned above in the code sample. How do I find the last valid entry in the List?</p>
<p>Should I use something like <code>integerList.Find(integerList[].m_MessageText == null;</code>?</p>
<p>If I use that it will need an index that will range from 0 to whatever maximum. Means I will have to use another for loop which I do not intend to use. Is there a shorter/better way?</p> | <p>If you just want to access the last item in the list you can do</p>
<pre><code>if (integerList.Count > 0)
{
// pre C#8.0 : var item = integerList[integerList.Count - 1];
// C#8.0 :
var item = integerList[^1];
}
</code></pre>
<p>to get the total number of items in the list you can use the <code>Count</code> property</p>
<pre><code>var itemCount = integerList.Count;
</code></pre> | {
"question_id": 1246918,
"question_date": "2009-08-07T20:48:08.520Z",
"question_score": 228,
"tags": "c#|list",
"answer_id": 1246955,
"answer_date": "2009-08-07T20:55:31.343Z",
"answer_score": 252
} |
Please answer the following Stack Overflow question:
Title: How to calculate the time interval between two time strings
<p>I have two times, a start and a stop time, in the format of 10:33:26 (HH:MM:SS). I need the difference between the two times. I've been looking through documentation for Python and searching online and I would imagine it would have something to do with the datetime and/or time modules. I can't get it to work properly and keep finding only how to do this when a date is involved.</p>
<p>Ultimately, I need to calculate the averages of multiple time durations. I got the time differences to work and I'm storing them in a list. I now need to calculate the average. I'm using regular expressions to parse out the original times and then doing the differences. </p>
<p>For the averaging, should I convert to seconds and then average?</p> | <p>Yes, definitely <a href="http://docs.python.org/library/datetime.html" rel="noreferrer"><code>datetime</code></a> is what you need here. Specifically, the <code>datetime.strptime()</code> method, which parses a string into a <code>datetime</code> object.</p>
<pre><code>from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
</code></pre>
<p>That gets you a <code>timedelta</code> object that contains the difference between the two times. You can do whatever you want with that, e.g. <a href="https://docs.python.org/3/library/datetime.html#datetime.timedelta.total_seconds" rel="noreferrer">converting it to seconds</a> or adding it to another <code>datetime</code>.</p>
<p>This will return a negative result if the end time is earlier than the start time, for example <code>s1 = 12:00:00</code> and <code>s2 = 05:00:00</code>. If you want the code to assume the interval crosses midnight in this case (i.e. it should assume the end time is never earlier than the start time), you can add the following lines to the above code:</p>
<pre><code>if tdelta.days < 0:
tdelta = timedelta(
days=0,
seconds=tdelta.seconds,
microseconds=tdelta.microseconds
)
</code></pre>
<p>(of course you need to include <code>from datetime import timedelta</code> somewhere). Thanks to J.F. Sebastian for pointing out this use case.</p> | {
"question_id": 3096953,
"question_date": "2010-06-22T20:38:16.823Z",
"question_score": 228,
"tags": "python|time|python-datetime",
"answer_id": 3096984,
"answer_date": "2010-06-22T20:42:31.827Z",
"answer_score": 276
} |
Please answer the following Stack Overflow question:
Title: JavaScript Form Submit - Confirm or Cancel Submission Dialog Box
<p>For a simple form with an alert that asks if fields were filled out correctly, I need a function that does this:</p>
<ul>
<li><p>Shows an alert box when button is clicked with two options:</p>
<ul>
<li>If "OK" is clicked, the form is submitted</li>
<li>If cancel is clicked, the alert box closes and the form can be adjusted and resubmitted</li>
</ul></li>
</ul>
<p>I think a JavaScript confirm would work but I can't seem to figure out how.</p>
<p>The code I have now is:</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 show_alert() {
alert("xxxxxx");
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
<input type="image" src="xxx" border="0" name="submit" onclick="show_alert();" alt="PayPal - The safer, easier way to pay online!" value="Submit">
</form></code></pre>
</div>
</div>
</p> | <p>A simple <strong>inline JavaScript confirm</strong> would suffice:</p>
<pre><code><form onsubmit="return confirm('Do you really want to submit the form?');">
</code></pre>
<p>No need for an <em>external function</em> unless you are doing <em>validation</em>, which you can do something like this:</p>
<pre><code><script>
function validate(form) {
// validation code here ...
if(!valid) {
alert('Please correct the errors in the form!');
return false;
}
else {
return confirm('Do you really want to submit the form?');
}
}
</script>
<form onsubmit="return validate(this);">
</code></pre> | {
"question_id": 6515502,
"question_date": "2011-06-29T03:39:59.260Z",
"question_score": 228,
"tags": "javascript|html|forms|submit|confirm",
"answer_id": 6515632,
"answer_date": "2011-06-29T04:02:56.697Z",
"answer_score": 476
} |
Please answer the following Stack Overflow question:
Title: Alter a MySQL column to be AUTO_INCREMENT
<p>I’m trying to modify a table to make its primary key column <code>AUTO_INCREMENT</code> after the fact. I have tried the following SQL, but got a syntax error notification.</p>
<pre class="lang-sql prettyprint-override"><code>ALTER TABLE document
ALTER COLUMN document_id AUTO_INCREMENT
</code></pre>
<p>Am I doing something wrong or is this not possible?</p>
<pre>
+--------------------+
| VERSION() |
+--------------------+
| 5.0.75-0ubuntu10.2 |
+--------------------+
</pre> | <pre><code>ALTER TABLE document MODIFY COLUMN document_id INT auto_increment
</code></pre> | {
"question_id": 2169080,
"question_date": "2010-01-30T19:16:44.800Z",
"question_score": 228,
"tags": "sql|mysql|alter-table",
"answer_id": 2169090,
"answer_date": "2010-01-30T19:19:39.087Z",
"answer_score": 437
} |
Please answer the following Stack Overflow question:
Title: php is null when empty?
<p>I have a question regarding <code>NULL</code> in PHP:</p>
<pre><code> $a = '';
if($a == NULL) {
echo 'is null';
}
</code></pre>
<p>Why do I see <strong>is null</strong> when <code>$a</code> is an empty string? Is that a bug?</p> | <p>What you're looking for is:</p>
<pre><code>if($variable === NULL) {...}
</code></pre>
<p>Note the <code>===</code>.<br>
When use <code>==</code>, as you did, PHP treats <em>NULL</em>, <em>false</em>, <em>0</em>, the <em>empty</em> string, and <em>empty</em> arrays as equal.</p> | {
"question_id": 8236354,
"question_date": "2011-11-23T01:44:56.927Z",
"question_score": 228,
"tags": "php|null",
"answer_id": 8236374,
"answer_date": "2011-11-23T01:47:29.473Z",
"answer_score": 379
} |
Please answer the following Stack Overflow question:
Title: Number of lines in a file in Java
<p>I use huge data files, sometimes I only need to know the number of lines in these files, usually I open them up and read them line by line until I reach the end of the file</p>
<p>I was wondering if there is a smarter way to do that</p> | <p>This is the fastest version I have found so far, about 6 times faster than readLines. On a 150MB log file this takes 0.35 seconds, versus 2.40 seconds when using readLines(). Just for fun, linux' wc -l command takes 0.15 seconds.</p>
<pre><code>public static int countLinesOld(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
}
</code></pre>
<p>EDIT, 9 1/2 years later: I have practically no java experience, but anyways I have tried to benchmark this code against the <code>LineNumberReader</code> solution below since it bothered me that nobody did it. It seems that especially for large files my solution is faster. Although it seems to take a few runs until the optimizer does a decent job. I've played a bit with the code, and have produced a new version that is consistently fastest:</p>
<pre><code>public static int countLinesNew(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int readChars = is.read(c);
if (readChars == -1) {
// bail out if nothing to read
return 0;
}
// make it easy for the optimizer to tune this loop
int count = 0;
while (readChars == 1024) {
for (int i=0; i<1024;) {
if (c[i++] == '\n') {
++count;
}
}
readChars = is.read(c);
}
// count remaining characters
while (readChars != -1) {
System.out.println(readChars);
for (int i=0; i<readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
readChars = is.read(c);
}
return count == 0 ? 1 : count;
} finally {
is.close();
}
}
</code></pre>
<p>Benchmark resuls for a 1.3GB text file, y axis in seconds. I've performed 100 runs with the same file, and measured each run with <code>System.nanoTime()</code>. You can see that <code>countLinesOld</code> has a few outliers, and <code>countLinesNew</code> has none and while it's only a bit faster, the difference is statistically significant. <code>LineNumberReader</code> is clearly slower.</p>
<p><a href="https://i.stack.imgur.com/fjQQB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fjQQB.png" alt="Benchmark Plot"></a></p> | {
"question_id": 453018,
"question_date": "2009-01-17T08:59:06.310Z",
"question_score": 228,
"tags": "java|large-files|line-numbers",
"answer_id": 453067,
"answer_date": "2009-01-17T09:35:17.373Z",
"answer_score": 249
} |
Please answer the following Stack Overflow question:
Title: Reflection: How to Invoke Method with parameters
<p>I am trying to invoke a method via reflection with parameters and I get:</p>
<blockquote>
<p>object does not match target type</p>
</blockquote>
<p>If I invoke a method without parameters, it works fine. Based on the following code if I call the method <code>Test("TestNoParameters")</code>, it works fine. However if I call <code>Test("Run")</code>, I get an exception. Is something wrong with my code?</p>
<p>My initial purpose was to pass an array of objects e.g. <code>public void Run(object[] options)</code> but this did not work and I tried something simpler e.g. string without success.</p>
<pre><code>// Assembly1.dll
namespace TestAssembly
{
public class Main
{
public void Run(string parameters)
{
// Do something...
}
public void TestNoParameters()
{
// Do something...
}
}
}
// Executing Assembly.exe
public class TestReflection
{
public void Test(string methodName)
{
Assembly assembly = Assembly.LoadFile("...Assembly1.dll");
Type type = assembly.GetType("TestAssembly.Main");
if (type != null)
{
MethodInfo methodInfo = type.GetMethod(methodName);
if (methodInfo != null)
{
object result = null;
ParameterInfo[] parameters = methodInfo.GetParameters();
object classInstance = Activator.CreateInstance(type, null);
if (parameters.Length == 0)
{
// This works fine
result = methodInfo.Invoke(classInstance, null);
}
else
{
object[] parametersArray = new object[] { "Hello" };
// The invoke does NOT work;
// it throws "Object does not match target type"
result = methodInfo.Invoke(methodInfo, parametersArray);
}
}
}
}
}
</code></pre> | <p>Change "methodInfo" to "classInstance", just like in the call with the null parameter array.</p>
<pre><code> result = methodInfo.Invoke(classInstance, parametersArray);
</code></pre> | {
"question_id": 2202381,
"question_date": "2010-02-04T19:02:49.200Z",
"question_score": 228,
"tags": "c#|reflection|parameters|methods|invoke",
"answer_id": 2202430,
"answer_date": "2010-02-04T19:08:19.890Z",
"answer_score": 257
} |
Please answer the following Stack Overflow question:
Title: Finding child element of parent with JavaScript
<p>What would the most efficient method be to find a child element of (with class or ID) of a particular parent element using pure javascript only. No jQuery or other frameworks.</p>
<p>In this case, I would need to find <strong>child1</strong> or <strong>child2</strong> of <strong>parent</strong>, assuming that the DOM tree could have multiple <strong>child1</strong> or <strong>child2</strong> class elements in the tree. I only want the elements of <strong>parent</strong></p>
<pre class="lang-html prettyprint-override"><code><div class="parent">
<div class="child1">
<div class="child2">
</div>
</div>
</div>
</code></pre> | <p>The <code>children</code> property returns an array of elements, like so:</p>
<pre><code>parent = document.querySelector('.parent');
children = parent.children; // [<div class="child1">]
</code></pre>
<p>There are alternatives to <code>querySelector</code>, like <code>document.getElementsByClassName('parent')[0]</code> if you so desire.</p>
<hr>
<p>Edit: Now that I think about it, you could just use <code>querySelectorAll</code> to get decendents of <code>parent</code> having a class name of <code>child1</code>:</p>
<pre><code>children = document.querySelectorAll('.parent .child1');
</code></pre>
<p>The difference between qS and qSA is that the latter returns <em>all</em> elements matching the selector, while the former only returns the first such element.</p> | {
"question_id": 16302045,
"question_date": "2013-04-30T14:13:06.240Z",
"question_score": 228,
"tags": "javascript|dom",
"answer_id": 16302110,
"answer_date": "2013-04-30T14:15:52.070Z",
"answer_score": 219
} |
Please answer the following Stack Overflow question:
Title: How to set background color of view transparent in React Native
<p>This is the style of the view that i have used</p>
<pre class="lang-js prettyprint-override"><code>backCover: {
position: 'absolute',
marginTop: 20,
top: 0,
bottom: 0,
left: 0,
right: 0,
}
</code></pre>
<p>Currently it has a white background. I can change the backgroundColor as i want like <code>'#343434'</code> but it accepts only max 6 hexvalue for color so I cannot give opacity on that like <code>'#00ffffff'</code>. I tried using opacity like this</p>
<pre class="lang-js prettyprint-override"><code>backCover: {
position: 'absolute',
marginTop: 20,
top: 0,
bottom: 0,
left: 0,
right: 0,
opacity: 0.5,
}
</code></pre>
<p>but it reduces visibility of view's content.
So any answers?</p> | <h2>Use <code>rgba</code> value for the <code>backgroundColor</code>.</h2>
<p>For example,</p>
<pre><code>backgroundColor: 'rgba(52, 52, 52, 0.8)'
</code></pre>
<p>This sets it to a grey color with 80% opacity, which is derived from the opacity decimal, <code>0.8</code>. This value can be anything from <code>0.0</code> to <code>1.0</code>.</p> | {
"question_id": 31336569,
"question_date": "2015-07-10T08:58:38.097Z",
"question_score": 228,
"tags": "react-native",
"answer_id": 31336654,
"answer_date": "2015-07-10T09:02:36.043Z",
"answer_score": 447
} |
Please answer the following Stack Overflow question:
Title: Change bootstrap navbar collapse breakpoint without using LESS
<p>Currently when the browser width drops below 768px, the navbar changes to collapsed mode. I want to change this width to 1000px so when the browser is below 1000px the navbar changes to collapsed mode. I want to do this without using LESS, I am using stylus not LESS. </p>
<p>My issue is the same as in this question: <a href="https://stackoverflow.com/questions/18192082/bootstrap-3-navbar-collapse?lq=1">Bootstrap 3 Navbar Collapse</a></p>
<p>But all the answers in that questions explain how to do it by changing LESS variable. I haven't been dealing with LESS, I am using stylus so I want to know how this can be done using stylus or another method. </p>
<p>Thanks! </p> | <p>You have to write a specific <strong>media query</strong> for this, from your question, below 768px, the navbar will collapse, so apply it above 768px and below 1000px, just like that:</p>
<pre><code>@media (min-width: 768px) and (max-width: 1000px) {
.collapse {
display: none !important;
}
}
</code></pre>
<p>This will hide the navbar collapse until the default occurrence of the bootstrap unit. As the collapse class flips the inner assets inside navbar collapse will be automatically hidden, like wise you have to set your css as you desired design.</p> | {
"question_id": 19827605,
"question_date": "2013-11-07T03:41:02.607Z",
"question_score": 228,
"tags": "css|twitter-bootstrap|responsive-design|navbar|collapse",
"answer_id": 19828558,
"answer_date": "2013-11-07T05:24:12.803Z",
"answer_score": 57
} |
Please answer the following Stack Overflow question:
Title: error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class
<p>First time using firestore and I'm getting this error. It seems to be a problem with Ivy, from my research. I don't have a lot of experience modifying tsconfig.app.json, which is the direction I've been pointed to, following other answers.</p>
<p>The only thing I was able to modify from the original project was to use Angular Fire 6 instead of 5, which I had done initially to follow a tutorial.</p>
<p>Here's package.json:</p>
<pre class="lang-json prettyprint-override"><code>{
"name": "language",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~9.0.1",
"@angular/cdk": "^9.0.0",
"@angular/common": "~9.0.1",
"@angular/compiler": "~9.0.1",
"@angular/core": "~9.0.1",
"@angular/fire": "^6.0.0-rc.1",
"@angular/flex-layout": "^9.0.0-beta.29",
"@angular/forms": "~9.0.1",
"@angular/material": "^9.0.0",
"@angular/platform-browser": "~9.0.1",
"@angular/platform-browser-dynamic": "~9.0.1",
"@angular/router": "~9.0.1",
"firebase": "^7.8.2",
"rxjs": "~6.5.4",
"rxjs-compat": "^6.5.4",
"tslib": "^1.10.0",
"zone.js": "~0.10.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.900.2",
"@angular/cli": "~9.0.2",
"@angular/compiler-cli": "~9.0.1",
"@angular/language-service": "~9.0.1",
"@types/node": "^12.11.1",
"@types/jasmine": "~3.3.8",
"@types/jasminewd2": "~2.0.3",
"codelyzer": "^5.1.2",
"jasmine-core": "~3.4.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"protractor": "~5.4.0",
"ts-node": "~7.0.0",
"tslint": "~5.15.0",
"typescript": "~3.7.5",
"@angular-devkit/architect": "^0.900.0-0 || ^0.900.0",
"firebase-tools": "^7.12.1",
"fuzzy": "^0.1.3",
"inquirer": "^6.2.2",
"inquirer-autocomplete-prompt": "^1.0.1"
}
}
</code></pre>
<p>angular.json</p>
<pre class="lang-json prettyprint-override"><code>{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"language": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/language",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": true,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "language:build"
},
"configurations": {
"production": {
"browserTarget": "language:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "language:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
"src/styles.scss"
],
"scripts": []
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"tsconfig.app.json",
"tsconfig.spec.json",
"e2e/tsconfig.json"
],
"exclude": [
"**/node_modules/**"
]
}
},
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "language:serve"
},
"configurations": {
"production": {
"devServerTarget": "language:serve:production"
}
}
},
"deploy": {
"builder": "@angular/fire:deploy",
"options": {}
}
}
}
},
"defaultProject": "language"
}
</code></pre>
<p>tsconfig.app.json</p>
<pre class="lang-json prettyprint-override"><code>{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": [],
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
],
"exclude": [
"src/test.ts",
"src/**/*.spec.ts"
]
}
</code></pre>
<p>Thanks!</p> | <p>Your module is not yet loaded by the Angular Server in <code>node</code> <code>ng serve</code>, so restart your server so the server loads the module that you just added in <code>@NgModule app.module.ts</code></p>
<p>By: <a href="https://randdsoft.net/" rel="noreferrer">Randd Soft</a> indonesian <a href="https://hacker62.com/" rel="noreferrer">Hacker 62</a></p> | {
"question_id": 60290309,
"question_date": "2020-02-18T22:24:39.430Z",
"question_score": 228,
"tags": "angular|google-cloud-firestore|angularfire",
"answer_id": 60410491,
"answer_date": "2020-02-26T09:21:27.770Z",
"answer_score": 289
} |
Please answer the following Stack Overflow question:
Title: TypeScript for ... of with index / key?
<p>As described <a href="https://basarat.gitbooks.io/typescript/content/docs/for...of.html">here</a> TypeScript introduces a foreach loop:</p>
<pre><code>var someArray = [9, 2, 5];
for (var item of someArray) {
console.log(item); // 9,2,5
}
</code></pre>
<p>But isn't there any index/key? I would expect something like:</p>
<pre><code>for (var item, key of someArray) { ... }
</code></pre> | <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach" rel="noreferrer"><code>.forEach</code></a> already has this ability:</p>
<pre><code>const someArray = [9, 2, 5];
someArray.forEach((value, index) => {
console.log(index); // 0, 1, 2
console.log(value); // 9, 2, 5
});
</code></pre>
<p>But if you want the abilities of <code>for...of</code>, then you can <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="noreferrer"><code>map</code></a> the array to the index and value:</p>
<pre><code>for (const { index, value } of someArray.map((value, index) => ({ index, value }))) {
console.log(index); // 0, 1, 2
console.log(value); // 9, 2, 5
}
</code></pre>
<p>That's a little long, so it may help to put it in a reusable function:</p>
<pre><code>function toEntries<T>(a: T[]) {
return a.map((value, index) => [index, value] as const);
}
for (const [index, value] of toEntries(someArray)) {
// ..etc..
}
</code></pre>
<p><strong>Iterable Version</strong></p>
<p>This will work when targeting ES3 or ES5 if you compile with the <code>--downlevelIteration</code> compiler option.</p>
<pre><code>function* toEntries<T>(values: T[] | IterableIterator<T>) {
let index = 0;
for (const value of values) {
yield [index, value] as const;
index++;
}
}
</code></pre>
<p><strong>Array.prototype.entries() - ES6+</strong></p>
<p>If you are able to target ES6+ environments then you can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries" rel="noreferrer"><code>.entries()</code></a> method as outlined in <a href="https://stackoverflow.com/a/36111163/188246">Arnavion's answer</a>.</p> | {
"question_id": 36108110,
"question_date": "2016-03-19T22:43:40.520Z",
"question_score": 228,
"tags": "for-loop|foreach|typescript",
"answer_id": 36108402,
"answer_date": "2016-03-19T23:16:15.097Z",
"answer_score": 414
} |
Please answer the following Stack Overflow question:
Title: Find column whose name contains a specific string
<p>I have a dataframe with column names, and I want to find the one that contains a certain string, but does not exactly match it. I'm searching for <code>'spike'</code> in column names like <code>'spike-2'</code>, <code>'hey spike'</code>, <code>'spiked-in'</code> (the <code>'spike'</code> part is always continuous). </p>
<p>I want the column name to be returned as a string or a variable, so I access the column later with <code>df['name']</code> or <code>df[name]</code> as normal. I've tried to find ways to do this, to no avail. Any tips?</p> | <p>Just iterate over <code>DataFrame.columns</code>, now this is an example in which you will end up with a list of column names that match:</p>
<pre><code>import pandas as pd
data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]}
df = pd.DataFrame(data)
spike_cols = [col for col in df.columns if 'spike' in col]
print(list(df.columns))
print(spike_cols)
</code></pre>
<p>Output:</p>
<pre><code>['hey spke', 'no', 'spike-2', 'spiked-in']
['spike-2', 'spiked-in']
</code></pre>
<p>Explanation:</p>
<ol>
<li><code>df.columns</code> returns a list of column names</li>
<li><code>[col for col in df.columns if 'spike' in col]</code> iterates over the list <code>df.columns</code> with the variable <code>col</code> and adds it to the resulting list if <code>col</code> contains <code>'spike'</code>. This syntax is <a href="http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="noreferrer">list comprehension</a>. </li>
</ol>
<p>If you only want the resulting data set with the columns that match you can do this:</p>
<pre><code>df2 = df.filter(regex='spike')
print(df2)
</code></pre>
<p>Output:</p>
<pre><code> spike-2 spiked-in
0 1 7
1 2 8
2 3 9
</code></pre> | {
"question_id": 21285380,
"question_date": "2014-01-22T14:17:43.450Z",
"question_score": 228,
"tags": "python|python-3.x|string|pandas|dataframe",
"answer_id": 21285575,
"answer_date": "2014-01-22T14:25:56.963Z",
"answer_score": 363
} |
Please answer the following Stack Overflow question:
Title: Change Schema Name Of Table In SQL
<p>I want to change schema name of table <code>Employees</code> in Database. In the current table <code>Employees</code> database schema name is <code>dbo</code> I want to change it to <code>exe</code>. How can I do it ? </p>
<p>Example:</p>
<p>FROM </p>
<pre><code>dbo.Employees
</code></pre>
<p>TO</p>
<pre><code>exe.Employees
</code></pre>
<p>I tried with this query:</p>
<pre><code>ALTER SCHEMA exe TRANSFER dbo.Employees
</code></pre>
<p>But this gives me an error:</p>
<blockquote>
<p>Cannot alter the schema 'exe', because it does not exist or you do not
have permission.</p>
</blockquote>
<p>What did I miss? </p> | <p><strong>Create Schema :</strong></p>
<pre><code>IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'exe'))
BEGIN
EXEC ('CREATE SCHEMA [exe] AUTHORIZATION [dbo]')
END
</code></pre>
<p><strong>ALTER Schema :</strong> </p>
<pre><code>ALTER SCHEMA exe
TRANSFER dbo.Employees
</code></pre> | {
"question_id": 15482838,
"question_date": "2013-03-18T17:13:28.593Z",
"question_score": 228,
"tags": "sql|sql-server|tsql|schema",
"answer_id": 15483172,
"answer_date": "2013-03-18T17:32:23.977Z",
"answer_score": 343
} |
Please answer the following Stack Overflow question:
Title: How to do a scatter plot with empty circles in Python?
<p>In Python, with Matplotlib, how can a scatter plot with <em>empty</em> circles be plotted? The goal is to draw empty circles around <em>some</em> of the colored disks already plotted by <code>scatter()</code>, so as to highlight them, ideally without having to redraw the colored circles.</p>
<p>I tried <code>facecolors=None</code>, to no avail.</p> | <p>From the <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.scatter" rel="noreferrer">documentation</a> for scatter:</p>
<pre><code>Optional kwargs control the Collection properties; in particular:
edgecolors:
The string ‘none’ to plot faces with no outlines
facecolors:
The string ‘none’ to plot unfilled outlines
</code></pre>
<p>Try the following:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(60)
y = np.random.randn(60)
plt.scatter(x, y, s=80, facecolors='none', edgecolors='r')
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/N7GUI.png" alt="example image"></p>
<p><strong>Note:</strong> For other types of plots see <a href="https://stackoverflow.com/questions/10956903/how-to-make-hollow-square-marks-with-matplotlib-in-python">this post</a> on the use of <code>markeredgecolor</code> and <code>markerfacecolor</code>.</p> | {
"question_id": 4143502,
"question_date": "2010-11-10T10:34:09.223Z",
"question_score": 228,
"tags": "python|matplotlib|geometry|scatter-plot|scatter",
"answer_id": 4146439,
"answer_date": "2010-11-10T16:07:16.127Z",
"answer_score": 334
} |
Please answer the following Stack Overflow question:
Title: How to set JFrame to appear centered, regardless of monitor resolution?
<p>While working with Java, I find it hard to position my main window in the center of the screen when I start the application.</p>
<p>Is there any way I can do that?
It doesn't have to be vertically centered, horizontal alignment is the more important goal for me. But vertical alignment is also welcome.</p> | <p>I always did it in this way:</p>
<pre><code>Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
</code></pre>
<p>where <code>this</code> is the JFrame involved.</p> | {
"question_id": 2442599,
"question_date": "2010-03-14T15:18:48.943Z",
"question_score": 228,
"tags": "java|swing|jframe|position",
"answer_id": 2442610,
"answer_date": "2010-03-14T15:22:12.347Z",
"answer_score": 253
} |
Please answer the following Stack Overflow question:
Title: How to compare two Dates without the time portion?
<p>I would like to have a compareTo method that ignores the time portion of a java.util.Date. I guess there are a number of ways to solve this. What's the simplest way?</p> | <p>Update: while Joda Time was a fine recommendation at the time, use the <a href="https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html" rel="noreferrer"><code>java.time</code></a> library from Java 8+ instead where possible.</p>
<hr>
<p>My preference is to use <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda Time</a> which makes this incredibly easy:</p>
<pre><code>DateTime first = ...;
DateTime second = ...;
LocalDate firstDate = first.toLocalDate();
LocalDate secondDate = second.toLocalDate();
return firstDate.compareTo(secondDate);
</code></pre>
<p>EDIT: As noted in comments, if you use <a href="http://joda-time.sourceforge.net/api-release/org/joda/time/DateTimeComparator.html#getDateOnlyInstance%28%29" rel="noreferrer"><code>DateTimeComparator.getDateOnlyInstance()</code></a> it's even simpler :)</p>
<pre><code>// TODO: consider extracting the comparator to a field.
return DateTimeComparator.getDateOnlyInstance().compare(first, second);
</code></pre>
<p>("Use Joda Time" is the basis of almost all SO questions which ask about <code>java.util.Date</code> or <code>java.util.Calendar</code>. It's a thoroughly superior API. If you're doing <em>anything</em> significant with dates/times, you should really use it if you possibly can.)</p>
<p>If you're absolutely <em>forced</em> to use the built in API, you should create an instance of <code>Calendar</code> with the appropriate date and using the appropriate time zone. You could then set each field in each calendar out of hour, minute, second and millisecond to 0, and compare the resulting times. Definitely icky compared with the Joda solution though :)</p>
<p>The time zone part is important: <code>java.util.Date</code> is <em>always</em> based on UTC. In most cases where I've been interested in a date, that's been a date <em>in a specific time zone</em>. That on its own will force you to use <code>Calendar</code> or Joda Time (unless you want to account for the time zone yourself, which I don't recommend.)</p>
<p>Quick reference for android developers </p>
<pre><code>//Add joda library dependency to your build.gradle file
dependencies {
...
implementation 'joda-time:joda-time:2.9.9'
}
</code></pre>
<p>Sample code (example)</p>
<pre><code>DateTimeComparator dateTimeComparator = DateTimeComparator.getDateOnlyInstance();
Date myDateOne = ...;
Date myDateTwo = ...;
int retVal = dateTimeComparator.compare(myDateOne, myDateTwo);
if(retVal == 0)
//both dates are equal
else if(retVal < 0)
//myDateOne is before myDateTwo
else if(retVal > 0)
//myDateOne is after myDateTwo
</code></pre> | {
"question_id": 1439779,
"question_date": "2009-09-17T16:02:56.133Z",
"question_score": 228,
"tags": "java|datetime",
"answer_id": 1439792,
"answer_date": "2009-09-17T16:05:05.193Z",
"answer_score": 224
} |
Please answer the following Stack Overflow question:
Title: Fastest way to check a string contain another substring in JavaScript?
<p>I'm working with a performance issue on JavaScript. So I just want to ask: what is the fastest way to check whether a string contains another substring (I just need the boolean value)? Could you please suggest your idea and sample snippet code?</p> | <p>You have three possibilites:</p>
<ol>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" rel="noreferrer">Regular expression</a>:</p>
<pre><code> (new RegExp('word')).test(str)
// or
/word/.test(str)
</code></pre>
</li>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf" rel="noreferrer"><code>indexOf</code></a>:</p>
<pre><code> str.indexOf('word') !== -1
</code></pre>
</li>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes" rel="noreferrer"><code>includes</code></a>:</p>
<pre><code> str.includes('word')
</code></pre>
</li>
</ol>
<p><del><a href="https://web.archive.org/web/20160403025124/https://jsperf.com/substring-test" rel="noreferrer">Regular expressions seem to be faster</a> (at least in Chrome 10).</del></p>
<p><a href="https://web.archive.org/web/20160403025124/https://jsperf.com/substring-test" rel="noreferrer"><strong>Performance test - short haystack</strong></a><br />
<a href="https://web.archive.org/web/20170212021025/http://jsperf.com/substring-test/3" rel="noreferrer"><strong>Performance test - long haystack</strong></a></p>
<hr>
**Update 2011:**
<p>It cannot be said with certainty which method is faster. The differences between the browsers is enormous. While in Chrome 10 <code>indexOf</code> seems to be faster, in Safari 5, <code>indexOf</code> is clearly slower than any other method.</p>
<p>You have to see and try for your self. It depends on your needs. For example a <em>case-insensitive</em> search is way faster with regular expressions.</p>
<hr>
<p><strong>Update 2018:</strong></p>
<p>Just to save people from running the tests themselves, here are the current results for most common browsers, the percentages indicate performance increase over the next fastest result (which varies between browsers):</p>
<p><strong>Chrome:</strong> indexOf (~98% faster) <code><-- wow</code>
<br><strong>Firefox:</strong> cached RegExp (~18% faster)
<br><strong>IE11:</strong> cached RegExp(~10% faster)
<br><strong>Edge:</strong> indexOf (~18% faster)
<br><strong>Safari:</strong> cached RegExp(~0.4% faster)</p>
<p>Note that <em>cached RegExp</em> is: <code>var r = new RegExp('simple'); var c = r.test(str);</code> as opposed to: <code>/simple/.test(str)</code></p> | {
"question_id": 5296268,
"question_date": "2011-03-14T08:26:07.493Z",
"question_score": 228,
"tags": "javascript|regex|substring",
"answer_id": 5296314,
"answer_date": "2011-03-14T08:31:27.787Z",
"answer_score": 389
} |
Please answer the following Stack Overflow question:
Title: Assign null to a SqlParameter
<p>The following code gives an error - "No implicit conversion from DBnull to int."</p>
<pre><code>SqlParameter[] parameters = new SqlParameter[1];
SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int);
planIndexParameter.Value = (AgeItem.AgeIndex== null) ? DBNull.Value : AgeItem.AgeIndex;
parameters[0] = planIndexParameter;
</code></pre> | <p>The problem is that the <code>?:</code> operator cannot determine the return type because you are either returning an <code>int</code> value or a DBNull type value, which are not compatible.</p>
<p>You can of course cast the instance of AgeIndex to be type <code>object</code> which would satisfy the <code>?:</code> requirement.</p>
<p>You can use the <code>??</code> null-coalescing operator as follows</p>
<pre><code>SqlParameter[] parameters = new SqlParameter[1];
SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int);
planIndexParameter.Value = (object)AgeItem.AgeIndex ?? DBNull.Value;
parameters[0] = planIndexParameter;
</code></pre>
<p>Here is a quote from the <a href="http://msdn.microsoft.com/en-us/library/ty67wk28.aspx" rel="noreferrer">MSDN documentation</a> for the <code>?:</code> operator that explains the problem</p>
<blockquote>
<p>Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.</p>
</blockquote> | {
"question_id": 4555935,
"question_date": "2010-12-29T16:42:07.917Z",
"question_score": 228,
"tags": "c#|dbnull|sqlparameter",
"answer_id": 4556007,
"answer_date": "2010-12-29T16:53:06.527Z",
"answer_score": 389
} |
Please answer the following Stack Overflow question:
Title: Set a cookie to never expire
<p>Looking at the <a href="http://php.net/manual/en/function.setcookie.php" rel="noreferrer">php documentation on setting a cookie</a> I see that I can set an expiration date for the cookie. You can set the cookie to expire at the end of the browser session or at some time in the future but I do not see a way to set the cookie to never expire. Is this even possible and how is this accomplished?</p> | <p>All cookies expire as per the <a href="http://www.faqs.org/rfcs/rfc2965.html" rel="noreferrer">cookie specification</a>, so this is not a PHP limitation.</p>
<p>Use a far future date. For example, set a cookie that expires in ten years:</p>
<pre><code>setcookie(
"CookieName",
"CookieValue",
time() + (10 * 365 * 24 * 60 * 60)
);
</code></pre>
<p>Note that if you set a date past <strong>2038</strong> in 32-bit PHP, the number will wrap around and you'll get a cookie that expires instantly.</p> | {
"question_id": 3290424,
"question_date": "2010-07-20T13:29:51.860Z",
"question_score": 228,
"tags": "php|cookies",
"answer_id": 3290474,
"answer_date": "2010-07-20T13:35:30.663Z",
"answer_score": 300
} |
Please answer the following Stack Overflow question:
Title: Recover unsaved SQL query scripts
<p>How to recover the unsaved scripts if the SSMS crashes / unsaved tab gets accidentally closed?</p> | <p>Posting this in case if somebody stumbles into same problem.</p>
<p>Googled for <a href="http://www.sql-programmers.com/retrieve-unsaved-sql-query-scripts.aspx">Retrieve unsaved Scripts</a> and found a solution.</p>
<p>Run the following <strong><code>select</code></strong> script. It provides a list of scripts and its time of execution in the last 24 hours. This will be helpful to retrieve the scripts, if we close our query window in SQL Server management studio without saving the script. It works for all executed scripts not only a view or procedure.</p>
<pre><code>Use <database>
SELECT execquery.last_execution_time AS [Date Time], execsql.text AS [Script] FROM sys.dm_exec_query_stats AS execquery
CROSS APPLY sys.dm_exec_sql_text(execquery.sql_handle) AS execsql
ORDER BY execquery.last_execution_time DESC
</code></pre> | {
"question_id": 15034832,
"question_date": "2013-02-22T23:16:39.470Z",
"question_score": 228,
"tags": "sql|sql-server|tsql|sql-server-2012|ssms",
"answer_id": 15035060,
"answer_date": "2013-02-22T23:37:04.033Z",
"answer_score": 472
} |
Please answer the following Stack Overflow question:
Title: Set height of chart in Chart.js
<p>I want to draw a horizontal bar chart with Chart.js but it keeps scaling the chart instead of using the height I assign the canvas form the script.</p>
<p>Is there any way to set the height of the graph from the script?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var ctx = $('#myChart');
ctx.height(500);
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
maintainAspectRatio: false,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<div class="graph">
<div class="chart-legend">
</div>
<div class="chart">
<canvas id="myChart"></canvas>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>See code on fiddle: <a href="https://jsfiddle.net/Trekels/fec0v5kj/" rel="nofollow noreferrer">Jsfiddle</a></p> | <p>Seems like <code>var ctx = $('#myChart');</code> is returning a list of elements. You would need to reference the first by using <code>ctx[0]</code>.
Also height is a property, not a function.</p>
<p>I did it this way in my code:</p>
<pre><code>var chartEl = document.getElementById("myChart");
chartEl.height = 500;
</code></pre> | {
"question_id": 41953158,
"question_date": "2017-01-31T08:47:55.390Z",
"question_score": 228,
"tags": "javascript|jquery|chart.js",
"answer_id": 41953355,
"answer_date": "2017-01-31T08:59:27.730Z",
"answer_score": 94
} |
Please answer the following Stack Overflow question:
Title: RegEx to extract all matches from string using RegExp.exec
<p>I'm trying to parse the following kind of string:</p>
<pre><code>[key:"val" key2:"val2"]
</code></pre>
<p>where there are arbitrary key:"val" pairs inside. I want to grab the key name and the value.
For those curious I'm trying to parse the database format of task warrior. </p>
<p>Here is my test string:</p>
<pre><code>[description:"aoeu" uuid:"123sth"]
</code></pre>
<p>which is meant to highlight that anything can be in a key or value aside from space, no spaces around the colons, and values are always in double quotes. </p>
<p>In node, this is my output:</p>
<pre><code>[deuteronomy][gatlin][~]$ node
> var re = /^\[(?:(.+?):"(.+?)"\s*)+\]$/g
> re.exec('[description:"aoeu" uuid:"123sth"]');
[ '[description:"aoeu" uuid:"123sth"]',
'uuid',
'123sth',
index: 0,
input: '[description:"aoeu" uuid:"123sth"]' ]
</code></pre>
<p>But <code>description:"aoeu"</code> also matches this pattern. How can I get all matches back?</p> | <p>Continue calling <code>re.exec(s)</code> in a loop to obtain all the matches:</p>
<pre><code>var re = /\s*([^[:]+):\"([^"]+)"/g;
var s = '[description:"aoeu" uuid:"123sth"]';
var m;
do {
m = re.exec(s);
if (m) {
console.log(m[1], m[2]);
}
} while (m);
</code></pre>
<p>Try it with this JSFiddle: <a href="https://jsfiddle.net/7yS2V/" rel="noreferrer">https://jsfiddle.net/7yS2V/</a></p> | {
"question_id": 6323417,
"question_date": "2011-06-12T17:27:40.453Z",
"question_score": 228,
"tags": "javascript|regex|regex-group|taskwarrior",
"answer_id": 6323598,
"answer_date": "2011-06-12T18:06:05.880Z",
"answer_score": 275
} |
Please answer the following Stack Overflow question:
Title: What is useState() in React?
<p>I am currently learning hooks concept in React and trying to understand below example.</p>
<pre><code>import { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
</code></pre>
<p>The above example increments the counter on the handler function parameter itself. What if I want to modify count value inside event handler function</p>
<p>Consider below example:</p>
<pre><code>setCount = () => {
//how can I modify count value here. Not sure if I can use setState to modify its value
//also I want to modify other state values as well here. How can I do that
}
<button onClick={() => setCount()}>
Click me
</button>
</code></pre> | <p><a href="https://reactjs.org/docs/hooks-overview.html" rel="noreferrer">React hooks</a> are a new way (still being developed) to access the core features of react such as <code>state</code> without having to use classes, in your example if you want to increment a counter directly in the handler function without specifying it directly in the <code>onClick</code> prop, you could do something like:</p>
<pre><code>...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...
const setCount = () => {
setCounter(count + 1);
setMoreStuff(...);
...
};
</code></pre>
<p>and onClick:</p>
<pre><code><button onClick={setCount}>
Click me
</button>
</code></pre>
<p><strong>Let's quickly explain what is going on in this line:</strong></p>
<pre><code>const [count, setCounter] = useState(0);
</code></pre>
<p><code>useState(0)</code> returns a tuple where the first parameter <code>count</code> is the current state of the counter and <code>setCounter</code> is the method that will allow us to update the counter's state. We can use the <code>setCounter</code> method to update the state of <code>count</code> anywhere - In this case we are using it inside of the <code>setCount</code> function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid <em>class based components</em> if not desired/needed.</p>
<p><a href="https://enmascript.com/articles/2018/10/26/react-conf-2018-understanding-react-hooks-proposal-with-simple-examples" rel="noreferrer">I wrote a complete article about hooks with multiple examples</a> (including counters) such as <a href="https://codepen.io/enmanuelduran/pen/LgMomz" rel="noreferrer">this codepen</a>, I made use of <code>useState</code>, <code>useEffect</code>, <code>useContext</code>, and <em>custom hooks</em>. I could get into more details about how hooks work on this answer but the documentation does a very good job explaining the <a href="https://reactjs.org/docs/hooks-overview.html#-state-hook" rel="noreferrer">state hook</a> and other hooks in detail, hope it helps.</p>
<p><strong>update:</strong> <a href="https://github.com/facebook/react/blob/master/CHANGELOG.md#1680-february-6-2019" rel="noreferrer">Hooks are not longer a proposal</a>, since version <strong>16.8</strong> they're now available to be used, there is a section in React's site that answers some of the <a href="https://reactjs.org/docs/hooks-faq.html" rel="noreferrer">FAQ</a>.</p> | {
"question_id": 53165945,
"question_date": "2018-11-06T04:56:10.770Z",
"question_score": 228,
"tags": "javascript|reactjs|react-native|react-hooks|react-state",
"answer_id": 53166194,
"answer_date": "2018-11-06T05:26:37.810Z",
"answer_score": 243
} |
Please answer the following Stack Overflow question:
Title: How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?
<p>How can I verify my XPath?</p>
<p>I am using Chrome Developers tool to inspect the elements and form my XPath. I verify it using the Chrome plugin XPath Checker, however it does not always give me the result. What is a better way to verify my XPath.</p>
<p>I have also tried using Firebug to inspect the bug and also using the FirePath to verify. But does Firepath also verify the XPath.</p>
<p>My last option would be to use the Selenium WebDriver to confirm my XPath. </p> | <h1>Chrome</h1>
<p>This can be achieved by three different approaches (see my blog article <a href="http://yizeng.me/2014/03/23/evaluate-and-validate-xpath-css-selectors-in-chrome-developer-tools/" rel="noreferrer">here</a> for more details):</p>
<ul>
<li>Search in <code>Elements</code> panel like below</li>
<li>Execute <code>$x()</code> and <code>$$()</code> in <code>Console</code> panel, as shown in Lawrence's <a href="https://stackoverflow.com/a/22571294/1177636">answer</a></li>
<li>Third party extensions (not really necessary in most of the cases, could be an overkill)</li>
</ul>
<p>Here is how you search XPath in <code>Elements</code> panel:</p>
<ol>
<li>Press <kbd>F12</kbd> to open Chrome Developer Tool</li>
<li>In "Elements" panel, press <kbd>Ctrl</kbd>+<kbd>F</kbd></li>
<li>In the search box, type in XPath or CSS Selector, if elements are found, they will be highlighted in yellow.</li>
</ol>
<p><img src="https://i.stack.imgur.com/qsj93.gif" alt="enter image description here"></p>
<h1>Firefox (since version 75)</h1>
<p>Since FF 75 it's possible to use raw xpath query without evaluation xpath expressions, see <a href="https://developer.mozilla.org/en-US/docs/Tools/Page_Inspector/How_to/Examine_and_edit_HTML#XPath_search" rel="noreferrer">documentation</a> for more info.</p>
<h1>Firefox (prior version 75)</h1>
<ol>
<li>Either select "Web Console" from the Web Developer submenu in the
Firefox Menu (or Tools menu if you display the menu bar or are on Mac OS X)<br>
or press the <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>K</kbd> (<kbd>Command</kbd>+<kbd>Option</kbd>+<kbd>K</kbd> on OS X) keyboard shortcut.</li>
<li><p>In the command line at the bottom use the following:</p>
<ul>
<li><p><code>$()</code>: Returns the first element that matches. Equivalent to <code>document.querySelector()</code> or calls the <code>$</code> function in the page, if it exists.</p></li>
<li><p><code>$$()</code>: Returns an array of DOM nodes that match. This is like for <code>document.querySelectorAll()</code>, but returns an array instead of a <code>NodeList</code>.</p></li>
<li><p><code>$x()</code>: Evaluates an XPath expression and returns an array of matching nodes.</p></li>
</ul></li>
</ol>
<hr>
<h1>Firefox (prior version 49)</h1>
<ol>
<li>Install <a href="http://getfirebug.com/" rel="noreferrer">Firebug</a></li>
<li>Install <a href="https://addons.mozilla.org/en-US/firefox/addon/firepath/" rel="noreferrer">Firepath</a></li>
<li>Press <kbd>F12</kbd> to open Firebug</li>
<li>Switch to <code>FirePath</code> panel</li>
<li>In dropdown, select XPathor CSS</li>
<li>Type in to locate</li>
</ol>
<p><img src="https://i.stack.imgur.com/59Noo.gif" alt="enter image description here"></p> | {
"question_id": 22571267,
"question_date": "2014-03-21T23:25:30.333Z",
"question_score": 228,
"tags": "google-chrome|firefox|selenium|xpath|selenium-webdriver",
"answer_id": 22573161,
"answer_date": "2014-03-22T03:41:23.403Z",
"answer_score": 426
} |
Please answer the following Stack Overflow question:
Title: How do I execute a stored procedure once for each row returned by query?
<p>I have a stored procedure that alters user data in a certain way. I pass it user_id and it does it's thing. I want to run a query on a table and then for each user_id I find run the stored procedure once on that user_id</p>
<p>How would I write query for this?</p> | <p>use a cursor</p>
<p>ADDENDUM: [MS SQL cursor example]</p>
<pre><code>declare @field1 int
declare @field2 int
declare cur CURSOR LOCAL for
select field1, field2 from sometable where someotherfield is null
open cur
fetch next from cur into @field1, @field2
while @@FETCH_STATUS = 0 BEGIN
--execute your sproc on each row
exec uspYourSproc @field1, @field2
fetch next from cur into @field1, @field2
END
close cur
deallocate cur
</code></pre>
<p>in MS SQL, <a href="http://www.sqlteam.com/article/cursors-an-overview" rel="noreferrer">here's an example article</a></p>
<p>note that cursors are slower than set-based operations, but faster than manual while-loops; more details <a href="https://stackoverflow.com/questions/287445/why-do-people-hate-sql-cursors-so-much">in this SO question</a></p>
<p>ADDENDUM 2: if you will be processing more than just a few records, pull them into a temp table first and run the cursor over the temp table; this will prevent SQL from escalating into table-locks and speed up operation</p>
<p>ADDENDUM 3: and of course, if you can inline whatever your stored procedure is doing to each user ID and run the whole thing as a single SQL update statement, that would be optimal</p> | {
"question_id": 886293,
"question_date": "2009-05-20T05:30:31.850Z",
"question_score": 228,
"tags": "sql|sql-server|stored-procedures",
"answer_id": 886314,
"answer_date": "2009-05-20T05:36:31.603Z",
"answer_score": 273
} |
Please answer the following Stack Overflow question:
Title: Java compiler level does not match the version of the installed Java project facet
<p>I have created a New Dynamic Project under Eclipse Helios Version, where my JRE Version is set to 1.6.
I have added Maven capabilities to the Web Application by clicking on <em>Configure</em> → <em>Convert to Maven Project</em>.</p>
<p>After adding this, a build error appeared in the Eclipse Problems view:</p>
<pre><code>Java compiler level does not match the version of the installed Java project facet.
Unknown Faceted Project Problem (Java Version Mismatch)
</code></pre>
<p>Please tell me how to resolve this error (I want to have my JRE version as 1.6 only).</p> | <p>Assuming that you are using the m2e plugin in Eclipse, you'll need to specify the <code>source</code> and <code>target</code> versions as 1.6 for <code>maven-compiler-plugin</code>. m2e uses these values to determine the project's Java compiler level. A snippet of the POM is shown below:</p>
<pre><code><build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</code></pre>
<p>Alternatively, you can specify the <code>maven.compiler.source</code> and <code>maven.compiler.target</code> properties with values of 1.6, that happen to be the equivalent:</p>
<pre><code><properties>
<maven.compiler.target>1.6</maven.compiler.target>
<maven.compiler.source>1.6</maven.compiler.source>
</properties>
</code></pre> | {
"question_id": 7715260,
"question_date": "2011-10-10T15:38:45.730Z",
"question_score": 228,
"tags": "eclipse|maven|m2eclipse",
"answer_id": 7715401,
"answer_date": "2011-10-10T15:50:42.690Z",
"answer_score": 176
} |
Please answer the following Stack Overflow question:
Title: Determine the number of lines within a text file
<p>Is there an easy way to programmatically determine the number of lines within a text file? </p> | <p><strong>Seriously belated edit: If you're using .NET 4.0 or later</strong></p>
<p>The <code>File</code> class has a new <a href="http://msdn.microsoft.com/en-us/library/dd383503.aspx" rel="noreferrer"><code>ReadLines</code></a> method which lazily enumerates lines rather than greedily reading them all into an array like <code>ReadAllLines</code>. So now you can have both efficiency and conciseness with:</p>
<pre><code>var lineCount = File.ReadLines(@"C:\file.txt").Count();
</code></pre>
<hr>
<p><strong>Original Answer</strong></p>
<p>If you're not too bothered about efficiency, you can simply write:</p>
<pre><code>var lineCount = File.ReadAllLines(@"C:\file.txt").Length;
</code></pre>
<p>For a more efficient method you could do:</p>
<pre><code>var lineCount = 0;
using (var reader = File.OpenText(@"C:\file.txt"))
{
while (reader.ReadLine() != null)
{
lineCount++;
}
}
</code></pre>
<p><strong>Edit: In response to questions about efficiency</strong></p>
<p>The reason I said the second was more efficient was regarding memory usage, not necessarily speed. The first one loads the entire contents of the file into an array which means it must allocate at least as much memory as the size of the file. The second merely loops one line at a time so it never has to allocate more than one line's worth of memory at a time. This isn't that important for small files, but for larger files it could be an issue (if you try and find the number of lines in a 4GB file on a 32-bit system, for example, where there simply isn't enough user-mode address space to allocate an array this large).</p>
<p>In terms of speed I wouldn't expect there to be a lot in it. It's possible that ReadAllLines has some internal optimisations, but on the other hand it may have to allocate a massive chunk of memory. I'd guess that ReadAllLines might be faster for small files, but significantly slower for large files; though the only way to tell would be to measure it with a Stopwatch or code profiler.</p> | {
"question_id": 119559,
"question_date": "2008-09-23T07:25:31.473Z",
"question_score": 228,
"tags": "c#|input|text-files",
"answer_id": 119572,
"answer_date": "2008-09-23T07:27:24.870Z",
"answer_score": 434
} |
Please answer the following Stack Overflow question:
Title: How to loop over directories in Linux?
<p>I am writing a script in bash on Linux and need to go through all subdirectory names in a given directory. How can I loop through these directories (and skip regular files)?</p>
<p><strong>For example:</strong><br>
the given directory is <code>/tmp/</code><br>
it has the following subdirectories: <code>/tmp/A, /tmp/B, /tmp/C</code></p>
<p>I want to retrieve A, B, C.</p> | <pre><code>cd /tmp
find . -maxdepth 1 -mindepth 1 -type d -printf '%f\n'
</code></pre>
<p>A short explanation: </p>
<ul>
<li><p><code>find</code> finds files (quite obviously)</p></li>
<li><p><code>.</code> is the current directory, which after the <code>cd</code> is <code>/tmp</code> (IMHO this is more flexible than having <code>/tmp</code> directly in the <code>find</code> command. You have only one place, the <code>cd</code>, to change, if you want more actions to take place in this folder)</p></li>
<li><p><code>-maxdepth 1</code> and <code>-mindepth 1</code> make sure that <code>find</code> only looks in the current directory and doesn't include <code>.</code> itself in the result</p></li>
<li><p><code>-type d</code> looks only for directories</p></li>
<li><p><code>-printf '%f\n</code> prints only the found folder's name (plus a newline) for each hit.</p></li>
</ul>
<p>Et voilà!</p> | {
"question_id": 2107945,
"question_date": "2010-01-21T08:57:21.790Z",
"question_score": 228,
"tags": "linux|bash",
"answer_id": 2107982,
"answer_date": "2010-01-21T09:04:01.910Z",
"answer_score": 144
} |
Please answer the following Stack Overflow question:
Title: JavaScript - Get minutes between two dates
<p>If I have two dates, how can I use <a href="http://en.wikipedia.org/wiki/JavaScript">JavaScript</a> to get the difference between the two dates in minutes?</p> | <p>You may checkout this 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-js lang-js prettyprint-override"><code>var today = new Date();
var Christmas = new Date(today.getFullYear() + "-12-25");
var diffMs = (Christmas - today); // milliseconds between now & Christmas
var diffDays = Math.floor(diffMs / 86400000); // days
var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
console.log(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas =)");</code></pre>
</div>
</div>
</p>
<p>or <code>var diffMins = Math.floor((...</code> to discard seconds if you don't want to round minutes.</p> | {
"question_id": 7709803,
"question_date": "2011-10-10T07:41:37.623Z",
"question_score": 228,
"tags": "javascript|datetime",
"answer_id": 7709819,
"answer_date": "2011-10-10T07:44:23.253Z",
"answer_score": 289
} |
Please answer the following Stack Overflow question:
Title: Purpose of #!/usr/bin/python3 shebang
<p>I have noticed this in a couple of scripting languages, but in this example, I am using python. In many tutorials, they would start with <code>#!/usr/bin/python3</code> on the first line. I don't understand why we have this.</p>
<ul>
<li>Shouldn't the operating system know it's a python script (obviously it's installed since you are making a reference to it)</li>
<li>What if the user is using a operating system that isn't unix based</li>
<li>The language is installed in a different folder for whatever reason</li>
<li>The user has a different version. Especially when it's not a full version number(Like Python3 vs Python32)</li>
</ul>
<p>If anything, I could see this breaking the python script because of the listed reasons above.</p> | <p><code>#!/usr/bin/python3</code> is a <a href="https://en.wikipedia.org/wiki/Shebang_(Unix)" rel="noreferrer"><strong>shebang line</strong></a>.</p>
<p>A shebang line defines where the interpreter is located. In this case, the <code>python3</code> interpreter is located in <code>/usr/bin/python3</code>. A shebang line could also be a <code>bash</code>, <code>ruby</code>, <code>perl</code> or any other scripting languages' interpreter, for example: <code>#!/bin/bash</code>.</p>
<p>Without the shebang line, the operating system does not know it's a python script, even if you set the execution flag (<code>chmod +x script.py</code>) on the script and run it like <code>./script.py</code>. To make the script run by default in python3, either invoke it as <code>python3 script.py</code> or set the shebang line.</p>
<p>You can use <code>#!/usr/bin/env python3</code> for portability across different systems in case they have the language interpreter installed in different locations.</p> | {
"question_id": 7670303,
"question_date": "2011-10-06T04:29:16.750Z",
"question_score": 228,
"tags": "python|scripting",
"answer_id": 7670338,
"answer_date": "2011-10-06T04:35:49.453Z",
"answer_score": 359
} |
Please answer the following Stack Overflow question:
Title: How can I set the focus (and display the keyboard) on my EditText programmatically
<p>I have a layout which contains some views like this:</p>
<pre><code><LinearLayout>
<TextView...>
<TextView...>
<ImageView ...>
<EditText...>
<Button...>
</linearLayout>
</code></pre>
<p>How can I set the focus (display the keyboard) on my <code>EditText</code> programmatically?</p>
<p>I've tried this and it works only when I launch my <code>Activity</code> normally, but when I launch it in a <code>TabHost</code>, it doesn't work.</p>
<pre><code>txtSearch.setFocusableInTouchMode(true);
txtSearch.setFocusable(true);
txtSearch.requestFocus();
</code></pre> | <p>Try this: </p>
<pre><code>EditText editText = (EditText) findViewById(R.id.myTextViewId);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
</code></pre>
<p><a href="http://developer.android.com/reference/android/view/View.html#requestFocus()">http://developer.android.com/reference/android/view/View.html#requestFocus()</a></p> | {
"question_id": 8991522,
"question_date": "2012-01-24T17:45:29.457Z",
"question_score": 228,
"tags": "android|focus|android-edittext",
"answer_id": 8991563,
"answer_date": "2012-01-24T17:48:56.030Z",
"answer_score": 420
} |
Please answer the following Stack Overflow question:
Title: Replacing all non-alphanumeric characters with empty strings
<p>I tried using this but didn't work-</p>
<pre><code>return value.replaceAll("/[^A-Za-z0-9 ]/", "");
</code></pre> | <p>Use <code>[^A-Za-z0-9]</code>. </p>
<p>Note: removed the space since that is not typically considered alphanumeric.</p> | {
"question_id": 1805518,
"question_date": "2009-11-26T20:28:42.157Z",
"question_score": 228,
"tags": "java|regex|non-alphanumeric",
"answer_id": 1805526,
"answer_date": "2009-11-26T20:30:59.980Z",
"answer_score": 285
} |
Please answer the following Stack Overflow question:
Title: What are the advantages of using getters and setters instead of functions or simply public fields in PHP?
<p>I'm not a PHP developer, so I'm wondering what the advantages and disadvantages are in PHP to using explicit getter/setters, in a pure OOP style, with private fields (the way I like):</p>
<pre><code>class MyClass {
private $firstField;
private $secondField;
public function getFirstField() {
return $this->firstField;
}
public function setFirstField($x) {
$this->firstField = $x;
}
public function getSecondField() {
return $this->secondField;
}
public function setSecondField($x) {
$this->secondField = $x;
}
}
</code></pre>
<p>or just public fields:</p>
<pre><code>class MyClass {
public $firstField;
public $secondField;
}
</code></pre> | <p>You can use <a href="http://www.php.net/manual/en/language.oop5.overloading.php" rel="noreferrer">php magic methods</a> <code>__get</code> and <code>__set</code>.</p>
<pre><code><?php
class MyClass {
private $firstField;
private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
}
?>
</code></pre> | {
"question_id": 4478661,
"question_date": "2010-12-18T15:29:32.280Z",
"question_score": 228,
"tags": "php|oop|coding-style|getter",
"answer_id": 4478690,
"answer_date": "2010-12-18T15:37:48.793Z",
"answer_score": 250
} |
Please answer the following Stack Overflow question:
Title: Copy folder recursively in Node.js
<p>Is there an easier way to copy a folder and all its content without manually doing a sequence of <code>fs.readir</code>, <code>fs.readfile</code>, <code>fs.writefile</code> recursively?</p>
<p>I am just wondering if I'm missing a function which would ideally work like this:</p>
<pre><code>fs.copy("/path/to/source/folder", "/path/to/destination/folder");
</code></pre>
<hr />
<p><em>Regarding this historic question. Note that <code>fs.cp</code> and <code>fs.cpSync</code> can copy folders recursively and are available in Node v16+</em></p> | <p>Since Node v16.7.0 it is possible to use <a href="https://nodejs.org/api/fs.html#fspromisescpsrc-dest-options" rel="noreferrer"><code>fs.cp</code></a> or <a href="https://nodejs.org/api/fs.html#fscpsyncsrc-dest-options" rel="noreferrer"><code>fs.cpSync</code></a> function.</p>
<pre class="lang-js prettyprint-override"><code>fs.cp(src, dest, {recursive: true});
</code></pre>
<p>Current stability (in Node v18.7.0) is <a href="https://nodejs.org/api/documentation.html#stability-index" rel="noreferrer">Experimental</a>.</p> | {
"question_id": 13786160,
"question_date": "2012-12-09T09:17:29.707Z",
"question_score": 228,
"tags": "javascript|node.js|fs",
"answer_id": 69807672,
"answer_date": "2021-11-02T08:58:20.280Z",
"answer_score": 34
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.