input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Passing Parameters JavaFX FXML <p>How can I pass parameters to a secondary window in javafx? Is there a way to communicate with the corresponding controller?</p> <p>For example: The user chooses a customer from a <code>TableView</code> and a new window is opened, showing the customer's info.</p> <pre><code>Stage newStage = new Stage(); try { AnchorPane page = (AnchorPane) FXMLLoader.load(HectorGestion.class.getResource(fxmlResource)); Scene scene = new Scene(page); newStage.setScene(scene); newStage.setTitle(windowTitle); newStage.setResizable(isResizable); if(showRightAway) { newStage.show(); } } </code></pre> <p><code>newStage</code> would be the new window. The problem is, I can't find a way to tell the controller where to look for the customer's info (by passing the id as parameter).</p> <p>Any ideas?</p>
<p><strong>Using MVC</strong></p> <p>Most of this answer focuses on a direct call to pass a parameter from a calling class to the controller.</p> <p>If instead, you want to decouple the caller and controller and use a more general architecture involving a model class with settable and listenable properties to achieve inter-controller communication, see the following basic overview:</p> <ul> <li><a href="https://stackoverflow.com/questions/32342864/applying-mvc-with-javafx">Applying MVC With JavaFx</a></li> </ul> <p><strong>Recommended Approach</strong></p> <p>This answer enumerates different mechanisms for passing parameters to FXML controllers.</p> <p>For small applications I highly recommend passing parameters directly from the caller to the controller - it's simple, straightforward and requires no extra frameworks.</p> <p>For larger, more complicated applications, it would be worthwhile investigating if you want to use <a href="http://www.martinfowler.com/articles/injection.html" rel="noreferrer">Dependency Injection</a> or <a href="https://github.com/google/guava/wiki/EventBusExplained" rel="noreferrer">Event Bus</a> mechanisms within your application.</p> <p><strong>Passing Parameters Directly From the Caller to the Controller</strong></p> <p>Pass custom data to an FXML controller by retrieving the controller from the FXML loader instance and calling a method on the controller to initialize it with the required data values.</p> <p>Something like the following code:</p> <pre><code>public Stage showCustomerDialog(Customer customer) { FXMLLoader loader = new FXMLLoader( getClass().getResource( &quot;customerDialog.fxml&quot; ) ); Stage stage = new Stage(StageStyle.DECORATED); stage.setScene( new Scene(loader.load()) ); CustomerDialogController controller = loader.getController(); controller.initData(customer); stage.show(); return stage; } ... class CustomerDialogController { @FXML private Label customerName; void initialize() {} void initData(Customer customer) { customerName.setText(customer.getName()); } } </code></pre> <p>A new FXMLLoader is constructed as shown in the sample code i.e. <code>new FXMLLoader(location)</code>. The location is a URL and you can generate such a URL from an FXML resource by:</p> <pre><code>new FXMLLoader(getClass().getResource(&quot;sample.fxml&quot;)); </code></pre> <p><em>Be careful NOT to use a static load function on the FXMLLoader, or you will not be able to get your controller from your loader instance.</em></p> <p>FXMLLoader instances themselves never know anything about domain objects. You do not directly pass application specific domain objects into the FXMLLoader constructor, instead you:</p> <ol> <li>Construct an FXMLLoader based upon fxml markup at a specified location</li> <li>Get a controller from the FXMLLoader instance.</li> <li>Invoke methods on the retrieved controller to provide the controller with references to the domain objects.</li> </ol> <p>This blog (by another writer) provides an alternate, but similar, <a href="https://web.archive.org/web/20160612045146/http://ed4becky.net/homepage/javafx-from-the-trenches-singleton-controllers/" rel="noreferrer">example</a>.</p> <p><strong>Setting a Controller on the FXMLLoader</strong></p> <pre><code>CustomerDialogController dialogController = new CustomerDialogController(param1, param2); FXMLLoader loader = new FXMLLoader( getClass().getResource( &quot;customerDialog.fxml&quot; ) ); loader.setController(dialogController); Pane mainPane = loader.load(); </code></pre> <p>You can construct a new controller in code, passing any parameters you want from your caller into the controller constructor. Once you have constructed a controller, you can set it on an FXMLLoader instance <em>before</em> you invoke the <code>load()</code> <em>instance</em> method.</p> <p><em>To set a controller on a loader (in JavaFX 2.x) you CANNOT also define a <code>fx:controller</code> attribute in your fxml file.</em></p> <p>Due to the limitation on the <code>fx:controller</code> definition in FXML, I personally prefer getting the controller from the FXMLLoader rather than setting the controller into the FXMLLoader.</p> <p><strong>Having the Controller Retrieve Parameters from an External Static Method</strong></p> <p>This method is exemplified by Sergey's answer to <a href="https://stackoverflow.com/a/10136403/1155209">Javafx 2.0 How-to Application.getParameters() in a Controller.java file</a>.</p> <p><strong>Use Dependency Injection</strong></p> <p>FXMLLoader supports dependency injection systems like Guice, Spring or Java EE CDI by allowing you to set a custom controller factory on the FXMLLoader. This provides a callback that you can use to create the controller instance with dependent values injected by the respective dependency injection system.</p> <p>An example of JavaFX application and controller dependency injection with Spring is provided in the answer to:</p> <ul> <li><a href="https://stackoverflow.com/questions/57887944/adding-spring-dependency-injection-in-javafx-jpa-repo-service">Adding Spring Dependency Injection in JavaFX (JPA Repo, Service)</a></li> </ul> <p>A really nice, clean dependency injection approach is exemplified by the <a href="https://github.com/AdamBien/afterburner.fx" rel="noreferrer">afterburner.fx framework</a> with a sample <a href="https://github.com/AdamBien/airhacks-control" rel="noreferrer">air-hacks application</a> that uses it. afterburner.fx relies on JEE6 <a href="http://docs.oracle.com/javaee/6/api/javax/inject/package-summary.html" rel="noreferrer">javax.inject</a> to perform the dependency injection.</p> <p><strong>Use an Event Bus</strong></p> <p>Greg Brown, the original FXML specification creator and implementor, often suggests considering use of an event bus, such as the Guava <a href="https://github.com/google/guava/wiki/EventBusExplained" rel="noreferrer">EventBus</a>, for communication between FXML instantiated controllers and other application logic.</p> <blockquote> <p>The EventBus is a simple but powerful publish/subscribe API with annotations that allows POJOs to communicate with each other anywhere in a JVM without having to refer to each other.</p> </blockquote> <p><strong>Follow-up Q&amp;A</strong></p> <blockquote> <p>on first method, why do you return Stage? The method can be void as well because you already giving the command show(); just before return stage;. How do you plan usage by returning the Stage</p> </blockquote> <p>It is a functional solution to a problem. A stage is returned from the <code>showCustomerDialog</code> function so that a reference to it can be stored by an external class which may wish to do something, such as hide the stage based on a button click in the main window, at a later time. An alternate, object-oriented solution could encapsulate the functionality and stage reference inside a CustomerDialog object or have a CustomerDialog extend Stage. A full example for an object-oriented interface to a custom dialog encapsulating FXML, controller and model data is beyond the scope of this answer, but may make a worthwhile blog post for anybody inclined to create one.</p> <hr /> <p><strong>Additional information supplied by StackOverflow user named <a href="https://stackoverflow.com/users/1281217/bgmf">@dzim</a></strong></p> <p><em>Example for Spring Boot Dependency Injection</em></p> <p>The question of how to do it &quot;The Spring Boot Way&quot;, there was a discussion about JavaFX 2, which I anserwered in the attached permalink. The approach is still valid and tested in March 2016, on Spring Boot v1.3.3.RELEASE: <a href="https://stackoverflow.com/a/36310391/1281217">https://stackoverflow.com/a/36310391/1281217</a></p> <hr /> <p>Sometimes, you might want to pass results back to the caller, in which case you can check out the answer to the related question:</p> <ul> <li><a href="https://stackoverflow.com/questions/48173320/javafx-fxml-parameter-passing-from-controller-a-to-b-and-back/48217255#48217255">JavaFX FXML Parameter passing from Controller A to B and back</a></li> </ul>
{ "question_id": 14187963, "question_date": "2013-01-06T23:33:12.743Z", "question_score": 221, "tags": "javafx|parameters|dependency-injection|parameter-passing|fxml", "answer_id": 14190310, "answer_date": "2013-01-07T05:19:27.600Z", "answer_score": 299 }
Please answer the following Stack Overflow question: Title: What does 'low in coupling and high in cohesion' mean <p>I have problems understanding the statement <code>low in coupling and high in cohesion</code>. I have googled and read a lot about this, but still finding it hard to understand.</p> <p>To what I understand is <code>High cohesion</code> means, that we should have classes that are specialized to perform a particular function. Hope this is correct? Like a credit card validation class, which is specialized to validate credit cards only.</p> <p>And still don't understand what low Coupling means?</p>
<p>What I believe is this: </p> <p>Cohesion refers to the degree to which the elements of a module/class belong together, it is suggested that the related code should be close to each other, so we should strive for high cohesion and bind all related code together as close as possible. It has to do with the elements <strong>within</strong> the module/class.</p> <p>Coupling refers to the degree to which the different modules/classes depend on each other, it is suggested that all modules should be independent as far as possible, that's why low coupling. It has to do with the elements <strong>among</strong> different modules/classes.</p> <p>To visualize the whole picture will be helpful:</p> <p><a href="https://i.stack.imgur.com/zhZv2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zhZv2.png" alt="enter image description here"></a></p> <p>The screenshot was taken from <a href="https://www.coursera.org/lecture/object-oriented-design/1-3-1-coupling-and-cohesion-q8wGt" rel="noreferrer">Coursera</a>.</p>
{ "question_id": 14000762, "question_date": "2012-12-22T06:57:35.280Z", "question_score": 221, "tags": "oop|ooad", "answer_id": 14000957, "answer_date": "2012-12-22T07:32:01.190Z", "answer_score": 326 }
Please answer the following Stack Overflow question: Title: PostgreSQL ERROR: canceling statement due to conflict with recovery <p>I'm getting the following error when running a query on a PostgreSQL db in standby mode. The query that causes the error works fine for 1 month but when you query for more than 1 month an error results.</p> <pre><code>ERROR: canceling statement due to conflict with recovery Detail: User query might have needed to see row versions that must be removed </code></pre> <p>Any suggestions on how to resolve? Thanks</p>
<p>Running queries on hot-standby server is somewhat tricky — it can fail, because during querying some needed rows might be updated or deleted on primary. As a primary does not know that a query is started on secondary it thinks it can clean up (vacuum) old versions of its rows. Then secondary has to replay this cleanup, and has to forcibly cancel all queries which can use these rows.</p> <p>Longer queries will be canceled more often.</p> <p>You can work around this by starting a repeatable read transaction on primary which does a dummy query and then sits idle while a real query is run on secondary. Its presence will prevent vacuuming of old row versions on primary.</p> <p>More on this subject and other workarounds are explained in <a href="http://www.postgresql.org/docs/current/static/hot-standby.html#HOT-STANDBY-CONFLICT" rel="noreferrer">Hot Standby — Handling Query Conflicts</a> section in documentation.</p>
{ "question_id": 14592436, "question_date": "2013-01-29T21:15:22.510Z", "question_score": 221, "tags": "postgresql|postgresql-9.1", "answer_id": 14594277, "answer_date": "2013-01-29T23:51:54.830Z", "answer_score": 130 }
Please answer the following Stack Overflow question: Title: Java synchronized method lock on object, or method? <p>If I have 2 synchronized methods in the same class, but each accessing different variables, can 2 threads access those 2 methods at the same time? Does the lock occur on the object, or does it get as specific as the variables inside the synchronized method? </p> <p>Example:</p> <pre><code>class X { private int a; private int b; public synchronized void addA(){ a++; } public synchronized void addB(){ b++; } } </code></pre> <p>Can 2 threads access the same instance of class X performing <code>x.addA(</code>) and <code>x.addB()</code> at the same time?</p>
<p>If you declare the method as <em>synchronized</em> (as you're doing by typing <code>public synchronized void addA()</code>) you synchronize on the <strong>whole</strong> object, so two thread accessing a different variable from this same object would block each other anyway. </p> <p>If you want to synchronize only on one variable at a time, so two threads won't block each other while accessing different variables, you have synchronize on them separately in <code>synchronized ()</code> blocks. If <code>a</code> and <code>b</code> were object references you would use:</p> <pre><code>public void addA() { synchronized( a ) { a++; } } public void addB() { synchronized( b ) { b++; } } </code></pre> <p>But since they're primitives you can't do this.</p> <p>I would suggest you to use <em>AtomicInteger</em> instead:</p> <pre><code>import java.util.concurrent.atomic.AtomicInteger; class X { AtomicInteger a; AtomicInteger b; public void addA(){ a.incrementAndGet(); } public void addB(){ b.incrementAndGet(); } } </code></pre>
{ "question_id": 3047564, "question_date": "2010-06-15T17:38:08.297Z", "question_score": 221, "tags": "java|multithreading|thread-safety|locking|synchronized", "answer_id": 3047638, "answer_date": "2010-06-15T17:48:33.363Z", "answer_score": 226 }
Please answer the following Stack Overflow question: Title: Group query results by month and year in postgresql <p>I have the following database table on a Postgres server: </p> <pre><code>id date Product Sales 1245 01/04/2013 Toys 1000 1245 01/04/2013 Toys 2000 1231 01/02/2013 Bicycle 50000 456461 01/01/2014 Bananas 4546 </code></pre> <p>I would like to create a query that gives the <code>SUM</code> of the <code>Sales</code> column and groups the results by month and year as follows:</p> <pre><code>Apr 2013 3000 Toys Feb 2013 50000 Bicycle Jan 2014 4546 Bananas </code></pre> <p>Is there a simple way to do that?</p>
<pre><code>select to_char(date,'Mon') as mon, extract(year from date) as yyyy, sum("Sales") as "Sales" from yourtable group by 1,2 </code></pre> <p>At the request of Radu, I will explain that query:</p> <p><code>to_char(date,'Mon') as mon,</code> : converts the "date" attribute into the defined format of the short form of month.</p> <p><code>extract(year from date) as yyyy</code> : Postgresql's "extract" function is used to extract the YYYY year from the "date" attribute.</p> <p><code>sum("Sales") as "Sales"</code> : The SUM() function adds up all the "Sales" values, and supplies a case-sensitive alias, with the case sensitivity maintained by using double-quotes.</p> <p><code>group by 1,2</code> : The GROUP BY function must contain all columns from the SELECT list that are not part of the aggregate (aka, all columns not inside SUM/AVG/MIN/MAX etc functions). This tells the query that the SUM() should be applied for each unique combination of columns, which in this case are the month and year columns. The "1,2" part is a shorthand instead of using the column aliases, though it is probably best to use the full "to_char(...)" and "extract(...)" expressions for readability.</p>
{ "question_id": 17492167, "question_date": "2013-07-05T15:18:24.213Z", "question_score": 221, "tags": "sql|postgresql", "answer_id": 17492310, "answer_date": "2013-07-05T15:26:58.663Z", "answer_score": 251 }
Please answer the following Stack Overflow question: Title: How to get key names from JSON using jq <p><code>curl http://testhost.test.com:8080/application/app/version | jq '.version' | jq '.[]'</code></p> <p>The above command outputs only the values as below:</p> <pre><code>"[email protected]" "2323" "test" "02-03-2014-13:41" "application" </code></pre> <p>How can I get the key names instead like the below:</p> <pre><code>email versionID context date versionName </code></pre>
<p>You can use:</p> <pre><code>jq 'keys' file.json </code></pre> <p>Complete example</p> <pre><code>$ cat file.json { &quot;Archiver-Version&quot; : &quot;Plexus Archiver&quot;, &quot;Build-Id&quot; : &quot;&quot;, &quot;Build-Jdk&quot; : &quot;1.7.0_07&quot;, &quot;Build-Number&quot; : &quot;&quot;, &quot;Build-Tag&quot; : &quot;&quot;, &quot;Built-By&quot; : &quot;cporter&quot;, &quot;Created-By&quot; : &quot;Apache Maven&quot;, &quot;Implementation-Title&quot; : &quot;northstar&quot;, &quot;Implementation-Vendor-Id&quot; : &quot;com.test.testPack&quot;, &quot;Implementation-Version&quot; : &quot;testBox&quot;, &quot;Manifest-Version&quot; : &quot;1.0&quot;, &quot;appname&quot; : &quot;testApp&quot;, &quot;build-date&quot; : &quot;02-03-2014-13:41&quot;, &quot;version&quot; : &quot;testBox&quot; } $ jq 'keys' file.json [ &quot;Archiver-Version&quot;, &quot;Build-Id&quot;, &quot;Build-Jdk&quot;, &quot;Build-Number&quot;, &quot;Build-Tag&quot;, &quot;Built-By&quot;, &quot;Created-By&quot;, &quot;Implementation-Title&quot;, &quot;Implementation-Vendor-Id&quot;, &quot;Implementation-Version&quot;, &quot;Manifest-Version&quot;, &quot;appname&quot;, &quot;build-date&quot;, &quot;version&quot; ] </code></pre> <p><strong>UPDATE:</strong> To create a BASH array using these keys:</p> <p>Using BASH 4+:</p> <pre><code>mapfile -t arr &lt; &lt;(jq -r 'keys[]' ms.json) </code></pre> <p>On older BASH you can do:</p> <pre><code>arr=() while IFS='' read -r line; do arr+=(&quot;$line&quot;) done &lt; &lt;(jq 'keys[]' ms.json) </code></pre> <p>Then print it:</p> <pre><code>printf &quot;%s\n&quot; ${arr[@]} &quot;Archiver-Version&quot; &quot;Build-Id&quot; &quot;Build-Jdk&quot; &quot;Build-Number&quot; &quot;Build-Tag&quot; &quot;Built-By&quot; &quot;Created-By&quot; &quot;Implementation-Title&quot; &quot;Implementation-Vendor-Id&quot; &quot;Implementation-Version&quot; &quot;Manifest-Version&quot; &quot;appname&quot; &quot;build-date&quot; &quot;version&quot; </code></pre>
{ "question_id": 23118341, "question_date": "2014-04-16T19:21:23.563Z", "question_score": 221, "tags": "json|shell|unix|key|jq", "answer_id": 23118607, "answer_date": "2014-04-16T19:36:11.903Z", "answer_score": 310 }
Please answer the following Stack Overflow question: Title: How to dynamically load a Python class <p>Given a string of a Python class, e.g. <code>my_package.my_module.MyClass</code>, what is the best possible way to load it?</p> <p>In other words I am looking for a equivalent <code>Class.forName()</code> in Java, function in Python. It needs to work on Google App Engine.</p> <p>Preferably this would be a function that accepts the FQN of the class as a string, and returns a reference to the class:</p> <pre><code>my_class = load_class('my_package.my_module.MyClass') my_instance = my_class() </code></pre>
<p>From the python documentation, here's the function you want:</p> <pre><code>def my_import(name): components = name.split('.') mod = __import__(components[0]) for comp in components[1:]: mod = getattr(mod, comp) return mod </code></pre> <p>The reason a simple <code>__import__</code> won't work is because any import of anything past the first dot in a package string is an attribute of the module you're importing. Thus, something like this won't work:</p> <pre><code>__import__('foo.bar.baz.qux') </code></pre> <p>You'd have to call the above function like so:</p> <pre><code>my_import('foo.bar.baz.qux') </code></pre> <p>Or in the case of your example:</p> <pre><code>klass = my_import('my_package.my_module.my_class') some_object = klass() </code></pre> <p><strong>EDIT</strong>: I was a bit off on this. What you're basically wanting to do is this:</p> <pre><code>from my_package.my_module import my_class </code></pre> <p>The above function is only necessary if you have a <em>empty</em> fromlist. Thus, the appropriate call would be like this:</p> <pre><code>mod = __import__('my_package.my_module', fromlist=['my_class']) klass = getattr(mod, 'my_class') </code></pre>
{ "question_id": 547829, "question_date": "2009-02-13T21:49:04.940Z", "question_score": 221, "tags": "python|reflection|python-import", "answer_id": 547867, "answer_date": "2009-02-13T22:02:57.683Z", "answer_score": 242 }
Please answer the following Stack Overflow question: Title: How to properly seed random number generator <p>I am trying to generate a random string in Go and here is the code I have written so far:</p> <pre><code>package main import ( "bytes" "fmt" "math/rand" "time" ) func main() { fmt.Println(randomString(10)) } func randomString(l int) string { var result bytes.Buffer var temp string for i := 0; i &lt; l; { if string(randInt(65, 90)) != temp { temp = string(randInt(65, 90)) result.WriteString(temp) i++ } } return result.String() } func randInt(min int, max int) int { rand.Seed(time.Now().UTC().UnixNano()) return min + rand.Intn(max-min) } </code></pre> <p>My implementation is very slow. Seeding using <code>time</code> brings the same random number for a certain time, so the loop iterates again and again. How can I improve my code?</p>
<p>Each time you set the same seed, you get the same sequence. So of course if you're setting the seed to the time in a fast loop, you'll probably call it with the same seed many times.</p> <p>In your case, as you're calling your <code>randInt</code> function until you have a different value, you're waiting for the time (as returned by Nano) to change.</p> <p><a href="http://en.wikipedia.org/wiki/Pseudorandom_number_generator" rel="noreferrer">As for all pseudo-random libraries</a>, you have to set the seed only once, for example when initializing your program unless you specifically need to reproduce a given sequence (which is usually only done for debugging and unit testing).</p> <p>After that you simply call <code>Intn</code> to get the next random integer.</p> <p>Move the <code>rand.Seed(time.Now().UTC().UnixNano())</code> line from the randInt function to the start of the main and everything will be faster. And lose the <code>.UTC()</code> call since:</p> <blockquote> <p>UnixNano returns t as a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC.</p> </blockquote> <p>Note also that I think you can simplify your string building:</p> <pre><code>package main import ( &quot;fmt&quot; &quot;math/rand&quot; &quot;time&quot; ) func main() { rand.Seed(time.Now().UnixNano()) fmt.Println(randomString(10)) } func randomString(l int) string { bytes := make([]byte, l) for i := 0; i &lt; l; i++ { bytes[i] = byte(randInt(65, 90)) } return string(bytes) } func randInt(min int, max int) int { return min + rand.Intn(max-min) } </code></pre>
{ "question_id": 12321133, "question_date": "2012-09-07T15:29:44.270Z", "question_score": 221, "tags": "random|go", "answer_id": 12321192, "answer_date": "2012-09-07T15:33:05.050Z", "answer_score": 286 }
Please answer the following Stack Overflow question: Title: Shell command to find lines common in two files <p>I'm sure I once found a shell command which could print the common lines from two or more files. What is its name?</p> <p>It was much simpler than <a href="https://linux.die.net/man/1/diff" rel="noreferrer"><code>diff</code></a>.</p>
<p>The command you are seeking is <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/comm.html" rel="noreferrer"><code>comm</code></a>. eg:-</p> <pre><code>comm -12 1.sorted.txt 2.sorted.txt </code></pre> <p>Here:</p> <p><strong>-1</strong> : suppress column 1 (lines unique to 1.sorted.txt)</p> <p><strong>-2</strong> : suppress column 2 (lines unique to 2.sorted.txt)</p>
{ "question_id": 373810, "question_date": "2008-12-17T06:36:55.330Z", "question_score": 221, "tags": "shell|command-line", "answer_id": 373819, "answer_date": "2008-12-17T06:40:58.020Z", "answer_score": 274 }
Please answer the following Stack Overflow question: Title: Why is a div with "display: table-cell;" not affected by margin? <p>I have <code>div</code> elements next to each other with <code>display: table-cell;</code>.</p> <p>I want to set <code>margin</code> between them, but <code>margin: 5px</code> has no effect. Why?</p> <p>My code:</p> <pre><code>&lt;div style="display: table-cell; margin: 5px; background-color: red;"&gt;1&lt;/div&gt; &lt;div style="display: table-cell; margin: 5px; background-color: green;"&gt;1&lt;/div&gt; </code></pre>
<h2>Cause</h2> <p>From <a href="https://developer.mozilla.org/en-US/docs/CSS/margin" rel="noreferrer">the MDN documentation</a>:</p> <blockquote> <p>[The margin property] applies to all elements except elements with table display types other than table-caption, table and inline-table</p> </blockquote> <p>In other words, the <code>margin</code> property is <em>not</em> applicable to <code>display:table-cell</code> elements.</p> <h2>Solution</h2> <p>Consider using the <a href="https://developer.mozilla.org/en-US/docs/CSS/border-spacing" rel="noreferrer"><code>border-spacing</code></a> property instead.</p> <p>Note it should be applied to a parent element with a <code>display:table</code> layout and <code>border-collapse:separate</code>.</p> <p>For example:</p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="table"&gt; &lt;div class="row"&gt; &lt;div class="cell"&gt;123&lt;/div&gt; &lt;div class="cell"&gt;456&lt;/div&gt; &lt;div class="cell"&gt;879&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre class="lang-css prettyprint-override"><code>.table {display:table;border-collapse:separate;border-spacing:5px;} .row {display:table-row;} .cell {display:table-cell;padding:5px;border:1px solid black;} </code></pre> <h2><strong>See <a href="http://jsfiddle.net/FhQwb/1/" rel="noreferrer">jsFiddle demo</a></strong></h2> <hr> <p><strong>Different margin horizontally and vertically</strong></p> <p>As mentioned by Diego Quirós, the <code>border-spacing</code> property also accepts two values to set a different margin for the horizontal and vertical axes.</p> <p>For example</p> <pre class="lang-css prettyprint-override"><code>.table {/*...*/border-spacing:3px 5px;} /* 3px horizontally, 5px vertically */ </code></pre>
{ "question_id": 16398823, "question_date": "2013-05-06T12:30:42.807Z", "question_score": 221, "tags": "html|css", "answer_id": 16398904, "answer_date": "2013-05-06T12:35:43.943Z", "answer_score": 319 }
Please answer the following Stack Overflow question: Title: Is the buildSessionFactory() Configuration method deprecated in Hibernate? <p>When I updated the Hibernate version from 3.6.8 to 4.0.0, I got a warning about deprecated method <code>buildSessionFactory()</code> in this line:</p> <pre><code>private static final SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); </code></pre> <p>the Javadoc recommends using another method</p> <p><code>buildSessionFactory(ServiceRegistry serviceRegistry)</code></p> <p>but in the <a href="http://docs.jboss.org/hibernate/core/4.0/manual/en-US/html/session-configuration.html#configuration-sessionfactory" rel="nofollow noreferrer">documentation</a> I found deprecated variant</p>
<p>Yes it is deprecated. Replace your SessionFactory with the following:</p> <p>In <strong>Hibernate 4.0, 4.1, 4.2</strong></p> <pre><code>private static SessionFactory sessionFactory; private static ServiceRegistry serviceRegistry; public static SessionFactory createSessionFactory() { Configuration configuration = new Configuration(); configuration.configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings( configuration.getProperties()). buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } </code></pre> <blockquote> <p><strong>UPDATE:</strong></p> </blockquote> <p>In <strong>Hibernate 4.3</strong> ServiceRegistryBuilder is <strong>deprecated</strong>. Use the following instead.</p> <pre><code>serviceRegistry = new StandardServiceRegistryBuilder().applySettings( configuration.getProperties()).build(); </code></pre>
{ "question_id": 8621906, "question_date": "2011-12-24T00:43:56.990Z", "question_score": 221, "tags": "java|hibernate|configuration|deprecated|bootstrapping", "answer_id": 8830848, "answer_date": "2012-01-12T06:07:18.213Z", "answer_score": 383 }
Please answer the following Stack Overflow question: Title: PHP function overloading <p>Coming from C++ background ;)<br> How can I overload PHP functions? </p> <p>One function definition if there are any arguments, and another if there are no arguments? Is it possible in PHP? Or should I use if else to check if there are any parameters passed from $_GET and POST?? and relate them?</p>
<p>You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name. Class <a href="http://www.php.net/manual/en/language.oop5.overloading.php" rel="noreferrer">method overloading</a> is different in PHP than in many other languages. PHP uses the same word but it describes a different pattern.</p> <p>You can, however, declare a <a href="http://en.wikipedia.org/wiki/Variadic_function" rel="noreferrer">variadic function</a> that takes in a variable number of arguments. You would use <a href="http://php.net/manual/en/function.func-num-args.php" rel="noreferrer"><code>func_num_args()</code></a> and <a href="http://php.net/manual/en/function.func-get-arg.php" rel="noreferrer"><code>func_get_arg()</code></a> to get the arguments passed, and use them normally.</p> <p>For example:</p> <pre><code>function myFunc() { for ($i = 0; $i &lt; func_num_args(); $i++) { printf("Argument %d: %s\n", $i, func_get_arg($i)); } } /* Argument 0: a Argument 1: 2 Argument 2: 3.5 */ myFunc('a', 2, 3.5); </code></pre>
{ "question_id": 4697705, "question_date": "2011-01-15T03:03:01.450Z", "question_score": 221, "tags": "php|arguments|overloading", "answer_id": 4697712, "answer_date": "2011-01-15T03:04:55.457Z", "answer_score": 243 }
Please answer the following Stack Overflow question: Title: How to put individual tags for a matplotlib scatter plot? <p>I am trying to do a scatter plot in matplotlib and I couldn't find a way to add tags to the points. For example:</p> <pre><code>scatter1=plt.scatter(data1["x"], data1["y"], marker="o", c="blue", facecolors="white", edgecolors="blue") </code></pre> <p>I want for the points in "y" to have labels as "point 1", "point 2", etc. I couldn't figure it out.</p>
<p>Perhaps use <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.annotate">plt.annotate</a>:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt N = 10 data = np.random.random((N, 4)) labels = ['point{0}'.format(i) for i in range(N)] plt.subplots_adjust(bottom = 0.1) plt.scatter( data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500, cmap=plt.get_cmap('Spectral')) for label, x, y in zip(labels, data[:, 0], data[:, 1]): plt.annotate( label, xy=(x, y), xytext=(-20, 20), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5), arrowprops=dict(arrowstyle = '-&gt;', connectionstyle='arc3,rad=0')) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/b5uhP.png" alt="enter image description here"></p>
{ "question_id": 5147112, "question_date": "2011-02-28T20:21:03.187Z", "question_score": 221, "tags": "python|matplotlib", "answer_id": 5147430, "answer_date": "2011-02-28T20:51:21.770Z", "answer_score": 383 }
Please answer the following Stack Overflow question: Title: How to escape hash character in URL <p>How can I escape the <code>#</code> hash sign (sometimes known as number sign or pound sign) sent in the query string of a URL?</p>
<p><a href="https://en.wikipedia.org/wiki/Percent-encoding" rel="nofollow noreferrer">Percent encoding</a>. Replace the hash with <code>%23</code>.</p>
{ "question_id": 5007352, "question_date": "2011-02-15T17:47:36.073Z", "question_score": 221, "tags": "html|http|query-string", "answer_id": 5007362, "answer_date": "2011-02-15T17:48:50.147Z", "answer_score": 367 }
Please answer the following Stack Overflow question: Title: Visual Studio Expand/Collapse keyboard shortcuts <p>In Visual Studio, if I have a code file open, I can press <kbd>CTRL</kbd> + <kbd>M</kbd> or <kbd>CTRL</kbd> + <kbd>M</kbd> + <kbd>O</kbd> to collapse all code blocks, regions, namespaces, etc.</p> <p>How to I do the opposite and expand everything?</p> <p>I have Googled this, but cannot seem to find a shortcut that works!</p>
<p><strong>Collapse to definitions</strong></p> <p><kbd>CTRL</kbd> + <kbd>M</kbd>, <kbd>O</kbd></p> <p><strong>Expand all outlining</strong></p> <p><kbd>CTRL</kbd> + <kbd>M</kbd>, <kbd>X</kbd></p> <p><strong>Expand or collapse everything</strong></p> <p><kbd>CTRL</kbd> + <kbd>M</kbd>, <kbd>L</kbd></p> <p><em>This also works with other languages like TypeScript and JavaScript</em></p>
{ "question_id": 14051589, "question_date": "2012-12-27T08:25:20.700Z", "question_score": 221, "tags": "visual-studio|visual-studio-2012|keyboard-shortcuts", "answer_id": 14051632, "answer_date": "2012-12-27T08:29:45.323Z", "answer_score": 372 }
Please answer the following Stack Overflow question: Title: How do I encode/decode HTML entities in Ruby? <p>I am trying to decode some HTML entities, such as <code>'&amp;amp;lt;'</code> becoming <code>'&lt;'</code>.</p> <p>I have an old gem (<a href="http://github.com/tma/html_helpers/" rel="noreferrer">html_helpers</a>) but it seems to have been abandoned twice.</p> <p>Any recommendations? I will need to use it in a model.</p>
<p><a href="https://rubygems.org/gems/htmlentities" rel="noreferrer">HTMLEntities</a> can do it:</p> <pre><code>: jmglov@laurana; sudo gem install htmlentities Successfully installed htmlentities-4.2.4 : jmglov@laurana; irb irb(main):001:0&gt; require 'htmlentities' =&gt; [] irb(main):002:0&gt; HTMLEntities.new.decode "&amp;iexcl;I&amp;#39;m highly&amp;nbsp;annoyed with character references!" =&gt; "¡I'm highly annoyed with character references!" </code></pre>
{ "question_id": 1600526, "question_date": "2009-10-21T12:36:33.283Z", "question_score": 221, "tags": "html|ruby", "answer_id": 5210999, "answer_date": "2011-03-06T14:19:04.557Z", "answer_score": 165 }
Please answer the following Stack Overflow question: Title: Throw keyword in function's signature <p>What is the technical reason why it is considered bad practice to use the C++ <code>throw</code> keyword in a function signature?</p> <pre><code>bool some_func() throw(myExc) { ... if (problem_occurred) { throw myExc("problem occurred"); } ... } </code></pre>
<p>No, it is not considered good practice. On the contrary, it is generally considered a bad idea.</p> <p><a href="http://www.gotw.ca/publications/mill22.htm" rel="noreferrer">http://www.gotw.ca/publications/mill22.htm</a> goes into a lot more detail about why, but the problem is partly that the compiler is unable to enforce this, so it has to be checked at runtime, which is usually undesirable. And it is not well supported in any case. (MSVC ignores exception specifications, except throw(), which it interprets as a guarantee that no exception will be thrown.</p>
{ "question_id": 1055387, "question_date": "2009-06-28T18:00:26.080Z", "question_score": 221, "tags": "c++|exception", "answer_id": 1055407, "answer_date": "2009-06-28T18:11:03.537Z", "answer_score": 136 }
Please answer the following Stack Overflow question: Title: ViewBag, ViewData and TempData <p>Could any body explain, when to use </p> <ol> <li>TempData</li> <li>ViewBag</li> <li>ViewData</li> </ol> <p>I have a requirement, where I need to set a value in a controller one, that controller will redirect to Controller Two and Controller Two will render the View.</p> <p>I have tried to use ViewBag, the value gets lost by the time I reach Controller Two.</p> <p>Can I know when to use and advantages or disadvantages? </p> <p>Thanks</p>
<blockquote> <p>1)TempData </p> </blockquote> <p>Allows you to store data that will survive for a redirect. Internally it uses the Session as backing store, after the redirect is made the data is automatically evicted. The pattern is the following:</p> <pre><code>public ActionResult Foo() { // store something into the tempdata that will be available during a single redirect TempData["foo"] = "bar"; // you should always redirect if you store something into TempData to // a controller action that will consume this data return RedirectToAction("bar"); } public ActionResult Bar() { var foo = TempData["foo"]; ... } </code></pre> <blockquote> <p>2)ViewBag, ViewData</p> </blockquote> <p>Allows you to store data in a controller action that will be used in the corresponding view. This assumes that the action returns a view and doesn't redirect. Lives only during the current request. </p> <p>The pattern is the following:</p> <pre><code>public ActionResult Foo() { ViewBag.Foo = "bar"; return View(); } </code></pre> <p>and in the view:</p> <pre><code>@ViewBag.Foo </code></pre> <p>or with ViewData:</p> <pre><code>public ActionResult Foo() { ViewData["Foo"] = "bar"; return View(); } </code></pre> <p>and in the view:</p> <pre><code>@ViewData["Foo"] </code></pre> <p><code>ViewBag</code> is just a dynamic wrapper around <code>ViewData</code> and exists only in ASP.NET MVC 3.</p> <p>This being said, none of those two constructs should ever be used. You should use view models and strongly typed views. So the correct pattern is the following:</p> <p>View model:</p> <pre><code>public class MyViewModel { public string Foo { get; set; } } </code></pre> <p>Action:</p> <pre><code>public Action Foo() { var model = new MyViewModel { Foo = "bar" }; return View(model); } </code></pre> <p>Strongly typed view:</p> <pre><code>@model MyViewModel @Model.Foo </code></pre> <hr> <p>After this brief introduction let's answer your question:</p> <blockquote> <p>My requirement is I want to set a value in a controller one, that controller will redirect to ControllerTwo and Controller2 will render the View.</p> </blockquote> <pre><code>public class OneController: Controller { public ActionResult Index() { TempData["foo"] = "bar"; return RedirectToAction("index", "two"); } } public class TwoController: Controller { public ActionResult Index() { var model = new MyViewModel { Foo = TempData["foo"] as string }; return View(model); } } </code></pre> <p>and the corresponding view (<code>~/Views/Two/Index.cshtml</code>):</p> <pre><code>@model MyViewModel @Html.DisplayFor(x =&gt; x.Foo) </code></pre> <hr> <p>There are drawbacks of using TempData as well: if the user hits F5 on the target page the data will be lost.</p> <p>Personally I don't use TempData neither. It's because internally it uses Session and I disable session in my applications. I prefer a more RESTful way to achieve this. Which is: in the first controller action that performs the redirect store the object in your data store and user the generated unique id when redirecting. Then on the target action use this id to fetch back the initially stored object:</p> <pre><code>public class OneController: Controller { public ActionResult Index() { var id = Repository.SaveData("foo"); return RedirectToAction("index", "two", new { id = id }); } } public class TwoController: Controller { public ActionResult Index(string id) { var model = new MyViewModel { Foo = Repository.GetData(id) }; return View(model); } } </code></pre> <p>The view stays the same.</p>
{ "question_id": 7993263, "question_date": "2011-11-03T10:22:38.357Z", "question_score": 221, "tags": "asp.net-mvc-3", "answer_id": 7993283, "answer_date": "2011-11-03T10:24:00.267Z", "answer_score": 310 }
Please answer the following Stack Overflow question: Title: sed fails with "unknown option to `s'" error <p>I'm trying to use </p> <pre><code>sed -i -e "s/.*seb.*/ \"$ftp_login_template\"/" $ftp_dir </code></pre> <p>however I get this error:</p> <pre><code>sed: -e expression #1, char 34: unknown option to `s' </code></pre> <p>I don't understand why since this works perfectly:</p> <pre><code>sed -i -e "s/.*wbspassword.*/ \"wbspassword\": \"$password\",/" $user_conf </code></pre> <p>Any ideas as to what I'm doing wrong? </p> <p>Could this be the problem? <code>ftp_login_template=\${user}:${password}:24:86::\/var\/lib\/clit.${user}\/downloads:\/bin\/false\"</code></p>
<p>The problem is with slashes: your variable contains them and the final command will be something like <code>sed "s/string/path/to/something/g"</code>, containing way too many slashes.</p> <p>Since <code>sed</code> can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:</p> <pre><code>replacement="/my/path" sed --expression "s@pattern@$replacement@" </code></pre> <p>Note that this is not bullet proof: if the replacement string later contains <code>@</code> it will break for the same reason, and any backslash sequences like <code>\1</code> will still be interpreted according to <code>sed</code> rules. Using <code>|</code> as a delimiter is also a nice option as it is similar in readability to <code>/</code>. </p>
{ "question_id": 9366816, "question_date": "2012-02-20T18:58:50.533Z", "question_score": 221, "tags": "sed", "answer_id": 9366940, "answer_date": "2012-02-20T19:08:48.777Z", "answer_score": 476 }
Please answer the following Stack Overflow question: Title: What is the difference between `new Object()` and object literal notation? <p>What is the difference between this constructor-based syntax for creating an object:</p> <pre><code>person = new Object() </code></pre> <p>...and this literal syntax:</p> <pre><code>person = { property1 : "Hello" }; </code></pre> <p>It appears that both do the same thing, although JSLint prefers you use object literal notation.</p> <p>Which one is better and why?</p>
<p>They both do the same thing (unless someone's done something unusual), other than that your second one creates an object <em>and</em> adds a property to it. But literal notation takes less space in the source code. It's clearly recognizable as to what is happening, so using <code>new Object()</code>, you are really just typing more and (in theory, if not optimized out by the JavaScript engine) doing an unnecessary function call.</p> <p>These </p> <pre><code>person = new Object() /*You should put a semicolon here too. It's not required, but it is good practice.*/ -or- person = { property1 : "Hello" }; </code></pre> <p>technically do not do the same thing. The first just creates an object. The second creates one and assigns a property. For the first one to be the same you then need a second step to create and assign the property.</p> <p>The "something unusual" that someone could do would be to shadow or assign to the default <code>Object</code> global:</p> <pre><code>// Don't do this Object = 23; </code></pre> <p>In that <em>highly-unusual</em> case, <code>new Object</code> will fail but <code>{}</code> will work.</p> <p>In practice, there's never a reason to use <code>new Object</code> rather than <code>{}</code> (unless you've done that very unusual thing).</p>
{ "question_id": 4597926, "question_date": "2011-01-04T20:09:56.973Z", "question_score": 221, "tags": "javascript|object|jslint", "answer_id": 4597935, "answer_date": "2011-01-04T20:10:47.477Z", "answer_score": 134 }
Please answer the following Stack Overflow question: Title: ORDER BY the IN value list <p>I have a simple SQL query in PostgreSQL 8.3 that grabs a bunch of comments. I provide a <em>sorted</em> list of values to the <code>IN</code> construct in the <code>WHERE</code> clause:</p> <pre><code>SELECT * FROM comments WHERE (comments.id IN (1,3,2,4)); </code></pre> <p>This returns comments in an arbitrary order which in my happens to be ids like <code>1,2,3,4</code>.</p> <p>I want the resulting rows sorted like the list in the <code>IN</code> construct: <code>(1,3,2,4)</code>.<br> How to achieve that?</p>
<p>You can do it quite easily with (introduced in PostgreSQL 8.2) VALUES (), ().</p> <p>Syntax will be like this:</p> <pre><code>select c.* from comments c join ( values (1,1), (3,2), (2,3), (4,4) ) as x (id, ordering) on c.id = x.id order by x.ordering </code></pre>
{ "question_id": 866465, "question_date": "2009-05-15T00:02:22.520Z", "question_score": 221, "tags": "sql|postgresql|sql-order-by|sql-in", "answer_id": 867578, "answer_date": "2009-05-15T08:32:50.907Z", "answer_score": 127 }
Please answer the following Stack Overflow question: Title: Twitter Bootstrap 3.0 how do I "badge badge-important" now <p>In version two I could use </p> <blockquote> <p>badge badge-important</p> </blockquote> <p>I see that the .badge element no longer has contextual (-success,-primary,etc..) classes.</p> <p>How do i achieve the same thing in version 3?</p> <p>Eg. I want warning badges and important badges in my UI</p>
<p>Just add this <strong>one-line</strong> class in your CSS, and use the bootstrap <code>label</code> component.</p> <pre><code>.label-as-badge { border-radius: 1em; } </code></pre> <p>Compare this <code>label</code> and <code>badge</code> side by side:</p> <pre><code>&lt;span class="label label-default label-as-badge"&gt;hello&lt;/span&gt; &lt;span class="badge"&gt;world&lt;/span&gt; </code></pre> <p><img src="https://i.stack.imgur.com/7PQhF.png" alt="enter image description here"></p> <p>They appear the same. But in the CSS, <code>label</code> uses <code>em</code> so it scales nicely, and it still has all the "-color" classes. So the label will scale to bigger font sizes better, and can be colored with label-success, label-warning, etc. Here are two examples:</p> <pre><code>&lt;span class="label label-success label-as-badge"&gt;Yay! Rah!&lt;/span&gt; </code></pre> <p><img src="https://i.stack.imgur.com/iByRp.png" alt="enter image description here"></p> <p>Or where things are bigger:</p> <pre><code>&lt;div style="font-size: 36px"&gt;&lt;!-- pretend an enclosing class has big font size --&gt; &lt;span class="label label-success label-as-badge"&gt;Yay! Rah!&lt;/span&gt; &lt;/div&gt; </code></pre> <p><img src="https://i.stack.imgur.com/BVbAY.png" alt="enter image description here"></p> <hr> <p><strong>11/16/2015</strong>: Looking at how we'll do this in Bootstrap 4</p> <p>Looks like <code>.badge</code> classes are completely gone. But there's a built-in <code>.label-pill</code> class <a href="https://github.com/twbs/bootstrap/blob/eea6690d0e47b25a02bb42e610fde7e5ecd247d7/dist/css/bootstrap.css#L4210-L4214">(here)</a> that looks like what we want.</p> <pre><code>.label-pill { padding-right: .6em; padding-left: .6em; border-radius: 10rem; } </code></pre> <p>In use it looks like this:</p> <pre><code>&lt;span class="label label-pill label-default"&gt;Default&lt;/span&gt; &lt;span class="label label-pill label-primary"&gt;Primary&lt;/span&gt; &lt;span class="label label-pill label-success"&gt;Success&lt;/span&gt; &lt;span class="label label-pill label-info"&gt;Info&lt;/span&gt; &lt;span class="label label-pill label-warning"&gt;Warning&lt;/span&gt; &lt;span class="label label-pill label-danger"&gt;Danger&lt;/span&gt; </code></pre> <p><a href="https://i.stack.imgur.com/vJjrx.png"><img src="https://i.stack.imgur.com/vJjrx.png" alt="enter image description here"></a></p> <hr> <p><strong>11/04/2014</strong>: Here's an update on why cross-pollinating alert classes with <code>.badge</code> is not so great. I think this picture sums it up:</p> <p><img src="https://i.stack.imgur.com/4Z25Q.png" alt="enter image description here"></p> <p>Those alert classes were not designed to go with badges. It renders them with a "hint" of the intended colors, but in the end consistency is thrown out the window and readability is questionable. Those alert-hacked badges are not visually cohesive.</p> <p>The <code>.label-as-badge</code> solution is only extending the bootstrap design. We are keeping intact all the decision making made by the bootstrap designers, namely the consideration they gave for readability and cohesion across all the possible colors, as well as the color choices themselves. The <code>.label-as-badge</code> class only adds rounded corners, and nothing else. There are no color definitions introduced. Thus, a single line of CSS.</p> <p>Yep, it is easier to just hack away and drop in those <code>.alert-xxxxx</code> classes -- you don't have to add <em>any</em> lines of CSS. Or you <em>could</em> care more about the little things and add one line.</p>
{ "question_id": 18730116, "question_date": "2013-09-10T23:03:36.390Z", "question_score": 221, "tags": "twitter-bootstrap|twitter-bootstrap-3", "answer_id": 26495054, "answer_date": "2014-10-21T19:47:43.153Z", "answer_score": 264 }
Please answer the following Stack Overflow question: Title: What's quicker and better to determine if an array key exists in PHP? <p>Consider these 2 examples...</p> <pre><code>$key = 'jim'; // example 1 if (isset($array[$key])) { // ... } // example 2 if (array_key_exists($key, $array)) { // ... } </code></pre> <p>I'm interested in knowing if either of these are better. I've always used the first, but have seen a lot of people use the second example on this site.</p> <p>So, which is better? Faster? Clearer intent?</p>
<p><code>isset()</code> is faster, but it's not the same as <code>array_key_exists()</code>.</p> <p><code>array_key_exists()</code> purely checks if the key exists, even if the value is <code>NULL</code>.</p> <p>Whereas <code>isset()</code> will return <code>false</code> if the key exist and value is <code>NULL</code>.</p>
{ "question_id": 700227, "question_date": "2009-03-31T06:17:31.197Z", "question_score": 221, "tags": "php|performance", "answer_id": 700257, "answer_date": "2009-03-31T06:23:39.513Z", "answer_score": 343 }
Please answer the following Stack Overflow question: Title: `col-xs-*` not working in Bootstrap 4 <p>I have not encountered this before, and I am having a very hard time trying to find the solution. When having a column equal to medium in bootstrap like so:</p> <pre><code>&lt;h1 class="text-center"&gt;Hello, world!&lt;/h1&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-12 text-center"&gt; &lt;h1&gt;vicki williams&lt;/h1&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>The text-align works fine: <a href="https://i.stack.imgur.com/g5WcO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/g5WcO.png" alt="enter image description here"></a></p> <p>But when making the column equal to extra small like so:</p> <pre><code> &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-12 text-center"&gt; &lt;h1&gt;vicki williams&lt;/h1&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Then the text-align no longer works: <a href="https://i.stack.imgur.com/HIIkx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HIIkx.png" alt="enter image description here"></a></p> <p>Is there some bootstrap concept that I am not understanding or is this in fact a error like I think it is. I have never had this issue, as my text always has aligned in the past with xs. Any help would be greatly appreciated. Here is my complete code:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;!-- Required meta tags --&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"&gt; &lt;!-- Bootstrap CSS --&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous"&gt; &lt;/head&gt; &lt;body&gt; &lt;h1 class="text-center"&gt;Hello, world!&lt;/h1&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-12 text-center"&gt; &lt;h1&gt;vicki williams&lt;/h1&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- jQuery first, then Tether, then Bootstrap JS. --&gt; &lt;script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p><code>col-xs-*</code> have been dropped in Bootstrap 4 in favor of <code>col-*</code>. </p> <p>Replace <code>col-xs-12</code> with <code>col-12</code> and it will work as expected.</p> <p>Also note <code>col-xs-offset-{n}</code> were replaced by <code>offset-{n}</code> in v4.</p>
{ "question_id": 41794746, "question_date": "2017-01-22T18:39:56.737Z", "question_score": 221, "tags": "html|css|twitter-bootstrap|twitter-bootstrap-4|text-alignment", "answer_id": 41795300, "answer_date": "2017-01-22T19:35:50.073Z", "answer_score": 570 }
Please answer the following Stack Overflow question: Title: Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host] <p>I have been googling for about 90 minutes now and still don't have an answer to this. Where do I set <code>default_url_options</code>? I've already set it for <code>config.action_mailer.default_url_options</code> to solve this same bug elsewhere, but now I'm getting this error when trying to use a URL helper inside an RSpec spec. I have no idea where it's expecting default_url_options to be set.</p> <pre><code> Failure/Error: listing_url(listing).should match(/\/\d+-\w+$/) RuntimeError: Missing host to link to! Please provide :host parameter or set default_url_options[:host] # ./spec/routing/listing_routing_spec.rb:9:in `block (3 levels) in &lt;top (required)&gt;' </code></pre> <p>This code has nothing to do with emails/ActionMailer, it just happens to need a URL instead of a path.</p> <p>Any ideas?</p>
<pre><code>Your::Application.routes.draw do default_url_options :host =&gt; "example.com" # ... snip ... end </code></pre> <p>Somewhere in <code>routes.rb</code> :)</p>
{ "question_id": 7219732, "question_date": "2011-08-28T08:02:16.020Z", "question_score": 221, "tags": "ruby-on-rails|rspec", "answer_id": 7219803, "answer_date": "2011-08-28T08:22:17.783Z", "answer_score": 85 }
Please answer the following Stack Overflow question: Title: Moq: How to get to a parameter passed to a method of a mocked service <p>Imagine this class</p> <pre><code>public class Foo { private Handler _h; public Foo(Handler h) { _h = h; } public void Bar(int i) { _h.AsyncHandle(CalcOn(i)); } private SomeResponse CalcOn(int i) { ...; } } </code></pre> <p>Mo(q)cking Handler in a test of Foo, how would I be able to check what <code>Bar()</code> has passed to <code>_h.AsyncHandle</code>?</p>
<p>You can use the Mock.Callback-method:</p> <pre><code>var mock = new Mock&lt;Handler&gt;(); SomeResponse result = null; mock.Setup(h =&gt; h.AsyncHandle(It.IsAny&lt;SomeResponse&gt;())) .Callback&lt;SomeResponse&gt;(r =&gt; result = r); // do your test new Foo(mock.Object).Bar(22); Assert.NotNull(result); </code></pre> <p>If you only want to check something simple on the passed in argument, you also can do it directly:</p> <pre><code>mock.Setup(h =&gt; h.AsyncHandle(It.Is&lt;SomeResponse&gt;(response =&gt; response != null))); </code></pre>
{ "question_id": 3269717, "question_date": "2010-07-17T00:39:24.757Z", "question_score": 221, "tags": "c#|moq", "answer_id": 3293014, "answer_date": "2010-07-20T18:16:44.110Z", "answer_score": 339 }
Please answer the following Stack Overflow question: Title: is there a Java equivalent to null coalescing operator (??) in C#? <p>Is it possible to do something similar to the following code in Java</p> <pre><code>int y = x ?? -1; </code></pre> <p><a href="https://stackoverflow.com/a/446839">More about <code>??</code></a></p>
<p>Sadly - no. The closest you can do is:</p> <pre><code>int y = (x != null) ? x : -1; </code></pre> <p>Of course, you can wrap this up in library methods if you feel the need to (it's unlikely to cut down on length much), but at the syntax level there isn't anything more succinct available.</p>
{ "question_id": 5223044, "question_date": "2011-03-07T17:35:14.030Z", "question_score": 221, "tags": "java|c#|equivalent|null-coalescing-operator", "answer_id": 5223065, "answer_date": "2011-03-07T17:36:55.340Z", "answer_score": 174 }
Please answer the following Stack Overflow question: Title: Call an action from within another action <p>I have the following setup for my actions:</p> <pre class="lang-js prettyprint-override"><code>get1: ({commit}) =&gt; { //things this.get2(); //this is my question! }, get2: ({commit}) =&gt; { //things }, </code></pre> <p>I want to be able to call one action from within another, so in this example I want to be able to call <code>get2()</code> from within <code>get1()</code>. Is this possible, and if so, how can I do it?</p>
<p>You have access to the <code>dispatch</code> method in the object passed in the first parameter:</p> <pre class="lang-js prettyprint-override"><code>get1: ({ commit, dispatch }) =&gt; { dispatch('get2'); }, </code></pre> <p>This is covered in the <a href="https://vuex.vuejs.org/guide/actions.html#dispatching-actions" rel="noreferrer">documentation</a>.</p>
{ "question_id": 45848974, "question_date": "2017-08-23T20:44:00.827Z", "question_score": 221, "tags": "vue.js|vuex", "answer_id": 45849125, "answer_date": "2017-08-23T20:55:29.250Z", "answer_score": 430 }
Please answer the following Stack Overflow question: Title: What are the differences between composer update and composer install? <p>What are the differences between <code>composer update</code> and <code>composer install</code>?</p>
<p><strong>composer update</strong></p> <p><code>composer update</code> will update your depencencies as they are specified in <code>composer.json</code></p> <p>For example, if you require this package as a dependency:</p> <pre><code>&quot;mockery/mockery&quot;: &quot;0.9.*&quot;, </code></pre> <p>and you have actually installed the <code>0.9.1</code> version of the package, running <code>composer update</code> will cause an upgrade of this package (for example to <code>0.9.2</code>, if it's already been released)</p> <p>in detail <code>composer update</code> will:</p> <ul> <li>Read <code>composer.json</code></li> <li>Remove installed packages that are no more required in <code>composer.json</code></li> <li>Check the availability of the latest versions of your required packages</li> <li>Install the latest versions of your packages</li> <li>Update <code>composer.lock</code> to store the installed packages version</li> </ul> <p><strong>composer install</strong></p> <p><code>composer install</code> will not update anything; it will just install all the dependencies as specified in the <code>composer.lock</code> file</p> <p>In detail:</p> <ul> <li>Check if <code>composer.lock</code> file exists (if not, it will run <code>composer update</code> and create it)</li> <li>Read <code>composer.lock</code> file</li> <li>Install the packages specified in the <code>composer.lock</code> file</li> </ul> <p><strong>When to install and when to update</strong></p> <ul> <li><p><code>composer update</code> is mostly used in the 'development phase', to upgrade our project packages according to what we have specified in the <code>composer.json</code> file,</p> </li> <li><p><code>composer install</code> is primarily used in the 'deploying phase' to install our application on a production server or on a testing environment, using the same dependencies stored in the composer.lock file created by composer update.</p> </li> </ul>
{ "question_id": 33052195, "question_date": "2015-10-10T09:03:42.087Z", "question_score": 221, "tags": "php|composer-php", "answer_id": 33052263, "answer_date": "2015-10-10T09:11:18.277Z", "answer_score": 394 }
Please answer the following Stack Overflow question: Title: Is there a way to get a visual diff on two branches in SourceTree? <p>Does Sourcetree offer a way to visualize differences between <code>git</code> branches?</p> <p>I'm looking for:</p> <ul> <li>names of files that have changed</li> <li>diffs between these files</li> </ul>
<p>Use <kbd>⌘</kbd> (OSX) or <kbd>CTRL</kbd> (Windows and Linux) and choose any two commits you like in log view. It does not matter what branch the commits belong to. </p> <p>As a result you will see something like...</p> <blockquote> <p>Displaying all changes between f03a18bf0370c62bb5fb5c6350589ad8def13aea and 4a4b176b852e7c8e83fffe94ea263042c59f0548</p> </blockquote> <p>...down below.</p>
{ "question_id": 30177189, "question_date": "2015-05-11T20:37:16.760Z", "question_score": 221, "tags": "git|git-branch|atlassian-sourcetree", "answer_id": 30178646, "answer_date": "2015-05-11T22:26:06.940Z", "answer_score": 279 }
Please answer the following Stack Overflow question: Title: Running a specific test case in Django when your app has a tests directory <p>The Django documentation (<a href="http://docs.djangoproject.com/en/1.3/topics/testing/#running-tests" rel="noreferrer">http://docs.djangoproject.com/en/1.3/topics/testing/#running-tests</a>) says that you can run individual test cases by specifying them:</p> <pre><code>$ ./manage.py test animals.AnimalTestCase </code></pre> <p>This assumes that you have your tests in a tests.py file in your Django application. If this is true, then this command works like expected.</p> <p>I have my tests for a Django application in a tests directory:</p> <pre><code>my_project/apps/my_app/ ├── __init__.py ├── tests │ ├── __init__.py │ ├── field_tests.py │ ├── storage_tests.py ├── urls.py ├── utils.py └── views.py </code></pre> <p>The <code>tests/__init__.py</code> file has a suite() function:</p> <pre><code>import unittest from my_project.apps.my_app.tests import field_tests, storage_tests def suite(): tests_loader = unittest.TestLoader().loadTestsFromModule test_suites = [] test_suites.append(tests_loader(field_tests)) test_suites.append(tests_loader(storage_tests)) return unittest.TestSuite(test_suites) </code></pre> <p>To run the tests I do:</p> <pre><code>$ ./manage.py test my_app </code></pre> <p>Trying to specify an individual test case raises an exception:</p> <pre><code>$ ./manage.py test my_app.tests.storage_tests.StorageTestCase ... ValueError: Test label 'my_app.tests.storage_tests.StorageTestCase' should be of the form app.TestCase or app.TestCase.test_method </code></pre> <p>I tried to do what the exception message said:</p> <pre><code>$ ./manage.py test my_app.StorageTestCase ... ValueError: Test label 'my_app.StorageTestCase' does not refer to a test </code></pre> <p>How do I specify an individual test case when my tests are in multiple files?</p>
<p>Check out <a href="https://github.com/jbalogh/django-nose" rel="noreferrer">django-nose</a>. This allows you to specify tests to run like:</p> <pre><code>python manage.py test another.test:TestCase.test_method </code></pre> <p>or as noted in comments, use the syntax:</p> <pre><code>python manage.py test another.test.TestCase.test_method </code></pre>
{ "question_id": 5875111, "question_date": "2011-05-03T20:11:34.187Z", "question_score": 221, "tags": "python|django|unit-testing", "answer_id": 5875223, "answer_date": "2011-05-03T20:20:41.373Z", "answer_score": 187 }
Please answer the following Stack Overflow question: Title: Find unused code <p>I have to refactor a large C# application, and I found a lot of functions that are never used. How can I check for unused code, so I can remove all the unused functions?</p>
<p>Yes, ReSharper does this. Right click on your solution and selection "Find Code Issues". One of the results is "Unused Symbols". This will show you classes, methods, etc., that aren't used.</p>
{ "question_id": 245963, "question_date": "2008-10-29T06:32:27.660Z", "question_score": 221, "tags": "c#|.net|refactoring", "answer_id": 3418352, "answer_date": "2010-08-05T19:20:22.573Z", "answer_score": 228 }
Please answer the following Stack Overflow question: Title: How do I create a new GitHub repo from a branch in an existing repo? <p>I have <strong>master</strong> and <strong>new-project</strong> branches. And now I'd like to create a brand new repo with its master based on the new-project branch.</p> <p>Background: I have one repository which contains three independent applications. It didn't start out this way. There was originally just one app in the repo. Over time, however, business needs have changed. One app became two (a legacy version and a re-write.) A web service was added. Separate branches were used to contain the three projects. However, they don't share any code. And so it'd be simpler to have them split out into their own repos.</p>
<p>I started with @user292677's idea, and refined it to solve my problem:</p> <ol> <li>Create the <strong>new-repo</strong> in github.</li> <li>cd to your local copy of the old repo you want to extract from, which is set up to track the <strong>new-project</strong> branch that will become the <strong>new-repo</strong>'s master.</li> <li><code>$ git push <a href="https://github.com/accountname/new-repo.git" rel="noreferrer">https://github.com/accountname/new-repo.git</a> +new-project:master</code> </li> </ol> <p>The new Github repo is finished. The result is;</p> <ul> <li>a new Github repository named <strong>new-repo</strong>,</li> <li>whose <code>master</code> corresponds to the old repo's <strong>new-project</strong>, with</li> <li>all history preserved.</li> </ul> <p>In fact, I found that by using this method, I could create the new repo with a hand-picked selection of branches, renamed as I wanted:</p> <p><code>$ git push [email protected]:accountname/new_repo +new-project:master +site3a:rails3</code></p> <p>The result is that the pre-existing <strong>site3a</strong> branch is now also moved to the new repo and will appear as <strong>rails3</strong>. This works really well: the network diagram shows the new <strong>master</strong> and <strong>rails3</strong> with full history and in their correct relationship to each other.</p> <p>Update 2013-12-07: Used this with another project, and verified that this recipe still works.</p> <p>Update 2018-01-11: Updated step 3. to use GitHub recommendation for https protocol. Recipe still works.</p>
{ "question_id": 9527999, "question_date": "2012-03-02T04:30:45.307Z", "question_score": 221, "tags": "git|github|branch", "answer_id": 9529847, "answer_date": "2012-03-02T07:58:20.717Z", "answer_score": 393 }
Please answer the following Stack Overflow question: Title: PHP - how to best determine if the current invocation is from CLI or web server? <p>I need to determine whether the current invocation of PHP is from the command line (CLI) or from the web server (in my case, Apache with mod_php).</p> <p>Any recommended methods?</p>
<p><code>php_sapi_name</code> is the function you will want to use as it returns a lowercase string of the interface type. In addition, there is the PHP constant <code>PHP_SAPI</code>. </p> <p>Documentation can be found here: <a href="http://php.net/php_sapi_name" rel="noreferrer">http://php.net/php_sapi_name</a></p> <p>For example, to determine if PHP is being run from the CLI, you could use this function:</p> <pre><code>function isCommandLineInterface() { return (php_sapi_name() === 'cli'); } </code></pre>
{ "question_id": 933367, "question_date": "2009-06-01T02:26:42.257Z", "question_score": 221, "tags": "php", "answer_id": 933375, "answer_date": "2009-06-01T02:34:43.007Z", "answer_score": 349 }
Please answer the following Stack Overflow question: Title: PHP sprintf escaping % <p>I want the following output:-</p> <blockquote> <p>About to deduct 50% of € 27.59 from your Top-Up account.</p> </blockquote> <p>when I do something like this:-</p> <pre><code>$variablesArray[0] = '€'; $variablesArray[1] = 27.59; $stringWithVariables = 'About to deduct 50% of %s %s from your Top-Up account.'; echo vsprintf($stringWithVariables, $variablesArray); </code></pre> <p>But it gives me this error <code>vsprintf() [function.vsprintf]: Too few arguments in ...</code> because it considers the <code>%</code> in <code>50%</code> also for replacement. How do I escape it?</p>
<p>Escape it with another <code>%</code>:</p> <pre><code>$stringWithVariables = 'About to deduct 50%% of %s %s from your Top-Up account.'; </code></pre>
{ "question_id": 3666734, "question_date": "2010-09-08T10:24:52.137Z", "question_score": 221, "tags": "php|escaping|printf", "answer_id": 3666749, "answer_date": "2010-09-08T10:26:43.723Z", "answer_score": 412 }
Please answer the following Stack Overflow question: Title: How to add Google Analytics Tracking ID to GitHub Pages <p>Could be a simple question but I am full of doubts right now about adding <strong>Google Analytics Tracking ID</strong> to <strong>GitHub page</strong>.</p> <p>I am using GitHub automatic page generator to create my GitHub page but it asks for "Google Analytics Tracking ID". I tried to sign up with Google Analytics but there on it asks for website URL.</p> <p>Now what I am supposed to do? </p> <p>One more ques: can we add Google Analytics Tracking ID later on after GitHub Page has been created?</p>
<p><strong>Update</strong>: Added steps descriptions for others <br></p> <p>Solved it:<br> had to include <code>username.github.io</code> (link that I want to track) in Google Analytics website section.</p> <p>you can check GitHub help page <a href="https://help.github.com/en/enterprise/2.14/user/articles/creating-pages-with-the-automatic-generator" rel="noreferrer">here</a> </p> <hr> <p><img src="https://i.stack.imgur.com/gCwkj.png" alt="enter image description here"></p> <hr> <p>After that I was provided with an Tracker ID. </p> <hr> <p><strong>Note:</strong> You can easily change or add more websites on Google Analytics page from your Google Analytics admin panel.</p> <hr> <p><strong>Update 2: - Adding Google Analytics Tracking ID to Already created Github pages</strong> (As requested by <a href="https://stackoverflow.com/users/2295672/avi-aryan">@avi-aryan</a> ) <br/></p> <ol> <li>Browse to your github pages branch - which would be something like - <br/>( <a href="https://github.com/" rel="noreferrer">https://github.com/</a><strong>YourUserName</strong>/<b>YourRepository</b>/tree/gh-pages ) <br/></li> <li>Then edit <code>index.html</code> from listed files</li> <li>Now in within <code>HEAD</code> tag of <code>index.html</code> - paste your Google Analytics Tracking ID Script ( if have already signed up for Google analytics then you can browse it under <strong>admin</strong> and then <strong>tracking info</strong> tab ) </li> </ol>
{ "question_id": 17207458, "question_date": "2013-06-20T07:14:51.147Z", "question_score": 221, "tags": "github|google-analytics|github-pages", "answer_id": 17209831, "answer_date": "2013-06-20T09:16:52.143Z", "answer_score": 181 }
Please answer the following Stack Overflow question: Title: App restarts rather than resumes <p>Hopefully someone can help me figure out, if not a solution, at least an explanation for a behaviour.</p> <p><strong>The Problem:</strong></p> <p><em>On some devices, pressing the launcher icon results in the current task being resumed, on others it results in the initial launch intent being fired (effectively restarting the app). Why does this happen?</em> </p> <p><strong>The Detail:</strong></p> <p>When you press the "Launcher Icon" the app starts normally - That is, I assume, an Intent is launched with the name of your first <code>Activity</code> with the action <code>android.intent.action.MAIN</code> and the category <code>android.intent.category.LAUNCHER</code>. This can't always be the case however:</p> <p>On the majority of devices, if you press the launcher icon after the app is already running, the currently running Activity in that process is resumed (<strong>NOT</strong> the initial <code>Activity</code>). It resumes in the same way as if you had selected it from the "Recent Tasks" in the OS menu. This is the behaviour I want on <em>all</em> devices.</p> <p>However, on selected other devices different behaviour occurs:</p> <ul> <li><p>On the Motorola Xoom, when you press the launcher icon, the App will <em>always</em> start the initial launch <code>Activity</code> regardless of what is currently running. I assume that the launcher icons always start the "LAUNCHER" intent.</p></li> <li><p>On the Samsung Tab 2, when you press the launcher icon, if you have just installed the app, it will always launch the initial <code>Activity</code> (Same as the Xoom) - however, after you restart the device after the install, the launcher icon will instead resume the app. I assume that these devices add "installed apps" into a lookup table on device startup which allow the launcher icons to correctly resume running tasks?</p></li> </ul> <p>I've read many answer that <em>sound</em> similar to my problem but simply adding <code>android:alwaysRetainTaskState="true"</code> or using <code>launchMode="singleTop"</code> to the <code>Activity</code> are not the answer.</p> <p><strong>Edit:</strong></p> <p>After the most recent launch of this app, we find that this behaviour has begun to occur on <em>all</em> devices after the first restart. Which seems crazy to me but looking through the restart process, I can't actually find what's going wrong.</p>
<p>Aha! (tldr; See the statements in bold at the bottom)</p> <p>I've found the problem... I think.</p> <p>So, I'll start off with a supposition. When you press the launcher, it either starts the default <code>Activity</code> or, if a <code>Task</code> started by a previous launch is open, it brings it to the front. Put another way - If at any stage in your navigation you create a new <code>Task</code> and <code>finish</code> the old one, the launcher will now no longer resume your app.</p> <p>If that supposition is true, I'm pretty sure that should be a bug, given that each <code>Task</code> is in the same process and is just as valid a resume candidate as the first one created?</p> <p>My problem then, was fixed by removing these flags from a couple of <code>Intents</code>:</p> <pre><code>i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK ); </code></pre> <p>While it's quite obvious the <code>FLAG_ACTIVITY_NEW_TASK</code> creates a new <code>Task</code>, I didn't appreciate that the above supposition was in effect. I did consider this a culprit and removed it to test and I was still having a problem so I dismissed it. However, I still had the below conditions:</p> <pre><code>i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) </code></pre> <p>My splash screen was starting the "main" <code>Activity</code> in my app using the above flag. Afterall, If I had "restart" my app and the <code>Activity</code> was still running, I would much rather preserve it's state information.</p> <p>You'll notice in the <a href="http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP">documentation</a> it makes no mention of starting a new <code>Task</code>:</p> <blockquote> <p>If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.</p> <p>For example, consider a task consisting of the activities: A, B, C, D. If D calls startActivity() with an Intent that resolves to the component of activity B, then C and D will be finished and B receive the given Intent, resulting in the stack now being: A, B.</p> <p>The currently running instance of activity B in the above example will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent. If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent().</p> <p>This launch mode can also be used to good effect in conjunction with FLAG_ACTIVITY_NEW_TASK: if used to start the root activity of a task, it will bring any currently running instance of that task to the foreground, and then clear it to its root state. This is especially useful, for example, when launching an activity from the notification manager.</p> </blockquote> <p>So, I had the situation as described below:</p> <ul> <li><code>A</code> launched <code>B</code> with <code>FLAG_ACTIVITY_CLEAR_TOP</code>, <code>A</code> finishes. </li> <li><code>B</code> wishes to restart a service so sends the user to <code>A</code> which has the service restart logic and UI (No flags).</li> <li><code>A</code> launches <code>B</code> with FLAG_ACTIVITY_CLEAR_TOP, <code>A</code> finishes.</li> </ul> <p>At this stage the second <code>FLAG_ACTIVITY_CLEAR_TOP</code> flag is restarting <code>B</code> which is in the task stack. I'm assuming this must destroy the <code>Task</code> and start a new one, causing my problem, which is a very difficult situation to spot if you ask me! </p> <p>So, if all of my supposition are correct:</p> <ul> <li><strong>The <code>Launcher</code> only resumes the initially created Task</strong></li> <li><strong><code>FLAG_ACTIVITY_CLEAR_TOP</code> will, if it restarts the only remaining <code>Activity</code>, also recreate a new <code>Task</code></strong></li> </ul>
{ "question_id": 19545889, "question_date": "2013-10-23T15:24:24.497Z", "question_score": 221, "tags": "android|android-lifecycle", "answer_id": 23133554, "answer_date": "2014-04-17T12:47:43.700Z", "answer_score": 22 }
Please answer the following Stack Overflow question: Title: Prevent browser from loading a drag-and-dropped file <p>I'm adding an html5 drag and drop uploader to my page.</p> <p>When a file is dropped into the upload area, everything works great.</p> <p>However, if I accidentally drop the file outside of the upload area, the browser loads the local file as if it is a new page.</p> <p>How can I prevent this behavior?</p> <p>Thanks!</p>
<p>You can add a event listener to the window that calls <code>preventDefault()</code> on all dragover and drop events.<br> Example:</p> <pre><code>window.addEventListener("dragover",function(e){ e = e || event; e.preventDefault(); },false); window.addEventListener("drop",function(e){ e = e || event; e.preventDefault(); },false); </code></pre>
{ "question_id": 6756583, "question_date": "2011-07-20T03:09:19.210Z", "question_score": 221, "tags": "javascript|jquery|html|drag-and-drop", "answer_id": 6756680, "answer_date": "2011-07-20T03:27:20.723Z", "answer_score": 354 }
Please answer the following Stack Overflow question: Title: Do git tags get pushed as well? <p>Since I created my repository it appears that the tags I have been creating are not pushed to the repository. When I do <code>git tag</code> on the local directory all the tags are present, but when I logon to the remote repository and do a <code>git tag</code>, only the first few show up.</p> <p>What could the problem be?.</p>
<p>You could do this:</p> <pre><code>git push --tags </code></pre>
{ "question_id": 2988088, "question_date": "2010-06-07T08:44:58.387Z", "question_score": 221, "tags": "git|git-tag", "answer_id": 2988099, "answer_date": "2010-06-07T08:48:47.490Z", "answer_score": 285 }
Please answer the following Stack Overflow question: Title: Why was the arguments.callee.caller property deprecated in JavaScript? <p>Why was the <code>arguments.callee.caller</code> property deprecated in JavaScript?</p> <p>It was added and then deprecated in JavaScript, but it was omitted altogether by ECMAScript. Some browser (Mozilla, IE) have always supported it and don't have any plans on the map to remove support. Others (Safari, Opera) have adopted support for it, but support on older browsers is unreliable.</p> <p>Is there a good reason to put this valuable functionality in limbo?</p> <p>(Or alternately, is there a better way to grab a handle on the calling function?)</p>
<p>Early versions of JavaScript did not allow named function expressions, and because of that we could not make a recursive function expression:</p> <pre><code> // This snippet will work: function factorial(n) { return (!(n&gt;1))? 1 : factorial(n-1)*n; } [1,2,3,4,5].map(factorial); // But this snippet will not: [1,2,3,4,5].map(function(n) { return (!(n&gt;1))? 1 : /* what goes here? */ (n-1)*n; }); </code></pre> <p>To get around this, <code>arguments.callee</code> was added so we could do:</p> <pre><code> [1,2,3,4,5].map(function(n) { return (!(n&gt;1))? 1 : arguments.callee(n-1)*n; }); </code></pre> <p>However this was actually a really bad solution as this (in conjunction with other arguments, callee, and caller issues) make inlining and tail recursion impossible in the general case (you can achieve it in select cases through tracing etc, but even the best code is sub optimal due to checks that would not otherwise be necessary). The other major issue is that the recursive call will get a different <code>this</code> value, for example:</p> <pre><code>var global = this; var sillyFunction = function (recursed) { if (!recursed) return arguments.callee(true); if (this !== global) alert("This is: " + this); else alert("This is the global"); } sillyFunction(); </code></pre> <p>Anyhow, EcmaScript 3 resolved these issues by allowing named function expressions, e.g.:</p> <pre><code> [1,2,3,4,5].map(function factorial(n) { return (!(n&gt;1))? 1 : factorial(n-1)*n; }); </code></pre> <p>This has numerous benefits:</p> <ul> <li><p>The function can be called like any other from inside your code.</p></li> <li><p>It does not pollute the namespace.</p></li> <li><p>The value of <code>this</code> does not change.</p></li> <li><p>It's more performant (accessing the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments" rel="noreferrer">arguments object</a> is expensive).</p></li> </ul> <h3>Whoops,</h3> <p>Just realised that in addition to everything else the question was about <code>arguments.callee.caller</code>, or more specifically <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller" rel="noreferrer"><code>Function.caller</code></a>.</p> <p>At any point in time you can find the deepest caller of any function on the stack, and as I said above, looking at the call stack has one single major effect: It makes a large number of optimizations impossible, or much much more difficult.</p> <p>Eg. if we can't guarantee that a function <code>f</code> will not call an unknown function, then it is not possible to inline <code>f</code>. Basically it means that any call site that may have been trivially inlinable accumulates a large number of guards, take:</p> <pre><code> function f(a, b, c, d, e) { return a ? b * c : d * e; } </code></pre> <p>If the js interpreter cannot guarantee that all the provided arguments are numbers at the point that the call is made, it needs to either insert checks for all the arguments before the inlined code, or it cannot inline the function.</p> <p>Now in this particular case a smart interpreter should be able to rearrange the checks to be more optimal and not check any values that would not be used. However in many cases that's just not possible and therefore it becomes impossible to inline.</p>
{ "question_id": 103598, "question_date": "2008-09-19T16:45:37.807Z", "question_score": 221, "tags": "javascript|ecma262", "answer_id": 235760, "answer_date": "2008-10-25T01:51:40.203Z", "answer_score": 262 }
Please answer the following Stack Overflow question: Title: Why historically do people use 255 not 256 for database field magnitudes? <p>You often see database fields set to have a magnitude of 255 characters, what is the traditional / historic reason why? I assume it's something to do with paging / memory limits, and performance but the distinction between 255 and 256 has always confused me.</p> <pre><code>varchar(255) </code></pre> <p>Considering this is a capacity or magnitude, <em>not an indexer</em>, <strong>why is 255 preferred over 256?</strong> Is a byte reserved for some purpose (terminator or null or something)?</p> <p>Presumably varchar(0) is a nonsense (has zero capacity)? In which case 2^8 of space should be 256 surely?</p> <p>Are there other magnitudes that provide performance benefits? For example is varchar(512) less performant than varchar(511) or varchar(510)?</p> <p>Is this value the same for all relations databases, old and new?</p> <p><strong>disclaimer</strong> - I'm a developer not a DBA, I use field sizes and types that suit my business logic where that is known, but I'd like to know the <em>historic</em> reason for this preference, even if it's no longer relevant (but even more if it still is relevant).</p> <h2>Edit:</h2> <p>Thanks for the answers, there seems to be some concensus that a byte is used to store size, but this doesn't settle the matter definitively in my mind.</p> <p>If the meta data (string length) is stored in the same contiguous memory/disk, it makes some sense. 1 byte of metadata and 255 bytes of string data, would suit each other very nicely, and fit into 256 contiguous bytes of storage, which presumably is neat and tidy.</p> <p>But...If the metadata (string length) is stored separately from the actual string data (in a master table perhaps), then to constrain the length of string's data by one byte, just because it's easier to store only a 1 byte integer of metadata seems a bit odd.</p> <p>In both cases, it would seem to be a subtlety that probably depends on the DB implementation. The practice of using 255 seems pretty widespread, so someone somewhere must have argued a good case for it in the beginning, can anyone remember what that case was/is? Programmers won't adopt any new practice without a reason, and this must have been new once.</p>
<p>With a maximum length of 255 characters, the DBMS can choose to use a single byte to indicate the length of the data in the field. If the limit were 256 or greater, two bytes would be needed.</p> <p>A value of length zero is certainly valid for <code>varchar</code> data (unless constrained otherwise). Most systems treat such an empty string as distinct from NULL, but some systems (notably Oracle) treat an empty string identically to NULL. For systems where an empty string is not NULL, an additional bit somewhere in the row would be needed to indicate whether the value should be considered NULL or not.</p> <p>As you note, this is a historical optimisation and is probably not relevant to most systems today.</p>
{ "question_id": 2340639, "question_date": "2010-02-26T09:40:47.810Z", "question_score": 221, "tags": "sql|rdbms-agnostic", "answer_id": 2340662, "answer_date": "2010-02-26T09:44:33.667Z", "answer_score": 187 }
Please answer the following Stack Overflow question: Title: How do I delete all untracked files from my working directory in Mercurial? <p>Is it possible to delete all untracked files from my working directory? Let's say I added a bunch of files to my working directory, didn't add them via 'hg add' and now want to get rid of those new files entirely?</p> <p>I'm on windows, although I'm using PowerShell, so a combined solution is also possible here.</p>
<p>Add the Mercurial Extension called <strong>purge</strong>. It is distributed by Mercurial.</p> <p>This extension adds a “purge” command to “hg” that removes files not known to Mercurial. i.e. untracked Files. So your command would be, </p> <pre><code>hg purge </code></pre> <p>It is not enabled by default, maybe to avoid accidentally removing files that you forgot to add.</p> <p>To install this extension, add this to your mercurial settings file (.hgrc on Unix, Mercurial.ini on Windows)</p> <pre><code>[extensions] purge = </code></pre> <p>To enable this extension temporarily you can use </p> <pre><code>hg purge --config extensions.purge= </code></pre>
{ "question_id": 1212370, "question_date": "2009-07-31T12:50:20.093Z", "question_score": 221, "tags": "mercurial", "answer_id": 1212486, "answer_date": "2009-07-31T13:18:03.167Z", "answer_score": 303 }
Please answer the following Stack Overflow question: Title: Azure Webjobs vs Azure Functions : How to choose <p>I've created some <a href="https://azure.microsoft.com/en-us/documentation/articles/websites-webjobs-resources/">Azure Webjobs</a> that use triggers and I've just learnt about <a href="https://azure.microsoft.com/en-us/documentation/services/functions/">Azure Functions</a>.</p> <p>From what I understand Azure Functions seem to overlap with Azure Webjobs features and I have some difficulty to understand when to choose between Function and Webjob:</p> <ul> <li><p>Unlike Webjobs, Functions can only be triggered, it hasn't been designed to run continuous process (but you can write code to create a continuous function).</p></li> <li><p>You can write Webjobs and Functions using many languages (C#, node.js, python ...) but you can write your function from the Azure portal so it is easier and quicker to develop test and deploy a Function.</p></li> <li><p>Webjobs run as background processes in the context of an App Service web app, API app, or mobile app whereas Functions run using a Classic/Dynamic App Service Plan. </p></li> <li><p>Regarding the scaling, Functions seems to give more possibilities since you can use a dynamic app service plan and you can scale a single function whereas for a webjob you have to scale the whole web app. </p></li> </ul> <p>So for sure there is a pricing difference, if you have an existing web app running you can use it to run a webjob without any additional cost but if I don't have an existing web app and I have to write code to trigger a queue should I use a webjob or a Function ?</p> <p>Is there any other considerations to keep in mind when you need to choose ?</p>
<p>There are a couple options here within App Service. I won't touch on Logic Apps or Azure Automation, which also touch this space.</p> <h2>Azure WebJobs</h2> <p><a href="https://azure.microsoft.com/en-us/documentation/articles/web-sites-create-web-jobs/" rel="noreferrer">This article</a> is honestly the best explanation, but I'll summarize here.</p> <h3>On Demand WebJobs aka. Scheduled WebJobs aka. Triggered WebJobs</h3> <p>Triggered WebJobs are WebJobs which are run once when a URL is called or when the <a href="https://azure.microsoft.com/en-us/documentation/articles/web-sites-create-web-jobs/#CreateScheduledCRON" rel="noreferrer">schedule property is present in schedule.job</a>. Scheduled WebJobs are just WebJobs which have had an Azure Scheduler Job created to call our URL on a schedule, but we also support the schedule property, as mentioned previously.</p> <p>Summary:</p> <ul> <li><code>+</code> Executable/Script on demand</li> <li><code>+</code> Scheduled executions</li> <li><code>-</code> Have to trigger via .scm endpoint</li> <li><code>-</code> Scaling is manual</li> <li><code>-</code> VM is always required</li> </ul> <h3>Continuous WebJobs (non SDK)</h3> <p>These jobs run forever and we will wake them up when they crash. You need to enable Always On for these to work, which means running them in Basic tier and above.</p> <p>Summary:</p> <ul> <li><code>+</code> Executable/Script always running</li> <li><code>-</code> Requires always on - Basic tier and above</li> <li><code>-</code> VM is always required</li> </ul> <h3>Continuous WebJobs with the WebJobs SDK</h3> <p>These aren't anything from a "WebJobs the feature" point of view. Essentially, we have this sweet SDK we wrote targeting WebJobs which lets you execute code based on simple triggers. I'll talk about this more later on.</p> <p>Summary:</p> <ul> <li><code>+</code> Executable/Script always running</li> <li><code>+</code> Richer logging/dashboard</li> <li><code>+</code> Triggers supported along with long running tasks</li> <li><code>-</code> Requires always on - Basic tier and above</li> <li><code>-</code> Scaling is manual to set up</li> <li><code>-</code> Getting started can be a bit tiresome</li> <li><code>-</code> VM is always required</li> </ul> <h2>Azure WebJobs SDK</h2> <p>Azure WebJobs SDK is a completely separate SDK from WebJobs the platform feature. It's designed to be run in a WebJob, but can really be run anywhere. We have customers who run them on worker roles and even on prem or other clouds, though support is only best effort.</p> <p>The SDK is just about making it easy to run some code in reaction to some event and make binding to services/etc. easy. This is honestly best covered in some <a href="https://azure.microsoft.com/en-us/documentation/articles/websites-dotnet-webjobs-sdk-get-started/" rel="noreferrer">docs</a>, but the heart of it is that "event" + "code" nature. We've also done some cool extensiblity work, but that's secondary to the core purpose.</p> <p>Summary:</p> <ul> <li>Most of these are mentioned above</li> <li><code>+</code> You can extend and run whatever you want. Full control.</li> <li><code>-</code> HTTP stuff is a little wonky, but it works</li> </ul> <h2>Azure Functions</h2> <p>Azure Functions is all about taking that core purpose of the WebJobs SDK, hosting it as a service, and making it easy to get started with other languages. We also introduce the "Serverless" concept here because it made a lot of sense to do so - we know how our SDK scales, so we can do intelligent things for you.</p> <p>Azure Functions is a very heavily managed experience. We aren't supporting bringing your own host. Currently, we don't support custom extensions but its something we're investigating. We're opinionated about what you can and can't do, but for the things we enable, they are slick, and easy to use and manage.</p> <p>Most of the "framework" things we've done to improve Functions go through the WebJobs SDK, though. For instance, we'll be uploading a new NuGet for WebJobs which really drastically increases the speed of logging, which has huge perf benefits for WebJobs SDK users. In shipping Functions as "WebJobs SDK as a Service" we've really improved a lot of experience issues.</p> <ul> <li><code>+</code> Lots of languages supported</li> <li><code>+</code> Fully managed, dynamic scaling</li> <li><code>+</code> Easy to use portal w/ UX for managing connections/etc.</li> <li><code>-</code> Host not customizable (yet)</li> <li><code>~</code> Runs in a separate "app" which requires some configuration in your repo, but makes long term maintenance much easier.</li> <li><code>~</code> <strike>No tooling (yet)</strike> Some tooling is now in alpha or preview - <a href="https://www.npmjs.com/package/azurefunctions" rel="noreferrer">https://www.npmjs.com/package/azurefunctions</a> (update Feb 2017: Visual Studio Tools for Azure Functions now available in preview: <a href="https://blogs.msdn.microsoft.com/webdev/2016/12/01/visual-studio-tools-for-azure-functions/" rel="noreferrer">https://blogs.msdn.microsoft.com/webdev/2016/12/01/visual-studio-tools-for-azure-functions/</a>)</li> </ul> <p>I'm probably biased since Functions is our latest and greatest, but feel free to shoot more cons for Functions my way.</p> <p>I'll probably end up publishing a blog which elaborates a bit more, but I tried to keep this as succinct as possible for this forum.</p>
{ "question_id": 36610952, "question_date": "2016-04-13T22:53:01.527Z", "question_score": 221, "tags": "azure|azure-webjobs|azure-functions", "answer_id": 36611919, "answer_date": "2016-04-14T00:44:39.327Z", "answer_score": 203 }
Please answer the following Stack Overflow question: Title: What does a tilde do when it precedes an expression? <pre><code>var attr = ~'input,textarea'.indexOf( target.tagName.toLowerCase() ) ? 'value' : 'innerHTML' </code></pre> <p>I saw it in an answer, and I've never seen it before.</p> <p>What does it mean?</p>
<p><code>~</code> is a <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators?redirectlocale=en-US&amp;redirectslug=Core_JavaScript_1.5_Reference/Operators/Bitwise_Operators" rel="noreferrer">bitwise operator</a> that flips all bits in its operand.</p> <p>For example, if your number was <code>1</code>, its binary representation of the <a href="https://en.wikipedia.org/wiki/IEEE_754-1985" rel="noreferrer">IEEE 754 float</a> (how JavaScript treats numbers) would be...</p> <pre><code>0011 1111 1111 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 </code></pre> <p>So <code>~</code> converts its operand to a 32 bit integer (bitwise operators in JavaScript do that)...</p> <pre><code>0000 0000 0000 0000 0000 0000 0000 0001 </code></pre> <p><sup>If it were a negative number, it'd be stored in 2's complement: invert all bits and add 1.</sup></p> <p>...and then flips all its bits...</p> <pre><code>1111 1111 1111 1111 1111 1111 1111 1110 </code></pre> <blockquote> <p>So what is the use of it, then? When might one ever use it?</p> </blockquote> <p>It has a quite a few uses. If you're writing low level stuff, it's handy. If you profiled your application and found a bottleneck, it could be made more performant by using bitwise tricks (as one <em>possible</em> tool in a much bigger bag).</p> <p>It's also a (generally) unclear <em>trick</em> to turn <code>indexOf()</code>'s <em>found</em> return value into <em>truthy</em> (while making <em>not found</em> as <em>falsy</em>) and people often use it for its side effect of truncating numbers to 32 bits (and dropping its decimal place by doubling it, effectively the same as <code>Math.floor()</code> for positive numbers). </p> <p>I say <em>unclear</em> because it's not immediately obvious what it is being used for. Generally, you want your code to communicate clearly to other people reading it. While using <code>~</code> may <em>look cool</em>, it's generally too clever for its own good. :)</p> <p>It's also less relevant now that JavaScript has <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes" rel="noreferrer"><code>Array.prototype.includes()</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes" rel="noreferrer"><code>String.prototype.includes()</code></a>. These return a boolean value. If your target platform(s) support it, you should prefer this for testing for the existence of a value in a string or array.</p>
{ "question_id": 12299665, "question_date": "2012-09-06T12:02:25.003Z", "question_score": 221, "tags": "javascript|syntax|bit-manipulation", "answer_id": 12299678, "answer_date": "2012-09-06T12:03:05.703Z", "answer_score": 305 }
Please answer the following Stack Overflow question: Title: Literal notation for Dictionary in C#? <p>I currently have a WebSocket between JavaScript and a server programmed in C#. In JavaScript, I can pass data easily using an associative array:</p> <pre><code>var data = {'test': 'val', 'test2': 'val2'}; </code></pre> <p>To represent this data object on the server side, I use a <code>Dictionary&lt;string, string&gt;</code>, but this is more 'typing-expensive' than in JavaScript:</p> <pre><code>Dictionary&lt;string, string&gt; data = new Dictionary&lt;string,string&gt;(); data.Add("test", "val"); data.Add("test2", "val2"); </code></pre> <p>Is there some kind of literal notation for associative arrays / <code>Dictionary</code>s in C#?</p>
<p>You use the <a href="https://msdn.microsoft.com/en-us/library/bb384062.aspx" rel="noreferrer">collection initializer</a> syntax, but you still need to make a <code>new Dictionary&lt;string, string&gt;</code> object first as the shortcut syntax is translated to a bunch of <code>Add()</code> calls (like your code):</p> <pre><code>var data = new Dictionary&lt;string, string&gt; { { "test", "val" }, { "test2", "val2" } }; </code></pre> <p>In C# 6, you now have the option of using a more intuitive syntax with Dictionary as well as any other type that supports <a href="https://msdn.microsoft.com/en-us/library/6x16t2tx.aspx" rel="noreferrer">indexers</a>. The above statement can be rewritten as:</p> <pre><code>var data = new Dictionary&lt;string, string&gt; { ["test"] = "val", ["test2"] = "val2" }; </code></pre> <p>Unlike collection initializers, this invokes the indexer setter under the hood, rather than an appropriate <code>Add()</code> method.</p>
{ "question_id": 4980500, "question_date": "2011-02-12T20:39:37.133Z", "question_score": 221, "tags": "c#|dictionary|literals", "answer_id": 4980512, "answer_date": "2011-02-12T20:42:32.633Z", "answer_score": 348 }
Please answer the following Stack Overflow question: Title: When would you use .git/info/exclude instead of .gitignore to exclude files? <p>I am a bit confused about the pros and cons of using <code>.git/info/exclude</code> and <code>.gitignore</code> to exclude files.</p> <p>Both of them are at the level of the repository/project, so how do they differ and when should we use <code>.git/info/exclude</code> ?</p>
<p>The advantage of <code>.gitignore</code> is that it can be checked into the repository itself, unlike <code>.git/info/exclude</code>. Another advantage is that you can have multiple <code>.gitignore</code> files, one inside each directory/subdirectory for directory specific ignore rules, unlike <code>.git/info/exclude</code>.</p> <p>So, <code>.gitignore</code> is available across all clones of the repository. Therefore, in large teams all people are ignoring the same kind of files Example <code>*.db</code>, <code>*.log</code>. And you can have more specific ignore rules because of multiple <code>.gitignore</code>.</p> <p><code>.git/info/exclude</code> is available for individual clones only, hence what one person ignores in his clone is not available in some other person's clone. For example, if someone uses <code>Eclipse</code> for development it may make sense for that developer to add <code>.build</code> folder to <code>.git/info/exclude</code> because other devs may not be using Eclipse.</p> <p>In general, files/ignore rules that have to be universally ignored should go in <code>.gitignore</code>, and otherwise files that you want to ignore only on your local clone should go into <code>.git/info/exclude</code></p>
{ "question_id": 22906851, "question_date": "2014-04-07T08:09:36.507Z", "question_score": 221, "tags": "git|gitignore", "answer_id": 22906964, "answer_date": "2014-04-07T08:15:28.383Z", "answer_score": 289 }
Please answer the following Stack Overflow question: Title: Java / Jakarta EE web development, where do I start and what skills do I need? <p>I want to learn, at least at a basic level, how to build Java web applications (coming from a .NET background). I would like to be able to build, deploy a simple CMS type application from the ground up.</p> <p>What exactly do I need to learn?</p> <p>Tomcat seems to be a good web server for Java.</p> <p>What options are there for the web? I know there is <a href="http://en.wikipedia.org/wiki/Hibernate_%28Java%29" rel="noreferrer">Hibernate</a> for an ORM.</p> <p>Does Java have MVC? What about <a href="http://en.wikipedia.org/wiki/JavaServer_Pages" rel="noreferrer">JSP</a>? Can MVC and JSP be together? <a href="http://en.wikipedia.org/wiki/NetBeans" rel="noreferrer">NetBeans</a>?</p> <p>Maybe a book that covers all of these?</p>
<p><sup><sup>(Updated Apr 2021)</sup></sup></p> <p>First of all, &quot;Java EE&quot; has since Sep 2019 been renamed to &quot;<strong>Jakarta EE</strong>&quot;, starting with version 8. Historically, there was also the term &quot;J2EE&quot; which covered versions 1.2 until 1.4. The &quot;Java EE&quot; covered versions 5 until 8. See also <a href="https://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition#History" rel="noreferrer">Java Platform, Enterprise Edition, History on Wikipedia</a>.</p> <blockquote> <p><em>What exactly do I need to learn?</em></p> </blockquote> <p>I assume that you're already familiar with client side technologies like <a href="https://htmldog.com/guides/html/" rel="noreferrer">HTML</a>, <a href="https://htmldog.com/guides/css/" rel="noreferrer">CSS</a> and <a href="https://htmldog.com/guides/javascript/" rel="noreferrer">JS</a>, so I won't go in detail with that. I also assume that you're already familiar with basic Java. Follow Oracle's <a href="https://docs.oracle.com/javase/tutorial/" rel="noreferrer">The Java Tutorials</a> and if possible, go get a <a href="https://www.amazon.com/s?k=ocp+java" rel="noreferrer">OCP book</a> or course as well.</p> <p>Then you can start with JSP/Servlet to learn the basic concepts of Java web development. Good tutorial can be found in <a href="https://eclipse-ee4j.github.io/jakartaee-tutorial/servlets.html" rel="noreferrer">Jakarta EE tutorial chapter 18 'Jakarta Servlet Technology'</a>. Note that since Java EE 6, <a href="https://eclipse-ee4j.github.io/jakartaee-tutorial/overview008.html#BNACN" rel="noreferrer">JSP is removed from the tutorial in favor of JSF</a> and that JSP has basically not changed since then. That's why you could safely use the fairly old <a href="https://docs.oracle.com/javaee/5/tutorial/doc/bnagx.html" rel="noreferrer">Java EE 5 tutorial</a> for this. Most important thing with regard to JSP is the fact that writing plain Java code in JSP files using <code>&lt;%</code> scriptlets <code>%&gt;</code> is officially discouraged since 2003. See also <a href="https://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files">How can I avoid Java code in JSP files, using JSP 2?</a> So any tutorials which still cover scriptlets should be skipped as they will definitely take you into a downward spiral of learning bad practices.</p> <p>Here on Stack Overflow, you can also find nice wiki pages about <a href="https://stackoverflow.com/tags/jsp/info">JSP</a>, <a href="https://stackoverflow.com/tags/servlets/info">Servlets</a>, <a href="https://stackoverflow.com/tags/jstl/info">JSTL</a> and <a href="https://stackoverflow.com/tags/el/info">EL</a> where you can learn the essentials and find more useful links.</p> <hr /> <blockquote> <p><em>Tomcat seems to be a good web server for Java.</em></p> </blockquote> <p>It is. It is however limited in capabilities. It's basically a barebones servlet container, implementing only the JSP/Servlet parts of the huge Java EE API. If you ever want to go EJB or JPA, then you'd like to pick another, e.g. <a href="https://wildfly.org" rel="noreferrer">WildFly</a>, <a href="https://tomee.apache.org/" rel="noreferrer">TomEE</a>, <a href="https://payara.fish" rel="noreferrer">Payara</a>, <a href="https://www.ibm.com/cloud/websphere-liberty" rel="noreferrer">Liberty</a>, <a href="https://www.oracle.com/middleware/technologies/weblogic.html" rel="noreferrer">WebLogic</a>, etc. Otherwise you have to use Spring instead of Java EE. It's namely not possible to install EJB in a barebones servlet container without modifying the core engine, you'd in case of Tomcat basically be reinventing TomEE. See also <a href="https://stackoverflow.com/questions/7295096">What exactly is Java EE?</a>, <a href="https://stackoverflow.com/questions/8081234/">How to properly install and configure JSF libraries via Maven?</a> and <a href="https://stackoverflow.com/questions/18995951/">How to install and use CDI on Tomcat?</a></p> <hr /> <blockquote> <p><em>I know there is Hibernate for an ORM.</em></p> </blockquote> <p>Previously, during the J2EE era, when JPA didn't exist and EJB2 was terrible, Hibernate was a standalone framework and often used in combination with Spring to supplant EJB. Since the introduction of JPA in Java EE 5 (2006), Hibernate has become a JPA implementation. You can learn JPA at <a href="https://eclipse-ee4j.github.io/jakartaee-tutorial/partpersist.html" rel="noreferrer">Jakarta EE tutorial part VIII</a>. Also, EJB3 was much improved based on lessons learnt from Spring. See also <a href="https://stackoverflow.com/questions/18369356">When is it necessary or convenient to use Spring or EJB3 or all of them together?</a></p> <hr /> <blockquote> <p><em>Does Java have MVC? What about JSP? Can MVC and JSP be together? JavaBeans?</em></p> </blockquote> <p><a href="https://stackoverflow.com/questions/5003142">You can</a>, but that's a lot of <a href="https://stackoverflow.com/questions/3541077/design-patterns-web-based-applications/">reinvention of the wheel</a> when it comes to tying the model with the view (conversion, validation, change listeners, etc). Jakarta EE's MVC framework is called <a href="https://stackoverflow.com/tags/jsf/info">JSF</a>. Prior to Java EE 6 it used to run on JSP, which is a fairly legacy view technology. JSP is been replaced by <a href="https://stackoverflow.com/tags/facelets/info">Facelets</a>. You can learn JSF at <a href="https://eclipse-ee4j.github.io/jakartaee-tutorial/partwebtier.html" rel="noreferrer">Jakarta EE tutorial part III chapters 7 - 17</a>. You can by the way also use JSF on Tomcat, you only have to install it separately. Installation instructions can be found at <a href="https://eclipse-ee4j.github.io/mojarra/" rel="noreferrer">Mojarra homepage</a>. WildFly, TomEE, Payara, Liberty, WebLogic, etc as being a complete Jakarta EE implementation already provide JSF (and CDI, BV, JSONP, JAX-RS, EJB, JPA, etc) out the box, so you don't need to install it separately. See also <a href="https://stackoverflow.com/questions/8081234/how-to-properly-install-and-configure-jsf-libraries-via-maven">How to properly install and configure JSF libraries via Maven?</a></p> <hr /> <blockquote> <p><em>Maybe a book that covers all of these?</em></p> </blockquote> <p>There are several books. I would recommend to start with a book <a href="https://www.amazon.com/s?k=jakarta+ee&amp;s=date-desc-rank" rel="noreferrer">focused on Jakarta EE in general</a>, a book <a href="https://www.amazon.com/s?k=jsf+java&amp;s=date-desc-rank" rel="noreferrer">more focused on JSF</a>, and a book <a href="https://www.amazon.com/s?k=jpa+java&amp;s=date-desc-rank" rel="noreferrer">more focused on JPA</a>. Ensure that you choose the most recent book covering the subject. First investigate the most recent available version and then ensure that the chosen book covers that. Thus do definitely not pick an old book for Java EE 5 or JSF 1.0 or so while there's currently already Jakarta EE 8 and JSF 2.3 available.</p> <p>Last but not least, please ignore code snippet scraping sites maintained by amateurs with primary focus on advertisement income instead of on teaching, such as roseindia, tutorialspoint, javabeat, journaldev, javatpoint, codejava, etc. They are easily recognizable by disturbing advertising links/banners and JSP code snippets containing <em>scriptlets</em>.</p> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/2095397/what-is-the-difference-between-jsf-servlet-and-jsp">What is the difference between JSF, Servlet and JSP?</a></li> <li><a href="https://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-shared-variables-and-multithreading">How do servlets work? Instantiation, sessions, shared variables and multithreading</a></li> <li><a href="https://stackoverflow.com/questions/4421839/what-is-the-need-of-jsf-when-ui-can-be-achieved-from-css-html-javascript-jquery/">What is the need of JSF, when UI can be achieved with JavaScript libraries such as jQuery and AngularJS</a></li> </ul>
{ "question_id": 1958808, "question_date": "2009-12-24T15:55:08.217Z", "question_score": 221, "tags": "jsp|servlets|jakarta-ee|model-view-controller", "answer_id": 1958854, "answer_date": "2009-12-24T16:07:35.413Z", "answer_score": 273 }
Please answer the following Stack Overflow question: Title: Combine the first two commits of a Git repository? <p>Suppose you have a history containing the three commits <i>A, B</i> and <i>C</i>:</p> <pre><code>A-B-C </code></pre> <p>I would like to combine the two commits <i>A</i> and <i>B</i> to one commit <i>AB</i>:</p> <pre><code>AB-C </code></pre> <p>I tried</p> <pre><code>git rebase -i A </code></pre> <p>which opens up my editor with the following contents:</p> <pre><code>pick e97a17b B pick asd314f C </code></pre> <p>I change this to</p> <pre><code>squash e97a17b B pick asd314f C </code></pre> <p>Then Git 1.6.0.4 says:</p> <pre><code>Cannot 'squash' without a previous commit </code></pre> <p>Is there a way or is this just impossible?</p>
<p>Use <code>git rebase -i --root</code> as of Git <a href="https://github.com/git/git/blob/master/Documentation/RelNotes/1.7.12.txt" rel="noreferrer">version 1.7.12</a>.</p> <p>In the interactive rebase file, change the second line of commit <em>B</em> to <em>squash</em> and leave the other lines at <em>pick</em>:</p> <pre><code>pick f4202da A squash bea708e B pick a8c6abc C </code></pre> <p>This will combine the two commits <em>A</em> and <em>B</em> to one commit <em>AB</em>.</p> <p>Found in <a href="https://stackoverflow.com/a/9254257/105137">this answer</a>.</p>
{ "question_id": 435646, "question_date": "2009-01-12T14:53:21.203Z", "question_score": 221, "tags": "git|rebase|git-rebase|git-rewrite-history", "answer_id": 21654379, "answer_date": "2014-02-09T02:14:48.493Z", "answer_score": 202 }
Please answer the following Stack Overflow question: Title: throw Error('msg') vs throw new Error('msg') <pre><code>var err1 = Error('message'); var err2 = new Error('message'); </code></pre> <p>What's the difference? Looking at them in the chrome console, they look identical. Same properties on the object and the same <code>__proto__</code> chain. Almost seems like <code>Error</code> acts like a factory.</p> <p>Which one is correct and why?</p>
<p>Both are fine; this is explicitly stated in <a href="https://es5.github.io/#x15.11.1" rel="noreferrer">the specification</a>:</p> <blockquote> <p>... Thus the function call <code>Error(…)</code> is equivalent to the object creation expression <code>new Error(…)</code> with the same arguments.</p> </blockquote>
{ "question_id": 13294658, "question_date": "2012-11-08T17:42:04.483Z", "question_score": 221, "tags": "javascript|exception", "answer_id": 13294683, "answer_date": "2012-11-08T17:43:22.373Z", "answer_score": 221 }
Please answer the following Stack Overflow question: Title: <%$, <%@, <%=, <%# ... what's the deal? <p>I've programmed in both classic ASP and ASP.NET, and I see different tags inside of the markup for server side code. </p> <p>I've recently come across a <a href="http://blogs.msdn.com/dancre/archive/2007/02/13/the-difference-between-lt-and-lt-in-asp-net.aspx" rel="noreferrer">good blog on MSDN</a> that goes over the difference between:</p> <ul> <li><code>&lt;%=</code> (percentage together with equals sign) and </li> <li><code>&lt;%#</code> (percent sign and hash/pound/octothorpe) </li> </ul> <p>(<code>&lt;%#</code> is evaluated only at databind, and <code>&lt;%=</code> is evaluated at render), but I also see:</p> <ul> <li><code>&lt;%$</code> (percent and dollar sign) and </li> <li><code>&lt;%@</code> (percent sign and at symbol).</li> </ul> <p>I believe <code>&lt;%@</code> loads things like assemblies and perhaps <code>&lt;%$</code> loads things from config files? I'm not too sure.</p> <p>I was just wondering if anyone could clarify all of this for me and possibly explain why it's important to create so many different tags that seemingly have a similar purpose?</p>
<ul> <li><code>&lt;% %&gt;</code> - is for <a href="http://msdn.microsoft.com/en-us/library/k6xeyd4z%28v=vs.100%29.aspx" rel="noreferrer">inline code</a> (especially logic flow)</li> <li><code>&lt;%$ %&gt;</code> - is for <a href="http://msdn.microsoft.com/en-us/library/d5bd1tad.aspx" rel="noreferrer">evaluating expressions</a> (like resource variables)</li> <li><code>&lt;%@ %&gt;</code> - is for <a href="http://msdn.microsoft.com/en-us/library/xz702w3e%28v=vs.100%29.aspx" rel="noreferrer">Page directives</a>, registering assemblies, importing namespaces, etc.</li> <li><code>&lt;%= %&gt;</code> - is short-hand for <code>Response.Write</code> (discussed <a href="http://msdn.microsoft.com/en-us/library/ms178135.aspx" rel="noreferrer">here</a>)</li> <li><code>&lt;%# %&gt;</code> - is used for <a href="http://support.microsoft.com/kb/307860#1a" rel="noreferrer">data binding expressions</a>.</li> <li><code>&lt;%: %&gt;</code> - is short-hand for <a href="http://weblogs.asp.net/scottgu/archive/2010/04/06/new-lt-gt-syntax-for-html-encoding-output-in-asp-net-4-and-asp-net-mvc-2.aspx" rel="noreferrer">Response.Write(Server.HTMLEncode())</a> ASP.net 4.0+</li> <li><code>&lt;%#: %&gt;</code> - is used for <a href="http://support.microsoft.com/kb/307860#1a" rel="noreferrer">data binding expressions</a> and is automatically HTMLEncoded.</li> <li><code>&lt;%-- --%&gt;</code> - is for <a href="http://msdn.microsoft.com/en-us/library/4acf8afk%28v=vs.100%29.aspx" rel="noreferrer">server-side comments</a></li> </ul>
{ "question_id": 957284, "question_date": "2009-06-05T18:12:53.080Z", "question_score": 221, "tags": "asp.net|server-tags", "answer_id": 957321, "answer_date": "2009-06-05T18:18:32.027Z", "answer_score": 312 }
Please answer the following Stack Overflow question: Title: Convert character to ASCII numeric value in java <p>I have <code>String name = &quot;admin&quot;;</code><br /> then I do <code>String charValue = name.substring(0,1); //charValue=&quot;a&quot;</code></p> <p>I want to convert the <code>charValue</code> to its ASCII value (97), how can I do this in java?</p>
<p>Very simple. Just cast your <code>char</code> as an <code>int</code>.</p> <pre><code>char character = 'a'; int ascii = (int) character; </code></pre> <p>In your case, you need to get the specific Character from the String first and then cast it. </p> <pre><code>char character = name.charAt(0); // This gives the character 'a' int ascii = (int) character; // ascii is now 97. </code></pre> <p>Though cast is not required explicitly, but its improves readability.</p> <pre><code>int ascii = character; // Even this will do the trick. </code></pre>
{ "question_id": 16458564, "question_date": "2013-05-09T09:30:22.690Z", "question_score": 220, "tags": "java|string|ascii", "answer_id": 16458580, "answer_date": "2013-05-09T09:31:08.197Z", "answer_score": 381 }
Please answer the following Stack Overflow question: Title: How to change column datatype in SQL Server database without losing data? <p>I have SQL Server database and I just realized that I can change the type of one of the columns from <code>int</code> to <code>bool</code>. </p> <p>How can I do that without losing the data that is already entered into that table? </p>
<p>You can easily do this using the following command. Any value of 0 will be turned into a 0 (BIT = false), anything else will be turned into 1 (BIT = true).</p> <pre><code>ALTER TABLE dbo.YourTable ALTER COLUMN YourColumnName BIT </code></pre> <p>The other option would be to create a new column of type <code>BIT</code>, fill it from the old column, and once you're done, drop the old column and rename the new one to the old name. That way, if something during the conversion goes wrong, you can always go back since you still have all the data..</p>
{ "question_id": 5136013, "question_date": "2011-02-27T21:14:22.520Z", "question_score": 220, "tags": "sql-server|sql-server-2008|alter", "answer_id": 5136055, "answer_date": "2011-02-27T21:18:12.640Z", "answer_score": 361 }
Please answer the following Stack Overflow question: Title: How to add a set path only for that batch file executing? <p>Basically, I know I can go through my control panel and modify the path variable. But, I'm wondering if there is a way to through batch programming have a temporary path included? That way it is only used during that batch file execution. I don't want to have people go in and modify their path variables just to use my batch file.</p>
<p>Just like any other environment variable, with <a href="http://ss64.com/nt/set.html"><code>SET</code></a>:</p> <pre><code>SET PATH=%PATH%;c:\whatever\else </code></pre> <p>If you want to have a little safety check built in first, check to see if the new path exists first:</p> <pre><code>IF EXIST c:\whatever\else SET PATH=%PATH%;c:\whatever\else </code></pre> <p>If you want that to be local to that batch file, use <a href="http://ss64.com/nt/setlocal.html"><code>setlocal</code></a>:</p> <pre><code>setlocal set PATH=... set OTHERTHING=... @REM Rest of your script </code></pre> <p>Read the docs carefully for <code>setlocal</code>/<code>endlocal</code> , and have a look at the other references on that site - <a href="http://ss64.com/nt/syntax-functions.html">Functions</a> is pretty interesting too and the syntax is tricky.</p> <p>The <a href="http://ss64.com/nt/syntax.html">Syntax</a> page should get you started with the basics.</p>
{ "question_id": 6832496, "question_date": "2011-07-26T15:24:26.800Z", "question_score": 220, "tags": "path|batch-file|command|command-prompt", "answer_id": 6832544, "answer_date": "2011-07-26T15:28:31.410Z", "answer_score": 361 }
Please answer the following Stack Overflow question: Title: Check substring exists in a string in C <p>I'm trying to check whether a string contains a substring in C like:</p> <pre><code>char *sent = "this is my sample example"; char *word = "sample"; if (/* sentence contains word */) { /* .. */ } </code></pre> <p>What is something to use instead of <code>string::find</code> in C++?</p>
<pre><code>if (strstr(sent, word) != NULL) { /* ... */ } </code></pre> <p>Note that <code>strstr</code> returns a pointer to the start of the word in <code>sent</code> if the word <code>word</code> is found.</p>
{ "question_id": 12784766, "question_date": "2012-10-08T15:28:00.250Z", "question_score": 220, "tags": "c|string", "answer_id": 12784812, "answer_date": "2012-10-08T15:30:23.003Z", "answer_score": 348 }
Please answer the following Stack Overflow question: Title: mongo - couldn't connect to server 127.0.0.1:27017 <p>I am coming from riak and redis where I never had an issue with this services starting, or to interact.</p> <p>This is a pervasive problem with mongo and am rather clueless. Restarting does not help.I am new to mongo. </p> <pre><code>mongo MongoDB shell version: 2.2.1 connecting to: test Fri Nov 9 16:44:06 Error: couldn't connect to server 127.0.0.1:27017 src/mongo/shell/mongo.js:91 exception: connect failed </code></pre> <p>This is what I see in the logs.</p> <pre><code> now open) Fri Nov 9 16:44:34 [conn47] end connection 10.29.16.208:5306 (1 connection now open) Fri Nov 9 16:45:04 [initandlisten] connection accepted from 10.29.16.208:5307 #48 (2 connections now open) Fri Nov 9 16:45:04 [conn48] end connection 10.29.16.208:5307 (1 connection now open) Fri Nov 9 16:45:04 [initandlisten] connection accepted from 10.29.16.208:5308 #49 (2 connections now open) Fri Nov 9 16:45:04 [conn49] end connection 10.29.16.208:5308 (1 connection now open) Fri Nov 9 16:45:34 [initandlisten] connection accepted from 10.29.16.208:5316 #50 (2 connections now open) Fri Nov 9 16:45:34 [conn50] end connection 10.29.16.208:5316 (1 connection now open) Fri Nov 9 16:45:34 [initandlisten] connection accepted from 10.29.16.208:5317 #51 (2 connections now open) Fri Nov 9 16:45:34 [conn51] end connection 10.29.16.208:5317 (1 connection now open) Fri Nov 9 16:46:04 [initandlisten] connection accepted from 10.29.16.208:5320 #52 (2 connections now open) Fri Nov 9 16:46:04 [conn52] end connection 10.29.16.208:5320 (1 connection now open) Fri Nov 9 16:46:04 [initandlisten] connection accepted from 10.29.16.208:5321 #53 (2 connections now open) Fri Nov 9 16:46:04 [conn53] end connection 10.29.16.208:5321 (1 conn </code></pre>
<p>This error is what you would see if the mongo shell was not able to talk to the mongod server.</p> <p>This could be because the address was wrong (host or IP) or that it was not running. One thing to note is the log trace provided does not cover the "Fri Nov 9 16:44:06" of your <code>mongo timestamp</code>. </p> <p>Can you:</p> <ol> <li>Provide the command line arguments (if any) used to start your mongod process</li> <li>Provide the log file activity from the mongod startup as well as logs during the mongo shell startup attempt?</li> <li>Confirm that your mongod process is being started on the same machine as the mongo shell?</li> </ol>
{ "question_id": 13312358, "question_date": "2012-11-09T16:48:39.633Z", "question_score": 220, "tags": "mongodb|pymongo", "answer_id": 13316906, "answer_date": "2012-11-09T22:24:20.237Z", "answer_score": 57 }
Please answer the following Stack Overflow question: Title: HTTP GET Request in Node.js Express <p>How can I make an HTTP request from within Node.js or Express.js? I need to connect to another service. I am hoping the call is asynchronous and that the callback contains the remote server's response.</p>
<p>Here is a snippet of some code from a sample of mine. It's asynchronous and returns a JSON object. It can do any form of GET request.</p> <p>Note that there are more optimal ways (just a sample) - for example, instead of concatenating the chunks you put into an array and join it etc... Hopefully, it gets you started in the right direction:</p> <pre><code>const http = require('http'); const https = require('https'); /** * getJSON: RESTful GET request returning JSON object(s) * @param options: http options object * @param callback: callback to pass the results JSON object(s) back */ module.exports.getJSON = (options, onResult) =&gt; { console.log('rest::getJSON'); const port = options.port == 443 ? https : http; let output = ''; const req = port.request(options, (res) =&gt; { console.log(`${options.host} : ${res.statusCode}`); res.setEncoding('utf8'); res.on('data', (chunk) =&gt; { output += chunk; }); res.on('end', () =&gt; { let obj = JSON.parse(output); onResult(res.statusCode, obj); }); }); req.on('error', (err) =&gt; { // res.send('error: ' + err.message); }); req.end(); }; </code></pre> <p>It's called by creating an options object like:</p> <pre><code>const options = { host: 'somesite.com', port: 443, path: '/some/path', method: 'GET', headers: { 'Content-Type': 'application/json' } }; </code></pre> <p>And providing a callback function.</p> <p>For example, in a service, I require the REST module above and then do this:</p> <pre><code>rest.getJSON(options, (statusCode, result) =&gt; { // I could work with the resulting HTML/JSON here. I could also just return it console.log(`onResult: (${statusCode})\n\n${JSON.stringify(result)}`); res.statusCode = statusCode; res.send(result); }); </code></pre> <h2>UPDATE</h2> <p>If you're looking for <code>async</code>/<code>await</code> (linear, no callback), promises, compile time support and intellisense, we created a lightweight HTTP and REST client that fits that bill:</p> <p><a href="https://github.com/Microsoft/typed-rest-client" rel="noreferrer">Microsoft typed-rest-client</a></p>
{ "question_id": 9577611, "question_date": "2012-03-06T03:43:19.930Z", "question_score": 220, "tags": "javascript|node.js|express|httprequest", "answer_id": 9577651, "answer_date": "2012-03-06T03:50:51.523Z", "answer_score": 238 }
Please answer the following Stack Overflow question: Title: Textarea Auto height <p>I want to make height of textarea equal to height of the text within it (And remove the scroll bar)</p> <p>HTML</p> <pre><code>&lt;textarea id="note"&gt;SOME TEXT&lt;/textarea&gt; </code></pre> <p>CSS</p> <pre><code>textarea#note { width:100%; direction:rtl; display:block; max-width:100%; line-height:1.5; padding:15px 15px 30px; border-radius:3px; border:1px solid #F7E98D; font:13px Tahoma, cursive; transition:box-shadow 0.5s ease; box-shadow:0 4px 6px rgba(0,0,0,0.1); font-smoothing:subpixel-antialiased; background:linear-gradient(#F9EFAF, #F7E98D); background:-o-linear-gradient(#F9EFAF, #F7E98D); background:-ms-linear-gradient(#F9EFAF, #F7E98D); background:-moz-linear-gradient(#F9EFAF, #F7E98D); background:-webkit-linear-gradient(#F9EFAF, #F7E98D); } </code></pre> <p>JsFiddle: <a href="http://jsfiddle.net/Tw9Rj/">http://jsfiddle.net/Tw9Rj/</a></p>
<p><s>It can be achieved using JS. Here is a 'one-line' <a href="http://jsfiddle.net/Tw9Rj/6/" rel="noreferrer">solution</a> using <a href="http://unwrongest.com/projects/elastic/" rel="noreferrer">elastic.js</a>:</p> <pre><code>$('#note').elastic(); </code></pre> <p></s></p> <p>Updated: Seems like elastic.js is not there anymore, but if you are looking for an external library, I can recommend <a href="http://www.jacklmoore.com/autosize/" rel="noreferrer">autosize.js by Jack Moore</a>. This is the working example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>autosize(document.getElementById("note"));</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>textarea#note { width:100%; box-sizing:border-box; direction:rtl; display:block; max-width:100%; line-height:1.5; padding:15px 15px 30px; border-radius:3px; border:1px solid #F7E98D; font:13px Tahoma, cursive; transition:box-shadow 0.5s ease; box-shadow:0 4px 6px rgba(0,0,0,0.1); font-smoothing:subpixel-antialiased; background:linear-gradient(#F9EFAF, #F7E98D); background:-o-linear-gradient(#F9EFAF, #F7E98D); background:-ms-linear-gradient(#F9EFAF, #F7E98D); background:-moz-linear-gradient(#F9EFAF, #F7E98D); background:-webkit-linear-gradient(#F9EFAF, #F7E98D); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://rawgit.com/jackmoore/autosize/master/dist/autosize.min.js"&gt;&lt;/script&gt; &lt;textarea id="note"&gt;Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.&lt;/textarea&gt;</code></pre> </div> </div> </p> <p>Check this similar topics too:</p> <p><a href="https://stackoverflow.com/questions/7477/autosizing-textarea-using-prototype">Autosizing textarea using Prototype</a></p> <p><a href="https://stackoverflow.com/questions/995168/textarea-to-resize-based-on-content-length">Textarea to resize based on content length</a></p> <p><a href="https://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize">Creating a textarea with auto-resize</a></p>
{ "question_id": 17772260, "question_date": "2013-07-21T12:19:16.603Z", "question_score": 220, "tags": "javascript|html|css", "answer_id": 17772322, "answer_date": "2013-07-21T12:25:43.663Z", "answer_score": 61 }
Please answer the following Stack Overflow question: Title: JS strings "+" vs concat method <p>I have some experience with Java and I know that strings concatenation with "+" operator produces new object. </p> <p>I'd like to know how to do it in JS in the best way, what is the best practice for it?</p>
<p>MDN has the following to say about <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/concat" rel="noreferrer"><code>string.concat()</code></a>:</p> <blockquote> <p>It is strongly recommended to use the string concatenation operators (+, +=) instead of this method for perfomance reasons</p> </blockquote> <p>Also see the <a href="https://web.archive.org/web/20170404182053/https://jsperf.com/concat-vs-plus-vs-join" rel="noreferrer">link</a> by @Bergi.</p>
{ "question_id": 16124032, "question_date": "2013-04-20T19:01:10.470Z", "question_score": 220, "tags": "javascript", "answer_id": 16124072, "answer_date": "2013-04-20T19:05:02.120Z", "answer_score": 315 }
Please answer the following Stack Overflow question: Title: Merging 2 branches together in GIT <p>I've only just started to use GIT and think its wonderful, however I'm a little confused over what the <code>merge</code> command does.</p> <p>Let us say we have a working project in the branch "A".</p> <p>I go home and make changes to this branch and save it as "B". Another programmer makes changes to "A" and saves it as "C".</p> <p>Is there a way to merge the two branches "B" and "C" together, then commit the changes as a new branch, say "D"?</p> <p>Or am missing the point of 'merge'?</p>
<p><code>merge</code> is used to bring two (or more) branches together.</p> <p>a little example:</p> <pre><code># on branch A: # create new branch B $ git checkout -b B # hack hack $ git commit -am "commit on branch B" # create new branch C from A $ git checkout -b C A # hack hack $ git commit -am "commit on branch C" # go back to branch A $ git checkout A # hack hack $ git commit -am "commit on branch A" </code></pre> <p>so now there are three separate branches (namely A B and C) with different heads</p> <p>to get the changes from B and C back to A, checkout A (already done in this example) and then use the merge command:</p> <pre><code># create an octopus merge $ git merge B C </code></pre> <p>your history will then look something like this:</p> <pre><code>…-o-o-x-------A |\ /| | B---/ | \ / C---/ </code></pre> <p>if you want to merge across repository/computer borders, have a look at <code>git pull</code> command, e.g. from the pc with branch A (this example will create two new commits):</p> <pre><code># pull branch B $ git pull ssh://host/… B # pull branch C $ git pull ssh://host/… C </code></pre>
{ "question_id": 3404294, "question_date": "2010-08-04T09:40:42.587Z", "question_score": 220, "tags": "git|merge|commit", "answer_id": 3404410, "answer_date": "2010-08-04T09:58:05.170Z", "answer_score": 284 }
Please answer the following Stack Overflow question: Title: What is the best way to do a substring in a batch file? <p>I want to get the name of the currently running batch file <strong>without</strong> the file extension. </p> <p>Thanks to <a href="https://stackoverflow.com/questions/343518/finding-out-the-file-name-of-the-running-batch-file">this link</a>, I have the file name <strong>with</strong> the extension... but what is the best way to do a substring in a batch file?</p> <p>Or is there another way to get the file name w/o the extension?</p> <p>It is safe to assume 3 letter extensions in this scenario.</p>
<p>Well, for just getting the filename of your batch the easiest way would be to just use <code>%~n0</code>.</p> <pre><code>@echo %~n0 </code></pre> <p>will output the name (without the extension) of the currently running batch file (unless executed in a subroutine called by <code>call</code>). The complete list of such “special” substitutions for path names can be found with <code>help for</code>, at the very end of the help:</p> <blockquote> <p>In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:</p> <pre><code>%~I - expands %I removing any surrounding quotes (") %~fI - expands %I to a fully qualified path name %~dI - expands %I to a drive letter only %~pI - expands %I to a path only %~nI - expands %I to a file name only %~xI - expands %I to a file extension only %~sI - expanded path contains short names only %~aI - expands %I to file attributes of file %~tI - expands %I to date/time of file %~zI - expands %I to size of file %~$PATH:I - searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string </code></pre> <p>The modifiers can be combined to get compound results:</p> <pre><code>%~dpI - expands %I to a drive letter and path only %~nxI - expands %I to a file name and extension only %~fsI - expands %I to a full path name with short names only </code></pre> </blockquote> <p>To precisely answer your question, however: Substrings are done using the <code>:~start,length</code> notation: </p> <pre><code>%var:~10,5% </code></pre> <p>will extract 5 characters from position 10 in the environment variable <code>%var%</code>.</p> <p><strong>NOTE:</strong> The index of the strings is zero based, so the first character is at position 0, the second at 1, etc.</p> <p>To get substrings of argument variables such as <code>%0</code>, <code>%1</code>, etc. you have to assign them to a normal environment variable using <code>set</code> first:</p> <pre><code>:: Does not work: @echo %1:~10,5 :: Assign argument to local variable first: set var=%1 @echo %var:~10,5% </code></pre> <p>The syntax is even more powerful: </p> <ul> <li><code>%var:~-7%</code> extracts the last 7 characters from <code>%var%</code> </li> <li><code>%var:~0,-4%</code> would extract all characters except the last four which would also rid you of the file extension (assuming three characters after the period [<code>.</code>]).</li> </ul> <p>See <code>help set</code> for details on that syntax.</p>
{ "question_id": 636381, "question_date": "2009-03-11T21:08:16.307Z", "question_score": 220, "tags": "batch-file|substring", "answer_id": 636391, "answer_date": "2009-03-11T21:11:12.633Z", "answer_score": 442 }
Please answer the following Stack Overflow question: Title: MySQL Removing Some Foreign keys <p>I have a table whose primary key is used in several other tables and has several foreign keys to other tables. </p> <pre><code>CREATE TABLE location ( locationID INT NOT NULL AUTO_INCREMENT PRIMARY KEY ... ) ENGINE = InnoDB; CREATE TABLE assignment ( assignmentID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, locationID INT NOT NULL, FOREIGN KEY locationIDX (locationID) REFERENCES location (locationID) ... ) ENGINE = InnoDB; CREATE TABLE assignmentStuff ( ... assignmentID INT NOT NULL, FOREIGN KEY assignmentIDX (assignmentID) REFERENCES assignment (assignmentID) ) ENGINE = InnoDB; </code></pre> <p>The problem is that when I'm trying to drop one of the foreign key columns (ie locationIDX) it gives me an error. </p> <blockquote> <p>"ERROR 1025 (HY000): Error on rename"</p> </blockquote> <p>How can I drop the column in the assignment table above without getting this error?</p>
<p>As explained <a href="http://bugs.mysql.com/bug.php?id=14347" rel="noreferrer">here</a>, seems the <em>foreign key</em> constraint has to be dropped by <strong>constraint name</strong> and not the <em>index</em> name.</p> <p>The syntax is:</p> <pre><code>ALTER TABLE footable DROP FOREIGN KEY fooconstraint; </code></pre>
{ "question_id": 838354, "question_date": "2009-05-08T05:25:54.607Z", "question_score": 220, "tags": "mysql|foreign-keys|constraints|mysql-error-1025", "answer_id": 838412, "answer_date": "2009-05-08T05:54:54.117Z", "answer_score": 512 }
Please answer the following Stack Overflow question: Title: Using Mockito's generic "any()" method <p>I have an interface with a method that expects an array of <code>Foo</code>:</p> <pre><code>public interface IBar { void doStuff(Foo[] arr); } </code></pre> <p>I am mocking this interface using Mockito, and I'd like to assert that <code>doStuff()</code> is called, but I don't want to validate what argument are passed - "don't care".</p> <p>How do I write the following code using <code>any()</code>, the generic method, instead of <code>anyObject()</code>?</p> <pre><code>IBar bar = mock(IBar.class); ... verify(bar).doStuff((Foo[]) anyObject()); </code></pre>
<p>Since Java 8 you can use the argument-less <code>any</code> method and the type argument will get inferred by the compiler:</p> <pre><code>verify(bar).doStuff(any()); </code></pre> <hr /> <h3>Explanation</h3> <p>The new thing in Java 8 is that the <a href="https://dev.java/learn/type-inference#target-types" rel="nofollow noreferrer"><em>target type</em></a> of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference (most of the time).</p> <p>In this case the parameter type of <code>doStuff</code> will be the target type for <code>any()</code>, and the return value type of <code>any()</code> will get chosen to match that argument type.</p> <p>This mechanism was added mainly to be able to compile lambda expressions, but it improves type inferences generally.</p> <hr /> <h3>Primitive types</h3> <p>This doesn't work with primitive types, unfortunately:</p> <pre><code>public interface IBar { void doPrimitiveStuff(int i); } verify(bar).doPrimitiveStuff(any()); // Compiles but throws NullPointerException verify(bar).doPrimitiveStuff(anyInt()); // This is what you have to do instead </code></pre> <p>The problem is that the compiler will infer <code>Integer</code> as the return value type of <code>any()</code>. Mockito will not be aware of this (due to type erasure) and return the default value for reference types, which is <code>null</code>. The runtime will try to unbox the null return value by calling the <code>intValue</code> method on it before passing it to <code>doStuff</code>, and the exception gets thrown.</p>
{ "question_id": 1778744, "question_date": "2009-11-22T13:50:00.467Z", "question_score": 220, "tags": "java|unit-testing|mocking|mockito", "answer_id": 30886011, "answer_date": "2015-06-17T08:19:59.910Z", "answer_score": 142 }
Please answer the following Stack Overflow question: Title: How to properly create composite primary keys - MYSQL <p>Here is a gross oversimplification of an intense setup I am working with. <code>table_1</code> and <code>table_2</code> both have auto-increment surrogate primary keys as the ID. <code>info</code> is a table that contains information about both <code>table_1</code> and <code>table_2</code>.</p> <pre><code>table_1 (id, field) table_2 (id, field, field) info ( ???, field) </code></pre> <p>I am trying to decided if I should make the primary key of <code>info</code> a composite of the IDs from <code>table_1</code> and <code>table_2</code>. If I were to do this, which of these makes most sense?<br> <em>( in this example I am combining ID 11209 with ID 437 )</em> </p> <p><code>INT(9)</code> 11209437 <em>(i can imagine why this is bad)</em><br> <code>VARCHAR (10)</code> 11209-437<br> <code>DECIMAL (10,4)</code> 11209.437 </p> <p>Or something else? </p> <p>Would this be fine to use this as the Primary Key on a MYSQL MYISAM DB?</p>
<p>I would use a composite (multi-column) key.</p> <pre><code>CREATE TABLE INFO ( t1ID INT, t2ID INT, PRIMARY KEY (t1ID, t2ID) ) </code></pre> <p>This way you can have t1ID and t2ID as foreign keys pointing to their respective tables as well.</p>
{ "question_id": 5835978, "question_date": "2011-04-29T18:38:47.817Z", "question_score": 220, "tags": "mysql|primary-key|myisam|composite-key|composite-primary-key", "answer_id": 5836070, "answer_date": "2011-04-29T18:47:09.243Z", "answer_score": 413 }
Please answer the following Stack Overflow question: Title: Difference between exit(0) and exit(1) in Python <p>What's the difference between <code>exit(0)</code> and <code>exit(1)</code> in Python?</p> <p>I tried looking around but didn't find a specific question on these lines. If it's already been answered, a link would be sufficient.</p>
<p>0 and 1 are the exit codes.</p> <p><code>exit(0)</code> means a clean exit without any errors / problems</p> <p><code>exit(1)</code> means there was some issue / error / problem and that is why the program is exiting.</p> <p>This is not Python specific and is pretty common. A non-zero exit code is treated as an abnormal exit, and at times, the error code indicates what the problem was. A zero error code means a successful exit.</p> <p>This is useful for other programs, shell, caller etc. to know what happened with your program and proceed accordingly.</p>
{ "question_id": 9426045, "question_date": "2012-02-24T05:49:34.173Z", "question_score": 220, "tags": "python|exit-code", "answer_id": 9426054, "answer_date": "2012-02-24T05:50:48.163Z", "answer_score": 332 }
Please answer the following Stack Overflow question: Title: How can I escape a single quote? <p>How can I escape a <code>'</code> (single quote) in HTML?</p> <p>This is where I'm trying to use it:</p> <pre><code>&lt;input type='text' id='abc' value='hel'lo'&gt; </code></pre> <p>The result for the above code is &quot;hel&quot; populated in the text box. I tried to replace <code>'</code> with <code>\'</code>, but this what I'm getting.</p> <pre><code>&lt;input type='text' id='abc' value='hel\'lo'&gt; </code></pre> <p>The result for the above code is &quot;hel&quot; populated in the text box.</p> <p>How can I successfully escape the single quotes?</p>
<p>You could use HTML entities:</p> <ul> <li><code>&amp;#39;</code> for <code>'</code></li> <li><code>&amp;#34;</code> for <code>"</code></li> <li>...</li> </ul> <p>For more, you can take a look at <em><a href="http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML" rel="noreferrer">Character entity references in HTML</a></em>.</p>
{ "question_id": 2428572, "question_date": "2010-03-11T20:52:45.497Z", "question_score": 220, "tags": "html|escaping", "answer_id": 2428594, "answer_date": "2010-03-11T20:55:20.277Z", "answer_score": 404 }
Please answer the following Stack Overflow question: Title: Difference between File.separator and slash in paths <p>What is the difference between using <code>File.separator</code> and a normal <code>/</code> in a Java Path-String?</p> <p>In contrast to double backslash <code>\\</code> platform independence seems not to be the reason, since both versions work under Windows and Unix.</p> <pre><code>public class SlashTest { @Test public void slash() throws Exception { File file = new File("src/trials/SlashTest.java"); assertThat(file.exists(), is(true)); } @Test public void separator() throws Exception { File file = new File("src" + File.separator + "trials" + File.separator + "SlashTest.java"); assertThat(file.exists(), is(true)); } } </code></pre> <p>To rephrase the question, if <code>/</code> works on Unix and Windows, why should one ever want to use <code>File.separator</code>?</p>
<p>With the Java libraries for dealing with files, you can safely use <code>/</code> (slash, not backslash) on all platforms. The library code handles translating things into platform-specific paths internally.</p> <p>You might want to use <code>File.separator</code> in UI, however, because it's best to show people what will make sense in their OS, rather than what makes sense to Java.</p> <p><strong>Update</strong>: I have not been able, in five minutes of searching, to find the "you can always use a slash" behavior documented. Now, I'm sure I've seen it documented, but in the absense of finding an official reference (because my memory isn't perfect), I'd stick with using <code>File.separator</code> because you <em>know</em> that will work.</p>
{ "question_id": 2417485, "question_date": "2010-03-10T14:15:10.920Z", "question_score": 220, "tags": "java", "answer_id": 2417546, "answer_date": "2010-03-10T14:22:28.473Z", "answer_score": 266 }
Please answer the following Stack Overflow question: Title: How do I create a MongoDB dump of my database? <p>What command should I use to create a MongoDB dump of my database?</p>
<p>Use <code>mongodump</code>:</p> <pre><code>$ ./mongodump --host prod.example.com connected to: prod.example.com all dbs DATABASE: log to dump/log log.errors to dump/log/errors.bson 713 objects log.analytics to dump/log/analytics.bson 234810 objects DATABASE: blog to dump/blog blog.posts to dump/log/blog.posts.bson 59 objects DATABASE: admin to dump/admin </code></pre> <p>Source: <a href="http://www.mongodb.org/display/DOCS/Import+Export+Tools" rel="noreferrer">http://www.mongodb.org/display/DOCS/Import+Export+Tools</a></p>
{ "question_id": 4880874, "question_date": "2011-02-02T22:52:43.270Z", "question_score": 220, "tags": "database|mongodb|database-dump", "answer_id": 4880894, "answer_date": "2011-02-02T22:54:55.080Z", "answer_score": 98 }
Please answer the following Stack Overflow question: Title: How do you programmatically update query params in react-router? <p>I can't seem to find how to update query params with react-router without using <code>&lt;Link/&gt;</code>. <code>hashHistory.push(url)</code> doesn't seem to register query params, and it doesn't seem like you can pass a query object or anything as a second argument.</p> <p>How do you change the url from <code>/shop/Clothes/dresses</code> to <code>/shop/Clothes/dresses?color=blue</code> in react-router without using <code>&lt;Link&gt;</code>? </p> <p>And is an <code>onChange</code> function really the only way to listen for query changes? Why aren't query changes automatically detected and reacted-to the way that param changes are?</p>
<p>Within the <code>push</code> method of <code>hashHistory</code>, you can specify your query parameters. For instance, </p> <pre><code>history.push({ pathname: '/dresses', search: '?color=blue' }) </code></pre> <p>or</p> <pre><code>history.push('/dresses?color=blue') </code></pre> <p>You can check out this <a href="https://github.com/mjackson/history" rel="noreferrer">repository</a> for additional examples on using <code>history</code></p>
{ "question_id": 40161516, "question_date": "2016-10-20T18:06:09.100Z", "question_score": 220, "tags": "reactjs|react-router", "answer_id": 40161954, "answer_date": "2016-10-20T18:31:26.423Z", "answer_score": 254 }
Please answer the following Stack Overflow question: Title: Javascript array search and remove string? <p>I have:</p> <pre><code>var array = new Array(); array.push("A"); array.push("B"); array.push("C"); </code></pre> <p>I want to be able to do something like:</p> <p><code>array.remove("B");</code></p> <p>but there is no remove function. How do I accomplish this?</p>
<p>I'm actually updating this thread with a more recent 1-line solution: </p> <pre><code>let arr = ['A', 'B', 'C']; arr = arr.filter(e =&gt; e !== 'B'); // will return ['A', 'C'] </code></pre> <p>The idea is basically to filter the array by selecting all elements different to the element you want to remove. </p> <p>Note: will remove all occurrences. </p> <p>EDIT:</p> <p>If you want to remove only the first occurence: </p> <pre><code>t = ['A', 'B', 'C', 'B']; t.splice(t.indexOf('B'), 1); // will return ['B'] and t is now equal to ['A', 'C', 'B'] </code></pre>
{ "question_id": 9792927, "question_date": "2012-03-20T18:40:18.257Z", "question_score": 220, "tags": "javascript|arrays", "answer_id": 44433050, "answer_date": "2017-06-08T10:21:28.203Z", "answer_score": 361 }
Please answer the following Stack Overflow question: Title: Clear icon inside input text <p>Is there a quick way to create an input text element with an icon on the right to clear the input element itself (like the google search box)?</p> <p>I looked around but I only found how to put an icon as background of the input element. Is there a jQuery plugin or something else?</p> <p>I want the icon inside the input text element, something like:</p> <pre><code>-------------------------------------------------- | X| -------------------------------------------------- </code></pre>
<p>Add a <code>type=&quot;search&quot;</code> to your input<br /> The support is pretty decent but will <strong>not work in IE&lt;10</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="search"&gt;</code></pre> </div> </div> </p> <hr> <h2>Older browsers</h2> <p>If you need <strong>IE9 support</strong> here are some workarounds</p> <h3>Using a standard <code>&lt;input type=&quot;text&quot;&gt;</code> and some HTML elements:</h3> <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>/** * Clearable text inputs */ $(".clearable").each(function() { const $inp = $(this).find("input:text"), $cle = $(this).find(".clearable__clear"); $inp.on("input", function(){ $cle.toggle(!!this.value); }); $cle.on("touchstart click", function(e) { e.preventDefault(); $inp.val("").trigger("input"); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>/* Clearable text inputs */ .clearable{ position: relative; display: inline-block; } .clearable input[type=text]{ padding-right: 24px; width: 100%; box-sizing: border-box; } .clearable__clear{ display: none; position: absolute; right:0; top:0; padding: 0 8px; font-style: normal; font-size: 1.2em; user-select: none; cursor: pointer; } .clearable input::-ms-clear { /* Remove IE default X */ display: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;span class="clearable"&gt; &lt;input type="text" name="" value="" placeholder=""&gt; &lt;i class="clearable__clear"&gt;&amp;times;&lt;/i&gt; &lt;/span&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <h2>Using only a <code>&lt;input class=&quot;clearable&quot; type=&quot;text&quot;&gt;</code> (No additional elements)</h2> <p><img src="https://i.stack.imgur.com/mwIK2.jpg" alt="Clear icon inside input element" /></p> <p>set a <code>class=&quot;clearable&quot;</code> and play with it's background image:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>/** * Clearable text inputs */ function tog(v){return v ? "addClass" : "removeClass";} $(document).on("input", ".clearable", function(){ $(this)[tog(this.value)]("x"); }).on("mousemove", ".x", function( e ){ $(this)[tog(this.offsetWidth-18 &lt; e.clientX-this.getBoundingClientRect().left)]("onX"); }).on("touchstart click", ".onX", function( ev ){ ev.preventDefault(); $(this).removeClass("x onX").val("").change(); }); // $('.clearable').trigger("input"); // Uncomment the line above if you pre-fill values from LS or server</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>/* Clearable text inputs */ .clearable{ background: #fff url(http://i.stack.imgur.com/mJotv.gif) no-repeat right -10px center; border: 1px solid #999; padding: 3px 18px 3px 4px; /* Use the same right padding (18) in jQ! */ border-radius: 3px; transition: background 0.4s; } .clearable.x { background-position: right 5px center; } /* (jQ) Show icon */ .clearable.onX{ cursor: pointer; } /* (jQ) hover cursor style */ .clearable::-ms-clear {display: none; width:0; height:0;} /* Remove IE default X */</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input class="clearable" type="text" name="" value="" placeholder="" /&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>The trick is to set some right padding (I used 18px) to the <code>input</code> and push the background-image right, out of sight (I used <code>right -10px center</code>).<br /> That 18px padding will prevent the text hide underneath the icon (while visible).<br /> jQuery will add the class <code>&quot;x&quot;</code> (if <code>input</code> has value) showing the clear icon.<br /> Now all we need is to target with jQ the inputs with class <code>x</code> and detect on <code>mousemove</code> if the mouse is inside that 18px &quot;x&quot; area; if inside, add the class <code>onX</code>.<br /> Clicking the <code>onX</code> class removes all classes, resets the input value and hides the icon.</p> <hr> <p>7x7px gif: <img src="https://i.stack.imgur.com/mJotv.gif" alt="Clear icon 7x7" /></p> <p>Base64 string:</p> <pre><code>data:image/gif;base64,R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs= </code></pre>
{ "question_id": 6258521, "question_date": "2011-06-06T22:00:35.550Z", "question_score": 220, "tags": "javascript|jquery|html|css", "answer_id": 6258628, "answer_date": "2011-06-06T22:11:44.043Z", "answer_score": 418 }
Please answer the following Stack Overflow question: Title: Splitting a list into N parts of approximately equal length <p>What is the best way to divide a list into <em>roughly</em> equal parts? For example, if the list has 7 elements and is split it into 2 parts, we want to get 3 elements in one part, and the other should have 4 elements.</p> <p>I'm looking for something like <code>even_split(L, n)</code> that breaks <code>L</code> into <code>n</code> parts.</p> <pre><code>def chunks(L, n): """ Yield successive n-sized chunks from L. """ for i in range(0, len(L), n): yield L[i:i+n] </code></pre> <p>The code above gives chunks of 3, rather than 3 chunks. I could simply transpose (iterate over this and take the first element of each column, call that part one, then take the second and put it in part two, etc), but that destroys the ordering of the items.</p>
<p><strong>This code is broken due to rounding errors. Do not use it!!!</strong></p> <pre><code>assert len(chunkIt([1,2,3], 10)) == 10 # fails </code></pre> <hr> <p>Here's one that could work:</p> <pre><code>def chunkIt(seq, num): avg = len(seq) / float(num) out = [] last = 0.0 while last &lt; len(seq): out.append(seq[int(last):int(last + avg)]) last += avg return out </code></pre> <p>Testing:</p> <pre><code>&gt;&gt;&gt; chunkIt(range(10), 3) [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]] &gt;&gt;&gt; chunkIt(range(11), 3) [[0, 1, 2], [3, 4, 5, 6], [7, 8, 9, 10]] &gt;&gt;&gt; chunkIt(range(12), 3) [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] </code></pre>
{ "question_id": 2130016, "question_date": "2010-01-25T03:19:28.967Z", "question_score": 220, "tags": "python|list|chunks", "answer_id": 2130035, "answer_date": "2010-01-25T03:27:31.450Z", "answer_score": 79 }
Please answer the following Stack Overflow question: Title: Downloading images with node.js <p>I'm trying to write a script to download images using node.js. This is what I have so far:</p> <pre><code>var maxLength = 10 // 10mb var download = function(uri, callback) { http.request(uri) .on('response', function(res) { if (res.headers['content-length'] &gt; maxLength*1024*1024) { callback(new Error('Image too large.')) } else if (!~[200, 304].indexOf(res.statusCode)) { callback(new Error('Received an invalid status code.')) } else if (!res.headers['content-type'].match(/image/)) { callback(new Error('Not an image.')) } else { var body = '' res.setEncoding('binary') res .on('error', function(err) { callback(err) }) .on('data', function(chunk) { body += chunk }) .on('end', function() { // What about Windows?! var path = '/tmp/' + Math.random().toString().split('.').pop() fs.writeFile(path, body, 'binary', function(err) { callback(err, path) }) }) } }) .on('error', function(err) { callback(err) }) .end(); } </code></pre> <p>I, however, want to make this more robust:</p> <ol> <li>Are there libraries that do this and do this better?</li> <li>Is there a chance that response headers lie (about length, about content type)?</li> <li>Are there any other status codes I should care about? Should I bother with redirects?</li> <li>I think I read somewhere that <code>binary</code> encoding is going to be deprecated. What do I do then?</li> <li>How can I get this to work on windows?</li> <li>Any other ways you can make this script better?</li> </ol> <p>Why: for a feature similar to imgur where users can give me a URL, I download that image, and rehost the image in multiple sizes.</p>
<p>I'd suggest using the <a href="https://github.com/mikeal/request" rel="noreferrer">request module</a>. Downloading a file is as simple as the following code:</p> <pre><code>var fs = require('fs'), request = require('request'); var download = function(uri, filename, callback){ request.head(uri, function(err, res, body){ console.log('content-type:', res.headers['content-type']); console.log('content-length:', res.headers['content-length']); request(uri).pipe(fs.createWriteStream(filename)).on('close', callback); }); }; download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){ console.log('done'); }); </code></pre>
{ "question_id": 12740659, "question_date": "2012-10-05T06:25:00.947Z", "question_score": 220, "tags": "node.js|image|download", "answer_id": 12751657, "answer_date": "2012-10-05T18:01:57.607Z", "answer_score": 462 }
Please answer the following Stack Overflow question: Title: Can dplyr package be used for conditional mutating? <p>Can the mutate be used when the mutation is conditional (depending on the values of certain column values)?</p> <p>This example helps showing what I mean.</p> <pre><code>structure(list(a = c(1, 3, 4, 6, 3, 2, 5, 1), b = c(1, 3, 4, 2, 6, 7, 2, 6), c = c(6, 3, 6, 5, 3, 6, 5, 3), d = c(6, 2, 4, 5, 3, 7, 2, 6), e = c(1, 2, 4, 5, 6, 7, 6, 3), f = c(2, 3, 4, 2, 2, 7, 5, 2)), .Names = c("a", "b", "c", "d", "e", "f"), row.names = c(NA, 8L), class = "data.frame") a b c d e f 1 1 1 6 6 1 2 2 3 3 3 2 2 3 3 4 4 6 4 4 4 4 6 2 5 5 5 2 5 3 6 3 3 6 2 6 2 7 6 7 7 7 7 5 2 5 2 6 5 8 1 6 3 6 3 2 </code></pre> <p>I was hoping to find a solution to my problem using the dplyr package (and yes I know this not code that should work, but I guess it makes the purpose clear) for creating a new column g:</p> <pre><code> library(dplyr) df &lt;- mutate(df, if (a == 2 | a == 5 | a == 7 | (a == 1 &amp; b == 4)){g = 2}, if (a == 0 | a == 1 | a == 4 | a == 3 | c == 4) {g = 3}) </code></pre> <p>The result of the code I am looking for should have this result in this particular example:</p> <pre><code> a b c d e f g 1 1 1 6 6 1 2 3 2 3 3 3 2 2 3 3 3 4 4 6 4 4 4 3 4 6 2 5 5 5 2 NA 5 3 6 3 3 6 2 NA 6 2 7 6 7 7 7 2 7 5 2 5 2 6 5 2 8 1 6 3 6 3 2 3 </code></pre> <p>Does anyone have an idea about how to do this in dplyr? This data frame is just an example, the data frames I am dealing with are much larger. Because of its speed I tried to use dplyr, but perhaps there are other, better ways to handle this problem?</p>
<p>Use <code>ifelse</code></p> <pre><code>df %&gt;% mutate(g = ifelse(a == 2 | a == 5 | a == 7 | (a == 1 &amp; b == 4), 2, ifelse(a == 0 | a == 1 | a == 4 | a == 3 | c == 4, 3, NA))) </code></pre> <p><strong>Added - if_else:</strong> Note that in dplyr 0.5 there is an <code>if_else</code> function defined so an alternative would be to replace <code>ifelse</code> with <code>if_else</code>; however, note that since <code>if_else</code> is stricter than <code>ifelse</code> (both legs of the condition must have the same type) so the <code>NA</code> in that case would have to be replaced with <code>NA_real_</code> .</p> <pre><code>df %&gt;% mutate(g = if_else(a == 2 | a == 5 | a == 7 | (a == 1 &amp; b == 4), 2, if_else(a == 0 | a == 1 | a == 4 | a == 3 | c == 4, 3, NA_real_))) </code></pre> <p><strong>Added - case_when</strong> Since this question was posted dplyr has added <code>case_when</code> so another alternative would be:</p> <pre><code>df %&gt;% mutate(g = case_when(a == 2 | a == 5 | a == 7 | (a == 1 &amp; b == 4) ~ 2, a == 0 | a == 1 | a == 4 | a == 3 | c == 4 ~ 3, TRUE ~ NA_real_)) </code></pre> <p><strong>Added - arithmetic/na_if</strong> If the values are numeric and the conditions (except for the default value of NA at the end) are mutually exclusive, as is the case in the question, then we can use an arithmetic expression such that each term is multiplied by the desired result using <code>na_if</code> at the end to replace 0 with NA.</p> <pre><code>df %&gt;% mutate(g = 2 * (a == 2 | a == 5 | a == 7 | (a == 1 &amp; b == 4)) + 3 * (a == 0 | a == 1 | a == 4 | a == 3 | c == 4), g = na_if(g, 0)) </code></pre>
{ "question_id": 24459752, "question_date": "2014-06-27T19:48:22.447Z", "question_score": 220, "tags": "r|if-statement|case-when|dplyr", "answer_id": 24459900, "answer_date": "2014-06-27T19:59:25.410Z", "answer_score": 276 }
Please answer the following Stack Overflow question: Title: How to return a value from a Form in C#? <p>I have a main form (let's call it frmHireQuote) that is a child of a main MDI form (frmMainMDI), that shows another form (frmImportContact) via ShowDialog() when a button is clicked.</p> <p>When the user clicks the 'OK' on frmImportContact, I want to pass a few string variables back to some text boxes on frmHireQuote.</p> <p>Note that there could be multiple instances of frmHireQuote, it's obviously important that I get back to the instance that called this instance of frmImportContact.</p> <p>What's the best method of doing this?</p>
<p>Create some public Properties on your <strong>sub-form</strong> like so </p> <pre><code>public string ReturnValue1 {get;set;} public string ReturnValue2 {get;set;} </code></pre> <p>then set this inside your <strong>sub-form</strong> ok button click handler</p> <pre><code>private void btnOk_Click(object sender,EventArgs e) { this.ReturnValue1 = "Something"; this.ReturnValue2 = DateTime.Now.ToString(); //example this.DialogResult = DialogResult.OK; this.Close(); } </code></pre> <p>Then in your <strong>frmHireQuote form</strong>, when you open the sub-form</p> <pre><code>using (var form = new frmImportContact()) { var result = form.ShowDialog(); if (result == DialogResult.OK) { string val = form.ReturnValue1; //values preserved after close string dateString = form.ReturnValue2; //Do something here with these values //for example this.txtSomething.Text = val; } } </code></pre> <p>Additionaly if you wish to cancel out of the <strong>sub-form</strong> you can just add a button to the form and set its <a href="http://msdn.microsoft.com/en-GB/library/system.windows.forms.button.dialogresult.aspx" rel="noreferrer">DialogResult</a> to <code>Cancel</code> and you can also set the <a href="http://msdn.microsoft.com/en-GB/library/system.windows.forms.form.cancelbutton%28v=vs.80%29.aspx" rel="noreferrer">CancelButton</a> property of the form to said button - this will enable the escape key to cancel out of the form.</p>
{ "question_id": 5233502, "question_date": "2011-03-08T14:03:46.330Z", "question_score": 220, "tags": "c#|.net|winforms|parameter-passing", "answer_id": 5233526, "answer_date": "2011-03-08T14:06:33.150Z", "answer_score": 442 }
Please answer the following Stack Overflow question: Title: In Chrome 55, prevent showing Download button for HTML 5 video <p>I am getting this download button with <code>&lt;video&gt;</code> tags in Chrome 55, but not on Chrome 54: <a href="https://i.stack.imgur.com/Ii1m2.png"><img src="https://i.stack.imgur.com/Ii1m2.png" alt="enter image description here"></a></p> <p>How can I remove this so no one can see the download button in Chrome 55?</p> <p>I have used <code>&lt;video&gt;</code> tag to embed this video on my web page. So, I want some kind of code to remove this download option.</p> <p>Here is my current code:</p> <pre><code>&lt;video width="512" height="380" controls&gt; &lt;source data-src="mov_bbb.ogg" type="video/mp4"&gt; &lt;/video&gt; </code></pre>
<p>This is the solution (from <a href="https://stackoverflow.com/questions/39602852/disable-download-button-for-google-chrome/40975859#40975859">this post</a>)</p> <pre><code>video::-internal-media-controls-download-button { display:none; } video::-webkit-media-controls-enclosure { overflow:hidden; } video::-webkit-media-controls-panel { width: calc(100% + 30px); /* Adjust as needed */ } </code></pre> <p>Update 2 : New Solution by @Remo</p> <pre><code>&lt;video width="512" height="380" controls controlsList="nodownload"&gt; &lt;source data-src="mov_bbb.ogg" type="video/mp4"&gt; &lt;/video&gt; </code></pre>
{ "question_id": 41115801, "question_date": "2016-12-13T07:38:27.123Z", "question_score": 220, "tags": "html|google-chrome|html5-video", "answer_id": 41136470, "answer_date": "2016-12-14T06:52:31.023Z", "answer_score": 199 }
Please answer the following Stack Overflow question: Title: Node.js create folder or use existing <p>I already have read the documentation of Node.js and, unless if I missed something, it does not tell what the parameters contain in certain operations, in particular <a href="http://nodejs.org/api/fs.html#fs_fs_mkdir_path_mode_callback" rel="noreferrer"><code>fs.mkdir()</code></a>. As you can see in the documentation, it's not very much.</p> <p>Currently, I have this code, which tries to create a folder or use an existing one instead:</p> <pre><code>fs.mkdir(path,function(e){ if(!e || (e &amp;&amp; e.code === 'EEXIST')){ //do something with contents } else { //debug console.log(e); } }); </code></pre> <p>But I wonder is this the right way to do it? Is checking for the code <code>EEXIST</code> the right way to know that the folder already exists? I know I can do <code>fs.stat()</code> before making the directory, but that would already be two hits to the filesystem.</p> <p>Secondly, is there a complete or at least a more detailed documentation of Node.js that contains details as to what error objects contain, what parameters signify etc.</p>
<p>Good way to do this is to use <a href="https://github.com/substack/node-mkdirp">mkdirp</a> module.</p> <pre><code>$ npm install mkdirp </code></pre> <p>Use it to run function that requires the directory. Callback is called after path is created or if path did already exists. Error <code>err</code> is set if mkdirp failed to create directory path.</p> <pre><code>var mkdirp = require('mkdirp'); mkdirp('/tmp/some/path/foo', function(err) { // path exists unless there was an error }); </code></pre>
{ "question_id": 13696148, "question_date": "2012-12-04T04:34:24.170Z", "question_score": 220, "tags": "javascript|node.js", "answer_id": 13696975, "answer_date": "2012-12-04T05:58:59.140Z", "answer_score": 244 }
Please answer the following Stack Overflow question: Title: Detect Safari browser <p>How to detect Safari browser using JavaScript? I have tried code below and it detects not only Safari but also Chrome browser.</p> <pre><code>function IsSafari() { var is_safari = navigator.userAgent.toLowerCase().indexOf('safari/') &gt; -1; return is_safari; } </code></pre>
<p>You can easily use index of Chrome to filter out Chrome:</p> <pre><code>var ua = navigator.userAgent.toLowerCase(); if (ua.indexOf('safari') != -1) { if (ua.indexOf('chrome') &gt; -1) { alert("1") // Chrome } else { alert("2") // Safari } } </code></pre>
{ "question_id": 7944460, "question_date": "2011-10-30T10:42:36.673Z", "question_score": 220, "tags": "javascript|browser-detection", "answer_id": 7944490, "answer_date": "2011-10-30T10:48:35.187Z", "answer_score": 124 }
Please answer the following Stack Overflow question: Title: Best lightweight web server (only static content) for Windows <p>I got application server running in Windows – IIS6.0 with Zend Server to execute PHP. I am looking for lightweight static content only web server on this same machine which will relive IIS form handling static content and increase performance.</p> <p>It need to be only static content web server – maximum small and maximum effective – lighttpd seems too big because allow to FastCGI.</p> <p>I am looking for: <b>Windows, static content only, fast, and lightweight</b>.</p> <p>I am using Windows Server 2003.</p>
<p>Have a look at <a href="https://github.com/cesanta/mongoose">mongoose</a>:</p> <ul> <li>single executable</li> <li>very small memory footprint</li> <li>allows multiple worker threads</li> <li>easy to install as service</li> <li>configurable with a configuration file if required</li> </ul>
{ "question_id": 5050851, "question_date": "2011-02-19T12:48:56.940Z", "question_score": 220, "tags": "windows|http|webserver|static-content", "answer_id": 5119307, "answer_date": "2011-02-25T15:50:05.503Z", "answer_score": 196 }
Please answer the following Stack Overflow question: Title: PHP 5.4 Call-time pass-by-reference - Easy fix available? <p>Is there any way to easily fix this issue or do I really need to rewrite all the legacy code?</p> <blockquote> <p>PHP Fatal error: Call-time pass-by-reference has been removed in ... on line 30</p> </blockquote> <p>This happens everywhere as variables are passed into functions as references throughout the code.</p>
<p>You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.</p> <p><a href="http://php.net/manual/language.references.pass.php" rel="noreferrer">From the documentation</a>:</p> <blockquote> <p><strong>There is no reference sign on a function call - only on function definitions.</strong> Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use <code>&amp;</code> in <code>foo(&amp;$a);</code>.</p> </blockquote> <p>For example, instead of using:</p> <pre><code>// Wrong way! myFunc(&amp;$arg); # Deprecated pass-by-reference argument function myFunc($arg) { } </code></pre> <p>Use:</p> <pre><code>// Right way! myFunc($var); # pass-by-value argument function myFunc(&amp;$arg) { } </code></pre>
{ "question_id": 8971261, "question_date": "2012-01-23T12:01:13.647Z", "question_score": 220, "tags": "php", "answer_id": 8971301, "answer_date": "2012-01-23T12:04:46.943Z", "answer_score": 352 }
Please answer the following Stack Overflow question: Title: How to split a dos path into its components in Python <p>I have a string variable which represents a dos path e.g:</p> <p><code>var = "d:\stuff\morestuff\furtherdown\THEFILE.txt"</code></p> <p>I want to split this string into:</p> <p><code>[ "d", "stuff", "morestuff", "furtherdown", "THEFILE.txt" ]</code></p> <p>I have tried using <code>split()</code> and <code>replace()</code> but they either only process the first backslash or they insert hex numbers into the string.</p> <p>I need to convert this string variable into a raw string somehow so that I can parse it.</p> <p>What's the best way to do this?</p> <p>I should also add that the contents of <code>var</code> i.e. the path that I'm trying to parse, is actually the return value of a command line query. It's not path data that I generate myself. Its stored in a file, and the command line tool is not going to escape the backslashes.</p>
<p>I've been bitten loads of times by people writing their own path fiddling functions and getting it wrong. Spaces, slashes, backslashes, colons -- the possibilities for confusion are not endless, but mistakes are easily made anyway. So I'm a stickler for the use of <code>os.path</code>, and recommend it on that basis.</p> <p>(However, the path to virtue is not the one most easily taken, and many people when finding this are tempted to take a slippery path straight to damnation. They won't realise until one day everything falls to pieces, and they -- or, more likely, somebody else -- has to work out why everything has gone wrong, and it turns out somebody made a filename that mixes slashes and backslashes -- and some person suggests that the answer is &quot;not to do that&quot;. Don't be any of these people. Except for the one who mixed up slashes and backslashes -- you could be them if you like.)</p> <p>You can get the drive and path+file like this:</p> <pre><code>drive, path_and_file = os.path.splitdrive(path) </code></pre> <p>Get the path and the file:</p> <pre><code>path, file = os.path.split(path_and_file) </code></pre> <p>Getting the individual folder names is not especially convenient, but it is the sort of honest middling discomfort that heightens the pleasure of later finding something that actually works well:</p> <pre><code>folders = [] while 1: path, folder = os.path.split(path) if folder != &quot;&quot;: folders.append(folder) elif path != &quot;&quot;: folders.append(path) break folders.reverse() </code></pre> <p>(This pops a <code>&quot;\&quot;</code> at the start of <code>folders</code> if the path was originally absolute. You could lose a bit of code if you didn't want that.)</p>
{ "question_id": 3167154, "question_date": "2010-07-02T15:41:56.960Z", "question_score": 220, "tags": "python", "answer_id": 3167684, "answer_date": "2010-07-02T17:01:24.577Z", "answer_score": 216 }
Please answer the following Stack Overflow question: Title: Using PUT method in HTML form <p>Can I use a PUT method in an HTML form to send data from the form to a server?</p>
<p>XHTML 1.x forms only support GET and POST. GET and POST are the only allowed values for the "method" attribute.</p>
{ "question_id": 8054165, "question_date": "2011-11-08T16:57:12.207Z", "question_score": 220, "tags": "html|forms|http", "answer_id": 8054251, "answer_date": "2011-11-08T17:04:05.700Z", "answer_score": 149 }
Please answer the following Stack Overflow question: Title: Check if Internet Connection Exists with jQuery? <p>How do you check if there is an internet connection using jQuery? That way I could have some conditionals saying &quot;use the google cached version of JQuery during production, use either that or a local version during development, depending on the internet connection&quot;.</p>
<p><strong>The best option for your specific case might be:</strong></p> <p>Right before your close <code>&lt;/body&gt;</code> tag:</p> <pre><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt;window.jQuery || document.write('&lt;script src="js/vendor/jquery-1.10.2.min.js"&gt;&lt;\/script&gt;')&lt;/script&gt; </code></pre> <p>This is probably the easiest way given that your issue is centered around jQuery.</p> <p><strong>If you wanted a more robust solution you could try:</strong></p> <pre><code>var online = navigator.onLine; </code></pre> <p>Read more about the <a href="http://www.w3.org/TR/offline-webapps/" rel="noreferrer">W3C's spec on offline web apps</a>, however be aware that this will work best in modern web browsers, doing so with older web browsers may not work as expected, or at all.</p> <p>Alternatively, an XHR request to your own server isn't that bad of a method for testing your connectivity. Considering one of the other answers state that there are too many points of failure for an XHR, if your XHR is flawed when establishing it's connection then it'll also be flawed during routine use anyhow. If your site is unreachable for any reason, then your other services running on the same servers will likely be unreachable also. That decision is up to you.</p> <p>I wouldn't recommend making an XHR request to someone else's service, even google.com for that matter. Make the request to your server, or not at all.</p> <h2>What does it mean to be "online"?</h2> <p>There seems to be some confusion around what being "online" means. Consider that the internet is a bunch of networks, however sometimes you're on a VPN, without access to the internet "at-large" or the world wide web. Often companies have their own networks which have limited connectivity to other external networks, therefore you could be considered "online". Being online only entails that you are connected to <em>a</em> network, not the availability nor reachability of the services you are trying to connect to.</p> <p>To determine if a host is reachable from your network, you could do this:</p> <pre><code>function hostReachable() { // Handle IE and more capable browsers var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" ); // Open new request as a HEAD to the root hostname with a random param to bust the cache xhr.open( "HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false ); // Issue request and handle response try { xhr.send(); return ( xhr.status &gt;= 200 &amp;&amp; (xhr.status &lt; 300 || xhr.status === 304) ); } catch (error) { return false; } } </code></pre> <p>You can also find the Gist for that here: <a href="https://gist.github.com/jpsilvashy/5725579" rel="noreferrer">https://gist.github.com/jpsilvashy/5725579</a></p> <p><strong>Details on local implementation</strong></p> <p>Some people have commented, "I'm always being returned false". That's because you're probably testing it out on your local server. Whatever server you're making the request to, you'll need to be able to respond to the HEAD request, that of course can be changed to a GET if you want.</p>
{ "question_id": 2384167, "question_date": "2010-03-05T02:23:21.797Z", "question_score": 220, "tags": "jquery|browser|offline|internet-connection", "answer_id": 2384227, "answer_date": "2010-03-05T02:40:43.890Z", "answer_score": 270 }
Please answer the following Stack Overflow question: Title: AngularJS : Factory and Service? <p><strong>EDIT Jan 2016:</strong> Since this still gets attention. Since asking this I've completed a few AngularJS projects, and for those I mostly used <code>factory</code>, built up an object and returned the object at the end. My statements below are still true, however.</p> <p><strong>EDIT :</strong> I think I finally understand the main difference between the two, and I have a code example to demonstrate. I also think this question is different to the proposed duplicate. The duplicate says that service is not instantiable, but if you set it up as I demonstrated below, it actually is. A service can be set up to be exactly the same as a factory. I will also provide code that shows where factory fails over service, which no other answer seems to do.</p> <p>If I set up VaderService like so (ie as a service):</p> <pre><code>var module = angular.module('MyApp.services', []); module.service('VaderService', function() { this.speak = function (name) { return 'Join the dark side ' + name; } }); </code></pre> <p>Then in my controller I can do this:</p> <pre><code>module.controller('StarWarsController', function($scope, VaderService) { $scope.luke = VaderService.speak('luke'); }); </code></pre> <p>With service, the VaderService injected in to the controller is instantiated, so I can just call VaderService.speak, however, if I change the VaderService to module.factory, <em>the code in the controller will no longer work</em>, and this is the main difference. With factory, the VaderService injected in to the controller is <em>not</em> instantiated, which is why you need to return an object when setting up a factory (see my example in the question).</p> <p>However, you can set up a service in the exact same way as you can set up a factory (IE have it return an object) and <strong>the service behaves the exact same as a factory</strong></p> <p>Given this information, I see <em>no</em> reason to use factory over service, service can do everything factory can and more.</p> <p>Original question below.</p> <hr> <p>I know this has been asked loads of times, but I really cannot see any functional difference between factories and services. I had read this tutorial: <a href="http://blogs.clevertech.biz/startupblog/angularjs-factory-service-provider">http://blogs.clevertech.biz/startupblog/angularjs-factory-service-provider</a></p> <p>And it seems to give a reasonably good explanation, however, I set up my app as follows:</p> <p>index.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;My App&lt;/title&gt; &lt;script src="lib/angular/angular.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/controllers.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/VaderService.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/app.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body ng-app="MyApp"&gt; &lt;table ng-controller="StarWarsController"&gt; &lt;tbody&gt; &lt;tr&gt;&lt;td&gt;{{luke}}&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>app.js:</p> <pre><code>angular.module('MyApp', [ 'MyApp.services', 'MyApp.controllers' ]); </code></pre> <p>controllers.js:</p> <pre><code>var module = angular.module('MyApp.controllers', []); module.controller('StarWarsController', function($scope, VaderService) { var luke = new VaderService('luke'); $scope.luke = luke.speak(); }); </code></pre> <p>VaderService.js</p> <pre><code>var module = angular.module('MyApp.services', []); module.factory('VaderService', function() { var VaderClass = function(padawan) { this.name = padawan; this.speak = function () { return 'Join the dark side ' + this.name; } } return VaderClass; }); </code></pre> <p>Then when I load up index.html I see "Join the dark side luke", great. Exactly as expected. However if I change VaderService.js to this (note module.service instead of module.factory):</p> <pre><code>var module = angular.module('MyApp.services', []); module.service('VaderService', function() { var VaderClass = function(padawan) { this.name = padawan; this.speak = function () { return 'Join the dark side ' + this.name; } } return VaderClass; }); </code></pre> <p>Then reload index.html (I made sure I emptied the cache and did a hard reload). It works <em>exactly</em> the same as it did with module.factory. So what is the real functional difference between the two??</p>
<h2><strong>Service</strong> vs <strong>Factory</strong></h2> <hr> <p><img src="https://i.stack.imgur.com/uLDiv.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/OeWFT.png" alt="enter image description here"></p> <p>The difference between factory and service is just like the difference between a function and an object</p> <p><strong>Factory Provider</strong></p> <ul> <li><p>Gives us the function's return value ie. You just create an object, add properties to it, then return that same object.When you pass this service into your controller, those properties on the object will now be available in that controller through your factory. (Hypothetical Scenario)</p></li> <li><p>Singleton and will only be created once </p></li> <li><p>Reusable components</p></li> <li><p>Factory are a great way for communicating between controllers like sharing data.</p></li> <li><p>Can use other dependencies</p></li> <li><p>Usually used when the service instance requires complex creation logic</p></li> <li><p>Cannot be injected in <code>.config()</code> function. </p></li> <li><p>Used for non configurable services</p></li> <li><p>If you're using an object, you could use the factory provider. </p></li> <li><p>Syntax: <code>module.factory('factoryName', function);</code></p></li> </ul> <p><strong>Service Provider</strong></p> <ul> <li><p>Gives us the instance of a function (object)- You just instantiated with the ‘new’ keyword and you’ll add properties to ‘this’ and the service will return ‘this’.When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service. (Hypothetical Scenario)</p></li> <li><p>Singleton and will only be created once </p></li> <li><p>Reusable components</p></li> <li><p>Services are used for communication between controllers to share data</p></li> <li><p>You can add properties and functions to a service object by using the <code>this</code> keyword</p></li> <li><p>Dependencies are injected as constructor arguments</p></li> <li><p>Used for simple creation logic</p></li> <li><p>Cannot be injected in <code>.config()</code> function. </p></li> <li><p>If you're using a class you could use the service provider</p></li> <li><p>Syntax: <code>module.service(‘serviceName’, function);</code></p></li> </ul> <p><strong><a href="http://jsfiddle.net/k3phygpz/" rel="noreferrer">Sample Demo</a></strong> </p> <p>In below example I have define <code>MyService</code> and <code>MyFactory</code>. Note how in <code>.service</code> I have created the service methods using <code>this.methodname.</code> In <code>.factory</code> I have created a factory object and assigned the methods to it.</p> <p><strong>AngularJS .service</strong></p> <hr> <pre><code>module.service('MyService', function() { this.method1 = function() { //..method1 logic } this.method2 = function() { //..method2 logic } }); </code></pre> <p><strong>AngularJS .factory</strong></p> <hr> <pre><code>module.factory('MyFactory', function() { var factory = {}; factory.method1 = function() { //..method1 logic } factory.method2 = function() { //..method2 logic } return factory; }); </code></pre> <hr> <p>Also Take a look at this beautiful stuffs</p> <p><strong><a href="https://stackoverflow.com/questions/13762228/confused-about-service-vs-factory">Confused about service vs factory</a></strong></p> <p><a href="http://blogs.clevertech.biz/startupblog/angularjs-factory-service-provider" rel="noreferrer"><strong>AngularJS Factory, Service and Provider</strong></a></p> <p><a href="https://stackoverflow.com/questions/15666048/angular-js-service-vs-provider-vs-factory"><strong>Angular.js: service vs provider vs factory?</strong></a></p>
{ "question_id": 23074875, "question_date": "2014-04-15T04:47:07.127Z", "question_score": 220, "tags": "javascript|angularjs|angularjs-service|angularjs-factory", "answer_id": 23076054, "answer_date": "2014-04-15T06:24:53.597Z", "answer_score": 301 }
Please answer the following Stack Overflow question: Title: python: Change the scripts working directory to the script's own directory <p>I run a python shell from crontab every minute:</p> <pre><code>* * * * * /home/udi/foo/bar.py </code></pre> <p><code>/home/udi/foo</code> has some necessary subdirectories, like <code>/home/udi/foo/log</code> and <code>/home/udi/foo/config</code>, which <code>/home/udi/foo/bar.py</code> refers to.</p> <p>The problem is that <code>crontab</code> runs the script from a different working directory, so trying to open <code>./log/bar.log</code> fails.</p> <p>Is there a nice way to tell the script to change the working directory to the script's own directory? I would fancy a solution that would work for any script location, rather than explicitly telling the script where it is.</p> <p><strong>EDIT:</strong></p> <pre><code>os.chdir(os.path.dirname(sys.argv[0])) </code></pre> <p>Was the most compact elegant solution. Thanks for your answers and explanations!</p>
<p>This will change your current working directory to so that opening relative paths will work:</p> <pre><code>import os os.chdir("/home/udi/foo") </code></pre> <p>However, you asked how to change into whatever directory your Python script is located, even if you don't know what directory that will be when you're writing your script. To do this, you can use the <code>os.path</code> functions:</p> <pre><code>import os abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) </code></pre> <p>This takes the filename of your script, converts it to an absolute path, then extracts the directory of that path, then changes into that directory.</p>
{ "question_id": 1432924, "question_date": "2009-09-16T13:21:51.827Z", "question_score": 220, "tags": "python|working-directory", "answer_id": 1432949, "answer_date": "2009-09-16T13:26:24.527Z", "answer_score": 268 }
Please answer the following Stack Overflow question: Title: Negate if condition in bash script <p>I'm new to bash and I'm stuck at trying to negate the following command:</p> <pre><code>wget -q --tries=10 --timeout=20 --spider http://google.com if [[ $? -eq 0 ]]; then echo "Sorry you are Offline" exit 1 </code></pre> <p>This if condition returns true if I'm connected to the internet. I want it to happen the other way around but putting <code>!</code> anywhere doesn't seem to work.</p>
<p>You can choose:</p> <pre><code>if [[ $? -ne 0 ]]; then # -ne: not equal if ! [[ $? -eq 0 ]]; then # -eq: equal if [[ ! $? -eq 0 ]]; then </code></pre> <p><code>!</code> inverts the return of the following expression, respectively.</p>
{ "question_id": 26475358, "question_date": "2014-10-20T21:36:36.317Z", "question_score": 220, "tags": "linux|bash|if-statement|negate", "answer_id": 26475397, "answer_date": "2014-10-20T21:39:33.367Z", "answer_score": 303 }
Please answer the following Stack Overflow question: Title: How to remove/ignore :hover css style on touch devices <p>I want to ignore all <code>:hover</code> CSS declarations if a user visits our website via touch device. Because the <code>:hover</code> CSS does not make sense, and it can even be disturbing if a tablet triggers it on click/tap because then it might stick until the element loses focus. To be honest, I don't know why touch devices feel the need to trigger <code>:hover</code> in first place - but this is reality, so this problem is reality as well.</p> <pre class="lang-css prettyprint-override"><code>a:hover { color:blue; border-color:green; /* etc. &gt; ignore all at once for touch devices */ } </code></pre> <p><strong>So, (how) can I remove/ignore all CSS <code>:hover</code> declarations at once (without having to know each one) for touch devices after having them declared?</strong></p>
<p><strong>2020 Solution - CSS only - No Javascript</strong></p> <p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/hover" rel="noreferrer">media hover</a> with <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/pointer" rel="noreferrer">media pointer</a> will help you resolve this issue. Tested on chrome Web and android mobile. I known this old question but I didn't find any solution like this.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>@media (hover: hover) and (pointer: fine) { a:hover { color: red; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;a href="#" &gt;Some Link&lt;/a&gt;</code></pre> </div> </div> </p>
{ "question_id": 23885255, "question_date": "2014-05-27T09:06:00.087Z", "question_score": 220, "tags": "html|css|hover|touch", "answer_id": 64553121, "answer_date": "2020-10-27T11:07:30.380Z", "answer_score": 107 }
Please answer the following Stack Overflow question: Title: Capitalize words in string <p>What is the best approach to capitalize words in a string?</p>
<p>The shortest implementation for capitalizing words within a string is the following using ES6's arrow functions: </p> <pre><code>'your string'.replace(/\b\w/g, l =&gt; l.toUpperCase()) // =&gt; 'Your String' </code></pre> <p>ES5 compatible implementation:</p> <pre><code>'your string'.replace(/\b\w/g, function(l){ return l.toUpperCase() }) // =&gt; 'Your String' </code></pre> <p>The regex basically matches the first letter of each word within the given string and transforms only that letter to uppercase:</p> <ul> <li><a href="http://www.w3schools.com/jsref/jsref_regexp_begin.asp" rel="noreferrer">\b</a> matches a word boundary (the beginning or ending of word);</li> <li><a href="http://www.w3schools.com/jsref/jsref_regexp_wordchar.asp" rel="noreferrer">\w</a> matches the following meta-character [a-zA-Z0-9].</li> </ul> <h3>For non-ASCII characters refer to this solution instead</h3> <pre><code>'ÿöur striñg'.replace(/(^|\s)\S/g, l =&gt; l.toUpperCase()) </code></pre> <p>This regex matches the first letter and every non-whitespace letter preceded by whitespace within the given string and transforms only that letter to uppercase:</p> <ul> <li><a href="https://www.w3schools.com/jsref/jsref_regexp_whitespace.asp" rel="noreferrer">\s</a> matches a whitespace character</li> <li><a href="https://www.w3schools.com/jsref/jsref_regexp_whitespace_non.asp" rel="noreferrer">\S</a> matches a non-whitespace character</li> <li><a href="https://www.w3schools.com/jsref/jsref_regexp_xy.asp" rel="noreferrer">(x|y)</a> matches any of the specified alternatives</li> </ul> <p>A non-capturing group could have been used here as follows <code>/(?:^|\s)\S/g</code> though the <code>g</code> flag within our regex wont capture sub-groups by design anyway.</p> <p>Cheers!</p>
{ "question_id": 2332811, "question_date": "2010-02-25T09:12:13.967Z", "question_score": 220, "tags": "javascript|string|capitalization", "answer_id": 38530325, "answer_date": "2016-07-22T15:31:12.810Z", "answer_score": 264 }
Please answer the following Stack Overflow question: Title: How do I check if a number is positive or negative in C#? <p>How do I check if a number is positive or negative in C#?</p>
<pre><code>bool positive = number &gt; 0; bool negative = number &lt; 0; </code></pre>
{ "question_id": 4099366, "question_date": "2010-11-04T17:23:49.877Z", "question_score": 220, "tags": "c#", "answer_id": 4099384, "answer_date": "2010-11-04T17:25:23.960Z", "answer_score": 237 }
Please answer the following Stack Overflow question: Title: Removing all non-numeric characters from string in Python <p>How do we remove all non-numeric characters from a string in Python?</p>
<pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.sub("[^0-9]", "", "sdkjh987978asd098as0980a98sd") '987978098098098' </code></pre>
{ "question_id": 1249388, "question_date": "2009-08-08T17:13:01.100Z", "question_score": 220, "tags": "python|numbers", "answer_id": 1249424, "answer_date": "2009-08-08T17:25:21.327Z", "answer_score": 371 }
Please answer the following Stack Overflow question: Title: how to customize `show processlist` in mysql? <p>I want to order by Time,but seems no way to do that ?</p> <pre><code>mysql&gt; show processlist; +--------+-------------+--------------------+------+---------+--------+----------------------------------+------------------------------------------------------------------------------------------------------+ | Id | User | Host | db | Command | Time | State | Info | +--------+-------------+--------------------+------+---------+--------+----------------------------------+------------------------------------------------------------------------------------------------------+ | 1 | system user | | NULL | Connect | 226953 | Waiting for master to send event | NULL | | 2 | system user | | v3 | Connect | 35042 | Locked | update postings a left join cities b on b.id=a.job_city_id left join states h on h.id=b.stat | | 313888 | irnadmin | 172.19.0.239:40136 | v3 | Sleep | 0 | | NULL | | 314075 | irnadmin | 172.19.0.239:41113 | v3 | Sleep | 0 | | NULL | | 314118 | irnadmin | 172.19.0.239:41282 | v3 | Query | 34978 | freeing items | SELECT id, screen_name, type, active, bound, LastLogin, robotno, protocol FROM accounts WHERE email_ | | 314686 | irnadmin | 172.19.0.239:43251 | v3 | Sleep | 0 | | NULL | | 314732 | irnadmin | 172.19.0.239:43436 | v3 | Query | 34978 | freeing items | SELECT id, screen_name, type, active, bound, LastLogin, robotno, protocol FROM accounts WHERE email_ | | 314984 | irnadmin | 172.19.0.239:44366 | v3 | Sleep | 2 | | NULL | | 315051 | irnadmin | 172.19.0.239:44713 | v3 | Query | 0 | NULL | NULL | | 315198 | irnadmin | 172.19.0.239:51569 | v3 | Sleep | 2 | | NULL | | 315280 | irnadmin | 172.19.0.239:51849 | v3 | Query | 34978 | freeing items | SELECT id, email_address, type, closed, robotno FROM accounts WHERE screen_name = 'ShantanuS' | | 315320 | irnadmin | 172.19.0.239:52045 | v3 | Query | 34978 | freeing items | SELECT id, screen_name, type, active, bound, LastLogin, robotno, protocol FROM accounts WHERE email_ | | 315384 | irnadmin | 172.19.0.239:52463 | v3 | Sleep | 1 | | NULL | | 452248 | irnadmin | 172.19.0.28:54899 | v3 | Query | 34978 | freeing items | SELECT id, email_address, type, closed, robotno FROM accounts WHERE screen_name = 'LIZW0218' | | 452291 | irnadmin | 172.19.0.28:55045 | v3 | Sleep | 1 | | NULL | | 452316 | irnadmin | 172.19.0.28:55144 | v3 | Sleep | 0 | | NULL | | 452353 | irnadmin | 172.19.0.28:55278 | v3 | Sleep | 0 | | NULL | | 452382 | irnadmin | 172.19.0.28:55371 | v3 | Query | 34978 | freeing items | SELECT o.account_id FROM online o JOIN accounts a ON a.id=o.account_id WHERE o.server_id IS NULL AND | | 452413 | irnadmin | 172.19.0.28:55479 | v3 | Sleep | 1 | | NULL | | 452541 | irnadmin | 172.19.0.28:55946 | v3 | Query | 34978 | freeing items | SELECT o.account_id FROM online o JOIN accounts a ON a.id=o.account_id WHERE o.server_id IS NULL AND | | 452626 | irnadmin | 172.19.0.28:56215 | v3 | Sleep | 2 | | NULL | | 452711 | irnadmin | 172.19.0.28:39916 | v3 | Sleep | 0 | | NULL | | 452781 | irnadmin | 172.19.0.28:40161 | v3 | Sleep | 1 | | NULL | | 452904 | irnadmin | 172.19.0.28:40955 | v3 | Query | 34978 | freeing items | select a.id, aa.screen_name, i.requester from interview_requests i left join accounts aa on aa.id=i. | | 453014 | irnadmin | 172.19.0.28:41291 | v3 | Query | 34978 | freeing items | SELECT o.account_id FROM online o JOIN accounts a ON a.id=o.account_id WHERE o.server_id IS NULL AND | | 453057 | irnadmin | 172.19.0.28:41377 | v3 | Query | 34978 | freeing items | select a.id, aa.screen_name, i.requester from interview_requests i left join accounts aa on aa.id=i. | | 453084 | irnadmin | 172.19.0.28:41441 | v3 | Sleep | 0 | | NULL | | 453112 | irnadmin | 172.19.0.28:41536 | v3 | Sleep | 0 | | NULL | | 453156 | irnadmin | 172.19.0.28:41653 | v3 | Query | 34978 | freeing items | SELECT protocol FROM accounts WHERE email_address= '***@gtalk.jabber.jobirn.c | | 453214 | irnadmin | 172.19.0.28:41800 | v3 | Sleep | 5 | | NULL | | 453243 | irnadmin | 172.19.0.28:41991 | v3 | Sleep | 0 | | NULL | | 453313 | irnadmin | 172.19.0.28:42255 | v3 | Query | 34978 | freeing items | SELECT o.account_id FROM online o JOIN accounts a ON a.id=o.account_id WHERE o.server_id IS NULL AND | | 453396 | irnadmin | 172.19.0.28:53718 | v3 | Sleep | 2 | | NULL | | 453476 | irnadmin | 172.19.0.28:54019 | v3 | Sleep | 0 | | NULL | | 453561 | irnadmin | 172.19.0.28:54352 | v3 | Sleep | 3 | | NULL | | 453594 | irnadmin | 172.19.0.28:54456 | v3 | Sleep | 0 | | NULL | | 453727 | irnadmin | 172.19.0.28:55166 | v3 | Query | 34978 | freeing items | SELECT id, screen_name, type, active, bound, LastLogin, robotno, protocol FROM accounts WHERE email_ | | 453786 | irnadmin | 172.19.0.28:55320 | v3 | Sleep | 4 | | NULL | | 610140 | irnadmin | 172.19.0.28:33848 | v3 | Query | 34978 | freeing items | select a.id, aa.screen_name, i.requester from interview_requests i left join accounts aa on aa.id=i. | | 685119 | irnadmin | 172.19.0.27:37251 | v3 | Query | 34980 | Sending data | select postings.id id,category, job_desc_title, IF(c1.name is not null,c1.name,IF(c2.name is not n | | 685226 | irnadmin | 172.19.0.139:57274 | v3 | Query | 34735 | Locked | SELECT job_desc_title,job_desc,job_state_name,job_city_name,company_categories.name,postings.categor | | 685229 | irnadmin | 172.19.0.139:57278 | v3 | Query | 34735 | Locked | SELECT job_desc_title,job_desc,job_state_name,job_city_name,company_categories.name,postings.categor | | 685232 | irnadmin | 172.19.0.139:57283 | v3 | Query | 34734 | Locked | select job_desc_title,job_desc from postings where id=287650 | | 685233 | irnadmin | 172.19.0.139:57286 | v3 | Query | 34734 | Locked | SELECT accounts.screen_name,postings.url url, accounts.type owner_type, postings.id ID, postings.job | | 685235 | irnadmin | 172.19.0.28:37502 | v3 | Query | 34734 | Locked | SELECT accounts.screen_name,postings.url url, accounts.type owner_type, postings.id ID, postings.job | | 686496 | irnadmin | 172.19.0.239:33306 | v3 | Query | 32589 | Locked | SELECT accounts.screen_name,postings.url url, accounts.type owner_type, postings.id ID, postings.job | | 686503 | irnadmin | 172.19.0.28:54051 | v3 | Query | 32588 | Locked | SELECT job_desc_title, job_desc, IF(postings.category IS NOT NULL, postings.category, job_categories | | 709550 | root | localhost | v3 | Query | 0 | NULL | show processlist | | 710084 | irnadmin | 172.19.0.27:53285 | NULL | Query | 0 | removing tmp table | show status where Variable_name='Threads_running' | +--------+-------------+--------------------+------+---------+--------+----------------------------------+------------------------------------------------------------------------------------------------------+ 49 rows in set (0.00 sec) </code></pre>
<p>Newer versions of SQL support the process list in information_schema:</p> <pre><code>SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST </code></pre> <p>You can ORDER BY in any way you like. </p> <p>The INFORMATION_SCHEMA.PROCESSLIST table was added in MySQL 5.1.7. You can find out which version you're using with:</p> <pre><code>SELECT VERSION() </code></pre>
{ "question_id": 929612, "question_date": "2009-05-30T11:53:17.753Z", "question_score": 220, "tags": "mysql|filter|sql-order-by|processlist", "answer_id": 929642, "answer_date": "2009-05-30T12:09:46.240Z", "answer_score": 395 }
Please answer the following Stack Overflow question: Title: "Insert if not exists" statement in SQLite <p>I have an SQLite database. I am trying to insert values (<code>users_id</code>, <code>lessoninfo_id</code>) in table <code>bookmarks</code>, only if both do not exist before in a row.</p> <pre><code>INSERT INTO bookmarks(users_id,lessoninfo_id) VALUES( (SELECT _id FROM Users WHERE User='"+$('#user_lesson').html()+"'), (SELECT _id FROM lessoninfo WHERE Lesson="+lesson_no+" AND cast(starttime AS int)="+Math.floor(result_set.rows.item(markerCount-1).starttime)+") WHERE NOT EXISTS ( SELECT users_id,lessoninfo_id from bookmarks WHERE users_id=(SELECT _id FROM Users WHERE User='"+$('#user_lesson').html()+"') AND lessoninfo_id=( SELECT _id FROM lessoninfo WHERE Lesson="+lesson_no+"))) </code></pre> <p>This gives an error saying:</p> <blockquote> <p>db error near where syntax.</p> </blockquote>
<p>If you have a table called memos that has two columns <code>id</code> and <code>text</code> you should be able to do like this:</p> <pre><code>INSERT INTO memos(id,text) SELECT 5, 'text to insert' WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert'); </code></pre> <p>If a record already contains a row where <code>text</code> is equal to 'text to insert' and <code>id</code> is equal to 5, then the insert operation will be ignored.</p> <p>I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.</p> <p>I would advice that you instead design your table so that no duplicates are allowed as explained in <a href="https://stackoverflow.com/a/19343100/1047662"><code>@CLs answer</code></a> below.</p>
{ "question_id": 19337029, "question_date": "2013-10-12T17:19:53.310Z", "question_score": 220, "tags": "sqlite|constraints|sql-insert", "answer_id": 19337206, "answer_date": "2013-10-12T17:38:06.723Z", "answer_score": 208 }
Please answer the following Stack Overflow question: Title: Basic authentication with fetch? <p>I want to write a simple basic authentication with fetch, but I keep getting a 401 error. It would be awesome if someone tells me what's wrong with the code:</p> <pre><code>let base64 = require('base-64'); let url = 'http://eu.httpbin.org/basic-auth/user/passwd'; let username = 'user'; let password = 'passwd'; let headers = new Headers(); //headers.append('Content-Type', 'text/json'); headers.append('Authorization', 'Basic' + base64.encode(username + &quot;:&quot; + password)); fetch(url, {method:'GET', headers: headers, //credentials: 'user:passwd' }) .then(response =&gt; response.json()) .then(json =&gt; console.log(json)); //.done(); </code></pre>
<p>You are missing a space between <code>Basic</code> and the encoded username and password. </p> <pre><code>headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password)); </code></pre>
{ "question_id": 43842793, "question_date": "2017-05-08T08:14:04.870Z", "question_score": 220, "tags": "javascript|fetch-api", "answer_id": 43843163, "answer_date": "2017-05-08T08:36:43.023Z", "answer_score": 198 }
Please answer the following Stack Overflow question: Title: Save the console.log in Chrome to a file <p>Does anyone know of a way to save the console.log output in Chrome to a file? Or how to copy the text out of the console?</p> <p>Say you are running a few hours of functional tests and you've got thousands of lines of console.log output in Chrome. How do you save it or export it?</p>
<p>I needed to do the same thing and this is the solution I found:</p> <ol> <li><p>Enable <a href="https://chromium.googlesource.com/chromium/src/+/refs/heads/main/docs/user_data_dir.md" rel="noreferrer">logging</a> from the command line using the flags:</p> <p><code>--enable-logging --v=1</code></p> </li> </ol> <p>This logs everything Chrome does internally, but it also logs all the <code>console.log()</code> messages as well. The log file is called <strong><code>chrome_debug.log</code></strong> and is located in the <code>User Data Directory</code> which can be overridden by supplying <code>--user-data-dir=PATH</code> (<a href="http://dev.chromium.org/user-experience/user-data-directory" rel="noreferrer">more info here</a>).</p> <ol start="2"> <li>Filter the log file you get for lines with <code>CONSOLE(\d+)</code>.</li> </ol> <p>Note that console logs do not appear with <code>--incognito</code>.</p>
{ "question_id": 7627113, "question_date": "2011-10-02T15:02:29.643Z", "question_score": 220, "tags": "google-chrome|console|logging", "answer_id": 10068090, "answer_date": "2012-04-09T01:43:32.350Z", "answer_score": 119 }
Please answer the following Stack Overflow question: Title: Setting environment variable in react-native? <p>I am using react-native to build a cross-platform app, but I do not know how to set the environment variable so that I can have different constants for different environments.</p> <p>Example:</p> <pre><code>development: BASE_URL: '', API_KEY: '', staging: BASE_URL: '', API_KEY: '', production: BASE_URL: '', API_KEY: '', </code></pre>
<p>Instead of hard-coding your app constants and doing a switch on the environment (I'll explain how to do that in a moment), I suggest using the <a href="http://12factor.net/config" rel="noreferrer">twelve factor</a> suggestion of having your build process define your <code>BASE_URL</code> and your <code>API_KEY</code>.</p> <p>To answer how to expose your environment to <code>react-native</code>, I suggest using Babel's <a href="https://www.npmjs.com/package/babel-plugin-transform-inline-environment-variables" rel="noreferrer">babel-plugin-transform-inline-environment-variables</a>.</p> <p>To get this working you need to download the plugin and then you will need to setup a <code>.babelrc</code> and it should look something like this:</p> <pre><code>{ &quot;presets&quot;: [&quot;react-native&quot;], &quot;plugins&quot;: [ &quot;transform-inline-environment-variables&quot; ] } </code></pre> <p>And so if you transpile your react-native code by running <code>API_KEY=my-app-id react-native bundle</code> (or start, run-ios, or run-android) then all you have to do is have your code look like this:</p> <pre><code>const apiKey = process.env['API_KEY']; </code></pre> <p>And then Babel will replace that with:</p> <pre><code>const apiKey = 'my-app-id'; </code></pre>
{ "question_id": 33117227, "question_date": "2015-10-14T05:26:38.530Z", "question_score": 220, "tags": "react-native|environment-variables", "answer_id": 37823398, "answer_date": "2016-06-14T22:52:23.837Z", "answer_score": 183 }
Please answer the following Stack Overflow question: Title: Differences between "BEGIN RSA PRIVATE KEY" and "BEGIN PRIVATE KEY" <p>Hi I was writing a program that imports private keys from a <code>.pem</code> file and create a private key object to use it later.. the problem I have faced is that some <code>pem</code> files header begin with </p> <pre><code>-----BEGIN PRIVATE KEY----- </code></pre> <p>while others begin with</p> <pre><code>-----BEGIN RSA PRIVATE KEY----- </code></pre> <p>through my search I knew that the first ones are <code>PKCS#8</code> formatted but I couldn't know what format does the other one belongs to.</p>
<p>See <a href="https://polarssl.org/kb/cryptography/asn1-key-structures-in-der-and-pem" rel="noreferrer">https://polarssl.org/kb/cryptography/asn1-key-structures-in-der-and-pem</a> (search the page for &quot;BEGIN RSA PRIVATE KEY&quot;) (<a href="https://web.archive.org/web/20140819203300/https://polarssl.org/kb/cryptography/asn1-key-structures-in-der-and-pem" rel="noreferrer">archive link</a> for posterity, just in case).</p> <p><code>BEGIN RSA PRIVATE KEY</code> is PKCS#1 and is just an RSA key. It is essentially just the key object from PKCS#8, but without the version or algorithm identifier in front. <code>BEGIN PRIVATE KEY</code> is PKCS#8 and indicates that the key type is included in the key data itself. From the link:</p> <blockquote> <p>The unencrypted PKCS#8 encoded data starts and ends with the tags:</p> <pre><code>-----BEGIN PRIVATE KEY----- BASE64 ENCODED DATA -----END PRIVATE KEY----- </code></pre> <p>Within the base64 encoded data the following DER structure is present:</p> <pre><code>PrivateKeyInfo ::= SEQUENCE { version Version, algorithm AlgorithmIdentifier, PrivateKey BIT STRING } AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters ANY DEFINED BY algorithm OPTIONAL } </code></pre> <p>So for an RSA private key, the OID is 1.2.840.113549.1.1.1 and there is a RSAPrivateKey as the PrivateKey key data bitstring.</p> </blockquote> <p>As opposed to <code>BEGIN RSA PRIVATE KEY</code>, which always specifies an RSA key and therefore doesn't include a key type OID. <code>BEGIN RSA PRIVATE KEY</code> is <code>PKCS#1</code>:</p> <blockquote> <p>RSA Private Key file <a href="https://www.rfc-editor.org/rfc/rfc3447#appendix-A.1.2" rel="noreferrer">(PKCS#1)</a></p> <p>The RSA private key PEM file is specific for RSA keys.</p> <p>It starts and ends with the tags:</p> <pre><code>-----BEGIN RSA PRIVATE KEY----- BASE64 ENCODED DATA -----END RSA PRIVATE KEY----- </code></pre> <p>Within the base64 encoded data the following DER structure is present:</p> <pre><code>RSAPrivateKey ::= SEQUENCE { version Version, modulus INTEGER, -- n publicExponent INTEGER, -- e privateExponent INTEGER, -- d prime1 INTEGER, -- p prime2 INTEGER, -- q exponent1 INTEGER, -- d mod (p-1) exponent2 INTEGER, -- d mod (q-1) coefficient INTEGER, -- (inverse of q) mod p otherPrimeInfos OtherPrimeInfos OPTIONAL } </code></pre> </blockquote>
{ "question_id": 20065304, "question_date": "2013-11-19T07:08:02.110Z", "question_score": 220, "tags": "openssl|rsa|private-key|pem", "answer_id": 20065522, "answer_date": "2013-11-19T07:23:20.510Z", "answer_score": 252 }
Please answer the following Stack Overflow question: Title: How to See the Contents of Windows library (*.lib) <p>I have a binary file - Windows static library (*.lib).<br> Is there a simple way to find out names of the functions and their interface from that library ?</p> <p>Something similar to <code>emfar</code> and <code>elfdump</code> utilities (on Linux systems) ?</p>
<p>Assuming you're talking about a static library, <code>DUMPBIN /SYMBOLS</code> shows the functions and data objects in the library. If you're talking about an import library (a <code>.lib</code> used to refer to symbols exported from a DLL), then you want <code>DUMPBIN /EXPORTS</code>.</p> <p>Note that for functions linked with the "C" binary interface, this still won't get you return values, parameters, or calling convention. That information isn't encoded in the <code>.lib</code> at all; you have to know that ahead of time (via prototypes in header files, for example) in order to call them correctly.</p> <p>For functions linked with the C++ binary interface, the calling convention and arguments are encoded in the exported name of the function (also called "name mangling"). <code>DUMPBIN /SYMBOLS</code> will show you both the "mangled" function name as well as the decoded set of parameters.</p>
{ "question_id": 305287, "question_date": "2008-11-20T13:25:10.100Z", "question_score": 220, "tags": "windows|static-libraries|libraries", "answer_id": 305444, "answer_date": "2008-11-20T14:31:02.167Z", "answer_score": 228 }
Please answer the following Stack Overflow question: Title: Forward host port to docker container <p>Is it possible to have a Docker container access ports opened by the host? Concretely I have MongoDB and RabbitMQ running on the host and I'd like to run a process in a Docker container to listen to the queue and (optionally) write to the database.</p> <p>I know I can forward a port from the container to the host (via the -p option) and have a connection to the outside world (i.e. internet) from within the Docker container but I'd like to not expose the RabbitMQ and MongoDB ports from the host to the outside world.</p> <p>EDIT: some clarification:</p> <pre><code>Starting Nmap 5.21 ( http://nmap.org ) at 2013-07-22 22:39 CEST Nmap scan report for localhost (127.0.0.1) Host is up (0.00027s latency). PORT STATE SERVICE 6311/tcp open unknown joelkuiper@vps20528 ~ % docker run -i -t base /bin/bash root@f043b4b235a7:/# apt-get install nmap root@f043b4b235a7:/# nmap 172.16.42.1 -p 6311 # IP found via docker inspect -&gt; gateway Starting Nmap 6.00 ( http://nmap.org ) at 2013-07-22 20:43 UTC Nmap scan report for 172.16.42.1 Host is up (0.000060s latency). PORT STATE SERVICE 6311/tcp filtered unknown MAC Address: E2:69:9C:11:42:65 (Unknown) Nmap done: 1 IP address (1 host up) scanned in 13.31 seconds </code></pre> <p>I had to do this trick to get any internet connection within the container: <a href="https://stackoverflow.com/questions/17394241/my-firewall-is-blocking-network-connections-from-the-docker-container-to-outside">My firewall is blocking network connections from the docker container to outside</a></p> <p><strong>EDIT</strong>: Eventually I went with creating a custom bridge using <a href="https://github.com/jpetazzo/pipework" rel="nofollow noreferrer">pipework</a> and having the services listen on the bridge IP's. I went with this approach instead of having MongoDB and RabbitMQ listen on the docker bridge because it gives more flexibility.</p>
<p>Your docker host exposes an adapter to all the containers. Assuming you are on recent ubuntu, you can run</p> <pre><code>ip addr </code></pre> <p>This will give you a list of network adapters, one of which will look something like</p> <pre><code>3: docker0: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc noqueue state UP link/ether 22:23:6b:28:6b:e0 brd ff:ff:ff:ff:ff:ff inet 172.17.42.1/16 scope global docker0 inet6 fe80::a402:65ff:fe86:bba6/64 scope link valid_lft forever preferred_lft forever </code></pre> <p>You will need to tell rabbit/mongo to bind to that IP (172.17.42.1). After that, you should be able to open connections to 172.17.42.1 from within your containers.</p>
{ "question_id": 17770902, "question_date": "2013-07-21T09:32:41.120Z", "question_score": 220, "tags": "linux|networking|port|docker", "answer_id": 18646069, "answer_date": "2013-09-05T21:14:27.687Z", "answer_score": 72 }
Please answer the following Stack Overflow question: Title: Google Maps API v3: Can I setZoom after fitBounds? <p>I have a set of points I want to plot on an embedded Google Map (API v3). I'd like the bounds to accommodate all points unless the zoom level is too low (i.e., zoomed out too much). My approach has been like this:</p> <pre><code>var bounds = new google.maps.LatLngBounds(); // extend bounds with each point gmap.fitBounds(bounds); gmap.setZoom( Math.max(6, gmap.getZoom()) ); </code></pre> <p>This doesn't work. The last line "gmap.setZoom()" doesn't change the zoom level of the map if called directly after fitBounds.</p> <p>Is there a way to get the zoom level of a bounds without applying it to the map? Other ideas to solve this?</p>
<p><strong>Edit</strong>: See Matt Diamond's comment below.</p> <p>Got it! Try this:</p> <pre><code>map.fitBounds(bounds); var listener = google.maps.event.addListener(map, "idle", function() { if (map.getZoom() &gt; 16) map.setZoom(16); google.maps.event.removeListener(listener); }); </code></pre> <p>Modify to your needs.</p>
{ "question_id": 2437683, "question_date": "2010-03-13T07:49:09.937Z", "question_score": 220, "tags": "javascript|google-maps|google-maps-api-3|fitbounds", "answer_id": 4065006, "answer_date": "2010-10-31T20:41:33.377Z", "answer_score": 370 }
Please answer the following Stack Overflow question: Title: npm install from Git in a specific version <p>Assumed that I have written a module for Node.js which I would like to keep private. I know that I can (should) add the line:</p> <pre><code>"private": "true" </code></pre> <p>to the <code>package.json</code> file, and I also know that I can <code>npm install</code> this module using a file system path or a link to a git repository, including GitHub.</p> <p>I also know that I can put such a file system path or a link to a git repo into <code>package.json</code>, so that the <code>dependencies</code> part may look somewhat like this:</p> <pre><code>"dependencies": { "myprivatemodule": "[email protected]:..." } </code></pre> <p>What I now want is not to link to the latest version, but to a specific one. The only possibility I know of is to link to a specific commit using its ID. But this is way less readable and worse maintainable than using a version number such as <code>0.3.1</code>.</p> <p>So my question is: Is it possible to specify such a version number anyway and make npm search the git repository for the latest commit that includes this version?</p> <p>If not, how do you resolve this issue in your projects? Do you live with commit IDs or is there a better solution to this?</p>
<p>A <a href="https://docs.npmjs.com/files/package.json#dependencies">dependency</a> has to be available from the <a href="https://docs.npmjs.com/misc/registry"><code>registry</code></a> to be installed just by <a href="https://docs.npmjs.com/files/package.json#dependencies">specifying a <code>version</code> descriptor</a>.</p> <p>You can certainly <a href="https://docs.npmjs.com/misc/registry#can-i-run-my-own-private-registry">create and use your own registry</a> instead of <a href="http://registry.npmjs.org/"><code>registry.npmjs.org</code></a> if your projects shouldn't be shared publicly.</p> <p>But, if it's not in a registry, it'll have to be referenced by <a href="https://docs.npmjs.com/files/package.json#urls-as-dependencies">URL</a> or <a href="https://docs.npmjs.com/files/package.json#git-urls-as-dependencies">Git URL</a>. To specify a version with a Git URL, include an appropriate <a href="https://www.kernel.org/pub/software/scm/git/docs/#_identifier_terminology"><code>&lt;commit-ish&gt;</code></a>, such as a tag, at the end as a <a href="https://en.wikipedia.org/wiki/Fragment_identifier">URL fragment</a>.</p> <p>Example, for a tag named <code>0.3.1</code>:</p> <pre><code>"dependencies": { "myprivatemodule": "[email protected]:...#0.3.1" } </code></pre> <blockquote> <p><strong>Note</strong>: The above snippet shows the base URL the same as it was posted in the question.</p> <p>The snipped portion (<code>...</code>) should be filled in:</p> <pre><code>"myprivatemodule": "[email protected]:{owner}/{project}.git#0.3.1" </code></pre> <p>And, a different address format will be needed when SSH access isn't available:</p> <pre><code>"myprivatemodule": "git://github.com/{owner}/{project}.git#0.3.1" </code></pre> </blockquote> <hr> <p>Depending on your OS, you may also be able to <a href="https://docs.npmjs.com/cli/link"><code>link</code></a> to the dependency in another folder where you have it cloned from Github.</p>
{ "question_id": 14187956, "question_date": "2013-01-06T23:32:25.113Z", "question_score": 220, "tags": "node.js|npm", "answer_id": 14188105, "answer_date": "2013-01-06T23:54:56.633Z", "answer_score": 224 }
Please answer the following Stack Overflow question: Title: How do I add a user when I'm using Alpine as a base image? <p>I'm using <code>alpine</code> (or an image that is based on Alpine) as the base image in my Dockerfile. Which instructions do I need to add to create a user? </p> <p>Eventually I'll use this user to run the application I'll place into the container so that the root user does not.</p>
<p>Alpine uses the command <code>adduser</code> and <code>addgroup</code> for creating users and groups (rather than <code>useradd</code> and <code>usergroup</code>).</p> <pre><code>FROM alpine:latest # Create a group and user RUN addgroup -S appgroup &amp;&amp; adduser -S appuser -G appgroup # Tell docker that all future commands should run as the appuser user USER appuser </code></pre> <p>The flags for <code>adduser</code> are:</p> <pre> Usage: adduser [OPTIONS] USER [GROUP] Create new user, or add USER to GROUP -h DIR Home directory -g GECOS GECOS field -s SHELL Login shell -G GRP Group -S Create a system user -D Don't assign a password -H Don't create home directory -u UID User id -k SKEL Skeleton directory (/etc/skel) </pre> <p><a href="https://wiki.alpinelinux.org/wiki/Setting_up_a_new_user" rel="noreferrer">Add new user official docs</a></p>
{ "question_id": 49955097, "question_date": "2018-04-21T11:04:23.807Z", "question_score": 220, "tags": "docker|alpine-linux", "answer_id": 49955098, "answer_date": "2018-04-21T11:04:23.807Z", "answer_score": 387 }