input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: public static const in TypeScript
<p>Is there such a thing as public static constants in TypeScript? I have a class that looks like:</p>
<pre><code>export class Library {
public static BOOK_SHELF_NONE: string = "None";
public static BOOK_SHELF_FULL: string = "Full";
}
</code></pre>
<p>In that class, I can do <code>Library.BOOK_SHELF_NONE</code> and the tsc doesn't complain. But if I try to use the class Library elsewhere, and try to do the same thing, it doesn't recognize it. </p> | <p>Here's what's this TS snippet compiled into (via <a href="http://www.typescriptlang.org/Playground">TS Playground</a>):</p>
<pre><code>define(["require", "exports"], function(require, exports) {
var Library = (function () {
function Library() {
}
Library.BOOK_SHELF_NONE = "None";
Library.BOOK_SHELF_FULL = "Full";
return Library;
})();
exports.Library = Library;
});
</code></pre>
<p>As you see, both properties defined as <code>public static</code> are simply attached to the exported function (as its properties); therefore they should be accessible as long as you properly access the function itself.</p> | {
"question_id": 22991968,
"question_date": "2014-04-10T15:08:54.630Z",
"question_score": 220,
"tags": "typescript",
"answer_id": 22992267,
"answer_date": "2014-04-10T15:22:21.983Z",
"answer_score": 26
} |
Please answer the following Stack Overflow question:
Title: How to implement debounce in Vue2?
<p>I have a simple input box in a Vue template and I would like to use debounce more or less like this:</p>
<pre class="lang-html prettyprint-override"><code><input type="text" v-model="filterKey" debounce="500">
</code></pre>
<p>However the <code>debounce</code> property has been <a href="https://github.com/vuejs/vue/issues/2873" rel="noreferrer">deprecated in Vue 2</a>. The recommendation only says: "use v-on:input + 3rd party debounce function".</p>
<p>How do you correctly implement it?</p>
<p>I've tried to implement it using <strong>lodash</strong>, <strong>v-on:input</strong> and <strong>v-model</strong>, but I am wondering if it is possible to do without the extra variable.</p>
<p><strong>In template:</strong></p>
<pre class="lang-html prettyprint-override"><code><input type="text" v-on:input="debounceInput" v-model="searchInput">
</code></pre>
<p><strong>In script:</strong></p>
<pre class="lang-js prettyprint-override"><code>data: function () {
return {
searchInput: '',
filterKey: ''
}
},
methods: {
debounceInput: _.debounce(function () {
this.filterKey = this.searchInput;
}, 500)
}
</code></pre>
<p>The filterkey is then used later in <code>computed</code> props.</p> | <p>I am using <a href="https://www.npmjs.com/package/debounce" rel="noreferrer">debounce</a> NPM package and implemented like this:</p>
<pre class="lang-html prettyprint-override"><code><input @input="debounceInput">
</code></pre>
<pre class="lang-js prettyprint-override"><code>methods: {
debounceInput: debounce(function (e) {
this.$store.dispatch('updateInput', e.target.value)
}, config.debouncers.default)
}
</code></pre>
<p>Using <a href="https://lodash.com/docs/#debounce" rel="noreferrer">lodash</a> and the example in the question, the implementation looks like this:</p>
<pre class="lang-html prettyprint-override"><code><input v-on:input="debounceInput">
</code></pre>
<pre class="lang-js prettyprint-override"><code>methods: {
debounceInput: _.debounce(function (e) {
this.filterKey = e.target.value;
}, 500)
}
</code></pre> | {
"question_id": 42199956,
"question_date": "2017-02-13T08:51:01.950Z",
"question_score": 220,
"tags": "vue.js|vuejs2|debouncing",
"answer_id": 42201508,
"answer_date": "2017-02-13T10:11:45.933Z",
"answer_score": 224
} |
Please answer the following Stack Overflow question:
Title: Are there any naming convention guidelines for REST APIs?
<p>When creating REST APIs, are there any guidelines or defacto standards for naming conventions within the API (eg: URL endpoint path components, querystring parameters)? Are camel caps the norm, or underscores? others?</p>
<p>For example:</p>
<pre><code>api.service.com/helloWorld/userId/x
</code></pre>
<p>or</p>
<pre><code>api.service.com/hello_world/user_id/x
</code></pre>
<p>Note: This is not a question of RESTful API design, rather the naming convention guidelines to use for the eventual path components and/or query string parameters used.</p>
<p>Any guidelines would be appreciated.</p> | <p>I think you should avoid camel caps. The norm is to use lower case letters. I would also avoid underscores and use dashes instead</p>
<p>So your URL should look like this (ignoring the design issues as you requested :-))</p>
<pre><code>api.service.com/hello-world/user-id/x
</code></pre> | {
"question_id": 778203,
"question_date": "2009-04-22T16:52:39.050Z",
"question_score": 220,
"tags": "rest|naming-conventions",
"answer_id": 785798,
"answer_date": "2009-04-24T13:15:38.963Z",
"answer_score": 164
} |
Please answer the following Stack Overflow question:
Title: What's the difference of $host and $http_host in Nginx
<p>In Nginx, what's the difference between variables <code>$host</code> and <code>$http_host</code>.</p> | <p><code>$host</code> is a variable of the <a href="https://nginx.org/en/docs/http/ngx_http_core_module.html#var_host" rel="noreferrer">Core</a> module.</p>
<blockquote>
<p>$host</p>
</blockquote>
<blockquote>
<p>This variable is equal to line Host in the header of request or
name of the server processing the request if the Host header is not
available.</p>
</blockquote>
<blockquote>
<p>This variable may have a different value from $http_host in such
cases: 1) when the Host input header is absent or has an empty value,
$host equals to the value of server_name directive; 2)when the value
of Host contains port number, $host doesn't include that port number.
$host's value is always lowercase since 0.8.17.</p>
</blockquote>
<p><code>$http_host</code> is also a variable of the same module but you won't find it with that name because it is defined generically as <code>$http_HEADER</code> (<a href="https://nginx.org/en/docs/http/ngx_http_core_module.html#var_http_" rel="noreferrer">ref</a>).</p>
<blockquote>
<p>$http_HEADER</p>
</blockquote>
<blockquote>
<p>The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;</p>
</blockquote>
<hr />
<p>Summarizing:</p>
<ul>
<li><code>$http_host</code> equals always the <code>HTTP_HOST</code> request header.</li>
<li><code>$host</code> equals <code>$http_host</code>, <strong>lowercase and without the port number</strong> (if present), <strong>except when <code>HTTP_HOST</code> is absent or is an empty value</strong>. In that case, <code>$host</code> equals the value of the <code>server_name</code> directive of the server which processed the request.</li>
</ul> | {
"question_id": 15414810,
"question_date": "2013-03-14T16:25:54.447Z",
"question_score": 220,
"tags": "configuration|nginx|http-headers",
"answer_id": 15414811,
"answer_date": "2013-03-14T16:25:54.447Z",
"answer_score": 269
} |
Please answer the following Stack Overflow question:
Title: Bootstrap Modal immediately disappearing
<p>I'm working on a website using bootstrap.</p>
<p>Basically, I wanted to use a modal in the home page, summoned by the button in the Hero Unit.</p>
<p>Button code:</p>
<pre><code><button type="button"
class="btn btn-warning btn-large"
data-toggle="modal"
data-target="#myModal">Open Modal</button>
</code></pre>
<p>Modal code: </p>
<pre><code><div class="modal hide fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">In Costruzione</h3>
</div>
<div class="modal-body">
<p>Test Modal: Bootstrap</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Chiudi</button>
<button class="btn btn-warning">Salva</button>
</div>
</div>
</code></pre>
<p>The problem is that as soon as I click on the button, the modal fades in and then immediately disappears.</p>
<p>I'd appreciate any help. </p>
<p>Also, how to change the dropdown triangle's color (pointing up, no hover)? I'm working on a website based on orange and brown and that blue thing is really annoying.</p> | <h2>A Likely Cause</h2>
<p>This is typical behavior for when the JavaScript for the Modal plugin gets loaded twice. Please check to make sure that the plugin isn't getting double loaded. Depending on the platform you are using, the modal code could be loaded from a number a sources. Some of the common ones are:</p>
<ul>
<li><strong>bootstrap.js</strong> (the full BootStrap JS suite)</li>
<li><strong>bootstrap.min.js</strong> (same as above, just minified)</li>
<li><strong>bootstrap-modal.js</strong> (the standalone plugin)</li>
<li>a dependency loader, e.g., <code>require('bootstrap')</code></li>
</ul>
<h2>Debugging Tips</h2>
<p>A good place to start is to inspect the registered <code>click</code> event listeners using the developer tools in your browser. Chrome, for instance, will list the JS source file where the code to register the listener can be found. Another option is to try searching the sources on the page for a phrase found in the Modal code, e.g., <code>var Modal</code>.</p>
<p>Unfortunately, these won't always find things in all cases. Inspecting the network requests can be a little more robust at giving you a picture of everything loaded on a page.</p>
<h2>A (Broken) Demo</h2>
<p>Here's a demo of what happens when you load both the <strong>bootstrap.js</strong> and <strong>bootstrap-modal.js</strong> (just to confirm your experience):</p>
<h2><a href="http://plnkr.co/edit/WwgzRX?p=preview" rel="noreferrer">Plunker</a></h2>
<p>If you scroll down to the bottom of the source on that page, you can remove or comment out the <code><script></code> line for the <strong>bootstrap-modal.js</strong> and then verify that now the modal will function as expected.</p> | {
"question_id": 13648979,
"question_date": "2012-11-30T16:19:11.287Z",
"question_score": 220,
"tags": "twitter-bootstrap|modal-dialog",
"answer_id": 13670437,
"answer_date": "2012-12-02T14:57:37.497Z",
"answer_score": 501
} |
Please answer the following Stack Overflow question:
Title: This Row already belongs to another table error when trying to add rows?
<p>I have a DataTable which has some rows and I am using the select to filter the rows to get a collection of DataRows which I then loop through using foreach and add it to another DataTable, but it is giving me the error "This Row already belongs to another table". Here is the code:</p>
<pre><code>DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();
DataRow[] orderRows = dt.Select("CustomerID = 2");
foreach (DataRow dr in orderRows)
{
dtSpecificOrders.Rows.Add(dr); //Error thrown here.
}
</code></pre> | <p>You need to create a new <code>Row</code> with the values from <code>dr</code> first. A <code>DataRow</code> can only belong to a single <code>DataTable</code>.</p>
<p>You can also use <code>Add</code> which takes an array of values:</p>
<pre><code>myTable.Rows.Add(dr.ItemArray)
</code></pre>
<p>Or probably even better:</p>
<pre><code>// This works because the row was added to the original table.
myTable.ImportRow(dr);
// The following won't work. No data will be added or exception thrown.
var drFail = dt.NewRow()
drFail["CustomerID"] = "[Your data here]";
// dt.Rows.Add(row); // Uncomment for import to succeed.
myTable.ImportRow(drFail);
</code></pre> | {
"question_id": 722052,
"question_date": "2009-04-06T15:47:55.670Z",
"question_score": 220,
"tags": "c#",
"answer_id": 722060,
"answer_date": "2009-04-06T15:50:00.487Z",
"answer_score": 361
} |
Please answer the following Stack Overflow question:
Title: Gradients on UIView and UILabels On iPhone
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/227005/manually-drawing-a-gradient-in-iphone-apps">Manually drawing a gradient in iPhone apps?</a> </p>
</blockquote>
<p>My application needs to display text in either a <code>UIView</code> or <code>UILabel</code> but the back ground must be a gradient as opposed to a true <code>UIColor</code>. Using a graphics program to create desired look is no good as the text may vary depending on data returned from a server.</p>
<p>Does anyone know the quickest way to tackle this?
Your thoughts are greatly appreciated.</p> | <p>You could also use a graphic image one pixel wide as the gradient, and set the view property to expand the graphic to fill the view (assuming you are thinking of a simple linear gradient and not some kind of radial graphic).</p> | {
"question_id": 422066,
"question_date": "2009-01-07T20:58:30.117Z",
"question_score": 220,
"tags": "iphone|ios|cocoa-touch|gradient",
"answer_id": 422831,
"answer_date": "2009-01-08T00:59:40.553Z",
"answer_score": 45
} |
Please answer the following Stack Overflow question:
Title: jQuery - Trigger event when an element is removed from the DOM
<p>I'm trying to figure out how to execute some js code when an element is removed from the page:</p>
<pre><code>jQuery('#some-element').remove(); // remove some element from the page
/* need to figure out how to independently detect the above happened */
</code></pre>
<p>is there an event tailored for that, something like:</p>
<pre><code>jQuery('#some-element').onremoval( function() {
// do post-mortem stuff here
});
</code></pre> | <p>Just checked, it is already built-in in current version of JQuery:</p>
<p>jQuery - v1.9.1</p>
<p>jQuery UI - v1.10.2</p>
<pre><code>$("#myDiv").on("remove", function () {
alert("Element was removed");
})
</code></pre>
<p><strong>Important</strong>: This is functionality of <strong>Jquery UI</strong> script (not JQuery), so you have to load both scripts (jquery and jquery-ui) to make it work. Here is example: <a href="http://jsfiddle.net/72RTz/" rel="noreferrer">http://jsfiddle.net/72RTz/</a></p> | {
"question_id": 2200494,
"question_date": "2010-02-04T14:46:04.437Z",
"question_score": 220,
"tags": "jquery|events|dom|triggers",
"answer_id": 16225393,
"answer_date": "2013-04-25T21:54:00.750Z",
"answer_score": 122
} |
Please answer the following Stack Overflow question:
Title: Map and Reduce in .NET
<p>What scenarios would warrant the use of the "<a href="http://en.wikipedia.org/wiki/MapReduce" rel="noreferrer">Map and Reduce</a>" algorithm?</p>
<p><br /> Is there a .NET implementation of this algorithm? </p> | <p>Linq equivalents of Map and Reduce:
If you’re lucky enough to have linq then you don’t need to write your own map and reduce functions. C# 3.5 and Linq already has it albeit under different names.</p>
<ul>
<li><p>Map is <code>Select</code>:</p>
<pre><code>Enumerable.Range(1, 10).Select(x => x + 2);
</code></pre></li>
<li><p>Reduce is <code>Aggregate</code>:</p>
<pre><code>Enumerable.Range(1, 10).Aggregate(0, (acc, x) => acc + x);
</code></pre></li>
<li><p>Filter is <code>Where</code>:</p>
<pre><code>Enumerable.Range(1, 10).Where(x => x % 2 == 0);
</code></pre></li>
</ul>
<p><a href="https://www.justinshield.com/2011/06/mapreduce-in-c/" rel="noreferrer">https://www.justinshield.com/2011/06/mapreduce-in-c/</a></p> | {
"question_id": 428798,
"question_date": "2009-01-09T16:40:21.737Z",
"question_score": 220,
"tags": "c#|mapreduce",
"answer_id": 13895253,
"answer_date": "2012-12-15T19:07:00.600Z",
"answer_score": 442
} |
Please answer the following Stack Overflow question:
Title: What are best practices for multi-language database design?
<p>What is the best way to create multi-language database? To create localized table for every table is making design and querying complex, in other case to add column for each language is simple but not dynamic, please help me to understand what is the best choose for enterprise applications</p> | <p>What we do, is to create two tables for each multilingual object.</p>
<p>E.g. the first table contains only language-neutral data (primary key, etc.) and the second table contains one record per language, containing the localized data plus the ISO code of the language.</p>
<p>In some cases we add a DefaultLanguage field, so that we can fall-back to that language if no localized data is available for a specified language.</p>
<p>Example:</p>
<pre><code>Table "Product":
----------------
ID : int
<any other language-neutral fields>
Table "ProductTranslations"
---------------------------
ID : int (foreign key referencing the Product)
Language : varchar (e.g. "en-US", "de-CH")
IsDefault : bit
ProductDescription : nvarchar
<any other localized data>
</code></pre>
<p>With this approach, you can handle as many languages as needed (without having to add additional fields for each new language).</p>
<hr>
<p><em>Update (2014-12-14): please have a look at <a href="https://stackoverflow.com/a/27474681/19635">this answer</a>, for some additional information about the implementation used to load multilingual data into an application.</em></p> | {
"question_id": 929410,
"question_date": "2009-05-30T09:17:23.607Z",
"question_score": 220,
"tags": "sql|database|database-design",
"answer_id": 929430,
"answer_date": "2009-05-30T09:28:40.057Z",
"answer_score": 267
} |
Please answer the following Stack Overflow question:
Title: jQuery .live() vs .on() method for adding a click event after loading dynamic html
<p>I am using jQuery v.1.7.1 where the .live() method is apparently deprecated. </p>
<p>The problem I am having is that when dynamically loading html into an element using:</p>
<pre><code>$('#parent').load("http://...");
</code></pre>
<p>If I try and add a click event afterwards it does not register the event using either of these methods:</p>
<pre><code>$('#parent').click(function() ...);
</code></pre>
<p>or</p>
<pre><code>// according to documentation this should be used instead of .live()
$('#child').on('click', function() ...);
</code></pre>
<p>What is the correct way to achieve this functionality? It only seems to work with .live() for me, but I shouldn't be using that method. Note that #child is a dynamically loaded element. </p>
<p>Thanks. </p> | <p>If you want the click handler to work for an element that gets loaded dynamically, then you set the event handler on a parent object (that does not get loaded dynamically) and give it a selector that matches your dynamic object like this:</p>
<pre><code>$('#parent').on("click", "#child", function() {});
</code></pre>
<p>The event handler will be attached to the <code>#parent</code> object and anytime a click event bubbles up to it that originated on <code>#child</code>, it will fire your click handler. This is called delegated event handling (the event handling is delegated to a parent object).</p>
<p>It's done this way because you can attach the event to the <code>#parent</code> object even when the <code>#child</code> object does not exist yet, but when it later exists and gets clicked on, the click event will bubble up to the <code>#parent</code> object, it will see that it originated on <code>#child</code> and there is an event handler for a click on <code>#child</code> and fire your event.</p> | {
"question_id": 8752321,
"question_date": "2012-01-06T01:29:26.273Z",
"question_score": 220,
"tags": "javascript|jquery|events|dom|handler",
"answer_id": 8752376,
"answer_date": "2012-01-06T01:35:32.387Z",
"answer_score": 614
} |
Please answer the following Stack Overflow question:
Title: How is the 'use strict' statement interpreted in Node.js?
<p>I have started to explore the Node.js and wrote many demo web application, to understand the flow of Node.js, Express.js, jade, etc.. </p>
<p>But one thing I came across recently, is the statement <code>"use strict"</code> as the first line inside every function and every <code>.js</code> file.</p>
<p>How exactly is it is interpreted by Node.js?</p> | <p><code>"use strict";</code></p>
<p>Basically it enables the strict mode.</p>
<blockquote>
<p>Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.</p>
</blockquote>
<p>As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the <a href="http://en.wikipedia.org/wiki/V8_%28JavaScript_engine%29" rel="noreferrer"><strong>V8</strong> JavaScript engine</a>. The <strong>V8 JavaScript Engine</strong> is an open source JavaScript engine developed by Google for Chrome web browser.</p>
<p>So, there will be no major difference how <code>"use strict";</code> is interpreted by the Chrome browser and Node.js.</p>
<p>Please read what is strict mode in JavaScript.</p>
<p>For more information:</p>
<ol>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode" rel="noreferrer">Strict mode</a></li>
<li><a href="http://www.novogeek.com/post/ECMAScript-5-Strict-mode-support-in-browsers-What-does-this-mean.aspx" rel="noreferrer">ECMAScript 5 Strict mode support in browsers</a></li>
<li><a href="http://www.yuiblog.com/blog/2010/12/14/strict-mode-is-coming-to-town/" rel="noreferrer">Strict mode is coming to town</a></li>
<li><a href="https://kangax.github.io/compat-table/strict-mode/" rel="noreferrer">Compatibility table for strict mode</a></li>
<li><a href="https://stackoverflow.com/questions/1335851/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it">Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it</a></li>
</ol>
<p><hr/>
<strong>ECMAScript 6:</strong></p>
<p>ECMAScript 6 Code & strict mode. Following is brief <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-strict-mode-code" rel="noreferrer">from the specification</a>:</p>
<blockquote>
<p><strong>10.2.1 Strict Mode Code</strong></p>
<p>An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:</p>
<ul>
<li>Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).</li>
<li><strong>Module code is always strict mode code.</strong></li>
<li>All parts of a ClassDeclaration or a ClassExpression are strict mode code.</li>
<li>Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.</li>
<li>Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.</li>
<li>Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.</li>
</ul>
</blockquote>
<p>Additionally if you are lost on what features are supported by your current version of Node.js, this <a href="http://node.green/" rel="noreferrer">node.green</a> can help you (leverages from the same data as <a href="https://kangax.github.io/compat-table/es6/" rel="noreferrer">kangax</a>).</p> | {
"question_id": 18417381,
"question_date": "2013-08-24T10:09:25.583Z",
"question_score": 220,
"tags": "javascript|node.js|use-strict",
"answer_id": 18417571,
"answer_date": "2013-08-24T10:30:27.793Z",
"answer_score": 210
} |
Please answer the following Stack Overflow question:
Title: Trying to mock datetime.date.today(), but not working
<p>Can anyone tell me why this isn't working?</p>
<pre><code>>>> import mock
>>> @mock.patch('datetime.date.today')
... def today(cls):
... return date(2010, 1, 1)
...
>>> from datetime import date
>>> date.today()
datetime.date(2010, 12, 19)
</code></pre>
<p>Perhaps someone could suggest a better way?</p> | <p>There are a few problems.</p>
<p>First of all, the way you're using <code>mock.patch</code> isn't quite right. When used as a decorator, it replaces the given function/class (in this case, <code>datetime.date.today</code>) with a <code>Mock</code> object <em>only within the decorated function</em>. So, only within your <code>today()</code> will <code>datetime.date.today</code> be a different function, which doesn't appear to be what you want.</p>
<p>What you really want seems to be more like this:</p>
<pre><code>@mock.patch('datetime.date.today')
def test():
datetime.date.today.return_value = date(2010, 1, 1)
print datetime.date.today()
</code></pre>
<p>Unfortunately, this won't work:</p>
<pre><code>>>> test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.macosx-10.6-universal/egg/mock.py", line 557, in patched
File "build/bdist.macosx-10.6-universal/egg/mock.py", line 620, in __enter__
TypeError: can't set attributes of built-in/extension type 'datetime.date'
</code></pre>
<p>This fails because Python built-in types are immutable - see <a href="https://stackoverflow.com/questions/192649/can-you-monkey-patch-methods-on-core-types-in-python/192857#192857">this answer</a> for more details.</p>
<p>In this case, I would subclass datetime.date myself and create the right function:</p>
<pre><code>import datetime
class NewDate(datetime.date):
@classmethod
def today(cls):
return cls(2010, 1, 1)
datetime.date = NewDate
</code></pre>
<p>And now you could do:</p>
<pre><code>>>> datetime.date.today()
NewDate(2010, 1, 1)
</code></pre> | {
"question_id": 4481954,
"question_date": "2010-12-19T06:54:38.750Z",
"question_score": 220,
"tags": "python|testing|datetime|mocking",
"answer_id": 4482067,
"answer_date": "2010-12-19T07:49:27.203Z",
"answer_score": 148
} |
Please answer the following Stack Overflow question:
Title: Correct way to populate an Array with a Range in Ruby
<p>I am working through a book which gives examples of Ranges being converted to equivalent arrays using their "to_a" methods</p>
<p>When i run the code in irb I get the following warning</p>
<pre><code> warning: default `to_a' will be obsolete
</code></pre>
<p>What is the the correct alternative to using to_a?</p>
<p>are there alternate ways to populate an array with a Range?</p> | <p>You can create an array with a range using splat,</p>
<pre><code>>> a=*(1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code></pre>
<p>using <code>Kernel</code> <code>Array</code> method,</p>
<pre><code>Array (1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code></pre>
<p>or using to_a</p>
<pre><code>(1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code></pre> | {
"question_id": 191329,
"question_date": "2008-10-10T13:41:47.203Z",
"question_score": 220,
"tags": "ruby|syntax",
"answer_id": 6587096,
"answer_date": "2011-07-05T18:22:15.647Z",
"answer_score": 394
} |
Please answer the following Stack Overflow question:
Title: Webpack.config how to just copy the index.html to the dist folder
<p>I am trying to automate assets going into /dist. I have the following config.js:</p>
<pre><code>module.exports = {
context: __dirname + "/lib",
entry: {
main: [
"./baa.ts"
]
},
output: {
path: __dirname + "/dist",
filename: "foo.js"
},
devtool: "source-map",
module: {
loaders: [
{
test: /\.ts$/,
loader: 'awesome-typescript-loader'
},
{ test: /\.css$/, loader: "style-loader!css-loader" }
]
},
resolve: {
// you can now require('file') instead of require('file.js')
extensions: ['', '.js', '.json']
}
}
</code></pre>
<p>I also want to include main.html from the directory that sits next to /lib, into the /dist folder when running webpack. How can I do this?</p>
<h1>UPDATE 1 2017_____________</h1>
<p>My favourite way to do this now is to use the <a href="https://github.com/jantimon/html-webpack-plugin" rel="noreferrer"><code>html-webpack-plugin</code></a> with a template file. Thanks to the accepted answer too! The advantage of this way is that the index file will also have the cachbusted js link added out of the box!</p> | <p><strong>Option 1</strong></p>
<p>In your <code>index.js</code> file (i.e. webpack entry) add a require to your <code>index.html</code> via <a href="https://github.com/webpack/file-loader" rel="noreferrer">file-loader</a> plugin, e.g.:</p>
<p><code>require('file-loader?name=[name].[ext]!../index.html');</code></p>
<p>Once you build your project with webpack, <code>index.html</code> will be in the output folder.</p>
<p><strong>Option 2</strong></p>
<p>Use <a href="https://www.npmjs.com/package/html-webpack-plugin" rel="noreferrer">html-webpack-plugin</a> to avoid having an index.html at all. Simply have webpack generate the file for you.</p>
<p>In this case if you want to keep your own <code>index.html</code> file as template, you may use this configuration:</p>
<pre class="lang-js prettyprint-override"><code>{
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
}
</code></pre>
<p>See the <a href="https://github.com/jantimon/html-webpack-plugin/blob/master/docs/template-option.md" rel="noreferrer">docs</a> for more information.</p> | {
"question_id": 32155154,
"question_date": "2015-08-22T10:39:26.683Z",
"question_score": 220,
"tags": "webpack",
"answer_id": 33519539,
"answer_date": "2015-11-04T10:33:04.787Z",
"answer_score": 198
} |
Please answer the following Stack Overflow question:
Title: What's the best way to set a single pixel in an HTML5 canvas?
<p>The HTML5 Canvas has no method for explicitly setting a single pixel.</p>
<p>It might be possible to set a pixel using a very short line, but then antialising and line caps might interfere.</p>
<p>Another way might be to create a small <code>ImageData</code> object and using:</p>
<pre><code>context.putImageData(data, x, y)
</code></pre>
<p>to put it in place.</p>
<p>Can anyone describe an efficient and reliable way of doing this?</p> | <p>There are two best contenders:</p>
<ol>
<li><p>Create a 1×1 image data, set the color, and <code>putImageData</code> at the location:</p>
<pre><code>var id = myContext.createImageData(1,1); // only do this once per page
var d = id.data; // only do this once per page
d[0] = r;
d[1] = g;
d[2] = b;
d[3] = a;
myContext.putImageData( id, x, y );
</code></pre></li>
<li><p>Use <code>fillRect()</code> to draw a pixel (there should be no aliasing issues):</p>
<pre><code>ctx.fillStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";
ctx.fillRect( x, y, 1, 1 );
</code></pre></li>
</ol>
<p>You can test the speed of these here: <a href="http://jsperf.com/setting-canvas-pixel/9" rel="noreferrer">http://jsperf.com/setting-canvas-pixel/9</a> or here <a href="https://www.measurethat.net/Benchmarks/Show/1664/1" rel="noreferrer">https://www.measurethat.net/Benchmarks/Show/1664/1</a> </p>
<p><strong>I recommend testing against browsers you care about for maximum speed.</strong> As of July 2017, <code>fillRect()</code> is 5-6× faster on Firefox v54 and Chrome v59 (Win7x64).</p>
<p>Other, sillier alternatives are:</p>
<ul>
<li><p>using <code>getImageData()/putImageData()</code> on the entire canvas; this is about 100× slower than other options.</p></li>
<li><p>creating a custom image using a data url and using <code>drawImage()</code> to show it:</p>
<pre><code>var img = new Image;
img.src = "data:image/png;base64," + myPNGEncoder(r,g,b,a);
// Writing the PNGEncoder is left as an exercise for the reader
</code></pre></li>
<li><p>creating another img or canvas filled with all the pixels you want and use <code>drawImage()</code> to blit just the pixel you want across. This would probably be very fast, but has the limitation that you need to pre-calculate the pixels you need.</p></li>
</ul>
<p><em>Note that my tests do not attempt to save and restore the canvas context <code>fillStyle</code>; this would slow down the <code>fillRect()</code> performance. Also note that I am not starting with a clean slate or testing the exact same set of pixels for each test.</em></p> | {
"question_id": 4899799,
"question_date": "2011-02-04T15:38:32.983Z",
"question_score": 220,
"tags": "html|canvas|pixel",
"answer_id": 4900656,
"answer_date": "2011-02-04T16:57:09.277Z",
"answer_score": 323
} |
Please answer the following Stack Overflow question:
Title: Access index of the parent ng-repeat from child ng-repeat
<p>I want to use the index of the parent list (foos) as an argument to a function call in the child list (foos.bars).</p>
<p>I found a post where someone recommends using $parent.$index, but <code>$index</code> is not a property of <code>$parent</code>.</p>
<p>How can I access the index of the parent <code>ng-repeat</code>?</p>
<pre><code><div ng-repeat="f in foos">
<div>
<div ng-repeat="b in foos.bars">
<a ng-click="addSomething($parent.$index)">Add Something</a>
</div>
</div>
</div>
</code></pre> | <p>My example code was correct and the issue was something else in my actual code. Still, I know it was difficult to find examples of this so I'm answering it in case someone else is looking.</p>
<pre><code><div ng-repeat="f in foos">
<div>
<div ng-repeat="b in foos.bars">
<a ng-click="addSomething($parent.$index)">Add Something</a>
</div>
</div>
</div>
</code></pre> | {
"question_id": 14807258,
"question_date": "2013-02-11T06:52:34.023Z",
"question_score": 220,
"tags": "javascript|angularjs|angularjs-ng-repeat",
"answer_id": 14822414,
"answer_date": "2013-02-11T22:51:09.630Z",
"answer_score": 284
} |
Please answer the following Stack Overflow question:
Title: Size-limited queue that holds last N elements in Java
<p>A very simple & quick question on Java libraries: is there a ready-made class that implements a <code>Queue</code> with a fixed maximum size - i.e. it always allows addition of elements, but it will silently remove head elements to accomodate space for newly added elements.</p>
<p>Of course, it's trivial to implement it manually:</p>
<pre><code>import java.util.LinkedList;
public class LimitedQueue<E> extends LinkedList<E> {
private int limit;
public LimitedQueue(int limit) {
this.limit = limit;
}
@Override
public boolean add(E o) {
super.add(o);
while (size() > limit) { super.remove(); }
return true;
}
}
</code></pre>
<p>As far as I see, there's no standard implementation in Java stdlibs, but may be there's one in Apache Commons or something like that?</p> | <p>Apache commons collections 4 has a <a href="https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/queue/CircularFifoQueue.html" rel="noreferrer">CircularFifoQueue<></a> which is what you are looking for. Quoting the javadoc:</p>
<blockquote>
<p>CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.</p>
</blockquote>
<pre><code> import java.util.Queue;
import org.apache.commons.collections4.queue.CircularFifoQueue;
Queue<Integer> fifo = new CircularFifoQueue<Integer>(2);
fifo.add(1);
fifo.add(2);
fifo.add(3);
System.out.println(fifo);
// Observe the result:
// [2, 3]
</code></pre>
<p>If you are using an older version of the Apache commons collections (3.x), you can use the <a href="https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/org/apache/commons/collections/buffer/CircularFifoBuffer.html" rel="noreferrer">CircularFifoBuffer</a> which is basically the same thing without generics.</p>
<p><em>Update</em>: updated answer following release of commons collections version 4 that supports generics.</p> | {
"question_id": 5498865,
"question_date": "2011-03-31T11:09:08.237Z",
"question_score": 220,
"tags": "collections|queue|java",
"answer_id": 5638128,
"answer_date": "2011-04-12T15:54:22.417Z",
"answer_score": 191
} |
Please answer the following Stack Overflow question:
Title: Is there a Newline constant defined in Java like Environment.Newline in C#?
<p>In C# there is the static property <a href="http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx" rel="noreferrer">Environment.Newline</a> that changed depending on the running platform.</p>
<p>Is there anything similar in Java?</p> | <p><strong>As of Java 7 (and Android API level 19):</strong></p>
<pre><code>System.lineSeparator()
</code></pre>
<p>Documentation: <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#lineSeparator%28%29" rel="noreferrer">Java Platform SE 7</a></p>
<hr>
<p><strong>For older versions of Java, use:</strong></p>
<pre><code>System.getProperty("line.separator");
</code></pre>
<p>See <a href="https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html" rel="noreferrer">https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html</a> for other properties.</p> | {
"question_id": 247059,
"question_date": "2008-10-29T14:43:35.437Z",
"question_score": 220,
"tags": "java",
"answer_id": 247069,
"answer_date": "2008-10-29T14:45:32.237Z",
"answer_score": 313
} |
Please answer the following Stack Overflow question:
Title: ESLint - "window" is not defined. How to allow global variables in package.json
<p>I am assigning a property to the global window object, but when I run eslint, I get this: </p>
<blockquote>
<p>"window" is not defined </p>
</blockquote>
<p>I see this <a href="http://eslint.org/docs/developer-guide/working-with-rules">here in the eslint docs</a>:</p>
<blockquote>
<p>the following defines window as a global variable for code that should not trigger the rule being tested:</p>
</blockquote>
<pre><code>valid: [
{
code: "window.alert()",
globals: [ "window" ]
}
]
</code></pre>
<p>I've tried adding something like this to the package.json file to have eslint allow "window" as a global variable, but I must be doing something wrong. From the docs it seems like I might need to do something like this in a separate file, but is there a way to define some allowed global variables right in the package.json file?</p> | <p>I found it on this page: <a href="http://eslint.org/docs/user-guide/configuring">http://eslint.org/docs/user-guide/configuring</a></p>
<p>In package.json, this works:</p>
<pre><code>"eslintConfig": {
"globals": {
"window": true
}
}
</code></pre> | {
"question_id": 30398825,
"question_date": "2015-05-22T14:03:58.517Z",
"question_score": 220,
"tags": "eslint",
"answer_id": 30400159,
"answer_date": "2015-05-22T15:07:04.537Z",
"answer_score": 113
} |
Please answer the following Stack Overflow question:
Title: Nested Git repositories?
<p>Can I nest Git repositories? I have:</p>
<pre><code> /project_root/
/project_root/my_project
/project_root/third_party_git_repository_used_by_my_project
</code></pre>
<p>Does it make sense to <code>git init/add</code> the <code>/project_root</code> to ease management of everything locally or do I have to manage <code>my_project</code> and the 3rd party one separately?</p> | <p>You may be looking for the Git feature called <a href="https://git.wiki.kernel.org/index.php/GitSubmoduleTutorial" rel="noreferrer">submodules</a>. This feature helps you manage dependent repositories that are nested inside your main repository.</p> | {
"question_id": 1871282,
"question_date": "2009-12-09T02:38:30.503Z",
"question_score": 220,
"tags": "git",
"answer_id": 1871304,
"answer_date": "2009-12-09T02:47:15.800Z",
"answer_score": 191
} |
Please answer the following Stack Overflow question:
Title: Crontab - Run in directory
<p>I would like to set a job to run daily in the root crontab. But I would like it to execute it from a particular directory so it can find all the files it needs, since the application has a bunch of relative paths.</p>
<p>Anyway, can I tell crontab to run from a particular directory?</p> | <p>All jobs are executed by a shell, so start that shell snippet by a command to change the directory.</p>
<pre><code>cd /path/to/directory && ./bin/myapp
</code></pre>
<p>Concerning the use of <code>&&</code> instead of <code>;</code>: normally it doesn't make a difference, but if the <code>cd</code> command fails (e.g. because the directory doesn't exist) with <code>&&</code> the application isn't executed, whereas with <code>;</code> it's executed (but <strong>not in the intended directory</strong>).</p> | {
"question_id": 8899737,
"question_date": "2012-01-17T18:28:08.677Z",
"question_score": 220,
"tags": "unix|directory|relative-path|crontab",
"answer_id": 8899878,
"answer_date": "2012-01-17T18:40:11.247Z",
"answer_score": 421
} |
Please answer the following Stack Overflow question:
Title: How important is the order of columns in indexes?
<p>I've heard that you should put columns that will be the most selective at the beginning of the index declaration. Example:</p>
<pre><code>CREATE NONCLUSTERED INDEX MyINDX on Table1
(
MostSelective,
SecondMost,
Least
)
</code></pre>
<p>First off, is what I'm saying correct? If so, am i likely to see large differences in performance by rearranging the order of the columns in my index or is it more of a "nice to do" practice?</p>
<p>The reason I'm asking is because after putting a query through the DTA it recommended that I create an index that had almost all of the same columns in it as an existing index, just in a different order. I was considering just adding the missing columns to the existing index and calling it good. Thoughts?</p> | <p>Look at an index like this:</p>
<pre><code>Cols
1 2 3
-------------
| | 1 | |
| A |---| |
| | 2 | |
|---|---| |
| | | |
| | 1 | 9 |
| B | | |
| |---| |
| | 2 | |
| |---| |
| | 3 | |
|---|---| |
</code></pre>
<p>See how restricting on A first, as your first column eliminates more results than restricting on your second column first? It's easier if you picture how the index must be traversed across, column 1, then column 2, etc...you see that lopping off most of the results in the fist pass makes the 2nd step that much faster. </p>
<p>Another case, if you queried on column 3, the optimizer wouldn't even use the index, because it's not helpful at all in narrowing down the result sets. <strong>Anytime you're in a query, narrowing down the number of results to deal with before the next step means better performance.</strong></p>
<p>Since the index is also stored this way, there's no backtracking across the index to find the first column when you're querying on it. </p>
<p>In short: No, it's not for show, there are real performance benefits.</p> | {
"question_id": 2292662,
"question_date": "2010-02-18T22:18:50.767Z",
"question_score": 220,
"tags": "sql|sql-server|sql-server-2005|tsql|indexing",
"answer_id": 2292716,
"answer_date": "2010-02-18T22:26:55.087Z",
"answer_score": 231
} |
Please answer the following Stack Overflow question:
Title: Difference between SurfaceView and View?
<p>When is it necessary, or better to use a <code>SurfaceView</code> instead of a <code>View</code>?</p> | <p>Views are all drawn on the same GUI thread which is also used for all user interaction.</p>
<p>So if you need to update GUI rapidly or if the rendering takes too much time and affects user experience then use <code>SurfaceView</code>.</p> | {
"question_id": 1243433,
"question_date": "2009-08-07T07:31:23.997Z",
"question_score": 220,
"tags": "android|graphics|2d",
"answer_id": 1243448,
"answer_date": "2009-08-07T07:36:03.130Z",
"answer_score": 219
} |
Please answer the following Stack Overflow question:
Title: Create empty queryset by default in django form fields
<p>I have this fields in form:</p>
<pre><code>city = forms.ModelChoiceField(label="city", queryset=MyCity.objects.all())
district = forms.ModelChoiceField(label="district", queryset=MyDistrict.objects.all())
area = forms.ModelChoiceField(label="area", queryset=MyArea.objects.all())
</code></pre>
<p>district comes from click on city and area comes from click on area. With <code>queryset=MyDistrict.objects.all()</code> and <code>queryset=MyArea.objects.all()</code> form will be very heavy. How can I make querysets empty by default?</p> | <p>You can have an empty queryset by doing this:</p>
<pre><code>MyModel.objects.none()
</code></pre>
<p>Although i don't know how are you going to use that form, you can put that as your field's queryset in order to get what you need...</p>
<p>You can find more information <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#none" rel="noreferrer">here</a></p> | {
"question_id": 11243559,
"question_date": "2012-06-28T11:25:02.790Z",
"question_score": 220,
"tags": "django|django-forms",
"answer_id": 11244370,
"answer_date": "2012-06-28T12:12:29.617Z",
"answer_score": 556
} |
Please answer the following Stack Overflow question:
Title: JSHint and jQuery: '$' is not defined
<p>The following JS:</p>
<pre><code>(function() {
"use strict";
$("#target").click(function(){
console.log("clicked");
});
}());
</code></pre>
<p>Yields:</p>
<pre><code>test.js: line 5, col 3, '$' is not defined.
</code></pre>
<p>When linted using JSHint 0.5.5. Any ideas?</p> | <p>If you are using a relatively recent version of JSHint, the generally preferred approach is to create a .jshintrc file in the root of your project, and put this config in it:</p>
<pre><code>{
"globals": {
"$": false
}
}
</code></pre>
<p>This declares to JSHint that $ is a global variable, and the false indicates that it should not be overridden.</p>
<p>The .jshintrc file was not supported in really old versions of JSHint (such as v0.5.5 like the original question in 2012). If you cannot or do not want to use the .jshintrc file, you can add this at the top of the script file:</p>
<pre><code>/*globals $:false */
</code></pre>
<p>There is also a shorthand "jquery" jshint option as seen on the <a href="http://www.jshint.com/docs/options/" rel="noreferrer">JSHint options page</a>..</p> | {
"question_id": 8852765,
"question_date": "2012-01-13T15:18:10.350Z",
"question_score": 220,
"tags": "javascript|jquery|lint|jshint",
"answer_id": 8854093,
"answer_date": "2012-01-13T16:45:03.480Z",
"answer_score": 389
} |
Please answer the following Stack Overflow question:
Title: Why are Docker container images so large?
<p>I made a simple image through Dockerfile from Fedora (initially 320 MB).</p>
<p>Added Nano (this tiny editor of 1MB size), and the size of the image has risen to 530 MB. I've added Git on top of that (30-ish MB), and then my image size sky-rockets to 830 MB. </p>
<p>Isn't that insane?</p>
<p>I've tried to export and import container to remove history/intermediate images. This effort saved up to 25 MB, now my image size is 804 MB. I've also tried to run many commands on one <code>RUN</code>, but still I'm getting the same initial 830MB.</p>
<p>I'm having my doubts if it is worth to use Docker at all. I mean, I barely installed anything and I'm hitting 1GB over. If I will have to add some serious stuff like a database and so on I might run out of disk space.</p>
<p>Anyone suffers from ridiculous size of images? How do you deal with it?</p>
<p>Unless my Dockerfile is horribly incorrect?</p>
<pre><code>FROM fedora:latest
MAINTAINER Me NotYou <[email protected]>
RUN yum -y install nano
RUN yum -y install git
</code></pre>
<p>but it's hard to imagine what could go wrong in here.</p> | <p>As @rexposadas said, images include all the layers and each layer includes all the dependencies for what you installed. It is also important to note that the base images (like <code>fedora:latest</code> tend to be very bare-bones. You may be surprised by the number of dependencies your installed software has.</p>
<p>I was able to make your installation significantly smaller by adding <code>yum -y clean all</code> to each line:</p>
<pre><code>FROM fedora:latest
RUN yum -y install nano && yum -y clean all
RUN yum -y install git && yum -y clean all
</code></pre>
<p>It is important to do that for each RUN, before the layer gets committed, or else deletes don't actually remove data. That is, in a union/copy-on-write file system, cleaning at the end doesn't really reduce file system usage because the real data is already committed to lower layers. To get around this you must clean at each layer.</p>
<pre><code>$ docker history bf5260c6651d
IMAGE CREATED CREATED BY SIZE
bf5260c6651d 4 days ago /bin/sh -c yum -y install git; yum -y clean a 260.7 MB
172743bd5d60 4 days ago /bin/sh -c yum -y install nano; yum -y clean 12.39 MB
3f2fed40e4b0 2 weeks ago /bin/sh -c #(nop) ADD file:cee1a4fcfcd00d18da 372.7 MB
fd241224e9cf 2 weeks ago /bin/sh -c #(nop) MAINTAINER Lokesh Mandvekar 0 B
511136ea3c5a 12 months ago 0 B
</code></pre> | {
"question_id": 24394243,
"question_date": "2014-06-24T18:57:40.683Z",
"question_score": 220,
"tags": "docker",
"answer_id": 24397597,
"answer_date": "2014-06-24T22:48:15.467Z",
"answer_score": 140
} |
Please answer the following Stack Overflow question:
Title: Mercurial: how to amend the last commit?
<p>I'm looking for a counter-part of <code>git commit --amend</code> in Mercurial, i.e. a way to modify the commit which my working copy is linked to. I'm only interested in the last commit, not an arbitrary earlier commit.</p>
<p>The requirements for this amend-procedure are:</p>
<ul>
<li><p>if possible, it should not require any extensions. It must <strong>not require non-default extensions</strong>, i.e. extensions which do not come with an official Mercurial installation.</p></li>
<li><p>if the commit to amend is one head of my current branch, <strong>no new head</strong> should be created. If the commit is not head, a new head may be created.</p></li>
<li><p>the procedure should be <strong>safe</strong> in a way that if for whatever reasons the amending fails, I want to have the same working copy and repository state restored as before the amending. With other words, if the amending itself can fail, there should be a fail-safe procedure to restore the working copy and repository state. I'm referring to "failures" which lie in the nature of the amend-procedure (like e.g. conflicts), not to file-system-related problems (like access restrictions, not being able to lock a file for writing, ...)</p></li>
</ul>
<p><strong>Update (1):</strong></p>
<ul>
<li>the procedure must be <strong>automatable</strong>, so it can be performed by a GUI client without any user interaction required.</li>
</ul>
<p><strong>Update (2):</strong></p>
<ul>
<li>files in the working directory must not be touched (there may be file system locks on certain modified files). This especially means, that a possible approach may at no point require a clean working directory.</li>
</ul> | <p>With the release of <a href="https://www.mercurial-scm.org/wiki/WhatsNew#Mercurial_2.2_.282012-05-01.29" rel="nofollow noreferrer">Mercurial 2.2</a>, you can use the <code>--amend</code> option with <code>hg commit</code> to update the last commit with the current working directory</p>
<p>From the <a href="http://www.selenic.com/mercurial/hg.1.html#commit" rel="nofollow noreferrer">command line reference</a>:</p>
<blockquote>
<p>The --amend flag can be used to amend the parent of the working directory with a new commit that contains the changes in the parent in addition to those currently reported by hg status, if there are any. The old commit is stored in a backup bundle in .hg/strip-backup (see hg help bundle and hg help unbundle on how to restore it).</p>
<p>Message, user and date are taken from the amended commit unless specified. When a message isn't specified on the command line, the editor will open with the message of the amended commit.</p>
</blockquote>
<p>The great thing is that this mechanism is "safe", because it relies on the relatively new "Phases" feature to prevent updates that would change history that's already been made available outside of the local repository.</p> | {
"question_id": 8182858,
"question_date": "2011-11-18T13:04:02.130Z",
"question_score": 220,
"tags": "mercurial|commit|git-amend|mercurial-commit",
"answer_id": 10419831,
"answer_date": "2012-05-02T18:46:37.820Z",
"answer_score": 296
} |
Please answer the following Stack Overflow question:
Title: How to test equality of Swift enums with associated values
<p>I want to test the equality of two Swift enum values. For example:</p>
<pre><code>enum SimpleToken {
case Name(String)
case Number(Int)
}
let t1 = SimpleToken.Number(123)
let t2 = SimpleToken.Number(123)
XCTAssert(t1 == t2)
</code></pre>
<p>However, the compiler won't compile the equality expression:</p>
<pre><code>error: could not find an overload for '==' that accepts the supplied arguments
XCTAssert(t1 == t2)
^~~~~~~~~~~~~~~~~~~
</code></pre>
<p>Do I have do define my own overload of the equality operator? I was hoping the Swift compiler would handle it automatically, much like Scala and Ocaml do.</p> | <h1>Swift 4.1+</h1>
<p>As <a href="https://stackoverflow.com/users/2396171/jedwidz">@jedwidz</a> has helpfully pointed out, from Swift 4.1 (due to <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0185-synthesize-equatable-hashable.md" rel="noreferrer">SE-0185</a>, Swift also supports synthesizing <code>Equatable</code> and <code>Hashable</code> for enums with associated values.</p>
<p>So if you're on Swift 4.1 or newer, the following will automatically synthesize the necessary methods such that <code>XCTAssert(t1 == t2)</code> works. The key is to add the <code>Equatable</code> protocol to your enum.</p>
<pre class="lang-swift prettyprint-override"><code>enum SimpleToken: Equatable {
case Name(String)
case Number(Int)
}
let t1 = SimpleToken.Number(123)
let t2 = SimpleToken.Number(123)
</code></pre>
<h1>Before Swift 4.1</h1>
<p>As others have noted, Swift doesn't synthesize the necessary equality operators automatically. Let me propose a cleaner (IMHO) implementation, though:</p>
<pre class="lang-swift prettyprint-override"><code>enum SimpleToken: Equatable {
case Name(String)
case Number(Int)
}
public func ==(lhs: SimpleToken, rhs: SimpleToken) -> Bool {
switch (lhs, rhs) {
case let (.Name(a), .Name(b)),
let (.Number(a), .Number(b)):
return a == b
default:
return false
}
}
</code></pre>
<p>It's far from ideal — there's a lot of repetition — but at least you don't need to do nested switches with if-statements inside.</p> | {
"question_id": 24339807,
"question_date": "2014-06-21T08:31:44.750Z",
"question_score": 220,
"tags": "swift",
"answer_id": 26703912,
"answer_date": "2014-11-02T20:18:24.340Z",
"answer_score": 277
} |
Please answer the following Stack Overflow question:
Title: How do I improve ASP.NET MVC application performance?
<p><strong>How do you improve your ASP.NET MVC application performance?</strong></p> | <p>A compiled list of possible sources of improvement are below:</p>
<p><strong>General</strong></p>
<ul>
<li>Make use of a profiler to discover memory leaks and performance problems in your application. personally I suggest <a href="http://www.jetbrains.com/profiler/" rel="noreferrer">dotTrace</a></li>
<li>Run your site in Release mode, not Debug mode, when in production, and also during performance profiling. Release mode is much faster. Debug mode can hide performance problems in your own code.</li>
</ul>
<p><strong>Caching</strong> </p>
<ul>
<li>Use <code>CompiledQuery.Compile()</code>
recursively avoiding
recompilation of your query
expressions</li>
<li>Cache not-prone-to-change
content using <code>OutputCacheAttribute</code>
to save unnecessary and action
executions</li>
<li>Use cookies for frequently accessed non sensitive information</li>
<li>Utilize <a href="http://www.google.co.uk/search?q=asp.net+mvc+etag" rel="noreferrer">ETags</a> and expiration - Write your custom <code>ActionResult</code> methods if necessary</li>
<li>Consider using the <code>RouteName</code> to organize your routes and then use it to generate
your links, and try not to use the expression tree based ActionLink method. </li>
<li>Consider implementing a route resolution caching strategy</li>
<li>Put repetitive code inside your <code>PartialViews</code>, avoid render it <em>xxxx</em> times: if you
end up calling the same partial 300 times in the same view, probably there is something
wrong with that. <a href="http://codeclimber.net.nz/archive/2009/04/17/how-to-improve-the-performances-of-asp.net-mvc-web-applications.aspx" rel="noreferrer">Explanation And Benchmarks</a></li>
</ul>
<p><strong>Routing</strong></p>
<ul>
<li><p>Use <code>Url.RouteUrl("User", new { username = "joeuser" })</code> to specify routes. <a href="http://www.slideshare.net/rudib/aspnet-mvc-performance" rel="noreferrer">ASP.NET MVC Perfomance by Rudi Benkovic</a></p></li>
<li><p>Cache route resolving using this helper <code>UrlHelperCached</code> <a href="http://www.slideshare.net/rudib/aspnet-mvc-performance" rel="noreferrer">ASP.NET MVC Perfomance by Rudi Benkovic</a></p></li>
</ul>
<p><strong>Security</strong></p>
<ul>
<li>Use Forms Authentication, Keep your frequently accessed sensitive data in the
authentication ticket</li>
</ul>
<p><strong>DAL</strong></p>
<ul>
<li>When accessing data via LINQ <a href="https://stackoverflow.com/questions/1106802/why-use-asqueryable-instead-of-list">rely on IQueryable</a></li>
<li><a href="https://stackoverflow.com/questions/1223194/loading-subrecords-in-the-repository-pattern">Leverage the Repository pattern</a></li>
<li>Profile your queries i.e. <a href="http://hibernatingrhinos.com/products/UberProf" rel="noreferrer">Uber Profiler</a></li>
<li>Consider second level cache for your queries and add them an scope and a timeout i.e. <a href="http://nhibernate.info/blog/2009/02/09/quickly-setting-up-and-using-nhibernate-s-second-level-cache.html" rel="noreferrer">NHibernate Second Cache</a> </li>
</ul>
<p><strong>Load balancing</strong></p>
<ul>
<li><p>Utilize reverse proxies, to spread the client load across your app instance. (Stack Overflow uses <a href="http://haproxy.1wt.eu/" rel="noreferrer">HAProxy</a> (<a href="http://www.microsoft.com/casestudies/Case_Study_Detail.aspx?casestudyid=4000006676" rel="noreferrer">MSDN</a>).</p></li>
<li><p>Use <a href="http://msdn.microsoft.com/en-in/library/ee728598(v=vs.98).aspx" rel="noreferrer">Asynchronous Controllers</a> to implement actions that depend on external resources processing.</p></li>
</ul>
<p><strong>Client side</strong></p>
<ul>
<li>Optimize your client side, use a tool like <a href="http://developer.yahoo.com/yslow/" rel="noreferrer">YSlow</a> for
suggestions to improve performance</li>
<li>Use AJAX to update components of your UI, avoid a whole page update when possible.</li>
<li>Consider implement a pub-sub architecture -i.e. Comet- for content delivery against
reload based in timeouts.</li>
<li>Move charting and graph generation logic to the client side if possible. Graph generation
is a expensive activity. Deferring to the client side your server from an
unnecessary burden, and allows you to work with graphs locally without make a new
request (i.e. Flex charting, <a href="http://www.workshop.rs/jqbargraph/" rel="noreferrer">jqbargraph</a>, <a href="http://www.reynoldsftw.com/2009/02/6-jquery-chart-plugins-reviewed/" rel="noreferrer">MoreJqueryCharts</a>).</li>
<li>Use CDN's for scripts and media content to improve loading on the client side (i.e. <a href="http://code.google.com/apis/ajaxlibs/documentation/" rel="noreferrer">Google CDN</a>)</li>
<li>Minify -<a href="http://code.google.com/closure/compiler/" rel="noreferrer">Compile</a>- your JavaScript in order to improve your script size</li>
<li>Keep cookie size small, since cookies are sent to the server on every request.</li>
<li>Consider using <a href="http://en.wikipedia.org/wiki/Link_prefetching" rel="noreferrer">DNS and Link Prefetching</a> when possible.</li>
</ul>
<p><strong>Global configuration</strong></p>
<ul>
<li><p>If you use Razor, add the following code in your global.asax.cs, by default, Asp.Net MVC renders with an aspx engine and a razor engine. This only uses the RazorViewEngine. </p>
<p><code>ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());</code></p></li>
<li><p>Add gzip (HTTP compression) and static cache (images, css, ...) in your web.config
<code><system.webServer>
<urlCompression doDynamicCompression="true" doStaticCompression="true" dynamicCompressionBeforeCache="true"/>
</system.webServer></code></p></li>
<li>Remove unused HTTP Modules</li>
<li>Flush your HTML as soon as it is generated (in your web.config) and disable viewstate if you are not using it
<code><pages buffer="true" enableViewState="false"></code></li>
</ul> | {
"question_id": 2246251,
"question_date": "2010-02-11T17:25:08.230Z",
"question_score": 220,
"tags": ".net|asp.net-mvc|performance|iis",
"answer_id": 2246628,
"answer_date": "2010-02-11T18:21:38.410Z",
"answer_score": 320
} |
Please answer the following Stack Overflow question:
Title: How to pass arguments into a Rake task with environment in Rails?
<p>I am able to pass in arguments as follows:</p>
<pre><code>desc "Testing args"
task: :hello, :user, :message do |t, args|
args.with_defaults(:message => "Thanks for logging on")
puts "Hello #{args[:user]}. #{:message}"
end
</code></pre>
<p>I am also able to load the current environment for a Rails application</p>
<pre><code>desc "Testing environment"
task: :hello => :environment do
puts "Hello #{User.first.name}."
end
</code></pre>
<p>What I would like to do is be able to have variables and environment</p>
<pre><code>desc "Testing environment and variables"
task: :hello => :environment, :message do |t, args|
args.with_defaults(:message => "Thanks for logging on")
puts "Hello #{User.first.name}. #{:message}"
end
</code></pre>
<p>But that is not a valid task call. Does anyone know how I can achieve this?</p> | <h3>TLDR;</h3>
<pre><code>task :t, [args] => [deps]
</code></pre>
<h3>Original Answer</h3>
<p>When you pass in arguments to rake tasks, you can require the environment using the :needs option. For example:</p>
<pre><code>
desc "Testing environment and variables"
task :hello, :message, :needs => :environment do |t, args|
args.with_defaults(:message => "Thanks for logging on")
puts "Hello #{User.first.name}. #{args.message}"
end
</code></pre>
<p>Updated per @Peiniau's comment below </p>
<p>As for Rails > 3.1 </p>
<pre><code>task :t, arg, :needs => [deps] # deprecated
</code></pre>
<p>Please use </p>
<pre><code>task :t, [args] => [deps]
</code></pre> | {
"question_id": 1357639,
"question_date": "2009-08-31T14:07:36.167Z",
"question_score": 220,
"tags": "ruby-on-rails|ruby|rake",
"answer_id": 1357903,
"answer_date": "2009-08-31T15:03:19.213Z",
"answer_score": 121
} |
Please answer the following Stack Overflow question:
Title: What do helper and helper_method do?
<p><code>helper_method</code> is straightforward: it makes some or all of the controller's methods available to the view.</p>
<p>What is <code>helper</code>? Is it the other way around, i.e., it imports helper methods into a file or a module? (Maybe the name <code>helper</code> and <code>helper_method</code> are alike. They may rather instead be <code>share_methods_with_view</code> and <code>import_methods_from_view</code>)</p>
<p><a href="http://apidock.com/rails/ActionController/Helpers/ClassMethods/helper" rel="noreferrer">reference</a> </p> | <p>The method <code>helper_method</code> is to explicitly share some methods defined in the controller to make them available for the view. This is used for any method that you need to access from both controllers and helpers/views (standard helper methods are not available in controllers). e.g. common use case:</p>
<pre><code>#application_controller.rb
def current_user
@current_user ||= User.find_by_id!(session[:user_id])
end
helper_method :current_user
</code></pre>
<p>the <code>helper</code> method on the other hand, is for importing an entire helper to the views provided by the controller (and it's inherited controllers). What this means is doing</p>
<pre><code># application_controller.rb
helper :all
</code></pre>
<p>For Rails > 3.1</p>
<pre><code># application.rb
config.action_controller.include_all_helpers = true
# This is the default anyway, but worth knowing how to turn it off
</code></pre>
<p>makes all helper modules available to all views (at least for all controllers inheriting from application_controller.</p>
<pre><code># home_controller.rb
helper UserHelper
</code></pre>
<p>makes the UserHelper methods available to views for actions of the home controller. This is equivalent to doing:</p>
<pre><code># HomeHelper
include UserHelper
</code></pre> | {
"question_id": 3992659,
"question_date": "2010-10-21T22:55:04.453Z",
"question_score": 220,
"tags": "ruby-on-rails|helper",
"answer_id": 3993323,
"answer_date": "2010-10-22T01:40:26.193Z",
"answer_score": 320
} |
Please answer the following Stack Overflow question:
Title: "You are running create-react-app 4.0.3 which is behind the latest release (5.0.0)"
<p>I got an error while creating a React application. How do I fix it?</p>
<p><a href="https://i.stack.imgur.com/aTDJz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aTDJz.png" alt="Enter image description here" /></a></p> | <p>It's fixed. I do <code>npx [email protected] my-app</code>.</p>
<p>Reference: <em><a href="https://stackoverflow.com/questions/70358474/error-while-creating-new-react-app-you-are-running-create-react-app-4-0-3-w/70358556#70358556">Error while creating new React app ("You are running `create-react-app` 4.0.3, which is behind the latest release (5.0.0)")</a></em></p> | {
"question_id": 70358643,
"question_date": "2021-12-15T04:58:02.777Z",
"question_score": 220,
"tags": "javascript|reactjs|npm-install|yarnpkg|npx",
"answer_id": 70358793,
"answer_date": "2021-12-15T05:23:48.683Z",
"answer_score": 175
} |
Please answer the following Stack Overflow question:
Title: In a django model custom save() method, how should you identify a new object?
<p>I want to trigger a special action in the save() method of a Django model object when I'm saving a new record (not updating an existing record.)</p>
<p>Is the check for (self.id != None) necessary and sufficient to guarantee the self record is new and not being updated? Any special cases this might overlook?</p> | <p><b>Updated:</b> With the clarification that <code>self._state</code> is not a private instance variable, but named that way to avoid conflicts, checking <code>self._state.adding</code> is now the preferable way to check.</p>
<hr/>
<pre><code>self.pk is None:
</code></pre>
<p>returns True within a new Model object, unless the object has a <code>UUIDField</code> as its <code>primary_key</code>.</p>
<p>The corner case you might have to worry about is whether there are uniqueness constraints on fields other than the id (e.g., secondary unique indexes on other fields). In that case, you could still have a new record in hand, but be unable to save it.</p> | {
"question_id": 907695,
"question_date": "2009-05-25T18:45:28.487Z",
"question_score": 220,
"tags": "django|django-models",
"answer_id": 907703,
"answer_date": "2009-05-25T18:49:03.630Z",
"answer_score": 237
} |
Please answer the following Stack Overflow question:
Title: Where to place AutoMapper.CreateMaps?
<p>I'm using <code>AutoMapper</code> in an <code>ASP.NET MVC</code> application. I was told that I should move the <code>AutoMapper.CreateMap</code> elsewhere as they have a lot of overhead. I'm not too sure how to design my application to put these calls in just 1 place.</p>
<p>I have a web layer, service layer and a data layer. Each a project of its own. I use <code>Ninject</code> to DI everything. I'll utilize <code>AutoMapper</code> in both web and service layers. </p>
<p>So what are your setup for <code>AutoMapper</code>'s CreateMap? Where do you put it? How do you call it?</p> | <p>Doesn't matter, as long as it's a static class. It's all about <em>convention</em>.</p>
<p>Our <em>convention</em> is that each "layer" (web, services, data) has a single file called <code>AutoMapperXConfiguration.cs</code>, with a single method called <code>Configure()</code>, where <code>X</code> is the layer.</p>
<p>The <code>Configure()</code> method then calls <code>private</code> methods for each area.</p>
<p>Here's an example of our web tier config:</p>
<pre><code>public static class AutoMapperWebConfiguration
{
public static void Configure()
{
ConfigureUserMapping();
ConfigurePostMapping();
}
private static void ConfigureUserMapping()
{
Mapper.CreateMap<User,UserViewModel>();
}
// ... etc
}
</code></pre>
<p>We create a method for each "aggregate" (User, Post), so things are separated nicely.</p>
<p>Then your <code>Global.asax</code>:</p>
<pre><code>AutoMapperWebConfiguration.Configure();
AutoMapperServicesConfiguration.Configure();
AutoMapperDomainConfiguration.Configure();
// etc
</code></pre>
<p>It's kind of like an "interface of words" - can't enforce it, but you expect it, so you can code (and refactor) if necessary.</p>
<p><strong>EDIT:</strong></p>
<p>Just thought I'd mention that I now use AutoMapper <a href="https://github.com/AutoMapper/AutoMapper/wiki/Configuration">profiles</a>, so the above example becomes:</p>
<pre><code>public static class AutoMapperWebConfiguration
{
public static void Configure()
{
Mapper.Initialize(cfg =>
{
cfg.AddProfile(new UserProfile());
cfg.AddProfile(new PostProfile());
});
}
}
public class UserProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<User,UserViewModel>();
}
}
</code></pre>
<p>Much cleaner/more robust.</p> | {
"question_id": 6825244,
"question_date": "2011-07-26T04:25:02.107Z",
"question_score": 220,
"tags": "asp.net-mvc|design-patterns|configuration|automapper",
"answer_id": 6825394,
"answer_date": "2011-07-26T04:51:44.627Z",
"answer_score": 223
} |
Please answer the following Stack Overflow question:
Title: Changing names of parameterized tests
<p>Is there a way to set my own custom test case names when using parameterized tests in JUnit4?</p>
<p>I'd like to change the default — <code>[Test class].runTest[n]</code> — to something meaningful.</p> | <p><strong>This feature has made it into <a href="https://github.com/junit-team/junit/wiki/Download-and-Install" rel="noreferrer">JUnit 4.11</a>.</strong></p>
<p>To use change the name of parameterized tests, you say:</p>
<pre><code>@Parameters(name="namestring")
</code></pre>
<p><em><code>namestring</code></em> is a string, which can have the following special placeholders:</p>
<ul>
<li><code>{index}</code> - the index of this set of arguments. The default <em><code>namestring</code></em> is <code>{index}</code>.</li>
<li><code>{0}</code> - the first parameter value from this invocation of the test.</li>
<li><code>{1}</code> - the second parameter value</li>
<li>and so on</li>
</ul>
<p>The final name of the test will be the name of the test method, followed by the <em><code>namestring</code></em> in brackets, as shown below.</p>
<p>For example (adapted from the unit test for the <code>Parameterized</code> annotation):</p>
<pre><code>@RunWith(Parameterized.class)
static public class FibonacciTest {
@Parameters( name = "{index}: fib({0})={1}" )
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
{ 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
}
private final int fInput;
private final int fExpected;
public FibonacciTest(int input, int expected) {
fInput= input;
fExpected= expected;
}
@Test
public void testFib() {
assertEquals(fExpected, fib(fInput));
}
private int fib(int x) {
// TODO: actually calculate Fibonacci numbers
return 0;
}
}
</code></pre>
<p>will give names like <code>testFib[1: fib(1)=1]</code> and <code>testFib[4: fib(4)=3]</code>. (The <code>testFib</code> part of the name is the method name of the <code>@Test</code>).</p> | {
"question_id": 650894,
"question_date": "2009-03-16T15:25:21.987Z",
"question_score": 220,
"tags": "java|junit|junit4|parameterized",
"answer_id": 10143872,
"answer_date": "2012-04-13T15:34:58.697Z",
"answer_score": 329
} |
Please answer the following Stack Overflow question:
Title: Mimicking sets in JavaScript?
<p>I'm working in JavaScript. I'd like to store a list of <em>unique</em>, unordered string values, with the following properties:</p>
<ol>
<li>a fast way to ask 'is A in the list'?</li>
<li>a fast way to do 'delete A from the list if it exists in the list'</li>
<li>a fast way to do 'add A to the list if it is not already present'.</li>
</ol>
<p>What I really want is a set. Any suggestions for the best way to mimic a set in JavaScript?</p>
<p>This <a href="https://stackoverflow.com/questions/5657219/set-of-objects-in-javascript">question recommends using an Object</a>, with the keys storing properties, and the values all set to true: is that a sensible way?</p> | <p>If you are programming in an ES6-capable environment (such as node.js, a specific browser with the ES6 capabilities you need or transpiling ES6 code for your environment), then you can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set" rel="nofollow noreferrer"><code>Set</code> object built into ES6</a>. It has very nice capabilities and can be used as is right in your environment.</p>
<hr />
<p>For many simple things in an ES5 environment, using an Object works very well. If <code>obj</code> is your object and <code>A</code> is a variable that has the value you want to operate on in the set, then you can do these:</p>
<p>Initialization code:</p>
<pre><code>// create empty object
var obj = {};
// or create an object with some items already in it
var obj = {"1":true, "2":true, "3":true, "9":true};
</code></pre>
<p><strong>Question 1:</strong> Is <code>A</code> in the list:</p>
<pre><code>if (A in obj) {
// put code here
}
</code></pre>
<p><strong>Question 2:</strong> Delete 'A' from the list if it's there:</p>
<pre><code>delete obj[A];
</code></pre>
<p><strong>Question 3:</strong> Add 'A' to the list if it wasn't already there</p>
<pre><code>obj[A] = true;
</code></pre>
<hr />
<p>For completeness, the test for whether <code>A</code> is in the list is a little safer with this:</p>
<pre><code>if (Object.prototype.hasOwnProperty.call(obj, A))
// put code here
}
</code></pre>
<p>because of potential conflict between built-in methods and/or properties on the base Object like the <code>constructor</code> property.</p>
<hr />
<p><strong>Sidebar on ES6:</strong> The current working version of <strong>ECMAScript 6</strong> or somethings called ES 2015 has a <strong>built-in Set object</strong>. It is implemented now in some browsers. Since browser availability changes over time, you can look at the line for <code>Set</code> in <a href="https://kangax.github.io/compat-table/es6/" rel="nofollow noreferrer">this ES6 compatibility table</a> to see the current status for browser availability.</p>
<p>One advantage of the built-in Set object is that it doesn't coerce all keys to a string like the Object does so you can have both 5 and "5" as separate keys. And, you can even use Objects directly in the set without a string conversion. Here's <a href="http://www.nczonline.net/blog/2012/09/25/ecmascript-6-collections-part-1-sets/" rel="nofollow noreferrer">an article</a> that describes some of the capabilities and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set" rel="nofollow noreferrer">MDN's documentation</a> on the Set object.</p>
<p>I have now written a polyfill for the ES6 set object so you could start using that now and it will automatically defer to the built-in set object if the browser supports it. This has the advantage that you're writing ES6 compatible code that will work all the way back to IE7. But, there are some downsides. The ES6 set interface takes advantage of the ES6 iterators so you can do things like <code>for (item of mySet)</code> and it will automatically iterate through the set for you. But, this type of language feature cannot be implemented via polyfill. You can still iterate an ES6 set without using the new ES6 languages features, but frankly without the new language features, it isn't as convenient as the other set interface I include below.</p>
<p>You can decide which one works best for you after looking at both. The ES6 set polyfill is here: <a href="https://github.com/jfriend00/ES6-Set" rel="nofollow noreferrer">https://github.com/jfriend00/ES6-Set</a>.</p>
<p>FYI, in my own testing, I've noticed that the Firefox v29 Set implementation is not fully up-to-date on the current draft of the spec. For example, you can't chain <code>.add()</code> method calls like the spec describes and my polyfill supports. This is probably a matter of a specification in motion as it is not yet finalized.</p>
<hr />
<p><strong>Pre-Built Set objects:</strong> If you want an already built object that has methods for operating on a set that you can use in any browser, you can use a series of different pre-built objects that implement different types of sets. There is a miniSet which is small code that implements the basics of a set object. It also has a more feature rich set object and several derivations including a Dictionary (let's you store/retrieve a value for each key) and an ObjectSet (let's you keep a set of objects - either JS objects or DOM objects where you either supply the function that generates a unique key for each one or the ObjectSet will generate the key for you).</p>
<p>Here's a copy of the code for the miniSet (most up-to-date code is <a href="https://github.com/jfriend00/Javascript-Set" rel="nofollow noreferrer">here on github</a>).</p>
<pre><code>"use strict";
//-------------------------------------------
// Simple implementation of a Set in javascript
//
// Supports any element type that can uniquely be identified
// with its string conversion (e.g. toString() operator).
// This includes strings, numbers, dates, etc...
// It does not include objects or arrays though
// one could implement a toString() operator
// on an object that would uniquely identify
// the object.
//
// Uses a javascript object to hold the Set
//
// This is a subset of the Set object designed to be smaller and faster, but
// not as extensible. This implementation should not be mixed with the Set object
// as in don't pass a miniSet to a Set constructor or vice versa. Both can exist and be
// used separately in the same project, though if you want the features of the other
// sets, then you should probably just include them and not include miniSet as it's
// really designed for someone who just wants the smallest amount of code to get
// a Set interface.
//
// s.add(key) // adds a key to the Set (if it doesn't already exist)
// s.add(key1, key2, key3) // adds multiple keys
// s.add([key1, key2, key3]) // adds multiple keys
// s.add(otherSet) // adds another Set to this Set
// s.add(arrayLikeObject) // adds anything that a subclass returns true on _isPseudoArray()
// s.remove(key) // removes a key from the Set
// s.remove(["a", "b"]); // removes all keys in the passed in array
// s.remove("a", "b", ["first", "second"]); // removes all keys specified
// s.has(key) // returns true/false if key exists in the Set
// s.isEmpty() // returns true/false for whether Set is empty
// s.keys() // returns an array of keys in the Set
// s.clear() // clears all data from the Set
// s.each(fn) // iterate over all items in the Set (return this for method chaining)
//
// All methods return the object for use in chaining except when the point
// of the method is to return a specific value (such as .keys() or .isEmpty())
//-------------------------------------------
// polyfill for Array.isArray
if(!Array.isArray) {
Array.isArray = function (vArg) {
return Object.prototype.toString.call(vArg) === "[object Array]";
};
}
function MiniSet(initialData) {
// Usage:
// new MiniSet()
// new MiniSet(1,2,3,4,5)
// new MiniSet(["1", "2", "3", "4", "5"])
// new MiniSet(otherSet)
// new MiniSet(otherSet1, otherSet2, ...)
this.data = {};
this.add.apply(this, arguments);
}
MiniSet.prototype = {
// usage:
// add(key)
// add([key1, key2, key3])
// add(otherSet)
// add(key1, [key2, key3, key4], otherSet)
// add supports the EXACT same arguments as the constructor
add: function() {
var key;
for (var i = 0; i < arguments.length; i++) {
key = arguments[i];
if (Array.isArray(key)) {
for (var j = 0; j < key.length; j++) {
this.data[key[j]] = key[j];
}
} else if (key instanceof MiniSet) {
var self = this;
key.each(function(val, key) {
self.data[key] = val;
});
} else {
// just a key, so add it
this.data[key] = key;
}
}
return this;
},
// private: to remove a single item
// does not have all the argument flexibility that remove does
_removeItem: function(key) {
delete this.data[key];
},
// usage:
// remove(key)
// remove(key1, key2, key3)
// remove([key1, key2, key3])
remove: function(key) {
// can be one or more args
// each arg can be a string key or an array of string keys
var item;
for (var j = 0; j < arguments.length; j++) {
item = arguments[j];
if (Array.isArray(item)) {
// must be an array of keys
for (var i = 0; i < item.length; i++) {
this._removeItem(item[i]);
}
} else {
this._removeItem(item);
}
}
return this;
},
// returns true/false on whether the key exists
has: function(key) {
return Object.prototype.hasOwnProperty.call(this.data, key);
},
// tells you if the Set is empty or not
isEmpty: function() {
for (var key in this.data) {
if (this.has(key)) {
return false;
}
}
return true;
},
// returns an array of all keys in the Set
// returns the original key (not the string converted form)
keys: function() {
var results = [];
this.each(function(data) {
results.push(data);
});
return results;
},
// clears the Set
clear: function() {
this.data = {};
return this;
},
// iterate over all elements in the Set until callback returns false
// myCallback(key) is the callback form
// If the callback returns false, then the iteration is stopped
// returns the Set to allow method chaining
each: function(fn) {
this.eachReturn(fn);
return this;
},
// iterate all elements until callback returns false
// myCallback(key) is the callback form
// returns false if iteration was stopped
// returns true if iteration completed
eachReturn: function(fn) {
for (var key in this.data) {
if (this.has(key)) {
if (fn.call(this, this.data[key], key) === false) {
return false;
}
}
}
return true;
}
};
MiniSet.prototype.constructor = MiniSet;
</code></pre> | {
"question_id": 7958292,
"question_date": "2011-10-31T18:56:08.690Z",
"question_score": 220,
"tags": "javascript",
"answer_id": 7958422,
"answer_date": "2011-10-31T19:06:50.790Z",
"answer_score": 263
} |
Please answer the following Stack Overflow question:
Title: Should private helper methods be static if they can be static
<p>Let's say I have a class designed to be instantiated. I have several private "helper" methods inside the class that do not require access to any of the class members, and operate solely on their arguments, returning a result.</p>
<pre><code>public class Example {
private Something member;
public double compute() {
double total = 0;
total += computeOne(member);
total += computeMore(member);
return total;
}
private double computeOne(Something arg) { ... }
private double computeMore(Something arg) {... }
}
</code></pre>
<p>Is there any particular reason to specify <code>computeOne</code> and <code>computeMore</code> as static methods - or any particular reason not to?</p>
<p>It is certainly easiest to leave them as non-static, even though they could certainly be static without causing any problems.</p> | <p>I prefer such helper methods to be <code>private static</code>; which will make it clear to the reader that they will not modify the state of the object. My IDE will also show calls to static methods in italics, so I will know the method is static without looking the signature.</p> | {
"question_id": 538870,
"question_date": "2009-02-11T21:24:32.597Z",
"question_score": 220,
"tags": "java|static|methods|static-methods",
"answer_id": 538914,
"answer_date": "2009-02-11T21:33:45.087Z",
"answer_score": 178
} |
Please answer the following Stack Overflow question:
Title: Library? Static? Dynamic? Or Framework? Project inside another project
<p>I have an existing iOS app and want to add a large chunk of code that I've been developing as another project just for ease of testing. The new chunk basically deals with saving an image to various sharing services, etc.. Because that sharing code needs a lot of testing and future updating, I was wondering what the best way to incorporate that code chunk into my existing app.</p>
<p>I don't know if it should be a static library, dynamic library or a framework, and honestly, I'm not really sure what the difference is, or how I should go about it and get it set up in Xcode.</p>
<p>All I know is that I need/want to keep a separate testing and updating app for the sharing code and have the main app use it.</p> | <p>First, some general definitions (specific to iOS):</p>
<p><strong>Static library</strong> - a unit of code linked at compile time, which does not change. </p>
<p>However, iOS static libraries are <strong>not</strong> allowed to contain images/assets (only code). You can get around this challenge by using a <strong>media bundle</strong> though.</p>
<p>A better, more formal definition can be found on Wikipedia <a href="http://en.wikipedia.org/wiki/Static_library" rel="noreferrer"> here</a>.</p>
<p><strong>Dynamic library</strong> - a unit of code and/or assets linked at runtime that <em>may</em> change. </p>
<p>However, only Apple is allowed to create dynamic libraries for iOS . You're not allowed to create these, as this will get your app rejected. (See <a href="https://stackoverflow.com/questions/4733847/can-you-build-dynamic-libraries-for-ios-and-load-them-at-runtime">this</a> other SO post for confirmation and reasoning on such).</p>
<p><strong>Software Framework</strong> - a compiled set of code that accomplishes a task... hence, you can actually have a <strong>static framework</strong> or a <strong>dynamic framework</strong>, which are typically just the compiled versions of the above.</p>
<p>See the <a href="http://en.wikipedia.org/wiki/Software_framework" rel="noreferrer">Wiki on Software Framework</a> for more details.</p>
<p>Hence on iOS, your only option is basically to use a static library or static framework (the main difference being that a static framework is distributed as a compiled <code>.a</code> file most often, whereas a static library may simply be included as a subproject - you can see all of the code - which is compiled first and its resulting <code>.a</code> file used as a dependency by the project).</p>
<p>Now that we're clear(er) on these terms, setting up a static library and supporting media bundle for iOS isn't too difficult, and there are many tutorials on how to do such. I personally would recommend this one:</p>
<p><a href="https://github.com/jverkoey/iOS-Framework" rel="noreferrer">https://github.com/jverkoey/iOS-Framework</a></p>
<p>This is a pretty straight-forward guide and doesn't have the disadvantage of dealing with "fake static libraries"... check it out for more info...</p>
<p>Once you've created your static library, it's as easy as including it as a <em>submodule</em> within Git for use across different projects.</p>
<p>Good Luck.</p>
<p><strong>EDIT</strong></p>
<p>Regarding a <em>subproject</em> within a project, as far as I know, to get this to work/compile correctly, you essentially have to set up a compile chain where the subproject is compiled first, which creates a static framework <code>.a</code> file that is used as a dependency by the project.</p>
<p>Here's another useful tutorial which talks about this:</p>
<p><a href="http://www.cocoanetics.com/2011/12/sub-projects-in-xcode/" rel="noreferrer">http://www.cocoanetics.com/2011/12/sub-projects-in-xcode/</a></p>
<p><strong>EDIT 2</strong></p>
<p>As of iOS 8, Apple now permits developers to create dynamic frameworks! (Note: your app must have a minimum target of iOS 8 to include a dynamic framework... back porting isn't allowed.)</p>
<p>This has been added as a new project template. In Xcode 6.1, this can be found at:</p>
<pre><code>New Project -> iOS -> Framework & Library -> Cocoa Touch Framework
</code></pre> | {
"question_id": 15331056,
"question_date": "2013-03-11T04:07:49.213Z",
"question_score": 220,
"tags": "ios|xcode|frameworks|static-libraries|dynamic-library",
"answer_id": 15331319,
"answer_date": "2013-03-11T04:41:05.843Z",
"answer_score": 253
} |
Please answer the following Stack Overflow question:
Title: Seeing escape characters when pressing the arrow keys in python shell
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p>
<p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p>
<pre><code>>>> import os
>>> ^[[A
</code></pre>
<p>where the last character comes from arrow-up. Or, using arrow-left:</p>
<pre><code>>>> impor^[[D
</code></pre>
<p>How can I fix this?</p>
<p>In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.</p> | <p>Looks like readline is not enabled. Check if <code>PYTHONSTARTUP</code> variable is defined, for me it points to <code>/etc/pythonstart</code> and that file is executed by the python process before going interactive, which setups readline/history handling.</p>
<p>Thanks to @chown here is the docs on this: <a href="http://docs.python.org/2/tutorial/interactive.html" rel="noreferrer">http://docs.python.org/2/tutorial/interactive.html</a></p> | {
"question_id": 893053,
"question_date": "2009-05-21T13:55:32.420Z",
"question_score": 220,
"tags": "python|shell|ssh|arrow-keys",
"answer_id": 893200,
"answer_date": "2009-05-21T14:27:22.183Z",
"answer_score": 39
} |
Please answer the following Stack Overflow question:
Title: How to find which promises are unhandled in Node.js UnhandledPromiseRejectionWarning?
<p>Node.js from version 7 has async/await syntactic sugar for handling promises and now in my code the following warning comes up quite often: </p>
<pre><code>(node:11057) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): ReferenceError: Error: Can't set headers
after they are sent.
(node:11057) DeprecationWarning: Unhandled promise rejections are
deprecated. In the future, promise rejections that are not handled
will terminate the Node.js process with a non-zero exit code.
</code></pre>
<p>Unfortunately there's no reference to the line where the catch is missing.
Is there any way to find it without checking every try/catch block?</p> | <p>listen <a href="https://nodejs.org/api/process.html#process_event_unhandledrejection" rel="noreferrer"><code>unhandledRejection</code></a> event of process.</p>
<pre><code>process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
// application specific logging, throwing an error, or other logic here
});
</code></pre> | {
"question_id": 43834559,
"question_date": "2017-05-07T17:31:40.647Z",
"question_score": 220,
"tags": "node.js|promise|async-await|warnings|unhandled-exception",
"answer_id": 43994999,
"answer_date": "2017-05-16T07:27:00.050Z",
"answer_score": 355
} |
Please answer the following Stack Overflow question:
Title: return statement vs exit() in main()
<p>Should I use <code>exit()</code> or just <code>return</code> statements in <code>main()</code>? Personally I favor the <code>return</code> statements because I feel it's like reading any other function and the flow control when I'm reading the code is smooth (in my opinion). And even if I want to refactor the <code>main()</code> function, having <code>return</code> seems like a better choice than <code>exit()</code>.</p>
<p>Does <code>exit()</code> do anything special that <code>return</code> doesn't?</p> | <p>Actually, there <em>is</em> a difference, but it's subtle. It has more implications for C++, but the differences are important.</p>
<p>When I call <code>return</code> in <code>main()</code>, destructors will be called for my locally scoped objects. If I call <code>exit()</code>, <strong>no destructor will be called for my locally scoped objects!</strong> Re-read that. <code>exit()</code> <strong>does not return</strong>. That means that once I call it, there are "no backsies." Any objects that you've created in that function will not be destroyed. Often this has no implications, but sometimes it does, like closing files (surely you want all your data flushed to disk?).</p>
<p>Note that <code>static</code> objects will be cleaned up even if you call <code>exit()</code>. Finally note, that if you use <code>abort()</code>, no objects will be destroyed. That is, no global objects, no static objects and no local objects will have their destructors called.</p>
<p><strong>Proceed with caution when favoring exit over return.</strong></p>
<p><a href="http://groups.google.com/group/gnu.gcc.help/msg/8348c50030cfd15a" rel="noreferrer">http://groups.google.com/group/gnu.gcc.help/msg/8348c50030cfd15a</a></p> | {
"question_id": 461449,
"question_date": "2009-01-20T14:15:10.780Z",
"question_score": 220,
"tags": "c++|c|coding-style|return|exit",
"answer_id": 461528,
"answer_date": "2009-01-20T14:30:54.290Z",
"answer_score": 303
} |
Please answer the following Stack Overflow question:
Title: Opposite of push();
<p>What is the opposite of the JavaScript <code>push();</code> method?</p>
<p>Say I had an array:</p>
<pre><code>var exampleArray = ['remove'];
</code></pre>
<p>I want to <code>push();</code> the word <code>'keep'</code> -</p>
<pre><code>exampleArray.push('keep');
</code></pre>
<p>How do I delete the string <code>'remove'</code> from the array?</p> | <p>Well, you've kind of asked two questions. The opposite of <code>push()</code> (as the question is titled) is <code>pop()</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var exampleArray = ['myName'];
exampleArray.push('hi');
console.log(exampleArray);
exampleArray.pop();
console.log(exampleArray);</code></pre>
</div>
</div>
</p>
<p><code>pop()</code> will remove the last element from <code>exampleArray</code> and return that element ("hi") but it will not delete the string "myName" from the array because "myName" is not the last element. </p>
<p>What you need is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift" rel="noreferrer"><code>shift()</code></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice" rel="noreferrer"><code>splice()</code></a>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var exampleArray = ['myName'];
exampleArray.push('hi');
console.log(exampleArray);
exampleArray.shift();
console.log(exampleArray);</code></pre>
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var exampleArray = ['myName'];
exampleArray.push('hi');
console.log(exampleArray);
exampleArray.splice(0, 1);
console.log(exampleArray);</code></pre>
</div>
</div>
</p>
<p>For more array methods, see: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Mutator_methods" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Mutator_methods</a></p> | {
"question_id": 25517633,
"question_date": "2014-08-27T01:35:58.167Z",
"question_score": 220,
"tags": "javascript|arrays|push",
"answer_id": 25517796,
"answer_date": "2014-08-27T01:56:25.693Z",
"answer_score": 144
} |
Please answer the following Stack Overflow question:
Title: When flexbox items wrap in column mode, container does not grow its width
<p>I am working on a nested flexbox layout which should work as follows:</p>
<p>The outermost level (<code>ul#main</code>) is a horizontal list that must expand to the right when more items are added to it. If it grows too big, there should be a horizontal scroll bar.</p>
<pre><code>#main {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
overflow-x: auto;
/* ...and more... */
}
</code></pre>
<p>Each item of this list (<code>ul#main > li</code>) has a header (<code>ul#main > li > h2</code>) and an inner list (<code>ul#main > li > ul.tasks</code>). This inner list is vertical and should wrap into columns when needed. When wrapping into more columns, its width should increase to make room for more items. This width increase should apply also to the containing item of the outer list.</p>
<pre><code>.tasks {
flex-direction: column;
flex-wrap: wrap;
/* ...and more... */
}
</code></pre>
<p>My problem is that the inner lists don't wrap when the height of the window gets too small. I have tried lots of tampering with all the flex properties, trying to follow the guidelines at <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/" rel="noreferrer">CSS-Tricks</a> meticulously, but no luck.</p>
<p>This <a href="http://jsfiddle.net/4p8fpLms/" rel="noreferrer">JSFiddle</a> shows what I have so far.</p>
<p><strong>Expected result</strong> <em>(what I want)</em>:</p>
<p><img src="https://i.stack.imgur.com/urybZ.png" alt="My desired output"></p>
<p><strong>Actual result</strong> <em>(what I get)</em>:</p>
<p><img src="https://i.stack.imgur.com/YAVx2.png" alt="My current output"></p>
<p><strong>Older result</strong> <em>(what I got in 2015)</em>:</p>
<p><img src="https://i.stack.imgur.com/t5SQd.png" alt="My older output"></p>
<h2>UPDATE</h2>
<p>After some investigation, this is beginning to look like a bigger issue. <strong>All major browsers behave the same way</strong>, and it has nothing to do with my flexbox design being nested. Even simpler flexbox column layouts refuse to increase the list's width when the items wrap.</p>
<p>This <a href="http://jsfiddle.net/nwccdwLw/1/" rel="noreferrer">other JSFiddle</a> clearly demonstrates the problem. In current versions of Chrome, Firefox and IE11, all items wrap correctly; the list's height increases in <code>row</code> mode, but its width does not increase in <code>column</code> mode. Also, there is no immediate reflow of elements at all when changing the height of a <code>column</code> mode, but there is in <code>row</code> mode.</p>
<p>However, the <a href="http://www.w3.org/TR/css-flexbox-1/#flex-flow-property" rel="noreferrer">official specs <em>(look specifically at example 5)</em></a> seem to indicate that what I want to do should be possible.</p>
<p>Can someone come up with a workaround to this problem?</p>
<h2>UPDATE 2</h2>
<p>After a lot of experimenting using JavaScript to update the height and width of various elements during resize events, I have come to the conclusion that it is too complex and too much trouble to try to solve it that way. Also, adding JavaScript definitely breaks the flexbox model, which should be kept as clean as possible.</p>
<p>For now, I'm falling back to <code>overflow-y: auto</code> instead of <code>flex-wrap: wrap</code> so that the inner container scrolls vertically when needed. It is not pretty, but it is one way forward that at least does not break useability too much.</p> | <h3>The Problem</h3>
<p>This looks like a fundamental deficiency in flex layout.</p>
<p>A flex container in column-direction will not expand to accommodate additional columns. (This is not a problem in <code>flex-direction: row</code>.)</p>
<p>This question has been asked many times (see list below), with no clean answers in CSS.</p>
<p>It's hard to pin this as a bug because the problem occurs across all major browsers. But it does raise the question:</p>
<blockquote>
<p>How is it possible that all major browsers got the flex container to
expand on wrap in row-direction but not in column-direction?</p>
</blockquote>
<p>You would think at least one of them would get it right. I can only speculate on the reason. Maybe it was a technically difficult implementation and was shelved for this iteration.</p>
<p><strong>UPDATE:</strong> The issue appears to be resolved in Edge v16.</p>
<hr />
<h3>Illustration of the Problem</h3>
<p>The OP created a useful demo illustrating the problem. I'm copying it here: <a href="http://jsfiddle.net/nwccdwLw/1/" rel="noreferrer">http://jsfiddle.net/nwccdwLw/1/</a></p>
<hr />
<h3>Workaround Options</h3>
<p>Hacky solutions from the Stack Overflow community:</p>
<ul>
<li><p><a href="https://stackoverflow.com/a/26231447/3597276">"It seems this issue cannot be solved only with CSS, so I propose you a JQuery solution."</a></p>
</li>
<li><p><a href="https://stackoverflow.com/a/41209546/3597276">"It's curious that most browsers haven't implemented column flex containers correctly, but the support for writing modes is reasonably good. Therefore, you can use a row flex container with a vertical writing mode."</a></p>
</li>
</ul>
<hr />
<h3>More Analysis</h3>
<ul>
<li><p><a href="https://bugs.chromium.org/p/chromium/issues/detail?id=507397" rel="noreferrer">Chromium Bug Report</a></p>
</li>
<li><p><a href="https://stackoverflow.com/a/41209186/3597276">Mark Amery's answer</a></p>
</li>
</ul>
<hr />
<h3>Other Posts Describing the Same Problem</h3>
<ul>
<li><a href="https://stackoverflow.com/q/28882458/3597276">Flex box container width doesn't grow</a></li>
<li><a href="https://stackoverflow.com/q/23408539/3597276">How can I make a display:flex container expand horizontally with its wrapped contents?</a></li>
<li><a href="https://stackoverflow.com/q/31135650/3597276">Flex-flow: column wrap. How to set container's width equal to content?</a></li>
<li><a href="https://stackoverflow.com/q/25555816/3597276">Flexbox flex-flow column wrap bugs in chrome?</a></li>
<li><a href="https://stackoverflow.com/q/18669216/3597276">How do I use "flex-flow: column wrap"?</a></li>
<li><a href="https://stackoverflow.com/q/34028493/3597276">Flex container doesn't expand when contents wrap in a column</a></li>
<li><a href="https://stackoverflow.com/q/35919908/3597276">flex-flow: column wrap, in a flex box causing overflow of parent container</a></li>
<li><a href="https://stackoverflow.com/q/26744648/3597276">Html flexbox container does not expand over wrapped children</a></li>
<li><a href="https://stackoverflow.com/q/36436476/3597276">Flexbox container and overflowing flex children?</a></li>
<li><a href="https://stackoverflow.com/q/29225296/3597276">How can I make a flexbox container that stretches to fit wrapped items?</a></li>
<li><a href="https://stackoverflow.com/q/37738257/3597276">Flex container calculating one column, when there are multiple columns</a></li>
<li><a href="https://stackoverflow.com/q/38202557/3597276">Make container full width with flex</a></li>
<li><a href="https://stackoverflow.com/q/40791544/3597276">Flexbox container resize possible?</a></li>
<li><a href="https://stackoverflow.com/q/42255391/937377">Flex-Wrap Inside Flex-Grow</a></li>
<li><a href="https://stackoverflow.com/q/43859223/3597276">Flexbox grow to contain</a></li>
<li><a href="https://stackoverflow.com/q/45733244/3597276">Expand flexbox element to its contents?</a></li>
<li><a href="https://stackoverflow.com/q/47452689/3597276">flexbox column stretch to fit content</a></li>
<li><a href="https://stackoverflow.com/q/48406237/3597276">https://stackoverflow.com/q/48406237/3597276</a></li>
<li><a href="https://stackoverflow.com/q/49801934/3597276">flex-flow: column wrap doesn't stretch the parent element's width</a></li>
<li><a href="https://stackoverflow.com/q/53122152/3597276">Why doesn't my <ul> expand width to cover all the <li>?</a></li>
<li><a href="https://stackoverflow.com/q/55709208/3597276">https://stackoverflow.com/q/55709208/3597276</a></li>
<li><a href="https://stackoverflow.com/q/56857047/3597276">Flexbox wrap not increasing the width of parent?</a></li>
<li><a href="https://stackoverflow.com/q/68745816/3597276">Absolute Flex container not changing to the correct width with defined max-height</a></li>
</ul> | {
"question_id": 33891709,
"question_date": "2015-11-24T10:55:00.110Z",
"question_score": 220,
"tags": "html|css|flexbox",
"answer_id": 33899301,
"answer_date": "2015-11-24T16:46:46.993Z",
"answer_score": 226
} |
Please answer the following Stack Overflow question:
Title: What are Flask Blueprints, exactly?
<p>I <em>have</em> read <a href="http://flask.pocoo.org/docs/blueprints/">the official Flask documentation</a> on Blueprints and even <a href="http://maximebf.com/blog/2012/11/getting-bigger-with-flask/#.U6ttiZSwK7M">one</a> or <a href="http://charlesleifer.com/blog/dont-sweat-small-stuff-use-flask-blueprints/">two</a> blog posts on using them.</p>
<p>I've even used them in my web app, but I don't completely understand what they are or how they fit into my app as a whole. How is it similar to an instance of my app but not quite? The documentation is comprehensive but I seek a layman explanation or an enlightening analogy to spark it for me. I was sufficiently perplexed when a colleague asked me to explain a Flask blueprint to them that I elected to ask here.</p> | <p>A blueprint is a template for generating a "section" of a web application. You can think of it as a mold:</p>
<p><img src="https://i.stack.imgur.com/kd1XW.jpg" alt="A medallion mold with a gold medallion freshly removed from it"></p>
<p>You can take the blueprint and apply it to your application in several places. Each time you apply it the blueprint will create a new version of its structure in the plaster of your application.</p>
<pre><code># An example
from flask import Blueprint
tree_mold = Blueprint("mold", __name__)
@tree_mold.route("/leaves")
def leaves():
return "This tree has leaves"
@tree_mold.route("/roots")
def roots():
return "And roots as well"
@tree_mold.route("/rings")
@tree_mold.route("/rings/<int:year>")
def rings(year=None):
return "Looking at the rings for {year}".format(year=year)
</code></pre>
<p>This is a simple mold for working with trees - it says that any application that deals with trees should provide access to its leaves, its roots, and its rings (by year). By itself, it is a hollow shell - it cannot route, it cannot respond, until it is impressed upon an application:</p>
<pre><code>from tree_workshop import tree_mold
app.register_blueprint(tree_mold, url_prefix="/oak")
app.register_blueprint(tree_mold, url_prefix="/fir")
app.register_blueprint(tree_mold, url_prefix="/ash")
</code></pre>
<p>Once it is created it may be "impressed" on the application by using the <code>register_blueprint</code> function - this "impresses" the mold of the blueprint on the application at the locations specified by <code>url_prefix</code>.</p> | {
"question_id": 24420857,
"question_date": "2014-06-26T00:50:32.830Z",
"question_score": 220,
"tags": "python|flask|wsgi",
"answer_id": 24420993,
"answer_date": "2014-06-26T01:11:21.817Z",
"answer_score": 323
} |
Please answer the following Stack Overflow question:
Title: Backwards migration with Django South
<p>Ok, so this seems like a really silly thing to ask, and I'm sure I'm missing something somewhere.</p>
<p>How do you perform a backwards migration using South on Django?</p>
<p>So I've tweaked my models, created a migration with <code>schemamigration</code>, run the migration with <code>migrate</code>, and now I realise that's not quite what I wanted and I want it back the way before.</p>
<p>Short of manually editing db tables and removing migration files, how should I go about rolling the migration back? I find references to backward migrations using South via Google, but have yet to find a solid code example for it.</p>
<p>Can anyone help?</p> | <p>You need to figure out the number of the migration <em>just before</em> the one you want to roll back.</p>
<p>Your app should have a migrations directory, with files in it named like</p>
<pre><code>0000_initial.py
0001_added_some_fields.py
0002_added_some_more_fields.py
0003_deleted_some_stuff.py
</code></pre>
<p>Normally, when you run <code>./manage.py migrate your_app</code>, South runs all new migrations, in order. (It looks at the database tables to decide which ones are 'new').</p>
<p>However, you can also specify any migration by number, and South will migrate your database, <em>either forward or backward</em>, to take it to that point. So, with the example files above, if you have already migrated up to 0003, and you wanted to run 0003 in reverse (undoing it, effectively), you would run</p>
<pre><code>./manage.py migrate your_app 0002
</code></pre>
<p>South would look at the database, realise that it has run 0003 already, and determine that it has to run the reverse migration for 0003 in order to get back to 0002.</p> | {
"question_id": 5814190,
"question_date": "2011-04-28T05:49:47.443Z",
"question_score": 220,
"tags": "django|migration|django-south",
"answer_id": 5814593,
"answer_date": "2011-04-28T06:35:51.407Z",
"answer_score": 335
} |
Please answer the following Stack Overflow question:
Title: How to find the created date of a repository project on GitHub?
<p>How can I find the created date of a project on GitHub? </p>
<p>Basically, I have to find the first commit to see the created date, however, some projects have 500 commits, which wastes a lot of time trying to get to the first commit page.</p>
<p>Is there a quicker way to get the created date?</p> | <blockquote>
<p>How can I find the created date of a project on GitHub?</p>
</blockquote>
<p>Use the <strong><a href="https://developer.github.com/v3/repos/#get" rel="noreferrer">Repos GitHub API</a></strong> to retrieve this information</p>
<ul>
<li><strong>Syntax</strong>: <code>https://api.github.com/repos/{:owner}/{:repository}</code></li>
<li><strong>Example:</strong> <code>https://api.github.com/repos/libgit2/libgit2sharp</code></li>
</ul>
<p>The JSON payload will expose a <code>created_at</code> member with the UTC date the repository was created.</p>
<p>Considering the <strong><a href="https://github.com/libgit2/libgit2sharp" rel="noreferrer">LibGit2Sharp</a></strong> repository above, one can see that it's been created on Feb, 2nd 2011 at 16:44:49 UTC.</p>
<p><strong>Note:</strong> The <code>created_at</code> won't necessarily reflect the date of the first commit. It's the date the repository has been created on GitHub. For instance, the <code>xunit/resharper-xunit</code> project was recently <strong><a href="http://sticklebackplastic.com/post/2014/05/02/ReSharper-runner-for-xUnitnet-20.aspx" rel="noreferrer">moved from codeplex to GitHub</a></strong>. The <code>created_at</code> date is <code>2014-05-01T11:17:56Z</code>, but the most of the commits date back much more farther than that.</p> | {
"question_id": 23611669,
"question_date": "2014-05-12T14:25:48.777Z",
"question_score": 220,
"tags": "github",
"answer_id": 23612723,
"answer_date": "2014-05-12T15:12:15.407Z",
"answer_score": 261
} |
Please answer the following Stack Overflow question:
Title: Is there an easy way to create ordinals in C#?
<p>Is there an easy way in C# to create <a href="http://en.wikipedia.org/wiki/Ordinal_numbers_%28linguistics%29" rel="noreferrer">Ordinals</a> for a number? For example:</p>
<ul>
<li>1 returns 1st</li>
<li>2 returns 2nd</li>
<li>3 returns 3rd</li>
<li>...etc</li>
</ul>
<p>Can this be done through <code>String.Format()</code> or are there any functions available to do this?</p> | <p>This page gives you a complete listing of all custom numerical formatting rules:</p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings" rel="noreferrer">Custom numeric format strings</a></p>
<p>As you can see, there is nothing in there about ordinals, so it can't be done using <code>String.Format</code>. However its not really that hard to write a function to do it.</p>
<pre><code>public static string AddOrdinal(int num)
{
if( num <= 0 ) return num.ToString();
switch(num % 100)
{
case 11:
case 12:
case 13:
return num + "th";
}
switch(num % 10)
{
case 1:
return num + "st";
case 2:
return num + "nd";
case 3:
return num + "rd";
default:
return num + "th";
}
}
</code></pre>
<p>Update: Technically Ordinals don't exist for <= 0, so I've updated the code above. Also removed the redundant <code>ToString()</code> methods.</p>
<p>Also note, this is not internationalized. I've no idea what ordinals look like in other languages.</p> | {
"question_id": 20156,
"question_date": "2008-08-21T14:55:48.947Z",
"question_score": 220,
"tags": "c#|.net|ordinals",
"answer_id": 20175,
"answer_date": "2008-08-21T15:03:47.973Z",
"answer_score": 339
} |
Please answer the following Stack Overflow question:
Title: Realistic usage of the C99 'restrict' keyword?
<p>I was browsing through some documentation and questions/answers and saw it mentioned. I read a brief description, stating that it would be basically a promise from the programmer that the pointer won't be used to point somewhere else. </p>
<p>Can anyone offer some realistic cases where its worth actually using this?</p> | <p><code>restrict</code> says that the pointer is the only thing that accesses the underlying object. It eliminates the potential for pointer aliasing, enabling better optimization by the compiler.</p>
<p>For instance, suppose I have a machine with specialized instructions that can multiply vectors of numbers in memory, and I have the following code:</p>
<pre><code>void MultiplyArrays(int* dest, int* src1, int* src2, int n)
{
for(int i = 0; i < n; i++)
{
dest[i] = src1[i]*src2[i];
}
}
</code></pre>
<p>The compiler needs to properly handle if <code>dest</code>, <code>src1</code>, and <code>src2</code> overlap, meaning it must do one multiplication at a time, from start to the end. By having <code>restrict</code>, the compiler is free to optimize this code by using the vector instructions.</p>
<p>Wikipedia has an entry on <code>restrict</code>, with another example, <a href="http://en.wikipedia.org/wiki/Restrict" rel="noreferrer">here</a>.</p> | {
"question_id": 745870,
"question_date": "2009-04-14T00:09:53.303Z",
"question_score": 220,
"tags": "c|gcc|c99|restrict-qualifier",
"answer_id": 745877,
"answer_date": "2009-04-14T00:16:26.267Z",
"answer_score": 216
} |
Please answer the following Stack Overflow question:
Title: Why does C# not provide the C++ style 'friend' keyword?
<p>The <a href="http://www.cplusplus.com/doc/tutorial/inheritance/" rel="noreferrer">C++ friend keyword</a> allows a <code>class A</code> to designate <code>class B</code> as its friend. This allows <code>Class B</code> to access the <code>private</code>/<code>protected</code> members of <code>class A</code>.</p>
<p>I've never read anything as to why this was left out of C# (and VB.NET). Most answers to this <a href="https://stackoverflow.com/questions/17434/when-should-you-use-friend-in-c">earlier StackOverflow question</a> seem to be saying it is a useful part of C++ and there are good reasons to use it. In my experience I'd have to agree.</p>
<p>Another <a href="https://stackoverflow.com/questions/200079/inheritance-trees-and-protected-constructors-in-c#200117">question</a> seems to me to be really asking how to do something similar to <code>friend</code> in a C# application. While the answers generally revolve around nested classes, it doesn't seem quite as elegant as using the <code>friend</code> keyword.</p>
<p>The original <a href="https://rads.stackoverflow.com/amzn/click/com/0201633612" rel="noreferrer" rel="nofollow noreferrer">Design Patterns book</a> uses it regularly throughout its examples.</p>
<p>So in summary, why is <code>friend</code> missing from C#, and what is the "best practice" way (or ways) of simulating it in C#?</p>
<p>(By the way, the <code>internal</code> keyword is <em>not</em> the same thing, it allows <em>all</em> classes within the entire assembly to access <code>internal</code> members, while <code>friend</code> allows you to give a certain class <em>complete access</em> to <em>exactly one</em> other class)</p> | <p>Having friends in programming is more-or-less considered "dirty" and easy to abuse. It breaks the relationships between classes and undermines some fundamental attributes of an OO language.</p>
<p>That being said, it is a nice feature and I've used it plenty of times myself in C++; and would like to use it in C# too. But I bet because of C#'s "pure" OOness (compared to C++'s pseudo OOness) MS decided that because Java has no friend keyword C# shouldn't either (just kidding ;))</p>
<p>On a serious note: internal is not as good as friend but it does get the job done. Remember that it is rare that you will be distributing your code to 3rd party developers not through a DLL; so as long as you and your team know about the internal classes and their use you should be fine.</p>
<p><strong>EDIT</strong> Let me clarify how the friend keyword undermines OOP.</p>
<p>Private and protected variables and methods are perhaps one of the most important part of OOP. The idea that objects can hold data or logic that only they can use allows you to write your implementation of functionality independent of your environment - and that your environment cannot alter state information that it is not suited to handle. By using friend you are coupling two classes' implementations together - which is much worse then if you just coupled their interface. </p> | {
"question_id": 203616,
"question_date": "2008-10-15T03:23:43.360Z",
"question_score": 220,
"tags": "c#|c++|design-patterns|oop|friend",
"answer_id": 203655,
"answer_date": "2008-10-15T03:40:47.333Z",
"answer_score": 70
} |
Please answer the following Stack Overflow question:
Title: Yank file name / path of current buffer in Vim
<p>Assuming the current buffer is a file open for edit, so <code>:e</code> does not display <code>E32: No file name</code>. </p>
<p>I would like to yank one or all of:</p>
<ul>
<li>The file name exactly as show on the status line, e.g. <code>~\myfile.txt</code></li>
<li>A full path to the file, e.g. <code>c:\foo\bar\myfile.txt</code></li>
<li>Just the file name, e.g. <code>myfile.txt</code></li>
</ul> | <p><strong>TL;DR</strong></p>
<p><code>:let @" = expand("%")</code>></p>
<p>this will copy the file name to the <em>unamed register</em>, then you can use good old <code>p</code> to paste it. and of course you can map this to a key for quicker use.</p>
<p><code>:nmap cp :let @" = expand("%")<cr></code></p>
<p>you can also use this for full path</p>
<p><code>:let @" = expand("%:p")</code></p>
<p><strong>Explanation</strong></p>
<p>Vim uses the <em>unnamed register</em> to store text that has been deleted or copied (yanked), likewise when you paste it reads the text from this register.</p>
<p>Using <code>let</code> we can manually store text in the register using <code>:let @" = "text"</code> but we can also store the result of an expression.</p>
<p>In the above example we use the function <code>expand</code> which expands wildcards and keywords. in our example we use <code>expand('%')</code> to expand the current file name. We can modify it as <code>expand('%:p')</code> for the full file name. </p>
<p>See <code>:help let</code> <code>:help expand</code> <code>:help registers</code> for details</p> | {
"question_id": 916875,
"question_date": "2009-05-27T16:56:30.157Z",
"question_score": 220,
"tags": "vim|clipboard|yank",
"answer_id": 954336,
"answer_date": "2009-06-05T05:01:12.853Z",
"answer_score": 251
} |
Please answer the following Stack Overflow question:
Title: How to make good reproducible pandas examples
<p>Having spent a decent amount of time watching both the <a href="/questions/tagged/r" class="post-tag" title="show questions tagged 'r'" rel="tag">r</a> and <a href="/questions/tagged/pandas" class="post-tag" title="show questions tagged 'pandas'" rel="tag">pandas</a> tags on SO, the impression that I get is that <code>pandas</code> questions are less likely to contain reproducible data. This is something that the R community has been pretty good about encouraging, and thanks to guides like <a href="https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example">this</a>, newcomers are able to get some help on putting together these examples. People who are able to read these guides and come back with reproducible data will often have much better luck getting answers to their questions.</p>
<p>How can we create good reproducible examples for <code>pandas</code> questions? Simple dataframes can be put together, e.g.:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'],
'income': [40000, 50000, 42000]})
</code></pre>
<p>But many example datasets need more complicated structure, e.g.:</p>
<ul>
<li><code>datetime</code> indices or data</li>
<li>Multiple categorical variables (is there an equivalent to R's <code>expand.grid()</code> function, which produces all possible combinations of some given variables?)</li>
<li>MultiIndex or Panel data</li>
</ul>
<p>For datasets that are hard to mock up using a few lines of code, is there an equivalent to R's <code>dput()</code> that allows you to generate copy-pasteable code to regenerate your datastructure?</p> | <p><em>Note: The ideas here are pretty generic for Stack Overflow, indeed <a href="http://sscce.org/" rel="noreferrer">questions</a>.</em></p>
<h3>Disclaimer: Writing a good question is <em>hard</em>.</h3>
<h2>The Good:</h2>
<ul>
<li><p>do include small* example DataFrame, either as runnable code:</p>
<pre><code>In [1]: df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B'])
</code></pre>
<p>or make it "copy and pasteable" using <code>pd.read_clipboard(sep='\s\s+')</code>, you can format the text for Stack Overflow highlight and use <kbd>Ctrl</kbd>+<kbd>K</kbd> (or prepend four spaces to each line), or place three backticks (```) above and below your code with your code unindented:</p>
<pre><code>In [2]: df
Out[2]:
A B
0 1 2
1 1 3
2 4 6
</code></pre>
<p>test <code>pd.read_clipboard(sep='\s\s+')</code> yourself.</p>
<p>* <em>I really do mean <strong>small</strong>. The vast majority of example DataFrames could be fewer than 6 rows <sup>[citation needed]</sup>, and <strong>I bet I can do it in 5 rows.</strong> Can you reproduce the error with <code>df = df.head()</code>? If not, fiddle around to see if you can make up a small DataFrame which exhibits the issue you are facing.</em></p>
<p>* <em>Every rule has an exception, the obvious one is for performance issues (<a href="http://ipython.org/ipython-doc/dev/interactive/tutorial.html#magic-functions" rel="noreferrer">in which case definitely use %timeit and possibly %prun</a>), where you should generate: <code>df = pd.DataFrame(np.random.randn(100000000, 10))</code>. Consider using <code>np.random.seed</code> so we have the exact same frame. Saying that, "make this code fast for me" is not strictly on topic for the site.</em></p>
</li>
<li><p>write out the outcome you desire (similarly to above)</p>
<pre><code>In [3]: iwantthis
Out[3]:
A B
0 1 5
1 4 6
</code></pre>
<p><em>Explain what the numbers come from: the 5 is sum of the B column for the rows where A is 1.</em></p>
</li>
<li><p>do show <em>the code</em> you've tried:</p>
<pre><code>In [4]: df.groupby('A').sum()
Out[4]:
B
A
1 5
4 6
</code></pre>
<p><em>But say what's incorrect: the A column is in the index rather than a column.</em></p>
</li>
<li><p>do show you've done some research (<a href="http://pandas.pydata.org/pandas-docs/stable/search.html?q=groupby+sum" rel="noreferrer">search the documentation</a>, <a href="https://stackoverflow.com/search?q=%5Bpandas%5D+groupby+sum">search Stack Overflow</a>), and give a summary:</p>
<blockquote>
<p>The docstring for sum simply states "Compute sum of group values"</p>
</blockquote>
<blockquote>
<p>The <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#cython-optimized-aggregation-functions" rel="noreferrer">groupby documentation</a> doesn't give any examples for this.</p>
</blockquote>
<p><em>Aside: the answer here is to use <code>df.groupby('A', as_index=False).sum()</code>.</em></p>
</li>
<li><p>if it's relevant that you have Timestamp columns, e.g. you're resampling or something, then be explicit and apply <code>pd.to_datetime</code> to them for good measure**.</p>
<pre><code>df['date'] = pd.to_datetime(df['date']) # this column ought to be date..
</code></pre>
<p>** <em>Sometimes this is the issue itself: they were strings.</em></p>
</li>
</ul>
<h2>The Bad:</h2>
<ul>
<li><p>don't include a MultiIndex, which <strong>we can't copy and paste</strong> (see above). This is kind of a grievance with Pandas' default display, but nonetheless annoying:</p>
<pre><code>In [11]: df
Out[11]:
C
A B
1 2 3
2 6
</code></pre>
<p><em>The correct way is to include an ordinary DataFrame with a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="noreferrer"><code>set_index</code></a> call:</em></p>
<pre><code>In [12]: df = pd.DataFrame([[1, 2, 3], [1, 2, 6]], columns=['A', 'B', 'C']).set_index(['A', 'B'])
In [13]: df
Out[13]:
C
A B
1 2 3
2 6
</code></pre>
</li>
<li><p>do provide insight to what it is when giving the outcome you want:</p>
<pre><code> B
A
1 1
5 0
</code></pre>
<p><em>Be specific about how you got the numbers (what are they)... double check they're correct.</em></p>
</li>
<li><p>If your code throws an error, do include the entire stack trace (this can be edited out later if it's too noisy). Show the line number (and the corresponding line of your code which it's raising against).</p>
</li>
</ul>
<h2>The Ugly:</h2>
<ul>
<li><p>don't link to a <a href="https://en.wikipedia.org/wiki/Comma-separated_values" rel="noreferrer">CSV</a> file we don't have access to (ideally don't link to an external source at all...)</p>
<pre><code>df = pd.read_csv('my_secret_file.csv') # ideally with lots of parsing options
</code></pre>
<p><em><strong>Most data is proprietary</strong> we get that: Make up similar data and see if you can reproduce the problem (something small).</em></p>
</li>
<li><p>don't explain the situation vaguely in words, like you have a DataFrame which is "large", mention some of the column names in passing (be sure not to mention their dtypes). Try and go into lots of detail about something which is completely meaningless without seeing the actual context. Presumably no one is even going to read to the end of this paragraph.</p>
<p><em>Essays are bad, it's easier with small examples.</em></p>
</li>
<li><p>don't include 10+ (100+??) lines of data munging before getting to your actual question.</p>
<p><em>Please, we see enough of this in our day jobs. We want to help, but <a href="https://www.youtube.com/watch?v=ECfRp-jwbI4" rel="noreferrer">not like this...</a>.</em>
<em>Cut the intro, and just show the relevant DataFrames (or small versions of them) in the step which is causing you trouble.</em></p>
</li>
</ul>
<h3>Anyway, have fun learning Python, NumPy and Pandas!</h3> | {
"question_id": 20109391,
"question_date": "2013-11-20T23:31:39.790Z",
"question_score": 220,
"tags": "python|pandas",
"answer_id": 20159305,
"answer_date": "2013-11-23T06:19:13.533Z",
"answer_score": 454
} |
Please answer the following Stack Overflow question:
Title: Running a Haskell program on the Android OS
<p>Forenote: This is an extension of the thread started on <a href="http://www.reddit.com/r/haskell/comments/ful84/haskell_on_android/" rel="noreferrer">/r/haskell</a></p>
<p>Lets start with the facts:</p>
<ul>
<li>Android is one awesome Operating System</li>
<li>Haskell is the best programming language on the planet</li>
</ul>
<p>Therefore, clearly, combining them would make Android development that much better. So essentially I would just like to know how I can write Haskell programs for the Android OS. My question is:</p>
<blockquote>
<p>How can I get a Haskell program to execute/run on the Android OS?</p>
</blockquote> | <p>A language that has recently come to my attention is <a href="http://eta-lang.org/" rel="noreferrer">Eta</a>.</p>
<p>Eta's compiler is a fork of GHC 7.10 which has a JVM backend. It is possible to use the generated JAR files to write Android apps and even use its Foreign Function Interface to call native Android Java libraries.</p>
<p>Brian McKenna has written a blog post about <a href="https://brianmckenna.org/blog/eta_android" rel="noreferrer">how to configure an Android Studio project to use an Eta library</a>.</p>
<p><img src="https://brianmckenna.org/blog/static/eta-android-studio-emulator.png" alt=""></p> | {
"question_id": 5151858,
"question_date": "2011-03-01T08:05:58.890Z",
"question_score": 220,
"tags": "android|haskell|executable",
"answer_id": 44081663,
"answer_date": "2017-05-20T03:37:41.193Z",
"answer_score": 18
} |
Please answer the following Stack Overflow question:
Title: Local function vs Lambda C# 7.0
<p>I am looking at the new implementations in <a href="https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/" rel="noreferrer"><strong>C# 7.0</strong></a> and I find it interesting that they have implemented local functions but I cannot imagine a scenario where a local function would be preferred over a lambda expression, and what is the difference between the two.</p>
<p>I do understand that lambdas are <code>anonymous</code> functions meanwhile local functions are not, but I can't figure out a real world scenario, where local function has advantages over lambda expressions </p>
<p>Any example would be much appreciated. Thanks.</p> | <p><a href="https://github.com/dotnet/roslyn/issues/3911">This was explained by Mads Torgersen in C# Design Meeting Notes where local functions were first discussed</a>:</p>
<blockquote>
<p>You want a helper function. You are only using it from within a single function, and it likely uses variables and type parameters that are in scope in that containing function. On the other hand, unlike a lambda you don't need it as a first class object, so you don't care to give it a delegate type and allocate an actual delegate object. Also you may want it to be recursive or generic, or to implement it as an iterator.</p>
</blockquote>
<p>To expand on it some more, the advantages are:</p>
<ol>
<li><p>Performance.</p>
<p>When creating a lambda, a delegate has to be created, which is an unnecessary allocation in this case. Local functions are really just functions, no delegates are necessary.</p>
<p>Also, local functions are more efficient with capturing local variables: lambdas usually capture variables into a class, while local functions can use a struct (passed using <code>ref</code>), which again avoids an allocation.</p>
<p>This also means calling local functions is cheaper and they can be inlined, possibly increasing performance even further.</p></li>
<li><p>Local functions can be recursive.</p>
<p>Lambdas can be recursive too, but it requires awkward code, where you first assign <code>null</code> to a delegate variable and then the lambda. Local functions can naturally be recursive (including mutually recursive).</p></li>
<li><p>Local functions can be generic.</p>
<p>Lambdas cannot be generic, since they have to be assigned to a variable with a concrete type (that type can use generic variables from the outer scope, but that's not the same thing).</p></li>
<li><p>Local functions can be implemented as an iterator.</p>
<p>Lambdas cannot use the <code>yield return</code> (and <code>yield break</code>) keyword to implement <code>IEnumerable<T></code>-returning function. Local functions can.</p></li>
<li><p>Local functions look better.</p>
<p>This is not mentioned in the above quote and might be just my personal bias, but I think that normal function syntax looks better than assigning a lambda to a delegate variable. Local functions are also more succinct.</p>
<p>Compare:</p>
<pre><code>int add(int x, int y) => x + y;
Func<int, int, int> add = (x, y) => x + y;
</code></pre></li>
</ol> | {
"question_id": 40943117,
"question_date": "2016-12-03T00:54:03.337Z",
"question_score": 220,
"tags": "c#|function|lambda|c#-7.0",
"answer_id": 40949214,
"answer_date": "2016-12-03T15:11:25.573Z",
"answer_score": 328
} |
Please answer the following Stack Overflow question:
Title: Why does this if-statement combining assignment and an equality check return true?
<p>I've been thinking of some beginner mistakes and I ended up with the one on the <code>if</code> statement. I expanded a bit the code to this:</p>
<pre><code>int i = 0;
if (i = 1 && i == 0) {
std::cout << i;
}
</code></pre>
<p>I have seen that the <code>if</code> statement returns true, and it <code>cout</code>'s <code>i</code> as <code>1</code>. If <code>i</code> is assigned <code>1</code> in the if statement, why did <code>i == 0</code> return <code>true</code>?</p> | <p>This has to do with <a href="https://en.cppreference.com/w/cpp/language/operator_precedence" rel="noreferrer">operator precedence</a>. </p>
<pre><code>if (i = 1 && i == 0)
</code></pre>
<p>is not</p>
<pre><code>if ((i = 1) && (i == 0))
</code></pre>
<p>because both <code>&&</code> and <code>==</code> have a higher precedence than <code>=</code>. What it really works out to is</p>
<pre><code>if (i = (1 && (i == 0)))
</code></pre>
<p>which assigns the result of <code>1 && (i == 0)</code> to <code>i</code>. So, if <code>i</code> starts at <code>0</code> then <code>i == 0</code> is <code>true</code>, so <code>1 && true</code> is <code>true</code> (or <code>1</code>), and then <code>i</code> gets set to <code>1</code>. Then since <code>1</code> is true, you enter the if block and print the value you assigned to <code>i</code>.</p> | {
"question_id": 56264674,
"question_date": "2019-05-22T20:38:40.740Z",
"question_score": 220,
"tags": "c++|if-statement",
"answer_id": 56264744,
"answer_date": "2019-05-22T20:44:13.163Z",
"answer_score": 396
} |
Please answer the following Stack Overflow question:
Title: How to make div background color transparent in CSS
<p>I'm not using CSS3. So I can't use <code>opacity</code> or <code>filter</code> attributes. Without using these attributes how can I make the <code>background-color</code> transparent of a <code>div</code>? It should be kind of the text box example in this <a href="http://www.w3schools.com/css/tryit.asp?filename=trycss_transparency">link</a>. Here the text box background color is transparent. I want to make the same, but without using the above mentioned attributes.</p> | <p>Opacity gives you translucency or transparency. See an example <a href="http://jsfiddle.net/Rt9BJ/1/" rel="noreferrer">Fiddle here</a>.</p>
<pre><code>-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; /* IE 8 */
filter: alpha(opacity=50); /* IE 5-7 */
-moz-opacity: 0.5; /* Netscape */
-khtml-opacity: 0.5; /* Safari 1.x */
opacity: 0.5; /* Good browsers */
</code></pre>
<p>Note: <a href="http://www.w3schools.com/css/css_image_transparency.asp" rel="noreferrer">these are NOT CSS3 properties</a></p>
<p>See <a href="http://css-tricks.com/snippets/css/cross-browser-opacity/" rel="noreferrer">http://css-tricks.com/snippets/css/cross-browser-opacity/</a></p> | {
"question_id": 11807286,
"question_date": "2012-08-04T08:57:45.093Z",
"question_score": 219,
"tags": "css|html|background-color|transparent",
"answer_id": 11807308,
"answer_date": "2012-08-04T09:03:22.777Z",
"answer_score": 145
} |
Please answer the following Stack Overflow question:
Title: How to determine day of week by passing specific date?
<p>For Example I have the date: "23/2/2010" (23th Feb 2010). I want to pass it to a function which would return the <strong>day of week</strong>. How can I do this?</p>
<p>In this example, the function should return <code>String</code> "Tue".</p>
<p>Additionally, if just the day ordinal is desired, how can that be retrieved?</p> | <p>Yes. Depending on your exact case:</p>
<ul>
<li><p>You can use <code>java.util.Calendar</code>:</p>
<pre><code>Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
</code></pre></li>
<li><p>if you need the output to be <code>Tue</code> rather than 3 (Days of week are indexed starting at 1 for Sunday, see Calendar.SUNDAY), instead of going through a calendar, just reformat the string: <code>new SimpleDateFormat("EE").format(date)</code> (<code>EE</code> meaning "day of week, short version")</p></li>
<li><p>if you have your input as string, rather than <code>Date</code>, you should use <code>SimpleDateFormat</code> to parse it: <code>new SimpleDateFormat("dd/M/yyyy").parse(dateString)</code></p></li>
<li><p>you can use joda-time's <code>DateTime</code> and call <code>dateTime.dayOfWeek()</code> and/or <code>DateTimeFormat</code>.</p></li>
<li><p>edit: since Java 8 you can now use java.time package instead of joda-time</p></li>
</ul> | {
"question_id": 5270272,
"question_date": "2011-03-11T07:44:24.083Z",
"question_score": 219,
"tags": "java|date",
"answer_id": 5270292,
"answer_date": "2011-03-11T07:47:15.563Z",
"answer_score": 397
} |
Please answer the following Stack Overflow question:
Title: MySQL: How to reset or change the MySQL root password?
<p>How do I change the MySQL root password and username in ubuntu server? Do I need to stop the mysql service before setting any changes? </p>
<p>I have a phpmyadmin setup as well, will phpmyadmin get updated automatically?</p> | <p>Set / change / reset the MySQL root password on Ubuntu Linux. Enter the following lines in your terminal.</p>
<ol>
<li>Stop the MySQL Server: <code>sudo /etc/init.d/mysql stop</code></li>
<li>Start the <code>mysqld</code> configuration: <code>sudo mysqld --skip-grant-tables &</code></li>
</ol>
<p>In some cases, you've to create the <code>/var/run/mysqld</code> first:</p>
<pre><code> sudo mkdir -v /var/run/mysqld && sudo chown mysql /var/run/mysqld
</code></pre>
<ol start="3">
<li>Login to MySQL as root: <code>mysql -u root mysql</code></li>
<li>Replace <code>YOURNEWPASSWORD</code> with your new password:</li>
</ol>
<p><strong>For MySQL < 8.0</strong></p>
<pre><code> UPDATE
mysql.user
SET
Password = PASSWORD('YOURNEWPASSWORD')
WHERE
User = 'root';
FLUSH PRIVILEGES;
exit;
</code></pre>
<blockquote>
<p>Note: on some versions, if <code>password</code> column doesn't exist, you may want to try:<br />
<code>UPDATE user SET authentication_string=password('YOURNEWPASSWORD') WHERE user='root';</code></p>
</blockquote>
<p><strong>Note: This method is not regarded as the most secure way of resetting the password, however, it works.</strong></p>
<p><strong>For MySQL >= 8.0</strong></p>
<pre class="lang-sql prettyprint-override"><code>ALTER USER 'root'@'localhost' IDENTIFIED BY 'YOURNEWPASSWORD';
</code></pre>
<p>References:</p>
<ol>
<li><a href="http://ubuntu.flowconsult.at/en/mysql-set-change-reset-root-password/" rel="noreferrer">Set / Change / Reset the MySQL root password on Ubuntu Linux</a></li>
<li><a href="http://dev.mysql.com/doc/refman/5.6/en/resetting-permissions.html" rel="noreferrer">How to Reset the Root Password (v5.6)</a></li>
<li><a href="https://dev.mysql.com/doc/refman/8.0/en/resetting-permissions.html" rel="noreferrer">How to Reset the Root Password (v8.0)</a></li>
</ol> | {
"question_id": 16556497,
"question_date": "2013-05-15T03:47:23.297Z",
"question_score": 219,
"tags": "mysql|ubuntu|phpmyadmin",
"answer_id": 16556534,
"answer_date": "2013-05-15T03:52:44.700Z",
"answer_score": 283
} |
Please answer the following Stack Overflow question:
Title: How to remove unwanted space between rows and columns in table?
<p>How do I remove the extra space between the rows and columns in the table.</p>
<p>I've tried changing the margin, padding, and various border properties on the table and tr and td.</p>
<p>I want the pictures to all be right next to each other to look like one big image.</p>
<p>How should I fix this?</p>
<p><strong>CSS</strong></p>
<pre><code>table {
border-collapse: collapse;
}
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Tera Byte Video Game Creation Camp</title>
<link rel="stylesheet" type="text/css" href="style.css"></link>
</head>
<body>
<table class="mytable" align="center">
<tr class="header">
<td colspan="3"><img src="images/home_01.png" /></td>
</tr>
<tr class="top">
<td colspan="3"><img src="images/home_02.png" /></td>
</tr>
<tr class="link-row">
<td><img src="images/home_03.png" /></td>
<td><img src="images/home_04.png" /></td>
<td><img src="images/home_05.png" /></td>
</tr>
<tr class="link-row">
<td><img src="images/home_07.png" /></td>
<td><img src="images/home_06.png" /></td>
<td><img src="images/home_08.png" /></td>
</tr>
<tr class="link-row">
<td><img src="images/home_09.png" /></td>
<td><img src="images/home_10.png" /></td>
<td><img src="images/home_11.png" /></td>
</tr>
<tr class="link-row">
<td><img src="images/home_12.png" /></td>
<td><img src="images/home_13.png" /></td>
<td><img src="images/home_14.png" /></td>
</tr>
<tr class="bottom">
<td colspan="3"><img src="images/home_15.png" /></td>
</tr>
</table>
</body>
</html>
</code></pre> | <p>Add this CSS reset to your CSS code: (<a href="http://meyerweb.com/eric/tools/css/reset/reset.css" rel="noreferrer">From here</a>)</p>
<pre><code>/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
</code></pre>
<p>It'll reset the CSS effectively, getting rid of the padding and margins.</p> | {
"question_id": 2279396,
"question_date": "2010-02-17T09:06:29.557Z",
"question_score": 219,
"tags": "html|css|html-table",
"answer_id": 2279508,
"answer_date": "2010-02-17T09:26:25.690Z",
"answer_score": 96
} |
Please answer the following Stack Overflow question:
Title: Java FileOutputStream Create File if not exists
<p>Is there a way to use FileOutputStream in a way that if a file (String filename) does not exist, then it will create it?</p>
<pre><code>FileOutputStream oFile = new FileOutputStream("score.txt", false);
</code></pre> | <p>It will throw a <code>FileNotFoundException</code> if the file doesn't exist and cannot be created (<a href="http://docs.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream%28java.lang.String,%20boolean%29" rel="noreferrer">doc</a>), but it will create it if it can. To be sure you probably should first test that the file exists before you create the <code>FileOutputStream</code> (and create with <code>createNewFile()</code> if it doesn't):</p>
<pre><code>File yourFile = new File("score.txt");
yourFile.createNewFile(); // if file already exists will do nothing
FileOutputStream oFile = new FileOutputStream(yourFile, false);
</code></pre> | {
"question_id": 9620683,
"question_date": "2012-03-08T15:58:48.093Z",
"question_score": 219,
"tags": "java|file|file-io|new-operator|fileoutputstream",
"answer_id": 9620718,
"answer_date": "2012-03-08T16:00:55.703Z",
"answer_score": 349
} |
Please answer the following Stack Overflow question:
Title: Video auto play is not working in Safari and Chrome desktop browser
<p>I spent quite a lot of time trying to figure out why video embedded like here:</p>
<pre><code><video height="256" loop autoplay muted controls id="vid">
<source type="video/mp4" src="video_file.mp4"></source>
<source type="video/ogg" src="video_file.ogg"></source>
</video>
</code></pre>
<p>starts playing automatically once the page is loaded in FireFox but cannot do autoplay in Webkit based browsers. This only happened on some random pages. So far I was unable to find the cause. I suspect some unclosed tags or extensive JS created by CMS editors.</p> | <p>The best fix I could get was adding this code just after the <code></video></code></p>
<pre><code><script>
document.getElementById('vid').play();
</script>
</code></pre>
<p>...not pretty but somehow works.</p>
<p><strong>UPDATE</strong>
Recently many browsers can only autoplay the videos with sound off, so you'll need to add <code>muted</code> attribute to the video tag too </p>
<pre><code><video autoplay muted>
...
</video>
</code></pre> | {
"question_id": 17994666,
"question_date": "2013-08-01T12:53:37.433Z",
"question_score": 219,
"tags": "javascript|html|google-chrome|safari|webkit",
"answer_id": 17994667,
"answer_date": "2013-08-01T12:53:37.433Z",
"answer_score": 458
} |
Please answer the following Stack Overflow question:
Title: How to handle the modal closing event in Twitter Bootstrap?
<p>In Twitter bootstrap, looking at the <a href="http://twitter.github.com/bootstrap/javascript.html#modals" rel="noreferrer">modals</a> documentation. I wasn't able to figure out if there is a way to listen to the close event of the modal and execute a function.</p>
<p>e.g. lets take this modal as an example:</p>
<pre><code><div class="modal-header">
<button type="button" class="close close_link" data-dismiss="modal" aria-hidden="true">&times;</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<a href="#" class="btn close_link" data-dismiss="modal">Close</a>
</div>
</code></pre>
<p>The X button on top and the close button on bottom can both hide/close the modal because of <code>data-dismiss="modal"</code>. So I wonder, if I could somehow listen to that?</p>
<p>Alternatively I could do it manually like this, I guess...</p>
<pre><code>$("#salesitems_modal").load(url, data, function() {
$(this).modal('show');
$(this).find(".close_link").click(modal_closing);
});
</code></pre>
<p>What do you think?</p> | <h3>Updated for Bootstrap 3 and 4</h3>
<p><a href="http://getbootstrap.com/javascript/#modals-usage" rel="noreferrer">Bootstrap 3</a> and <a href="https://getbootstrap.com/docs/4.0/components/modal/#events" rel="noreferrer">Bootstrap 4</a> docs refer two events you can use.</p>
<blockquote>
<p><strong>hide.bs.modal</strong>: This event is fired immediately when the hide instance method has been called.<br>
<strong>hidden.bs.modal</strong>: This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).</p>
</blockquote>
<p>And provide an example on how to use them:</p>
<pre><code>$('#myModal').on('hidden.bs.modal', function () {
// do something…
})
</code></pre>
<h3>Legacy Bootstrap 2.3.2 answer</h3>
<p><a href="http://getbootstrap.com/2.3.2/javascript.html" rel="noreferrer">Bootstrap's documentation</a> refers two events you can use.</p>
<blockquote>
<p><strong>hide</strong>: This event is fired immediately when the hide instance method has been called.<br>
<strong>hidden</strong>: This event is fired when the modal has finished being hidden from the user (will wait for css transitions to complete).</p>
</blockquote>
<p>And provides an example on how to use them:</p>
<pre><code>$('#myModal').on('hidden', function () {
// do something…
})
</code></pre> | {
"question_id": 12319171,
"question_date": "2012-09-07T13:33:14.033Z",
"question_score": 219,
"tags": "jquery|twitter-bootstrap|modal-dialog",
"answer_id": 12319710,
"answer_date": "2012-09-07T14:04:27.433Z",
"answer_score": 436
} |
Please answer the following Stack Overflow question:
Title: anaconda update all possible packages?
<p>I tried the <code>conda search --outdated</code>, there are lots of outdated packages, for example the scipy is 0.17.1 but the latest is 0.18.0. However, when I do the <code>conda update --all</code>. It will not update any packages.</p>
<p><strong>update 1</strong></p>
<pre><code>conda update --all --alt-hint
Fetching package metadata .......
Solving package specifications: ..........
# All requested packages already installed.
# packages in environment at /home/user/opt/anaconda2:
#
</code></pre>
<p><strong>update 2</strong></p>
<p>I can update those packages separately. I can do <code>conda update scipy</code>. But why I cannot update all of them in one go?</p> | <p>TL;DR: <strong>dependency conflicts:</strong> Updating one <strong>requires</strong> <em>(by it's requirements)</em> to downgrade another</p>
<p>You are right:</p>
<pre><code>conda update --all
</code></pre>
<p>is actually the way to go<sup>1</sup>. Conda always tries to upgrade the packages to the newest version in the series (say Python 2.x or 3.x). </p>
<h2>Dependency conflicts</h2>
<p>But it is possible that there are dependency conflicts (which prevent a further upgrade). Conda usually warns very explicitly if they occur.</p>
<p>e.g. X requires Y <5.0, so Y will never be >= 5.0</p>
<p>That's why you 'cannot' upgrade them all.</p>
<h3>Resolving</h3>
<p><em>To add: maybe it could work but a newer version of X working with Y > 5.0 is not available in conda. It is possible to install with pip, since more packages are available in pip. But be aware that pip also installs packages if dependency conflicts exist and that it usually breaks your conda environment in the sense that you cannot reliably install with conda anymore. If you do that, do it as a last resort and after all packages have been installed with conda. It's rather a hack.</em></p>
<p>A safe way you can try is to add <a href="https://conda-forge.org/" rel="noreferrer">conda-forge</a> as a channel when upgrading (add <code>-c conda-forge</code> as a flag) or any other channel you find that contains your package <em>if you really need this new version</em>. This way conda does also search in this places for available packages.</p>
<p><strong>Considering your update</strong>: You <em>can</em> upgrade them each separately, but doing so will not only include an upgrade but also a downgrade of another package as well. Say, to add to the example above:</p>
<p>X > 2.0 requires Y < 5.0, X < 2.0 requires Y > 5.0</p>
<p>So upgrading Y > 5.0 implies downgrading X to < 2.0 and vice versa.</p>
<p>(<em>this is a pedagogical example, of course, but it's the same in reality, usually just with more complicated dependencies and sub-dependencies</em>)</p>
<p>So you still cannot upgrade <em>them all</em> by doing the upgrades separately; the dependencies are just not satisfiable so earlier or later, an upgrade will downgrade an already upgraded package again. Or break the compatibility of the packages (which you usually don't want!), which is only possible by explicitly invoking an <em>ignore-dependencies</em> and <em>force</em>-command. But that is only to <em>hack</em> your way around issues, definitely not the normal-user case!</p>
<hr>
<p><sup>1</sup> If you actually want to update the packages of your installation, which you usually <em>don't</em>. The command run in the base environment will update the packages in this, but usually you should work with virtual environments (<code>conda create -n myenv</code> and then <code>conda activate myenv</code>). Executing <code>conda update --all</code> inside such an environment will update the packages <em>inside</em> this environment. However, since the base environment is also an environment, the answer applies to both cases in the same way.</p> | {
"question_id": 38972052,
"question_date": "2016-08-16T10:06:52.217Z",
"question_score": 219,
"tags": "python|anaconda|conda",
"answer_id": 44072944,
"answer_date": "2017-05-19T14:43:05.320Z",
"answer_score": 350
} |
Please answer the following Stack Overflow question:
Title: Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type
<p>I am trying to import components from react-materialize as -</p>
<pre><code>import {Navbar, NavItem} from 'react-materialize';
</code></pre>
<p>But when the webpack is compiling my <code>.tsx</code> it throws an error for the above as -</p>
<pre><code>ERROR in ./src/common/navbar.tsx
(3,31): error TS7016: Could not find a declaration file for module 'react-materi
alize'. 'D:\Private\Works\Typescript\QuickReact\node_modules\react-materialize\l
ib\index.js' implicitly has an 'any' type.
</code></pre>
<p>Is there any resolution for this? I'm unsure how to resolve this import statement to work with <code>ts-loader</code> and webpack.</p>
<p>The <code>index.js</code> of react-materialize looks likes this. But how do I resolve this for the module import in my own files?</p>
<p><a href="https://github.com/react-materialize/react-materialize/blob/master/src/index.js" rel="noreferrer">https://github.com/react-materialize/react-materialize/blob/master/src/index.js</a></p> | <p>For those who wanted to know that how did I overcome this . I did a hack kind of stuff .</p>
<p>Inside my project I created a folder called <code>@types</code> and added it to tsconfig.json for find all required types from it . So it looks somewhat like this -</p>
<pre class="lang-json prettyprint-override"><code>"typeRoots": [
"../node_modules/@types",
"../@types"
]
</code></pre>
<p>And inside that I created a file called <code>alltypes.d.ts</code> . To find the unknown types from it . so for me these were the unknown types and I added it over there.</p>
<pre><code>declare module 'react-materialize';
declare module 'react-router';
declare module 'flux';
</code></pre>
<p>So now the typescript didn't complain about the types not found anymore . :) win win situation now :)</p> | {
"question_id": 41462729,
"question_date": "2017-01-04T11:29:14.327Z",
"question_score": 219,
"tags": "reactjs|webpack|webpack-2",
"answer_id": 41631658,
"answer_date": "2017-01-13T09:48:12.320Z",
"answer_score": 126
} |
Please answer the following Stack Overflow question:
Title: Post parameter is always null
<p>Since upgrading to RC for WebAPI I'm having some real odd issue when calling POST on my WebAPI.
I've even gone back to the basic version generated on new project. So:</p>
<pre><code>public void Post(string value)
{
}
</code></pre>
<p>and calling from Fiddler:</p>
<pre><code>Header:
User-Agent: Fiddler
Host: localhost:60725
Content-Type: application/json
Content-Length: 29
Body:
{
"value": "test"
}
</code></pre>
<p>When I debug, the string "value" is never being assigned to. It's just always NULL.
Anyone having this issue?</p>
<p>(I first saw the issue with a more complex type)</p>
<p>The problem is not only bound to ASP.NET MVC 4, the same problem occurs for a fresh ASP.NET MVC 3 project after RC installation</p> | <p>Since you have only one parameter, you could try decorating it with the <code>[FromBody]</code> attribute, or change the method to accept a DTO with value as a property, as I suggested here: <a href="https://stackoverflow.com/questions/10955629/mvc4-rc-webapi-parameter-binding/10956025">MVC4 RC WebApi parameter binding</a></p>
<p>UPDATE: The official ASP.NET site was updated today with an excellent explanation: <a href="https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-1" rel="noreferrer">https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-1</a></p>
<p>In a nutshell, when sending a single simple type in the body, send just the value prefixed with an equal sign (=), e.g. body:</p>
<p><code>=test</code></p> | {
"question_id": 10984040,
"question_date": "2012-06-11T16:29:19.670Z",
"question_score": 219,
"tags": "c#|.net|asp.net-web-api|asp.net-web-api-routing",
"answer_id": 10986030,
"answer_date": "2012-06-11T19:05:37.163Z",
"answer_score": 108
} |
Please answer the following Stack Overflow question:
Title: Android - How To Override the "Back" button so it doesn't Finish() my Activity?
<p>I currently have an Activity that when it gets displayed a Notification will also get displayed in the Notification bar.</p>
<p>This is so that when the User presses home and the Activity gets pushed to the background they can get back to the Activity via the Notification.</p>
<p>The problem arises when a User presses the back button, my Activity gets destroyed but the Notification remains as I want the user to be able to press back but still be able to get to the Activity via the Notification. But when a USER tries this I get Null Pointers as its trying to start a new activity rather than bringing back the old one.</p>
<p>So essentially I want the Back button to act the exact same as the Home button and here is how I have tried so far:</p>
<hr>
<pre><code> @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (Integer.parseInt(android.os.Build.VERSION.SDK) < 5
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
Log.d("CDA", "onKeyDown Called");
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
public void onBackPressed() {
Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
return;
}
</code></pre>
<hr>
<p>However the above code still seems to allow my Activity to be destroyed, How can I stop my Activity from being destroyed when the back button is pressed?</p> | <p>Remove your key listener or return <code>true</code> when you have <code>KEY_BACK</code>.</p>
<p>You just need the following to catch the back key (Make sure not to call <em>super</em> in <code>onBackPressed()</code>).</p>
<p>Also, if you plan on having a service run in the background, make sure to look at <code>startForeground()</code> and make sure to have an ongoing notification or else Android will kill your service if it needs to free memory.</p>
<pre><code>@Override
public void onBackPressed() {
Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
</code></pre> | {
"question_id": 3141996,
"question_date": "2010-06-29T15:05:07.613Z",
"question_score": 219,
"tags": "android|android-activity|nullpointerexception|back-button|onkeypress",
"answer_id": 3142471,
"answer_date": "2010-06-29T16:00:10.140Z",
"answer_score": 306
} |
Please answer the following Stack Overflow question:
Title: How can I match a string with a regex in Bash?
<p>I am trying to write a bash script that contains a function so when given a <code>.tar</code>, <code>.tar.bz2</code>, <code>.tar.gz</code> etc. file it uses tar with the relevant switches to decompress the file.</p>
<p>I am using if elif then statements which test the filename to see what it ends with and I cannot get it to match using regex metacharacters.</p>
<p>To save constantly rewriting the script I am using 'test' at the command line, I thought the statement below should work, I have tried every combination of brackets, quotes and metacharaters possible and still it fails.</p>
<pre><code>test sed-4.2.2.tar.bz2 = tar\.bz2$; echo $?
(this returns 1, false)
</code></pre>
<p>I'm sure the problem is a simple one and I've looked everywhere, yet I cannot fathom how to do it. Does someone know how I can do this?</p> | <p>To match regexes you need to use the <code>=~</code> operator.</p>
<p>Try this:</p>
<pre><code>[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched
</code></pre>
<p>Alternatively, you can use wildcards (instead of regexes) with the <code>==</code> operator:</p>
<pre><code>[[ sed-4.2.2.tar.bz2 == *tar.bz2 ]] && echo matched
</code></pre>
<p>If portability is not a concern, I recommend using <code>[[</code> instead of <code>[</code> or <code>test</code> as it is safer and more powerful. See <a href="http://mywiki.wooledge.org/BashFAQ/031">What is the difference between test, [ and [[ ?</a> for details.</p> | {
"question_id": 17420994,
"question_date": "2013-07-02T08:35:05.320Z",
"question_score": 219,
"tags": "regex|string|bash",
"answer_id": 17421041,
"answer_date": "2013-07-02T08:37:37.560Z",
"answer_score": 347
} |
Please answer the following Stack Overflow question:
Title: How do I use $rootScope in Angular to store variables?
<p>How do I use <code>$rootScope</code> to store variables in a controller I want to later access in another controller? For example:</p>
<pre><code>angular.module('myApp').controller('myCtrl', function($scope) {
var a = //something in the scope
//put it in the root scope
});
angular.module('myApp').controller('myCtrl2', function($scope) {
var b = //get var a from root scope somehow
//use var b
});
</code></pre>
<p>How would I do this?</p> | <p>Variables set at the root-scope are available to the controller scope via prototypical inheritance.</p>
<p>Here is a modified version of @Nitish's demo that shows the relationship a bit clearer:
<a href="http://jsfiddle.net/TmPk5/6/" rel="noreferrer">http://jsfiddle.net/TmPk5/6/</a></p>
<p>Notice that the rootScope's variable is set when the module initializes, and then each of the inherited scope's get their own copy which can be set independently (the <code>change</code> function). Also, the rootScope's value can be updated too (the <code>changeRs</code> function in <code>myCtrl2</code>)</p>
<pre><code>angular.module('myApp', [])
.run(function($rootScope) {
$rootScope.test = new Date();
})
.controller('myCtrl', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
})
.controller('myCtrl2', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.changeRs = function() {
$rootScope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
});
</code></pre> | {
"question_id": 18880737,
"question_date": "2013-09-18T19:31:51.360Z",
"question_score": 219,
"tags": "angularjs|angularjs-scope|angularjs-controller|rootscope",
"answer_id": 18881189,
"answer_date": "2013-09-18T19:55:08.393Z",
"answer_score": 251
} |
Please answer the following Stack Overflow question:
Title: If '<selector>' is an Angular component, then verify that it is part of this module
<p>I am new in Angular2. I have tried to create a component but showing an error.</p>
<p>This is the <code>app.component.ts</code> file.</p>
<pre><code>import { Component } from '@angular/core';
import { MyComponentComponent } from './my-component.component';
@Component({
selector: 'my-app',
template: `
<h1>Hello {{name}}</h1>
<h4>Something</h4>
<my-component></my-component>
`,
directives: [MyComponentComponent]
})
export class AppComponent { name = 'Sam' }
</code></pre>
<p>This is the component which i want to create.</p>
<pre><code>import { Component } from '@angular/core';
@Component({
selector: 'my-component',
template: `
<p>This is my article</p>
`
})
export class MyComponentComponent {
}
</code></pre>
<p>Showing the two errors:</p>
<ol>
<li>If <code>my-component</code> is an Angular component, then verify that it is part of this module.</li>
<li>If <code>my-component</code> is a Web Component then add <code>CUSTOM_ELEMENTS_SCHEMA</code> to the <code>@NgModule.schemas</code> of this component to suppress this message. </li>
</ol>
<p>Please Help.</p> | <p>Your <code>MyComponentComponent</code> should be in <code>MyComponentModule</code>.</p>
<p>And in <code>MyComponentModule</code>, you should place the <code>MyComponentComponent</code> inside the "exports".</p>
<p>Something like this, see code below.</p>
<pre><code>@NgModule({
imports: [],
exports: [MyComponentComponent],
declarations: [MyComponentComponent],
providers: [],
})
export class MyComponentModule {
}
</code></pre>
<p>and place the <code>MyComponentModule</code> in the <code>imports</code> in <code>app.module.ts</code> like this (see code below).</p>
<pre><code>import { MyComponentModule } from 'your/file/path';
@NgModule({
imports: [MyComponentModule]
declarations: [AppComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
</code></pre>
<p>After doing so, the selector of your component can now be recognized by the app.</p>
<p>You can learn more about it here: <a href="https://angular-2-training-book.rangle.io/handout/modules/feature-modules.html" rel="noreferrer">https://angular-2-training-book.rangle.io/handout/modules/feature-modules.html</a></p>
<p>Cheers!</p> | {
"question_id": 43937387,
"question_date": "2017-05-12T12:06:46.253Z",
"question_score": 219,
"tags": "angular|typescript",
"answer_id": 46557638,
"answer_date": "2017-10-04T05:32:24.753Z",
"answer_score": 262
} |
Please answer the following Stack Overflow question:
Title: Set keyboard caret position in html textbox
<p>Does anybody know how to move the keyboard caret in a textbox to a particular position?</p>
<p>For example, if a text-box (e.g. input element, not text-area) has 50 characters in it and I want to position the caret before character 20, how would I go about it?</p>
<p>This is in differentiation from this question: <a href="https://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area">jQuery Set Cursor Position in Text Area</a> , which requires jQuery. </p> | <p>Excerpted from Josh Stodola's <em><a href="https://web.archive.org/web/20090210030453/http://blog.josh420.com/archives/2007/10/setting-cursor-position-in-a-textbox-or-textarea-with-javascript.aspx" rel="nofollow noreferrer">Setting keyboard caret Position in a Textbox or TextArea with Javascript</a></em></p>
<p>A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish:</p>
<pre><code>function setCaretPosition(elemId, caretPos) {
var elem = document.getElementById(elemId);
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
</code></pre>
<p>The first expected parameter is the ID of the element you wish to insert the keyboard caret on. If the element is unable to be found, nothing will happen (obviously). The second parameter is the caret positon index. Zero will put the keyboard caret at the beginning. If you pass a number larger than the number of characters in the elements value, it will put the keyboard caret at the end.</p>
<p>Tested on IE6 and up, Firefox 2, Opera 8, Netscape 9, SeaMonkey, and Safari. Unfortunately on Safari it does not work in combination with the onfocus event).</p>
<p>An example of using the above function to force the keyboard caret to jump to the end of all textareas on the page when they receive focus:</p>
<pre><code>function addLoadEvent(func) {
if(typeof window.onload != 'function') {
window.onload = func;
}
else {
if(func) {
var oldLoad = window.onload;
window.onload = function() {
if(oldLoad)
oldLoad();
func();
}
}
}
}
// The setCaretPosition function belongs right here!
function setTextAreasOnFocus() {
/***
* This function will force the keyboard caret to be positioned
* at the end of all textareas when they receive focus.
*/
var textAreas = document.getElementsByTagName('textarea');
for(var i = 0; i < textAreas.length; i++) {
textAreas[i].onfocus = function() {
setCaretPosition(this.id, this.value.length);
}
}
textAreas = null;
}
addLoadEvent(setTextAreasOnFocus);
</code></pre> | {
"question_id": 512528,
"question_date": "2009-02-04T17:54:51.593Z",
"question_score": 219,
"tags": "javascript|textbox|input",
"answer_id": 512542,
"answer_date": "2009-02-04T17:59:10.727Z",
"answer_score": 236
} |
Please answer the following Stack Overflow question:
Title: Ajax success event not working
<p>I have a registration form and am using <code>$.ajax</code> to submit it.</p>
<p><strong>This is my AJAX request:</strong></p>
<pre><code>$(document).ready(function() {
$("form#regist").submit(function() {
var str = $("#regist").serialize();
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
}
});
return false;
});
});
</code></pre>
<p>In my <em>submit1.php</em> file I check for the existence of fields <em>email address</em> and <em>username</em> in the database.
I wish to display an error message if those value exist <strong>without a page refresh</strong>.</p>
<p>How can I add this to the <em>success</em> callback of my AJAX request?</p> | <p>The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with <code>error:</code> callback function.</p>
<p>You don't seem to need JSON in that function anyways, so you can also take out the <code>dataType: 'json'</code> row.</p> | {
"question_id": 1969476,
"question_date": "2009-12-28T13:31:04.570Z",
"question_score": 219,
"tags": "javascript|jquery|ajax",
"answer_id": 1969520,
"answer_date": "2009-12-28T13:41:56.577Z",
"answer_score": 425
} |
Please answer the following Stack Overflow question:
Title: libpng warning: iCCP: known incorrect sRGB profile
<p>I'm trying to load a PNG image using SDL but the program doesn't work and this error appears in the console</p>
<blockquote>
<p>libpng warning: iCCP: known incorrect sRGB profile</p>
</blockquote>
<p>Why does this warning appear? What should I do to solve this problem?</p> | <p>Libpng-1.6 is more stringent about checking ICC profiles than previous versions. You can ignore the warning. To get rid of it, remove the iCCP chunk from the PNG image.</p>
<p>Some applications treat warnings as errors; if you are using such an application you do have to remove the chunk. You can do that with any of a variety of PNG editors such as ImageMagick's</p>
<pre class="lang-bash prettyprint-override"><code>convert in.png out.png
</code></pre>
<p>To remove the invalid iCCP chunk from all of the PNG files in a folder (directory), you can use <code>mogrify</code> from ImageMagick:</p>
<pre class="lang-bash prettyprint-override"><code>mogrify *.png
</code></pre>
<p>This requires that your ImageMagick was built with libpng16. You can easily check it by running:</p>
<pre class="lang-bash prettyprint-override"><code>convert -list format | grep PNG
</code></pre>
<p>If you'd like to find out which files need to be fixed instead of blindly processing all of them, you can run</p>
<pre class="lang-bash prettyprint-override"><code>pngcrush -n -q *.png
</code></pre>
<p>where the <code>-n</code> means don't rewrite the files and <code>-q</code> means suppress most of the output except for warnings. Sorry, there's no option yet in pngcrush to suppress everything but the warnings.</p>
<hr>
<p>Binary Releases of ImageMagick are <a href="http://www.imagemagick.org/script/download.php" rel="noreferrer">here</a></p>
<hr>
<p>For Android Projects (Android Studio) navigate into <code>res</code> folder.</p>
<p>For example:</p>
<pre class="lang-bash prettyprint-override"><code>C:\{your_project_folder}\app\src\main\res\drawable-hdpi\mogrify *.png
</code></pre> | {
"question_id": 22745076,
"question_date": "2014-03-30T14:20:19.900Z",
"question_score": 219,
"tags": "c++|warnings|sdl|rgb|libpng",
"answer_id": 22747902,
"answer_date": "2014-03-30T18:19:07.410Z",
"answer_score": 227
} |
Please answer the following Stack Overflow question:
Title: Remove blank lines with grep
<p>I tried <code>grep -v '^$'</code> in Linux and that didn't work. This file came from a Windows file system.</p> | <p>Try the following:</p>
<pre><code>grep -v -e '^$' foo.txt
</code></pre>
<p>The <code>-e</code> option allows regex patterns for matching.</p>
<p>The single quotes around <code>^$</code> makes it work for Cshell. Other shells will be happy with either single or double quotes.</p>
<p>UPDATE: This works for me for a file with blank lines or "all white space" (such as windows lines with <code>\r\n</code> style line endings), whereas the above only removes files with blank lines and unix style line endings:</p>
<pre><code>grep -v -e '^[[:space:]]*$' foo.txt
</code></pre> | {
"question_id": 3432555,
"question_date": "2010-08-08T00:10:51.337Z",
"question_score": 219,
"tags": "text|terminal|grep|newline",
"answer_id": 3432574,
"answer_date": "2010-08-08T00:17:13.440Z",
"answer_score": 375
} |
Please answer the following Stack Overflow question:
Title: Horizontal ListView in Android?
<p>Is it possible to make the <code>ListView</code> horizontally? I have done this using a gallery view, but the selected item comes to the center of the screen automatically. I don't want the selected item at the same spot I clicked. How can I rectify this problem? My idea was to set the <code>ListView</code> with a horizontal scroll. Share your idea?</p> | <p>As per Android Documentation <a href="https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html" rel="noreferrer"><code>RecyclerView</code></a> is the new way to organize the items in listview and to be displayed horizontally</p>
<p><strong>Advantages:</strong></p>
<ol>
<li>Since by using Recyclerview Adapter, <a href="http://developer.android.com/training/improving-layouts/smooth-scrolling.html" rel="noreferrer">ViewHolder pattern</a> is
automatically implemented</li>
<li>Animation is easy to perform</li>
<li>Many more features</li>
</ol>
<p><strong>More Information about <code>RecyclerView</code>:</strong></p>
<ol>
<li><a href="http://www.grokkingandroid.com/first-glance-androids-recyclerview/" rel="noreferrer">grokkingandroid.com</a></li>
<li><a href="http://antonioleiva.com/recyclerview/" rel="noreferrer">antonioleiva.com</a></li>
</ol>
<p><strong>Sample:</strong></p>
<p><a href="http://www.survivingwithandroid.com/2014/07/android-recyclerview.html" rel="noreferrer">survivingwithandroid.com</a></p>
<p>Just add the below block to make the <code>ListView</code> to horizontal from vertical</p>
<p><strong>Code-snippet</strong></p>
<pre><code>LinearLayoutManager layoutManager= new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(layoutManager);
</code></pre> | {
"question_id": 3240331,
"question_date": "2010-07-13T18:43:09.903Z",
"question_score": 219,
"tags": "android|listview|gallery|horizontal-scrolling",
"answer_id": 29648713,
"answer_date": "2015-04-15T11:13:43Z",
"answer_score": 125
} |
Please answer the following Stack Overflow question:
Title: Docker - a way to give access to a host USB or serial device?
<p>Last time I checked, <a href="http://www.docker.com/" rel="noreferrer">Docker didn't have any means to give container access to host serial or USB port</a>. Is there a trick which allows doing that?</p> | <p>There are a couple of options. You can use the <code>--device</code> flag that use can use to access USB devices without <code>--privileged</code> mode:</p>
<pre><code>docker run -t -i --device=/dev/ttyUSB0 ubuntu bash
</code></pre>
<p>Alternatively, assuming your USB device is available with drivers working, etc. on the host in <code>/dev/bus/usb</code>, you can mount this in the container using <a href="https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities" rel="noreferrer">privileged mode</a> and the <a href="https://docs.docker.com/userguide/dockervolumes/" rel="noreferrer">volumes option</a>. For example:</p>
<pre><code>docker run -t -i --privileged -v /dev/bus/usb:/dev/bus/usb ubuntu bash
</code></pre>
<p>Note that as the name implies, <code>--privileged</code> is <a href="https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/" rel="noreferrer">insecure</a> and should be handled with care.</p> | {
"question_id": 24225647,
"question_date": "2014-06-15T00:56:48.087Z",
"question_score": 219,
"tags": "docker",
"answer_id": 24231872,
"answer_date": "2014-06-15T16:48:52.927Z",
"answer_score": 280
} |
Please answer the following Stack Overflow question:
Title: Modify table: How to change 'Allow Nulls' attribute from not null to allow null
<p>How to change one attribute in a table using T-SQL to allow nulls (not null --> null)? Alter table maybe?</p> | <pre><code>-- replace NVARCHAR(42) with the actual type of your column
ALTER TABLE your_table
ALTER COLUMN your_column NVARCHAR(42) NULL
</code></pre> | {
"question_id": 3889916,
"question_date": "2010-10-08T11:12:06.417Z",
"question_score": 219,
"tags": "sql|sql-server|sql-server-2008",
"answer_id": 3889944,
"answer_date": "2010-10-08T11:16:32.957Z",
"answer_score": 384
} |
Please answer the following Stack Overflow question:
Title: How to format DateTime in Flutter
<p>I am trying to display the current <code>DateTime</code> in a <code>Text</code> widget after tapping on a button. The following works, but I'd like to change the format.</p>
<p><strong>Current approach</strong></p>
<pre><code>DateTime now = DateTime.now();
currentTime = new DateTime(now.year, now.month, now.day, now.hour, now.minute);
Text('$currentTime'),
</code></pre>
<p><strong>Result</strong></p>
<p><code>YYYY-MM-JJ HH-MM:00.000</code></p>
<p><strong>Question</strong></p>
<p>How can I remove the <code>:00.000</code> part?</p> | <p>You can use <code>DateFormat</code> from <strong><a href="https://pub.dev/packages/intl" rel="noreferrer">intl</a></strong> package.</p>
<pre class="lang-dart prettyprint-override"><code>import 'package:intl/intl.dart';
DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);
</code></pre> | {
"question_id": 51579546,
"question_date": "2018-07-29T10:54:30.240Z",
"question_score": 219,
"tags": "android|ios|flutter|datetime|dart",
"answer_id": 51579740,
"answer_date": "2018-07-29T11:15:31.700Z",
"answer_score": 438
} |
Please answer the following Stack Overflow question:
Title: Best way to use PHP to encrypt and decrypt passwords?
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/5089841/php-2-way-encryption-i-need-to-store-passwords-that-can-be-retrieved">PHP 2-way encryption: I need to store passwords that can be retrieved</a> </p>
</blockquote>
<p>I plan to store foreign account information for my users on my website, aka rapidshare username and passwords, etc... I want to keep information secure, but I know that if I hash their information, I can't retrieve it for later use. </p>
<p>Base64 is decrypt-able so there's no point using that just plain off.
My idea is to scramble the user and pass before and after it gets base64ed that way even after you decrypt it, you get some funny looking text if you try to decrypt. Is there a php function that accepts values that will make an unique scramble of a string and de-scramble it later when the value is reinputed?</p>
<p>Any suggestions?</p> | <p><strong>You should not encrypt passwords, instead you should hash them using an algorithm like bcrypt. <a href="https://stackoverflow.com/a/6337021/2224584">This answer explains how to properly implement password hashing in PHP</a>.</strong> Still, here is how you would encrypt/decrypt:</p>
<pre><code>$key = 'password to (en/de)crypt';
$string = ' string to be encrypted '; // note the spaces
</code></pre>
<p><strong>To Encrypt:</strong></p>
<pre><code>$iv = mcrypt_create_iv(
mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC),
MCRYPT_DEV_URANDOM
);
$encrypted = base64_encode(
$iv .
mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true),
$string,
MCRYPT_MODE_CBC,
$iv
)
);
</code></pre>
<p><strong>To Decrypt:</strong></p>
<pre><code>$data = base64_decode($encrypted);
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
$decrypted = rtrim(
mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true),
substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)),
MCRYPT_MODE_CBC,
$iv
),
"\0"
);
</code></pre>
<hr>
<p><strong>Warning</strong>: The above example encrypts information, but it does not authenticate the ciphertext to prevent tampering. <a href="https://paragonie.com/blog/2015/05/using-encryption-and-authentication-correctly" rel="noreferrer">You should <em>not</em> rely on unauthenticated encryption for security</a>, especially since the code as provided is vulnerable to padding oracle attacks.</p>
<p>See also:</p>
<ul>
<li><a href="https://stackoverflow.com/a/30189841/2224584">https://stackoverflow.com/a/30189841/2224584</a></li>
<li><a href="https://stackoverflow.com/a/30166085/2224584">https://stackoverflow.com/a/30166085/2224584</a></li>
<li><a href="https://stackoverflow.com/a/30159120/2224584">https://stackoverflow.com/a/30159120/2224584</a></li>
</ul>
<p>Also, don't just use a "password" for an encryption key. <strong>Encryption keys are random strings.</strong></p>
<hr>
<p><a href="http://3v4l.org/CJfSn" rel="noreferrer">Demo at 3v4l.org</a>:</p>
<pre><code>echo 'Encrypted:' . "\n";
var_dump($encrypted); // "m1DSXVlAKJnLm7k3WrVd51omGL/05JJrPluBonO9W+9ohkNuw8rWdJW6NeLNc688="
echo "\n";
echo 'Decrypted:' . "\n";
var_dump($decrypted); // " string to be encrypted "
</code></pre> | {
"question_id": 1289061,
"question_date": "2009-08-17T16:39:02.723Z",
"question_score": 219,
"tags": "php|mcrypt|encryption|scramble",
"answer_id": 1289114,
"answer_date": "2009-08-17T16:49:56.117Z",
"answer_score": 303
} |
Please answer the following Stack Overflow question:
Title: reducing number of plot ticks
<p>I have too many ticks on my graph and they are running into each other.</p>
<p>How can I reduce the number of ticks? </p>
<p>For example, I have ticks:</p>
<pre><code>1E-6, 1E-5, 1E-4, ... 1E6, 1E7
</code></pre>
<p>And I only want:</p>
<pre><code>1E-5, 1E-3, ... 1E5, 1E7
</code></pre>
<p>I've tried playing with the <code>LogLocator</code>, but I haven't been able to figure this out.</p> | <p>Alternatively, if you want to simply set the number of ticks while allowing matplotlib to position them (currently only with <code>MaxNLocator</code>), there is <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.locator_params" rel="noreferrer"><code>pyplot.locator_params</code></a>,</p>
<pre><code>pyplot.locator_params(nbins=4)
</code></pre>
<p>You can specify specific axis in this method as mentioned below, default is both:</p>
<pre><code># To specify the number of ticks on both or any single axes
pyplot.locator_params(axis='y', nbins=6)
pyplot.locator_params(axis='x', nbins=10)
</code></pre> | {
"question_id": 6682784,
"question_date": "2011-07-13T17:08:16.583Z",
"question_score": 219,
"tags": "python|matplotlib",
"answer_id": 13418954,
"answer_date": "2012-11-16T14:51:17.677Z",
"answer_score": 324
} |
Please answer the following Stack Overflow question:
Title: Is there a way that I can check if a data attribute exists?
<p>Is there some way that I can run the following:</p>
<pre><code>var data = $("#dataTable").data('timer');
var diffs = [];
for(var i = 0; i + 1 < data.length; i++) {
diffs[i] = data[i + 1] - data[i];
}
alert(diffs.join(', '));
</code></pre>
<p><strong>Only</strong> if there is an attribute called data-timer on the element with an id of #dataTable?</p> | <pre><code>if ($("#dataTable").data('timer')) {
...
}
</code></pre>
<p>NOTE this only returns <code>true</code> if the data attribute is not empty string or a "falsey" value e.g. <code>0</code> or <code>false</code>.</p>
<p>If you want to check for the existence of the data attribute, even if empty, do this:</p>
<pre><code>if (typeof $("#dataTable").data('timer') !== 'undefined') {
...
}
</code></pre> | {
"question_id": 12161132,
"question_date": "2012-08-28T14:09:59.653Z",
"question_score": 219,
"tags": "javascript|jquery",
"answer_id": 12161190,
"answer_date": "2012-08-28T14:12:33.890Z",
"answer_score": 349
} |
Please answer the following Stack Overflow question:
Title: Android Studio suddenly cannot resolve symbols
<p>Android Studio 0.4.2 was working fine and today I opened it and almost everything was red and the auto-completion had stopped working. I look at the imports and AS seems to be telling me it can't find <strong>android.support.v4</strong> all of a sudden (offering me the option to remove the unused imports). (<strong>android.support.v7</strong> seems to be fine though).</p>
<p>Things I have tried: </p>
<ul>
<li>Rebuilding the project</li>
<li>Cleaning the project</li>
<li>Syncing with Gradle Files</li>
<li>Closing the Project, closing AS and relaunching / reopening</li>
<li>File > Invalidate Caches / Restart</li>
<li>Examining Lint, didn't see anything obvious</li>
<li>Double checking all support libraries are up to date in the SDK manager</li>
<li>Examining my Build.gradle, although no changes and it's the same as usual, the way it was working all the time.</li>
</ul>
<p>Here it is in case it's relevant:</p>
<pre><code>buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.7.+'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
}
android {
compileSdkVersion 19
buildToolsVersion '19.0.0'
defaultConfig {
minSdkVersion 8
targetSdkVersion 19
}
}
dependencies {
compile 'com.android.support:support-v4:19.0.0'
compile 'com.android.support:gridlayout-v7:19.0.0'
compile 'com.android.support:appcompat-v7:19.0.0'
compile 'com.google.android.gms:play-services:4.0.30'
compile project(':libraries:facebook')
compile files('libs/core.jar')
}
</code></pre>
<p>When I hit "Sync with Gradle" and open "Project Settings" I get a red error telling me I have duplicate library references and to remove the unused ones..
<img src="https://i.stack.imgur.com/YACON.jpg" alt="enter image description here"></p>
<p>My project compiles and runs fine but I really need the autocomplete working!! Does anyone have any suggestions?</p>
<p><img src="https://i.stack.imgur.com/ZzJDV.jpg" alt="enter image description here"></p> | <p>You've already gone down the list of most things that would be helpful, but you could try:</p>
<ul>
<li>Exit Android Studio</li>
<li>Back up your project</li>
<li>Delete all the .iml files and the .idea folder</li>
<li>Relaunch Android Studio and reimport your project</li>
</ul>
<p>By the way, the error messages you see in the Project Structure dialog are bogus for the most part. </p>
<p>UPDATE:</p>
<p>Android Studio 0.4.3 is available in the canary update channel, and should hopefully solve most of these issues. There may be some lingering problems; if you see them in 0.4.3, let us know, and try to give us a reliable set of steps to reproduce so we can ensure we've taken care of all code paths.</p> | {
"question_id": 21100688,
"question_date": "2014-01-13T20:24:29.683Z",
"question_score": 219,
"tags": "android|import|gradle|android-studio",
"answer_id": 21100896,
"answer_date": "2014-01-13T20:39:56.273Z",
"answer_score": 240
} |
Please answer the following Stack Overflow question:
Title: Java Delegates?
<p>Does the Java language have delegate features, similar to how C# has support for delegates?</p> | <p>Not really, no.</p>
<p>You may be able to achieve the same effect by using reflection to get Method objects you can then invoke, and the other way is to create an interface with a single 'invoke' or 'execute' method, and then instantiate them to call the method your interested in (i.e. using an anonymous inner class).</p>
<p>You might also find this article interesting / useful : <a href="https://web.archive.org/web/20210225165533/https://www.blueskyprojects.com/print-design/" rel="nofollow noreferrer">A Java Programmer Looks at C# Delegates (@blueskyprojects.com)</a></p> | {
"question_id": 44912,
"question_date": "2008-09-04T22:45:00.030Z",
"question_score": 219,
"tags": "java|delegates",
"answer_id": 44928,
"answer_date": "2008-09-04T22:54:49.447Z",
"answer_score": 166
} |
Please answer the following Stack Overflow question:
Title: How to get a file or blob from an object URL?
<p>I am allowing the user to load images into a page via drag&drop and other methods. When an image is dropped, I'm using <code>URL.createObjectURL</code> to convert to an object URL to display the image. I am not revoking the url, as I do reuse it.</p>
<p>So, when it comes time to create a <code>FormData</code> object so I can allow them to upload a form with one of those images in it, is there some way I can then reverse that Object URL back into a <code>Blob</code> or <code>File</code> so I can then append it to a <code>FormData</code> object?</p> | <p>Modern solution:</p>
<pre><code>let blob = await fetch(url).then(r => r.blob());
</code></pre>
<p>The url can be an object url or a normal url.</p> | {
"question_id": 11876175,
"question_date": "2012-08-09T03:00:12.593Z",
"question_score": 219,
"tags": "javascript|html|fileapi|blobs",
"answer_id": 52410044,
"answer_date": "2018-09-19T16:04:41.453Z",
"answer_score": 222
} |
Please answer the following Stack Overflow question:
Title: PHP check whether property exists in object or class
<p>I understand PHP does not have a pure object variable, but I want to check whether a property is in the given object or class.</p>
<pre><code>$ob = (object) array('a' => 1, 'b' => 12);
</code></pre>
<p>or</p>
<pre><code>$ob = new stdClass;
$ob->a = 1;
$ob->b = 2;
</code></pre>
<p>In <strong>JS,</strong> I can write this to check if variable <code>a</code> exists in an object:</p>
<pre><code>if ('a' in ob)
</code></pre>
<p>In <strong>PHP,</strong> can anything like this be done?</p> | <p><a href="http://php.net/manual/en/function.property-exists" rel="noreferrer"><h3>property_exists( mixed $class , string $property )</h3></a></p>
<pre><code>if (property_exists($ob, 'a'))
</code></pre>
<hr />
<p><a href="http://php.net/manual/en/function.isset.php" rel="noreferrer"><h3>isset( mixed $var [, mixed $... ] )</h3></a></p>
<p><strong>NOTE</strong> : Mind that <strong>isset() will return false if property is null</strong></p>
<pre><code>if (isset($ob->a))
</code></pre>
<hr />
<p>Example 1:</p>
<pre><code>$ob->a = null
var_dump(isset($ob->a)); // false
</code></pre>
<p>Example 2:</p>
<pre><code>class Foo
{
public $bar = null;
}
$foo = new Foo();
var_dump(property_exists($foo, 'bar')); // true
var_dump(isset($foo->bar)); // false
</code></pre> | {
"question_id": 14414379,
"question_date": "2013-01-19T12:30:49.447Z",
"question_score": 219,
"tags": "php|class|variables|object|parameters",
"answer_id": 14414386,
"answer_date": "2013-01-19T12:32:10.450Z",
"answer_score": 369
} |
Please answer the following Stack Overflow question:
Title: How do you create a Swift Date object?
<p>How do you create a date object from a date in swift xcode.</p>
<p>eg in javascript you would do:
<code>var day = new Date('2014-05-20');</code></p> | <p><em>Swift has its own <code>Date</code> type. No need to use <code>NSDate</code>.</em></p>
<h1>Creating a Date and Time in Swift</h1>
<p>In Swift, dates and times are stored in a 64-bit floating point number measuring the number of seconds since the reference date of January 1, 2001 at 00:00:00 <a href="http://www.timeanddate.com/time/aboututc.html" rel="noreferrer">UTC</a>. This is expressed in the <a href="https://developer.apple.com/reference/foundation/date" rel="noreferrer"><code>Date</code> structure</a>. The following would give you the current date and time:</p>
<pre><code>let currentDateTime = Date()
</code></pre>
<p>For creating other date-times, you can use one of the following methods.</p>
<p><strong>Method 1</strong></p>
<p>If you know the number of seconds before or after the 2001 reference date, you can use that.</p>
<pre><code>let someDateTime = Date(timeIntervalSinceReferenceDate: -123456789.0) // Feb 2, 1997, 10:26 AM
</code></pre>
<p><strong>Method 2</strong></p>
<p>Of course, it would be easier to use things like years, months, days and hours (rather than relative seconds) to make a <code>Date</code>. For this you can use <code>DateComponents</code> to specify the components and then <code>Calendar</code> to create the date. The <code>Calendar</code> gives the <code>Date</code> context. Otherwise, how would it know what time zone or calendar to express it in?</p>
<pre><code>// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 1980
dateComponents.month = 7
dateComponents.day = 11
dateComponents.timeZone = TimeZone(abbreviation: "JST") // Japan Standard Time
dateComponents.hour = 8
dateComponents.minute = 34
// Create date from components
let userCalendar = Calendar(identifier: .gregorian) // since the components above (like year 1980) are for Gregorian
let someDateTime = userCalendar.date(from: dateComponents)
</code></pre>
<p>Other time zone abbreviations can be found <a href="https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations" rel="noreferrer">here</a>. If you leave that blank, then the default is to use the user's time zone.</p>
<p><strong>Method 3</strong></p>
<p>The most succinct way (but not necessarily the best) could be to use <code>DateFormatter</code>.</p>
<pre><code>let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let someDateTime = formatter.date(from: "2016/10/08 22:31")
</code></pre>
<p>The <a href="http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns" rel="noreferrer">Unicode technical standards show other formats</a> that <code>DateFormatter</code> supports.</p>
<h1>Notes</h1>
<p>See <a href="https://stackoverflow.com/a/33343958/3681880">my full answer</a> for how to display the date and time in a readable format. Also read these excellent articles:</p>
<ul>
<li><a href="http://www.globalnerdy.com/2016/08/18/how-to-work-with-dates-and-times-in-swift-3-part-1-dates-calendars-and-datecomponents/" rel="noreferrer">How to work with dates and times in Swift 3, part 1: Dates, Calendars, and DateComponents</a></li>
<li><a href="http://www.globalnerdy.com/2016/08/22/how-to-work-with-dates-and-times-in-swift-3-part-2-dateformatter/" rel="noreferrer">How to work with dates and times in Swift 3, part 2: DateFormatter</a></li>
<li><a href="http://www.globalnerdy.com/2016/08/29/how-to-work-with-dates-and-times-in-swift-3-part-3-date-arithmetic/" rel="noreferrer">How to work with dates and times in Swift 3, part 3: Date arithmetic</a></li>
</ul> | {
"question_id": 24089999,
"question_date": "2014-06-06T20:18:00.157Z",
"question_score": 219,
"tags": "ios|iphone|swift|nsdate",
"answer_id": 33344575,
"answer_date": "2015-10-26T11:24:53.600Z",
"answer_score": 355
} |
Please answer the following Stack Overflow question:
Title: Finding index of character in Swift String
<p>It's time to admit defeat...</p>
<p>In Objective-C, I could use something like: </p>
<pre><code>NSString* str = @"abcdefghi";
[str rangeOfString:@"c"].location; // 2
</code></pre>
<p>In Swift, I see something similar: </p>
<pre><code>var str = "abcdefghi"
str.rangeOfString("c").startIndex
</code></pre>
<p>...but that just gives me a <code>String.Index</code>, which I can use to subscript back into the original string, but not extract a location from. </p>
<p>FWIW, that <code>String.Index</code> has a private ivar called <code>_position</code> that has the correct value in it. I just don't see how it's exposed.</p>
<p>I know I could easily add this to String myself. I'm more curious about what I'm missing in this new API.</p> | <p>You are not the only one who couldn't find the solution.</p>
<p><code>String</code> doesn't implement <code>RandomAccessIndexType</code>. Probably because they enable characters with different byte lengths. That's why we have to use <code>string.characters.count</code> (<code>count</code> or <code>countElements</code> in Swift 1.x) to get the number of characters. That also applies to positions. The <code>_position</code> is probably an index into the raw array of bytes and they don't want to expose that. The <code>String.Index</code> is meant to protect us from accessing bytes in the middle of characters.</p>
<p>That means that any index you get must be created from <code>String.startIndex</code> or <code>String.endIndex</code> (<code>String.Index</code> implements <code>BidirectionalIndexType</code>). Any other indices can be created using <code>successor</code> or <code>predecessor</code> methods.</p>
<p>Now to help us with indices, there is a set of methods (functions in Swift 1.x):</p>
<p><em>Swift 4.x</em></p>
<pre><code>let text = "abc"
let index2 = text.index(text.startIndex, offsetBy: 2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let characterIndex2 = text.index(text.startIndex, offsetBy: 2)
let lastChar2 = text[characterIndex2] //will do the same as above
let range: Range<String.Index> = text.range(of: "b")!
let index: Int = text.distance(from: text.startIndex, to: range.lowerBound)
</code></pre>
<p><em>Swift 3.0</em></p>
<pre><code>let text = "abc"
let index2 = text.index(text.startIndex, offsetBy: 2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let characterIndex2 = text.characters.index(text.characters.startIndex, offsetBy: 2)
let lastChar2 = text.characters[characterIndex2] //will do the same as above
let range: Range<String.Index> = text.range(of: "b")!
let index: Int = text.distance(from: text.startIndex, to: range.lowerBound)
</code></pre>
<p><em>Swift 2.x</em></p>
<pre><code>let text = "abc"
let index2 = text.startIndex.advancedBy(2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let lastChar2 = text.characters[index2] //will do the same as above
let range: Range<String.Index> = text.rangeOfString("b")!
let index: Int = text.startIndex.distanceTo(range.startIndex) //will call successor/predecessor several times until the indices match
</code></pre>
<p><em>Swift 1.x</em></p>
<pre><code>let text = "abc"
let index2 = advance(text.startIndex, 2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let range = text.rangeOfString("b")
let index: Int = distance(text.startIndex, range.startIndex) //will call succ/pred several times
</code></pre>
<p>Working with <code>String.Index</code> is cumbersome but using a wrapper to index by integers (see <a href="https://stackoverflow.com/a/25152652/669586">https://stackoverflow.com/a/25152652/669586</a>) is dangerous because it hides the inefficiency of real indexing.</p>
<p>Note that Swift indexing implementation has the problem that <b>indices/ranges created for one string cannot be reliably used for a different string</b>, for example:</p>
<p><em>Swift 2.x</em></p>
<pre><code>let text: String = "abc"
let text2: String = ""
let range = text.rangeOfString("b")!
//can randomly return a bad substring or throw an exception
let substring: String = text2[range]
//the correct solution
let intIndex: Int = text.startIndex.distanceTo(range.startIndex)
let startIndex2 = text2.startIndex.advancedBy(intIndex)
let range2 = startIndex2...startIndex2
let substring: String = text2[range2]
</code></pre>
<p><em>Swift 1.x</em></p>
<pre><code>let text: String = "abc"
let text2: String = ""
let range = text.rangeOfString("b")
//can randomly return nil or a bad substring
let substring: String = text2[range]
//the correct solution
let intIndex: Int = distance(text.startIndex, range.startIndex)
let startIndex2 = advance(text2.startIndex, intIndex)
let range2 = startIndex2...startIndex2
let substring: String = text2[range2]
</code></pre> | {
"question_id": 24029163,
"question_date": "2014-06-04T04:42:23.520Z",
"question_score": 219,
"tags": "string|swift",
"answer_id": 24056932,
"answer_date": "2014-06-05T09:49:32.170Z",
"answer_score": 255
} |
Please answer the following Stack Overflow question:
Title: How to set an iframe src attribute from a variable in AngularJS
<p>I'm trying to set the <code>src</code> attribute of an iframe from a variable and I can't get it to work...</p>
<p>The markup:</p>
<pre><code><div class="col-xs-12" ng-controller="AppCtrl">
<ul class="">
<li ng-repeat="project in projects">
<a ng-click="setProject(project.id)" href="">{{project.url}}</a>
</li>
</ul>
<iframe ng-src="{{trustSrc(currentProject.url)}}">
Something wrong...
</iframe>
</div>
</code></pre>
<p>controllers/app.js:</p>
<pre><code>function AppCtrl ($scope) {
$scope.projects = {
1 : {
"id" : 1,
"name" : "Mela Sarkar",
"url" : "http://blabla.com",
"description" : "A professional portfolio site for McGill University professor Mela Sarkar."
},
2 : {
"id" : 2,
"name" : "Good Watching",
"url" : "http://goodwatching.com",
"description" : "Weekend experiment to help my mom decide what to watch."
}
};
$scope.setProject = function (id) {
$scope.currentProject = $scope.projects[id];
console.log( $scope.currentProject );
}
}
</code></pre>
<p>With this code, nothing gets inserted into the iframe's <code>src</code> attribute. It's just blank.</p>
<p><strong>Update 1:</strong>
I injected the <code>$sce</code> dependancy into the AppCtrl and $sce.trustUrl() now works without throwing errors. However it returns <code>TrustedValueHolderType</code> which I'm not sure how to use to insert an actual URL. The same type is returned whether I use $sce.trustUrl() inside the interpolation braces in the attribute <code>src="{{trustUrl(currentProjectUrl))}}"</code> or if I do it inside the controller when setting the value of currentProjectUrl. I even tried it with both.</p>
<p><strong>Update 2:</strong>
I figured out how to return the url from the trustedUrlHolder using .toString() but when I do that, it throws the security warning when I try to pass it into the src attribute.</p>
<p><strong>Update 3:</strong>
It works if I use trustAsResourceUrl() in the controller and pass that to a variable used inside the ng-src attribute:</p>
<pre><code>$scope.setProject = function (id) {
$scope.currentProject = $scope.projects[id];
$scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
console.log( $scope.currentProject );
console.log( $scope.currentProjectUrl );
}
</code></pre>
<p>My problem seems to be solved by this, although I'm not quite sure why.</p> | <p>I suspect looking at the excerpt that the function <code>trustSrc</code> from <code>trustSrc(currentProject.url)</code> is not defined in the controller. </p>
<p>You need to inject the <a href="http://docs.angularjs.org/api/ng.$sce" rel="noreferrer"><code>$sce</code> service</a> in the controller and <code>trustAsResourceUrl</code> the <code>url</code> there.</p>
<p>In the controller:</p>
<pre class="lang-js prettyprint-override"><code>function AppCtrl($scope, $sce) {
// ...
$scope.setProject = function (id) {
$scope.currentProject = $scope.projects[id];
$scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
}
}
</code></pre>
<p>In the Template:</p>
<pre class="lang-html prettyprint-override"><code><iframe ng-src="{{currentProjectUrl}}"> <!--content--> </iframe>
</code></pre> | {
"question_id": 20045150,
"question_date": "2013-11-18T10:11:49.263Z",
"question_score": 219,
"tags": "javascript|html|angularjs|iframe|angularjs-directive",
"answer_id": 20045301,
"answer_date": "2013-11-18T10:18:57.337Z",
"answer_score": 372
} |
Please answer the following Stack Overflow question:
Title: Nested rows with bootstrap grid system?
<p>I want 1 larger image with 4 smaller images in a 2x2 format like this: </p>
<p><img src="https://i.stack.imgur.com/tdxuMm.png" alt="Figure 1 Example"></p>
<p>My initial thought was to house everything in one row. Then create two columns, and, in the second column, create two rows and two columns to create the 1x1 and 2x2 effect. </p>
<p>However, this doesn't seem to be possible, or I am just not doing it correctly?</p> | <h2>Bootstrap Version 3.x</h2>
<p>As always, read Bootstrap's great documentation:</p>
<p><strong>3.x Docs</strong>: <a href="https://getbootstrap.com/docs/3.3/css/#grid-nesting" rel="noreferrer">https://getbootstrap.com/docs/3.3/css/#grid-nesting</a></p>
<p>Make sure the parent level row is inside of a <code>.container</code> element. Whenever you'd like to nest rows, just open up a new <code>.row</code> inside of your column.</p>
<p>Here's a simple layout to work from:</p>
<pre class="lang-html prettyprint-override"><code><div class="container">
<div class="row">
<div class="col-xs-6">
<div class="big-box">image</div>
</div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-6"><div class="mini-box">1</div></div>
<div class="col-xs-6"><div class="mini-box">2</div></div>
<div class="col-xs-6"><div class="mini-box">3</div></div>
<div class="col-xs-6"><div class="mini-box">4</div></div>
</div>
</div>
</div>
</div>
</code></pre>
<h2>Bootstrap Version 4.0</h2>
<p><strong>4.0 Docs</strong>: <a href="http://getbootstrap.com/docs/4.0/layout/grid/#nesting" rel="noreferrer">http://getbootstrap.com/docs/4.0/layout/grid/#nesting</a></p>
<p>Here's an updated version for 4.0, but you should really read the entire docs section on the grid so you understand how to leverage this powerful feature</p>
<pre class="lang-html prettyprint-override"><code><div class="container">
<div class="row">
<div class="col big-box">
image
</div>
<div class="col">
<div class="row">
<div class="col mini-box">1</div>
<div class="col mini-box">2</div>
</div>
<div class="row">
<div class="col mini-box">3</div>
<div class="col mini-box">4</div>
</div>
</div>
</div>
</div>
</code></pre>
<h3>Demo in Fiddle <a href="http://jsfiddle.net/KyleMit/fbtw6/" rel="noreferrer">jsFiddle 3.x</a> | <a href="http://jsfiddle.net/KyleMit/4bo2uxgs/" rel="noreferrer">jsFiddle 4.0</a></h3>
<p>Which will look like this (<em>with a little bit of added styling</em>):</p>
<p><img src="https://i.imgur.com/y2kk0xi.png" alt="screenshot"></p> | {
"question_id": 24659471,
"question_date": "2014-07-09T16:49:55.367Z",
"question_score": 219,
"tags": "css|html|twitter-bootstrap|grid|grid-system",
"answer_id": 24661416,
"answer_date": "2014-07-09T18:39:25.857Z",
"answer_score": 345
} |
Please answer the following Stack Overflow question:
Title: Laravel PHP Command Not Found
<p>I have installed Laravel using composer without problems, but when I try to execute "<em>laravel</em>" in my terminal I have this typical error:</p>
<blockquote>
<p>-bash: laravel: command not found</p>
</blockquote>
<p>If I read the documentation of the official site I need to do that:</p>
<blockquote>
<p>Make sure to place the ~/.composer/vendor/bin directory in your PATH so the laravel executable is found when you run the <em>laravel</em> command in your terminal.</p>
</blockquote>
<p>But I don't know how to do (I'm new on terminal console commands).</p>
<p>Can you help me with that? Thanks!!</p> | <p>Ok, I did that and it works:</p>
<pre><code>nano ~/.bash_profile
</code></pre>
<p>And paste</p>
<pre><code>export PATH=~/.composer/vendor/bin:$PATH
</code></pre>
<p>do <code>source ~/.bash_profile</code> and enjoy ;)</p>
<p><strong>Important</strong>: If you want to know the difference between <em>bash_profile</em> and <em>bashrc</em> please check this <a href="http://www.joshstaiger.org/archives/2005/07/bash_profile_vs.html" rel="noreferrer">link</a></p>
<p><strong>Note:</strong> For Ubuntu 16.04 running laravel 5.1, the path is: ~/.config/composer/vendor/bin</p>
<p><strong>On other platforms:</strong> To check where your Composer global directory is, run <code>composer global about</code>. Add <code>/vendor/bin</code> to the directory that gets listed after "Changed current directory to ..." to get the path you should add to your <code>PATH</code>.</p> | {
"question_id": 26376516,
"question_date": "2014-10-15T07:10:37.997Z",
"question_score": 219,
"tags": "php|bash|laravel",
"answer_id": 26376773,
"answer_date": "2014-10-15T07:24:55.823Z",
"answer_score": 351
} |
Please answer the following Stack Overflow question:
Title: Raw SQL Query without DbSet - Entity Framework Core
<p>With Entity Framework Core removing <code>dbData.Database.SqlQuery<SomeModel></code> I can't find a solution to build a raw SQL Query for my full-text search query that will return the tables data and also the rank. </p>
<p>The only method I've seen to build a raw SQL query in Entity Framework Core is via <code>dbData.Product.FromSql("SQL SCRIPT");</code> which isn't useful as I have no DbSet that will map the rank I return in the query.</p>
<p><strong>Any Ideas???</strong></p> | <h2>If you're using EF Core 3.0 or newer</h2>
<p>You need to use <a href="https://docs.microsoft.com/ef/core/modeling/keyless-entity-types?tabs=data-annotations" rel="nofollow noreferrer">keyless entity types</a>, previously known as query types:</p>
<blockquote>
<p>This feature was added in EF Core 2.1 under the name of query types.
In EF Core 3.0 the concept was renamed to keyless entity types. The
[Keyless] Data Annotation became available in EFCore 5.0.</p>
</blockquote>
<p>To use them you need to first mark your class <code>SomeModel</code> with <code>[Keyless]</code> data annotation or through fluent configuration with <code>.HasNoKey()</code> method call like below:</p>
<pre><code>public DbSet<SomeModel> SomeModels { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<SomeModel>().HasNoKey();
}
</code></pre>
<p>After that configuration, you can use one of the methods <a href="https://docs.microsoft.com/ef/core/querying/raw-sql" rel="nofollow noreferrer">explained here</a> to execute your SQL query. For example you can use this one:</p>
<pre><code>var result = context.SomeModels.FromSqlRaw("SQL SCRIPT").ToList();
var result = await context.SomeModels.FromSql("SQL_SCRIPT").ToListAsync();
</code></pre>
<hr />
<h2>If you're using EF Core 2.1</h2>
<p>If you're using EF Core 2.1 Release Candidate 1 available since 7 may 2018, you can take advantage of the proposed new feature which is <a href="https://docs.microsoft.com/ef/core/modeling/query-types" rel="nofollow noreferrer">query types</a>:</p>
<blockquote>
<p>In addition to entity types, an EF Core model can contain query types,
which can be used to carry out database queries against data that
isn't mapped to entity types.</p>
</blockquote>
<p>When to use query type?</p>
<blockquote>
<p>Serving as the return type for ad hoc FromSql() queries.</p>
<p>Mapping to database views.</p>
<p>Mapping to tables that do not have a primary key defined.</p>
<p>Mapping to queries defined in the model.</p>
</blockquote>
<p>So you no longer need to do all the hacks or workarounds proposed as answers to your question. Just follow these steps:</p>
<p>First you defined a new property of type <code>DbQuery<T></code> where <code>T</code> is the type of the class that will carry the column values of your SQL query. So in your <code>DbContext</code> you'll have this:</p>
<pre><code>public DbQuery<SomeModel> SomeModels { get; set; }
</code></pre>
<p>Secondly use <code>FromSql</code> method like you do with <code>DbSet<T></code>:</p>
<pre><code>var result = context.SomeModels.FromSql("SQL_SCRIPT").ToList();
var result = await context.SomeModels.FromSql("SQL_SCRIPT").ToListAsync();
</code></pre>
<p>Also note that <code>DbContext</code>s are <a href="https://docs.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/partial-classes-and-methods" rel="nofollow noreferrer">partial classes</a>, so you can create one or more separate files to organize your 'raw SQL DbQuery' definitions as best suits you.</p> | {
"question_id": 35631903,
"question_date": "2016-02-25T15:44:12.020Z",
"question_score": 219,
"tags": "c#|entity-framework-core",
"answer_id": 50452479,
"answer_date": "2018-05-21T15:54:14.993Z",
"answer_score": 226
} |
Please answer the following Stack Overflow question:
Title: How to delete a whole folder and content?
<p>I want the users of my application to be able to delete the DCIM folder (which is located on the SD card and contains subfolders).</p>
<p>Is this possible, if so how?</p> | <p>Let me tell you first thing you cannot delete the DCIM folder because it is a system folder. As you delete it manually on phone it will delete the contents of that folder, but not the DCIM folder. You can delete its contents by using the method below:</p>
<p><strong>Updated</strong> as per comments</p>
<pre><code>File dir = new File(Environment.getExternalStorageDirectory()+"Dir_name_here");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
</code></pre> | {
"question_id": 4943629,
"question_date": "2011-02-09T10:32:41.130Z",
"question_score": 219,
"tags": "android|file-io|directory|delete-directory",
"answer_id": 4943771,
"answer_date": "2011-02-09T10:45:01.760Z",
"answer_score": 325
} |
Please answer the following Stack Overflow question:
Title: sqlite database default time value 'now'
<p>Is it possible in a sqlite database to craete a table that has a timestamp column that default to <code>DATETIME('now')</code> ?</p>
<p>Like this:</p>
<pre><code>CREATE TABLE test (
id INTEGER PRIMARY KEY AUTOINCREMENT,
t TIMESTAMP DEFAULT DATETIME('now')
);
</code></pre>
<p>This gives an error... How to resolve?</p> | <p>i believe you can use</p>
<pre><code>CREATE TABLE test (
id INTEGER PRIMARY KEY AUTOINCREMENT,
t TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
);
</code></pre>
<p>as of version 3.1 (<a href="http://www.sqlite.org/lang_createtable.html" rel="noreferrer">source</a>)</p> | {
"question_id": 200309,
"question_date": "2008-10-14T07:56:27.897Z",
"question_score": 219,
"tags": "sql|sqlite",
"answer_id": 200329,
"answer_date": "2008-10-14T08:01:44.233Z",
"answer_score": 332
} |
Please answer the following Stack Overflow question:
Title: Getting value of enum on string conversion
<p>I have the following enum defined:</p>
<pre><code>from enum import Enum
class D(Enum):
x = 1
y = 2
print(D.x)
</code></pre>
<p>now the printed value is</p>
<pre><code>D.x
</code></pre>
<p>instead, I wanted the enum's value to be print</p>
<pre><code>1
</code></pre>
<p>What can be done to achieve this functionality?</p> | <p>You are printing the enum <em>object</em>. Use the <code>.value</code> attribute if you wanted just to print that:</p>
<pre><code>print(D.x.value)
</code></pre>
<p>See the <a href="https://docs.python.org/3/library/enum.html#programmatic-access-to-enumeration-members-and-their-attributes"><em>Programmatic access to enumeration members and their attributes</em> section</a>:</p>
<blockquote>
<p>If you have an enum member and need its name or value:</p>
<pre><code>>>>
>>> member = Color.red
>>> member.name
'red'
>>> member.value
1
</code></pre>
</blockquote>
<p>You could add a <code>__str__</code> method to your enum, if all you wanted was to provide a custom string representation:</p>
<pre><code>class D(Enum):
def __str__(self):
return str(self.value)
x = 1
y = 2
</code></pre>
<p>Demo:</p>
<pre><code>>>> from enum import Enum
>>> class D(Enum):
... def __str__(self):
... return str(self.value)
... x = 1
... y = 2
...
>>> D.x
<D.x: 1>
>>> print(D.x)
1
</code></pre> | {
"question_id": 24487405,
"question_date": "2014-06-30T09:54:24.870Z",
"question_score": 219,
"tags": "python|python-3.x|enums|python-3.4",
"answer_id": 24487545,
"answer_date": "2014-06-30T10:01:17.080Z",
"answer_score": 358
} |
Please answer the following Stack Overflow question:
Title: Numpy: Get random set of rows from 2D array
<p>I have a very large 2D array which looks something like this:</p>
<pre><code>a=
[[a1, b1, c1],
[a2, b2, c2],
...,
[an, bn, cn]]
</code></pre>
<p>Using numpy, is there an easy way to get a new 2D array with, e.g., 2 random rows from the initial array <code>a</code> (without replacement)?</p>
<p>e.g.</p>
<pre><code>b=
[[a4, b4, c4],
[a99, b99, c99]]
</code></pre> | <pre><code>>>> A = np.random.randint(5, size=(10,3))
>>> A
array([[1, 3, 0],
[3, 2, 0],
[0, 2, 1],
[1, 1, 4],
[3, 2, 2],
[0, 1, 0],
[1, 3, 1],
[0, 4, 1],
[2, 4, 2],
[3, 3, 1]])
>>> idx = np.random.randint(10, size=2)
>>> idx
array([7, 6])
>>> A[idx,:]
array([[0, 4, 1],
[1, 3, 1]])
</code></pre>
<p>Putting it together for a general case:</p>
<pre><code>A[np.random.randint(A.shape[0], size=2), :]
</code></pre>
<p>For non replacement (numpy 1.7.0+):</p>
<pre><code>A[np.random.choice(A.shape[0], 2, replace=False), :]
</code></pre>
<p>I do not believe there is a good way to generate random list without replacement before 1.7. Perhaps you can setup a small definition that ensures the two values are not the same.</p> | {
"question_id": 14262654,
"question_date": "2013-01-10T16:30:47.063Z",
"question_score": 219,
"tags": "python|numpy",
"answer_id": 14262743,
"answer_date": "2013-01-10T16:35:09.710Z",
"answer_score": 274
} |
Please answer the following Stack Overflow question:
Title: Standard Android menu icons, for example refresh
<p>The Android SDK offers the standard menu icons via <code>android.R.drawable.X</code>. However, some standard icons, such as <code>ic_menu_refresh</code> (the refresh icon), are missing from <code>android.R</code>.</p>
<p>Is there any way to get the original icons, maybe by extracting them from the applications? I already checked the Android source, but it's a bit too huge to look everywhere for the images.</p>
<p>I know the <a href="http://androiddrawables.com/" rel="noreferrer">Android Drawables</a> website, but I would like to get the correct <em>hdpi</em>, <em>mdpi</em> and <em>ldpi</em> version, preferable the original ones.</p> | <p>Never mind, I found it in the source: <a href="https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/" rel="noreferrer">base.git/core/res/res</a> and subdirectories.</p>
<p>As others said in the comments, if you have the Android SDK installed it’s also on your computer. The path is <code>[SDK]/platforms/android-[VERSION]/data/res</code>.</p> | {
"question_id": 2687027,
"question_date": "2010-04-21T22:35:04.360Z",
"question_score": 219,
"tags": "android|android-drawable|android-icons",
"answer_id": 2687060,
"answer_date": "2010-04-21T22:43:13.497Z",
"answer_score": 208
} |
Please answer the following Stack Overflow question:
Title: Random / noise functions for GLSL
<p>As the GPU driver vendors don't usually bother to implement <code>noiseX</code> in GLSL, I'm looking for a <em>"graphics randomization swiss army knife"</em> utility function set, preferably optimised to use within GPU shaders. I prefer GLSL, but code any language will do for me, I'm ok with translating it on my own to GLSL.</p>
<p>Specifically, I'd expect:</p>
<p>a) <strong>Pseudo-random functions</strong> - N-dimensional, uniform distribution over [-1,1] or over [0,1], calculated from M-dimensional seed (ideally being any value, but I'm OK with having the seed restrained to, say, 0..1 for uniform result distribution). Something like:</p>
<pre><code>float random (T seed);
vec2 random2 (T seed);
vec3 random3 (T seed);
vec4 random4 (T seed);
// T being either float, vec2, vec3, vec4 - ideally.
</code></pre>
<p>b) <strong>Continous noise</strong> like Perlin Noise - again, N-dimensional, +- uniform distribution, with constrained set of values and, well, looking good (some options to configure the appearance like Perlin levels could be useful too). I'd expect signatures like:</p>
<pre><code>float noise (T coord, TT seed);
vec2 noise2 (T coord, TT seed);
// ...
</code></pre>
<p>I'm not very much into random number generation theory, so I'd most eagerly go for a <strong>pre-made solution</strong>, but I'd also appreciate answers like <em>"here's a very good, efficient 1D rand(), and let me explain you how to make a good N-dimensional rand() on top of it..."</em> .</p> | <p>For very simple pseudorandom-looking stuff, I use this oneliner that I found on the internet somewhere:</p>
<pre><code>float rand(vec2 co){
return fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453);
}
</code></pre>
<p>You can also generate a noise texture using whatever PRNG you like, then upload this in the normal fashion and sample the values in your shader; I can dig up a code sample later if you'd like.</p>
<p>Also, check out <a href="http://www.davidcornette.com/glsl/GLSL-noise.zip" rel="noreferrer">this file</a> for GLSL implementations of Perlin and Simplex noise, by Stefan Gustavson.</p> | {
"question_id": 4200224,
"question_date": "2010-11-16T23:50:50.387Z",
"question_score": 219,
"tags": "random|shader|glsl|noise|perlin-noise",
"answer_id": 4275343,
"answer_date": "2010-11-25T09:12:38.677Z",
"answer_score": 311
} |
Please answer the following Stack Overflow question:
Title: Convert Float to Int in Swift
<p>I want to convert a <code>Float</code> to an <code>Int</code> in Swift. Basic casting like this does not work because these types are not primitives, unlike <code>float</code>s and <code>int</code>s in Objective-C</p>
<pre><code>var float: Float = 2.2
var integer: Int = float as Float
</code></pre>
<p>But this produces the following error message:</p>
<blockquote>
<p>'Float' is not convertible to 'Int'</p>
</blockquote>
<p>Any idea how to property convert from <code>Float</code> to <code>Int</code>?</p> | <p>You can convert <code>Float</code> to <code>Int</code> in Swift like this:</p>
<pre><code>var myIntValue:Int = Int(myFloatValue)
println "My value is \(myIntValue)"
</code></pre>
<p>You can also achieve this result with @paulm's comment:</p>
<pre><code>var myIntValue = Int(myFloatValue)
</code></pre> | {
"question_id": 24029917,
"question_date": "2014-06-04T05:46:52.173Z",
"question_score": 219,
"tags": "swift|casting|type-conversion",
"answer_id": 24030079,
"answer_date": "2014-06-04T05:59:48.683Z",
"answer_score": 342
} |
Please answer the following Stack Overflow question:
Title: Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa
<p>In my application, I have an <code>EditText</code> whose default input type is set to <code>android:inputType="textPassword"</code> by default. It has a <code>CheckBox</code> to its right, which is when checked, changes the input type of that EditText to NORMAL PLAIN TEXT. Code for that is</p>
<pre><code>password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
</code></pre>
<p>My problem is, when that CheckBox is unchecked it should again set the input type to PASSWORD. I've done it using-</p>
<pre><code>password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
</code></pre>
<p>But, the text inside that edittext is still visible. And for surprise, when I change the orientation, it automatically sets the input type to PASSWORD and the text inside is bulleted (shown like a password).</p>
<p>Any way to achieve this?</p> | <p>Add an extra attribute to that <code>EditText</code> programmatically and you are done:</p>
<pre><code>password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
</code></pre>
<p>For numeric password (pin):</p>
<pre><code>password.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
</code></pre>
<p>Also, make sure that the cursor is at the end of the text in the <code>EditText</code> because when you change the input type the cursor will be automatically set to the starting point. So I suggest using the following code:</p>
<pre><code>et_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
et_password.setSelection(et_password.getText().length());
</code></pre>
<p>When using Data Binding, you can make use of the following code:</p>
<pre><code><data>
<import type="android.text.InputType"/>
.
.
.
<EditText
android:inputType='@{someViewModel.isMasked ?
(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD) :
InputType.TYPE_CLASS_TEXT }'
</code></pre>
<p>If using Kotlin:</p>
<pre><code>password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
</code></pre> | {
"question_id": 9892617,
"question_date": "2012-03-27T15:26:23.183Z",
"question_score": 219,
"tags": "android|passwords|android-edittext",
"answer_id": 9893496,
"answer_date": "2012-03-27T16:14:30.630Z",
"answer_score": 405
} |
Please answer the following Stack Overflow question:
Title: How do you clear the focus in javascript?
<p>I know this shouldn't be that hard, but I couldn't find the answer on Google.</p>
<p>I want to execute a piece of javascript that will clear the focus from whatever element it is on without knowing ahead of time which element the focus is on. It has to work on firefox 2 as well as more modern browsers.</p>
<p>Is there a good way to do this?</p> | <p>Answer: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement" rel="noreferrer"><code>document.activeElement</code></a></p>
<p>To do what you want, use <code>document.activeElement.blur()</code></p>
<p>If you need to support Firefox 2, you can also use this:</p>
<pre><code>function onElementFocused(e)
{
if (e && e.target)
document.activeElement = e.target == document ? null : e.target;
}
if (document.addEventListener)
document.addEventListener("focus", onElementFocused, true);
</code></pre> | {
"question_id": 2520650,
"question_date": "2010-03-26T01:35:12.653Z",
"question_score": 219,
"tags": "javascript|focus",
"answer_id": 2520670,
"answer_date": "2010-03-26T01:39:16.843Z",
"answer_score": 240
} |
Please answer the following Stack Overflow question:
Title: java.net.URLEncoder.encode(String) is deprecated, what should I use instead?
<p>I get the following warning when using <code>java.net.URLEncoder.encode</code>:</p>
<pre>warning: [deprecation] encode(java.lang.String)
in java.net.URLEncoder has been deprecated</pre>
<p>What should I be using instead?</p> | <p>Use the other <code>encode</code> method in <a href="http://docs.oracle.com/javase/8/docs/api/java/net/URLEncoder.html#encode-java.lang.String-java.lang.String-" rel="noreferrer">URLEncoder</a>:</p>
<pre><code>URLEncoder.encode(String, String)
</code></pre>
<p>The first parameter is the text to encode; the second is the name of the character encoding to use (e.g., <code>UTF-8</code>). For example:</p>
<pre><code>System.out.println(
URLEncoder.encode(
"urlParameterString",
java.nio.charset.StandardCharsets.UTF_8.toString()
)
);
</code></pre> | {
"question_id": 213506,
"question_date": "2008-10-17T19:19:39.590Z",
"question_score": 219,
"tags": "java|url|network-programming|deprecated",
"answer_id": 213519,
"answer_date": "2008-10-17T19:22:59.070Z",
"answer_score": 306
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.